 
generic.templates = {};

generic.templates.RediTemplate = Class.create( Template, {
	initialize: function ( template, pattern ) {
		this.template = template?template:'';
		this.readyState = template?1:0;
		this.pattern = pattern?pattern:Template.Pattern; 
		this.queue = new Array();		
		return;
	},
	load: function(template) {
	    this.template = template.toString(); 
	    this.readyState = 1; 
	    this.onReadyState();
	}, 
	evaluateCallback: function (options) {  
	    this.options = {
	      object:       {},
	      callback: 	function () {}
	    };
	    Object.extend(this.options, options || { });  
	    if (this.readyState) {   
			this.options.callback(this.evaluate(this.options.object));
	    } else { 
			this.queue.push({
				qtype: 'callback',
				obj: this.options.object,
				fnc: this.options.callback
			});
	     }
	     return;		
	},
	onReadyState: function () {
		while (q = this.queue.shift()) {
			var object = q.obj;
			var qtype = q.qtype;
			var callback = q.fnc;
			var elm;
			callback(this.evaluate(object)); 
		}
	}
});	

generic.templates.Factory = Class.create( Hash, {  
	templatesHash: false,
	get: function (args) {  
		var key = args.path;
		var bRefresh = args.bRefresh || false; 
		var templateString = args.templateString || false;
		
		//RediTemplate previously created
		if (typeof this._object[key] != "undefined" && !bRefresh) {  
			return this._object[key];
		}
		
		//create RediTemplate 
		this._object[key] = new generic.templates.RediTemplate();  
		
		//check if the path is a key in a hash
		if (this.templateHash) { 
		    try { if (key.indexOf(this.templateHash)==0) templateString = eval(key); } catch(e) {}
		}
		
		//check if using a string (either via args.templateString or via the hash)
		if (templateString) {
			this._object[key].load(templateString); 
			return this._object[key];
		} 
		
		//get template via Ajax
		var url = key;
		var tAjax = new Ajax.Request(url, {
		    method: 'get',
		    onSuccess: function(transport) {   
		        this._object[key].load(transport.responseText);
		    }.bind(this)
		});
		return this._object[key];	
	}	
});

generic.templates.factory = new generic.templates.Factory();
