/* ---------------------------------------------------------
   jlo Add Control
   Author: Tim Kinnane www.owlandfox.com
   Pattern by: Tim Kinnane www.owlandfox.com
   Version: 1.0 2 Nov 2010
   Description: Button with functions for setting up controls
   and element lists
--------------------------------------------------------- */
(function($){
	// Initialise - applied to the element that plugin is run on
	$.fn.jloAddControl = function(options) {
		var opts = $.extend(true, {}, $.fn.jloAddControl.defaults, options); // combine passed in args with defaults
		var count = $(this).length; // how many elements being used
		var collection = $(this); // store elements collection for getting index of current for suffix
		return this.each(function() { // apply to all jquery elements in selector and return self for chaining
			var o = $.extend({}, opts, $(this).data()); // Extend passed options with any preexisting data
			var myself = $(this); // for easy access to self
			o.before.call(this); // do anything needed prior to init
			//myself.children().remove();
			//myself.empty(); // clear anything in the element first, just in case
			myself.addClass(o.className).css(o.css); // add class and css from options 
			var idsuffix = (count > 1) ? "-"+collection.index(this) : ""; // use numbered suffix for id'ing multiple elements
			if(myself.attr('id') == "") myself.attr("id", o.id+idsuffix); // if no id set, use id from defaults
			myself.data(o); // store all current options in element data
			if (o.addLabel) myself.prepend($('<label>'+o.title+'</label>')); // add a label to element if required
			/* CUSTOM FUNCTIONALITY HERE ---------------------------------------------------------------> */
			
			var container = $(o.containerid);
			
			myself.click(function() {
				
				var controls = $('<div />');
				var count = myself.data('count') + 1;
				myself.data('count');
				container.append(controls);
				// Disable the button if the max count is reached
				if(count >= o.maxControls) {
					myself.attr("disabled", "disabled");
					myself.addClass('disabled');
				}
				
				if (o.controltype == 'txt') {
					var ypos = ((count-1)*o.textSpacing)+10;
					var text = "Text "+count;
					controls.attr('id', "text-controls-"+count);
					controls.jloData({ startText: text, startx: '10', starty: ypos });
					controls.jloTextControl({
						after: function() {
							myself.data('afteradd').call(controls, text);
						}
					});
				} else {
					var text = 'Image '+count;
					controls.attr('id', "image-controls-"+count);
					controls.jloImageControl({
						after: function() {
							myself.data('afteradd').call(controls, text);
						}
					});
				}
				controls.click();
				myself.data('count', count);
			});
			
			/* END CUSTOM FUNCTIONALITY <---------------------------------------------------------------- */
			myself.bind('click', function() { myself.data('clicked').call(this) }); // call custom function for after its clicked
			if(o.chainClick){myself.bind('click',function(e,bc){bc?bc.push(this):bc=[this];$(myself.data('chainTo')).each(function(){if($(bc).index(this)<0)$(this).triggerHandler('click',[bc])})})}; // my super function to tie click events together
			if (o.focus) myself.focus(); // focus on self
			o.after.call(this);
		});
	}
	$.fn.jloRemoveControl = function(chain) {
		var myself = $(this);
		var mydata = myself.data();
		// remove the controls in the chain (normally just one), then remove anything they are chained to
		if (chain.length >0) {
			chain.fadeOut('fast', function(){
				var subchain = $(this).data('chainTo');
				if (subchain && subchain.length >0) {
					subchain.fadeOut('fast', function(){
						$(this).remove();
					});
				}
				$(this).remove();
			});
		}
		
		var newCount = mydata.count -1;
		myself.data('count', newCount);
		myself.removeAttr('disabled');
		myself.removeClass('disabled');
		
		mydata.removed.call(this); // Call custom function for doing additional stuff
		return myself;
	}
	
	// Set some defaults
	$.fn.jloAddControl.defaults = {
		/* CUSTOM PROPERTIES AND METHODS */
		
		controltype: 'txt',
		textSpacing: 35,
		containerid: '',
		maxControls: 3,
		count: 0,
		afteradd: function() {},
		
		/* PATTERN DEFAULTS... */
		id: 'add-control',
		className: 'control-button',
		title: 'Add Control',

		addLabel: false,
		css: {}, // default style object
		chainTo: [], // array of elements that this plugin is attached to - allows chaining events from one to the next
		chainClick: false, // will fire click event on chained elements when it is clicked
		before: function() {}, // function to call before initialising elements
		after: function() {}, // function to call when initialised
		clicked: function() {}, // function to call after click event processed
		updated: function() {}, // function to call when something is updated
		error: function() {}, // function to call when an error occurs
		removed: function() {}, // function to call if plugin element removed
		debug: false, // do or don't do debuging type stuff
		focus: false // grab focus on self after init
	}
})(jQuery); // ALL DONE
