/*
    Copyright (c) 2007 artBits snc http://www.artbits.it

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
    and associated documentation files (the "Software"), to deal in the Software without restriction,
     including without limitation the rights to use, copy, modify, merge, publish, distribute, 
     sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
     furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or 
    substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
    BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
    DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

// save users that don't have firebug from crashes
if(!console){var console={};console.log=function(){};}

var TemplateEngine = {

	_version: 0.2,                          // jsTemplate version
	_path: "templates/",                    // The path of the *.jtf files on server, remeber the final slash!
	_cache: {},                             // Cached templates are stored here
	_requested: [],                         // a queque of requests
	_working: "",                           // the current working request
	_ieSpecific:[""],	                    // template listed here has a specific version for IE
	_myRequest: null,                       // XHR object
	
	/*
	    Explicitally load templates from server
	    @param name: the template name without the extension
	    @param callback: a function called when the template is loaded
	    @return null
	*/
	loadTemplate: function(name, callBack){
	    // Check if the template requires a specific version for IE
		if(TemplateEngine._needIeSpecific(name)){
		    name = name + "_ie";
	    }
		
		if(TemplateEngine.isLoaded(name)){
			if(arguments.length > 1){
				callBack();
			}
			return;
		}
		
		this._requested.push({name: name, callBack:callBack});
		if(this._working == "") this._requestTemplate();	// inizia il ciclo di download
	},
	
	/*
	    Render a specific template with the data passed.
	    It works also with template that aren't in cache
	    @param name: the template name
	    @param data: an object containing data
	    @param callBack: a function called when the operation finished
	    @return string: the rendered template
	*/
	render: function(name, data, callBack){

	    if(TemplateEngine._needIeSpecific(name)){
		    name = name + "_ie";
	    }
	    
		var template = this.get(name);

		if(this.isLoaded(name) == false){
			this.loadTemplate(name, callBack);
			return;
		}
		
		template = TemplateEngine._completeTransformation(data, template);
		
		try{
		    template = eval(template);
		}catch(e){
		    console.log(e);
		    return null;
		}
		
		var templateCaller = "template(";
		for(el in data){
		    templateCaller += data[el] + ", ";
		}
		templateCaller = templateCaller.substr(0, templateCaller.length - 2);
		templateCaller += ");";

		var result = null;
		
		try{
		    result = eval(templateCaller);
		}catch(e){
		    console.log(e);
		    return null;
		}
		return result;
	},
	
	/*
	    Check the cache for template
	    @param name: the template name
	    @return boolean
	*/
	isLoaded: function(name){
		if(this.get(name) != null){
			return true;
		}else{
			return false;
		}
	},
	
	/*
	    Store a template into the cache
	    @param name: the name of the template
	    @param template: the string containing the template
	*/
	set: function(name, template){
	    var translated = TemplateEngine._translate(template);
	    TemplateEngine._cache[name] = translated;
	},
	
	get: function(name){
	    if(this._cache.hasOwnProperty(name)){
	        return this._cache[name];
	    }
	    return null;
	},
	
	/*
	    Reload all the template in cache. It can be useful for debugging
	*/
	reloadAll: function(){
		for(var el in this._cache){this.loadTemplate(el);}
	},
	
	/*****************************************************************
							Private Methods
	******************************************************************/
	
	_createXHR: function(){
        var xmlhttp = null;
	    try {
	        xmlhttp = new XMLHttpRequest();
        } catch(e) {
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        xmlhttp.onreadystatechange = TemplateEngine._connectionHandler;
        return xmlhttp;
    },
    
    _translate: function(template){
        
        var output = "\nvar _jtfOutput = [];";
        var pos = 0;
        var start = 0;
        var end = 0;
        var translated = "";
        // <#=[1-9-A-Z-a-z-\W]*#>
        /* transform <#= something #> tag into <# write(something) #> */
        while(1){
            start = template.indexOf("<#=", pos);
            if(start < 0) break;
            translated += template.substring(pos, start + 2);
            translated += "write(";
            end = template.indexOf("#>", start + 2);
            translated += template.substring(start + 3, end).replace(/\s/gi,"");
            translated += "); #>";
            pos = end + 2;
        }
        translated += template.substring(pos, template.length);

        template = translated;
        translated = "";
        pos = 0;
        /* Now transform the template into the code of a function */
        while(1){
            start = template.indexOf("<#", pos);
            if(start < 0) break;  // End of file
            translated += "\nwrite(\"" + template.substring(pos, start).replace(/\n/gi,"") + "\");";
            end = template.indexOf("#>", start + 2);
            translated += "\n" + template.substring(start + 2, end);
            pos = end + 2;
        }
        translated += "\nwrite(\"" + template.substring(pos, template.length).replace(/\n/gi,"") + "\");";
        
        // Delete commands that doesn't anything
        translated = translated.replace(/write\(""\);/g, "");
        
        // expand write macro
        translated = translated.replace(/write\(/g,"_jtfOutput.push(");
        
        var trail = "return _jtfOutput.join('')};";
        return [output, translated, trail].join("");
    },
    
    _connectionHandler: function(){
        if (TemplateEngine._myRequest.readyState == 4) {
            if (TemplateEngine._myRequest.status == 200) {
                TemplateEngine._templateLoaded();
            }else{
                TemplateEngine._failedLoading();
            }
        }
    },
    
    _needIeSpecific: function(name){
        var founded = false;
		for(var i = 0; i < TemplateEngine._ieSpecific.length; i++){
		    if(TemplateEngine._ieSpecific[i] == name){
		        founded = true;
		    }
		}
		if(founded && navigator.appName == "Microsoft Internet Explorer"){
			return true;
		}
		return false;
    },
    
	_templateLoaded: function(){
        var r = TemplateEngine._myRequest;
		this.set(this._working.name, r.responseText);
		if(this._working.callBack){
			this._working.callBack();
		}
		this._endLoading();
	},
	
	_failedLoading: function(){
	    var r = TemplateEngine._myRequest;
		this._endLoading();
	},
	
	_endLoading: function(){
		this._working = "";
		if(this._requested.length == 0) return;
		this._requestTemplate();
	},
	
	_completeTransformation: function(data, template){
	    var el;
		var head = "template = function(";
		for(el in data){
		    head += el + ", ";
		}
		head = head.substr(0, head.length - 2);
		head += "){";
		
		return [head, template].join('');
	},
	
	_requestTemplate: function(){
		if(this._working != "") return; // Sto gia' scaricando un template

		this._working = this._requested.shift();
		if(this._myRequest == null){
		    this._myRequest = TemplateEngine._createXHR();
		}
		this._myRequest.open("GET",
		                    this._path + this._working.name);
        this._myRequest.send(null);
	}
	
}