/*
 * jQuery json template plug-in v0.0.4
 *
 * Copyright (c) 2009 Ryan Day
 * http://ryanday.org
 * 18 - aug - 2009
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($){
	$.fn.extend({
		getJSONPTemplate:function(templateSelector,jsonurl,params,complete,beforeComplete){
			this.getJSONTemplate(templateSelector,jsonurl+"?callback=?",params,complete,beforeComplete);
			return this;
		},
		getJSONTemplate:function(templateSelector,jsonurl,params,complete,beforeComplete){
			var contentArea = this[0];
			if(contentArea){
				$.getJSON(jsonurl,params,function(json){
					if(typeof beforeComplete == 'function'){
						this.cb = beforeComplete;
						json = this.cb(json);
					}
					//do templating here
					$(contentArea).JSONTemplate(templateSelector,json);
					//stop templating
					
					if(complete){
						this.cb = complete;
						this.cb(json);
					}
				});
			}
			return this;
		},
		JSONTemplate:function(templateSelector,json){
			var templateTagOpen = '%';
			var templateTagClose = '%';
			var contentArea = this[0];

			var template = $(templateSelector).clone()[0];
			if(template){
				/**
				 *this allows you to handle a one row type result
				 * takes a basic object as an argument
				 *	{taco:'happy',price:1.50}
				 * and turns it into
				 *	[{taco:'happy',price:1.50}]
				 * we can itterate over it without changing the multi dimensional array type data structure logic in the loop.
				 *
				 * the != 'object' check allows you to work with true multi dimensional arrays
				 *[as opposed to the assumtion of an array of objects (aka: associative arrays or hashes)]
				 *
				 * 	[['one','two','three'],['one','two','three']]
				 */
				if(!json[0] || typeof json[0] != 'object') json = [json];

				var regExps = {};

				$.each(json[0],function(k,v){
					fields = $(template).find(".field-"+k);
					if(fields.length){
						var tag = templateTagOpen+k+templateTagClose;
						fields.html(tag);
						regExps[tag] = new RegExp(tag);
					}
				});
				
				var compiled = '';
				var templateString = $(template).outerHTML();

				$.each(json,function(k,row){
					var preCompiled = templateString;
					$.each(row,function(k,v){
						var tag = templateTagOpen+k+templateTagClose;
						if(regExps[tag]) preCompiled = preCompiled.replace(regExps[tag],v);
					});
					compiled += preCompiled;
				});
				
				$(contentArea).html(compiled);
			}
			return this;
		},
		outerHTML:function(html){
			//allow getter setter functionality
			if(html) return this.replaceWith(html);
			var clone = $(this[0]).clone()[0];
			return $((clone.nodeName.toLowerCase() == 'tr'?'<table>':'<div>')).append(clone).html();
		}
	});
})(jQuery);