/* FellsWharfDesign - Mike Cohen
 * 
 * Options:
 * ---------------------------------------------------------------------------
 * Required:
 * 		-query: coldfusion query returned with returnformat=json
 * 		{"COLUMNS":["ColumnName 1","ColumnName 2"],"DATA":[[Column1Value1,column2Value2]]}
 * 		-data: array of arrays
 * 			   |						recordset 						|
 * 			   |		first row		   ||		second row			|
 * 			  [[column1Value1,column2value1][column1Value2,column2Value2]]
 * 
 * 		-columns: array of columns
 * 			  [column1,column2]
 *
 * 		-ajax (object): Options for a jquery ajax call. Use to return a query defined above. If you return
 * 						coldfusion query with returnformat="json" this will be able to use that response. 
 * 
 * 		
 * 
 * ----------------------------------------------------------------------------
 * Optional:
 * 		-grabWith (string): This is the value you want to wrap your variables with
 * 				  in your template code, it defaults to !variable!. But 
 * 				  you can customize what you use as your wrapper.
 * 				  (Remember this is case-INSENSITIVE!)
 * 						
 * 						So if you wanted:
 * 						
 * 						<div>My name is Mike</div>
 * 
 * 						Use:
 * 
 * 						<div>My name is !name!</div>
 * 		-remove (boolean): This specifies whether to delete the current target data content before loading records
 * 		
 * 		-target: selector of where you want this data to go, defaults to below template
 * 
 * 		-post: write a function to run on each row after variables are replaced
 * 				arguments: post(new content string, options object, current Row Data, Column Data,current Row Number);
 * 
 * Variables Available:
 * 		index = refers to the result
 */

(function($){
	$.templateDisplay = {
		defaults: {
			target:"none",
			remove:true,
			data: null,
			columns: null,
			grabWith: "!",
			template: null,
			query: null,
			ajax: {
				url: null
			},
			post:null
		}
	};
	$.fn.extend({
		templateDisplay: function(options){
			/*create settings*/
			options = $.extend($.templateDisplay.defaults, options);
			/*set template*/
			options.template = this;
			
			$(".templateDisplaydefault").remove();
			
			/*hide template and check if target is defined*/
			if(options.target=="none"){
				options.target = new Array();
				$(options.template).each(
					function(index){
						$(this).after(
							$(this).clone().empty().attr({
								className:"templateDisplaydefault"+index,
								id:""
							})
						);
						options.target.push(".templateDisplaydefault"+index);
					}
				).hide();		
			}else{
				if(isArray(options.template))
					options.target = new Array(options.target);					 
			}
			
			/*init some vars*/
			var results;
			if(!options.target.length){
				return alert("Template and target our required, one may be missing,ERROR");
			}
			if (options.template == null) 
				return alert("template is not defined,ERROR");
			if ((options.data && options.query) || (options.columns && options.query || (options.ajax.url && options.query) || (options.ajax.url && options.data) || (options.ajax.url && options.columns))) {
				alert("query, data, and url are mutually exclusive");
			}
			else {
				if (!options.query && !options.ajax.url) {
					/*get data*/
					if (options.data) 
						var tdata = options.data;
					else 
						return alert("No Data?");
					/*get columns*/
					if (options.columns) 
						var tcols = options.columns;
					else 
						return alert("No Columns?");
				}
				else {
					if (options.query) {
						/*get query*/
						
						var tcols = options.query.COLUMNS;
						var tdata = options.query.DATA;
					}
					else {
						options.ajax.success = function(d){
							var tcols = d.COLUMNS;
							var tdata = d.DATA;
							runCreation(tdata,tcols);
						};
						options.ajax.dataType="json";/*Force JSON*/
						$.ajax(options.ajax);
					}
				}
				
				if(!options.ajax.url){
					runCreation();
				}
			}
			
			function isArray(thing){
				if((typeof thing == "object") && (thing instanceof Array))
					return true;
				return false;
			};
			
			/*run*/			
			function runCreation(opdata,opcols){
				if(opdata){
					tdata = opdata;
					tcols = opcols;
				}
				
				/*if a table or something that needs to be modified*/
				/*preProcessor(options.template);*/
				
				if(options.remove){
					for(var i=0;i<options.target.length;i++){
						
						$(options.target[i]).empty();
					}
					
				}
				
				
				
				for (var r = 0; r < tdata.length; r++) {
					try{
						results = $(options.template).get(0).innerHTML;
					}catch(e){
						return alert("target issue, error, does it exist");
					}
					
					for (var c = 0; c < tcols.length; c++) {
						results = replace(options.grabWith, results, tcols[c], tdata[r][c],r);
					}
					if($.isFunction(options.post)){
						results = options.post(results/*new content*/,options/*options*/,tdata[r]/*Rowdata*/,tcols/*cols*/,r+1/*row*/);
					}
					for(var i=0;i<options.target.length;i++){
						$(options.target[i]).append(results);
					}
				}
				
				return true;
			};
			
			/*function preProcessor(template){
				template.each(function(){
					switch(this.nodeName){
						case "TABLE":		
						break;
						case "DIV":
						break;
						default: 
						break;
					}
				});
			}*/
			
			/*replace*/
			function replace(grabWith, string, colName, newString, row){
				var regex = new RegExp(grabWith + colName + grabWith, "gim");
				var index = new RegExp(grabWith + "index" + grabWith, "gim");
				return string.replace(regex, newString).replace(index, row+1);
			};

		}
	});
})(jQuery);
