jtemplate = function(html){ if(this.init){ this.init(html); } };
jtemplate.prototype = {
	html:'',
	replaces:null,
	conditions:null,
	regxReplace:/\$\{(.*?)?\}/g,
	regxCondition:/\$if\{(.*?)?\}((.*\n)*?)?\$endif/g,
	init: function(html){
		this.replaces = new Array();
		this.conditions = new Array();
		this.html = html;
		this.parse();
	},
	parse: function(){
		this.parseReplaces();
		this.parseConditions();
	},
	parseReplaces: function(){
		var matches = this.html.match(this.regxReplace);
		var len = (matches ? matches.length : 0);
		for(var i=0; i<len; i++){
			var val = matches[i];
			if(!this.hasItem(this.replaces, val)){
				var func = val.replace(this.regxReplace, "$1");
				this.replaces.push({value:val,replaceFunction:this.createReplaceFunction(func)});
			}				
		}
	},
	parseConditions: function(){
		var matches = this.html.match(this.regxCondition);
		var len = (matches ? matches.length : 0);
		for(var i=0; i<len; i++){
			var val = matches[i];
			var func = val.replace(this.regxCondition, "$1");
			var innerhtml = val.replace(this.regxCondition, "$2");
			this.conditions.push({value:val,content:innerhtml,conditionFunction:this.createConditionFunction(func)});
		}
	},
	apply: function(obj) {
		var outHtml = this.html;
		for(var i=0; i<this.conditions.length; i++){
			try{
				var condition = this.conditions[i];
				if(condition.conditionFunction && condition.conditionFunction(obj)){
					outHtml = this.replaceAll(outHtml, condition.value, condition.content);
				}
				else{ outHtml = this.replaceAll(outHtml, condition.value, ''); }
			}catch(ex){}
		}
		for(var j=0; j<this.replaces.length; j++){
			try{
				var part = this.replaces[j];
				if(outHtml.indexOf(part.value) > -1){
					var replaceText = part.replaceFunction(obj);
					outHtml = this.replaceAll(outHtml, part.value, (replaceText ? replaceText : ''));
				}
			}catch(ex){}
		}
		return outHtml;
	},
	createReplaceFunction: function(func){
		var funcString = 'var $t=$T; var val=' + func + '; return (val ? val : "");';
		return new Function('$T', funcString)
	},
	createConditionFunction: function(func){
		var funcString = 'var $t=$T; var val=(' + func + '); return (val ? true : false);';
		return new Function('$T', funcString)
	},
	replaceAll: function(value, find, replace){
		var i = value.indexOf(find);
		var c = value;
		while (i > -1){
			c = c.replace(find, replace); 
			i = c.indexOf(find);
		}
		return c;
	},
	hasItem: function(arr, val){
		for(var i=0; i<arr.length; i++){
			if(arr[i].value == val)
				return true;
		}
		return false;
	}
};

(function(){
	if(typeof jQuery!='undefined'){
		jQuery.template = function(html) {
			return new jtemplate(html);
		};
	}
})();