/* ---------------------------------------------------------
   jlo Functions - used by most jlo Plugins
   Author: Tim Kinnane www.owlandfox.com
   Pattern by: Tim Kinnane www.owlandfox.com
   Version: 1.0 2 Nov 2010
   Description: 
--------------------------------------------------------- */
(function($){

	// chaing an element to a given element or array of elements
	// takes an array of elements, returns self
	$.fn.chainTo = function(chain) {
		return this.each(function() {
			var myself = $(this);
			var chainTo = myself.data('chainTo');
			if(!chainTo.length) chainTo = chain; // if not already chained, just use the given chain
			else $(chain).each(function() { if ($(chainTo).index(this)<0) chainTo.push(this) }); // add to chain unless already in it
			myself.data('chainTo', chainTo);
		});
	}
	
	// get data, add new data, save data	
	$.fn.jloData = function(obj) {
		return this.each(function() {
			var olddata = $(this).data();
			var newdata = $.extend({}, olddata, obj);
			$(this).data(newdata);
		});
	};

	// output data to a given element for debuging
	$.fn.jloDebug = function(el, title, clear) {
		return this.each(function() {
			if (clear) $(el).html("");
			if (!title) title = "Data Debug";
			var thedata = $(this).jloDataFilter();
			var dataHTML = '<table class="meta"><thead><tr><th colspan=2>'+title+'</th></tr></thead><tbody>';
			$.each(thedata, function(label, value){
				dataHTML += '<tr><td class="two">'+label+'</td><td class="meta_desc five">'+value+'</td></tr>';
			});
			dataHTML += '</tbody></table>';
			dataDIV = $('<div />');
			dataDIV.html(dataHTML);
			el.append(dataDIV);
		});
	};
		
	// sort the wheat from the chaff
	// returns data with some default and any additional keys omitted
	$.fn.jloDataFilter = function(additional) {
		var ignore = $.fn.jloDataFilter.ignorekeys;
		// if additional keys given (as comma seperated) remove spaces and make an array to join with defaults
		if (typeof additional != 'undefined') {
			additional = $(additional).split(' ').join('');
			filtered = filtered.concat($(additional).join(','));
		}
		var filtered = {};
		$.each($(this).data(), function(key, value) {
			if (!($.inArray(key, ignore) > -1) && ! $.isFunction(value))
				{
				if (typeof(value) == 'object')
					{
					$.each(value, function(key, value)
						{
						if (!($.inArray(key, ignore) > -1))
							filtered[key] = value;
						});
					}
				else
					filtered[key] = value;
				}
		});
		return filtered;
	};
	
	// Set defaults for plugin
	$.fn.jloDataFilter.ignorekeys = [
		'events',
		'handle',
		'controller',
		'draggable',
		'fxqueue',
		'debug',
		'image_base',
		'server_path',
		'username',
		'proceed_url',
		'layoutid_var',
		'snapping',
		'classname',
		'onLayerSelect',
		'chainTo'
	]; // ignore keys are the data elements that don't need to be saved to DB
	
	// convert attributes of an element into data properties
	// if an tag name or array of tag names is given, it will omit those tag types
	$.fn.jloMakeData = function(omit) {
		return this.each(function() {
			var dataobj = {};
			var tag = this.tagName.toLowerCase();
			var index = $(this).parent().children(tag).index(this);
			
			if (tag == "img")
			{
				dataobj = {
					index: index,
					type: 'img',
					src: $(this).attr('src'),
					width: $(this).width(),
					height: $(this).height(),
					top: $(this).css('top'),
					left: $(this).css('left')
				};
			}
			else if (tag == 'span' || tag == 'p')
			{
			   dataobj = {
					index: index,
					type: 'txt',
					input: $(this).data('input'),
					value: $(this).text(),
					top: $(this).css('top'),
					left: $(this).css('left'),
					font: $(this).css('font-family'),
					size: $(this).css('font-size'),
					colour: $(this).css('color')
				};
			}
			$(this).data('dataobj', dataobj);
		});
	};

	// save layout and layer meta - called as method of layout object
	// accepts names for array output, action file, after save and fuctions for response
	// server side script has to repond with "error:" for it to detect an error
	$.fn.jloDataSave = function(parentname, childname, action, after, error) {
		var myself = $(this);
		var saveObj = {};
		// make object from all data in current layers starting with the layout itself
		saveObj[parentname] = myself.jloDataFilter();
		$.each(myself.children(), function(index, child) {
			saveObj[childname+'-'+index] = $(child).jloDataFilter();
		});
		var saveParam = $.param(saveObj); // pass object to ajax file
		$.ajax({
			type: 'POST',
			url: action,
			data: saveObj,
			dataType: 'text',
			success: function(response) {
				response = $.trim(response);
				if (error) {
					// test for error in response and call error func
					subresponse = response.split(":");
					if ($.trim(subresponse[0]) == "error") {
						errormessage = $.trim(subresponse[1]);
						error.call(this, errormessage);
						return false;
					}
				}
				after.call(this, response);
				return true;
			}
		});
	};

})(jQuery); // ALL DONE
