var templateParserPrefixKey = "";
function callFunction(func, param) {
	eval("" + func + "(param)");
}
function templateParse(parserHTML, json) {

	var replaceString;
	var regul;
	
	parserHTML = parserHTML.replace(/\n/g,"");

	regul = new RegExp("{" + templateParserPrefixKey + "replaceById:(.*?)#~#(.*?)}","m");
	replaceByIdMatches = parserHTML.match(regul);
	
	if(replaceByIdMatches != undefined) {
			
			elementIDs = replaceByIdMatches[1].split(",");
			elementKeys = replaceByIdMatches[2].split(",");
			
			if(elementIDs.length != undefined) {
				for(j=0;j<elementIDs.length;j++) {
	
					document.getElementById(elementIDs[j]).innerHTML = json[elementKeys[j]];
				}
			} else if(replaceByIdMatches[1] != "") {
				if($(replaceByIdMatches[1]) != undefined) {
					document.getElementById(replaceByIdMatches[1]).innerHTML = json[replaceByIdMatches[2]];
				}
			}
		
	}
	regul = new RegExp("{" + templateParserPrefixKey + "callFunction:(.*?)#~#(.*?)}","m");
	callFunctionsMatches = parserHTML.match(regul);
	
	if(callFunctionsMatches != undefined) {
			
			elementIDs = callFunctionsMatches[1].split(",");
			elementKeys = callFunctionsMatches[2].split(",");
			
			if(elementIDs.length != undefined) {

				for(j=0; j<elementIDs.length; j++) {
					
					if(json[elementKeys[j]] != undefined) {
						callFunction(elementIDs[j], json[elementKeys[j]]);
					} else {
						callFunction(elementIDs[j], {});
					}
				}
			} else if(callFunctionsMatches[1] != "") {

					callFunction(callFunctionsMatches[1], callFunctionsMatches[2]);
					
			}
	}
	
	for (var key in json) {
		
//		console.log(key + ":", typeof json[key]);
		if(json[key] == null) { json[key] = ""; }
		
		if(typeof json[key] != "object" && json[key] !== false) {
			
			// alert(key);
			regul = new RegExp("{" + key + "}", "g");
//			console.log("RegKey:", "{" + key + "}");
			parserHTML = parserHTML.replace(regul, json[key]);	
			
		} else if(json[key] === false) {
//			console.log(json[key]);
			
			regul = new RegExp("{" + key + "}(.*?){/" + key + "}","m");
			
			parserHTML = parserHTML.replace(regul, "");
			
		} else {
			
			regul = new RegExp("{" + key + "}(.*?){/" + key + "}","m");
			htmlPart = parserHTML.match(regul);
			
			replaceString = "";
				
//			console.log("parserHTML",parserHTML);
			if(htmlPart != null) {
				templateParserPrefixKey = key + ".";
				
				for(a = 0;a < json[key].length;a++) {
					
					replaceString += templateParse(htmlPart[1], json[key][a]);
				}
				templateParserPrefixKey = "";
				
				parserHTML = parserHTML.replace(regul, replaceString);
			}	
		}

	}
	
	return parserHTML.replace(/{(.*?)}/g, "");
}

function generateObject() {
	var returnValue = {};

	for(var a = 0; a < arguments.length; a++) {
		returnValue[arguments[a]] = arguments[a+1];
		a = a + 1;
	}
	// console.log(returnValue);
	return returnValue;
}
