/*
 * JavaScript Template Engine
 * by Jairo Luiz 
 */
Template = function(template) {
	
	template = template.replace(/\n/g, "")
					   .replace(/\r/g, "")
					   .replace(/\'/g, "\\\'");						
	
	var regex = /(#\{)(\w|\.)*(\})/gm;
		
	var match = null;
	var variable = null;
	var text = null;
	var init = 0;
	
	var funcBody = ["var __body__ = [];"];
	while (match = regex.exec(template)){
		variable = match[0];
		variable = variable.substring(2, variable.length - 1);
		
		text = template.substring(init, match.index);
		funcBody.push("__body__.push('" + text + "');");
		init = regex.lastIndex;		
		
		funcBody.push("__body__.push(" + variable + ");");		
	}	
	
	text = template.substring(init);
	funcBody.push("__body__.push('" + text + "');");
	funcBody.push("return __body__.join('');")	

	return {		
		evaluate: function(context) {
			var obj = {};
			var preFuncBody = [];
			for (var property in context) {
				obj[property] = context[property];
				preFuncBody.push("var " + property + " = this." + property + ";"); 
			}
						
			obj.__eval__ = new Function(preFuncBody.join("\n") + funcBody.join("\n"));					
		
			return obj.__eval__();
		}	
	}
}

TemplateLoader = function() {
	
	var getXmlHttpRequest = function _getXmlHttpRequest() {
		try {
			return new XMLHttpRequest();
		} catch (e) {
			try {
				return new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
	};
	
	var request = getXmlHttpRequest();

	return {
		load: function(uri) {			
			request.open("GET", uri, false);
			request.send("");
			return request.responseText;
		}
	}
}
