var Handlebars = require('handlebars');
var cheerio = require('cheerio');

var binder = {};

(function()
{
	this.modules = {};
	
	this.getHtml = function(html, params, callback)
	{
		var $ = cheerio.load(html);
		
		this.databind($, "body", function(html)
		{
			$ = cheerio.load(html);
			html = $("body").html();
			
			var template = Handlebars.compile(html);
			
			$("body").html(template(params));
			callback($.html());
		});
	};
	
	this.databind = function($, selector, callback)
	{
		try
		{
			var that = this;
			
			var list = $(selector).find("*[data-bind]");
			
			var forEach = require('async-foreach').forEach;
			forEach(list, function(element, index)
			{
				var done = this.async();
				
				var moduleName = $(element).attr("data-bind");
				var param = $(element).attr("data-param");
				var templateId = $(element).attr("data-template");
				var template = "";
				
				$(element).removeAttr("data-bind");
				$(element).removeAttr("data-param");
				$(element).removeAttr("data-template");
				
				if(templateId)
				{
					var template = $(templateId).html();
					$("head").append($(templateId).remove());
				}
				else
				{
					done();
				}
				
				try
				{
					param = JSON.parse(param);
					
					template = template.replace(/&quot;/gi, "\"").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&apos;/gi, "\'");
					
					template = Handlebars.compile(template);
					
					if(that.modules.hasOwnProperty(moduleName))
					{
						that.modules[moduleName](param, function(data)
						{
							$(element).html(template(data));
							that.databind($, element, function(html)
							{
								done();
							});
						});
					}
					else
					{
						done();
					}
				}
				catch(err)
				{
					//에러 표시를 어딘가 해줘야함.
					console.log(err.stack);
					$(element).html(err.stack);
				}
			},
			function()
			{
				callback($.html());
			});
		}
		catch(err)
		{
			console.log(err.stack);
			callback($.html());
		}
	};
	
}).call(binder);

module.exports = binder;
@@ -1039,28 +1039,24 @@
 %0A%09%09%09%09%7B%0A%09%09%09%09%09
-var 
 template = $
@@ -1072,24 +1072,24 @@
 Id).html();%0A
+
 %09%09%09%09%09$(%22head
@@ -1178,24 +1178,40 @@
 %09%09try%0A%09%09%09%09%7B%0A
+%09%09%09%09%09if(param)%0A%09
 %09%09%09%09%09param =
@@ -1230,16 +1230,162 @@
 param);%0A
+%09%09%09%09%09else%0A%09%09%09%09%09%09param = %7B%7D%0A%09%09%09%09%09%0A%09%09%09%09%09if(!template)%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09//%ED%85%9C%ED%94%8C%EB%A6%BF %EC%97%86%EB%8B%A4%EA%B3%A0 %ED%91%9C%EC%8B%9C.%0A%09%09%09%09%09%09$(element).html(%22Template not found.%22);%0A%09%09%09%09%09%09done();%0A%09%09%09%09%09%7D%0A
 %09%09%09%09%09%0A%09%09

Check empty parameter.