/* ---------------------------------------------------------
   jlo Image Control
   Author: Tim Kinnane www.owlandfox.com
   Pattern by: Tim Kinnane www.owlandfox.com
   Version: 1.0 2 Nov 2010
   Description: Sets up a set of controls for an associated image
--------------------------------------------------------- */
(function($){
	// Initialise - applied to the element that plugin is run on
	$.fn.jloImageControl = function(options) {
		var opts = $.extend(true, {}, $.fn.jloImageControl.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 imgHolder = $('<div />').css({
				width: o.thumb_size,
				height: o.thumb_size
			}).addClass('img-container');
			var imgThumb = $('<img />').addClass('img-thumb');
			var positioner = $('<div />').jloPositioner({ className: 'position-control' });
			var scaler = $('<div />').jloScaler({ className: 'scale-control' });
			myself.append(imgHolder);
			imgHolder.append(imgThumb);
			myself.append(positioner);
			myself.append(scaler);
			scaler.hide();
			positioner.hide();
			imgThumb.hide();
			
			var uploader = $('<div />').addClass('jlo-uploader');
			myself.prepend(uploader);
			uploader.jloUploader({
				updated: function(path, name, dimension) { // after upload
					imgThumb.attr('src', path);
					imgThumb.attr(dimension, o.thumb_size);
					myself.data('file', path);
					myself.data('dimension', dimension);
					uploader.hide();
					imgThumb.show();
					positioner.show();
					scaler.show();
					
					// add layer to layout
					var newLayer = $('<img />');
					$('#layout').append(newLayer);
					newLayer.jloLayer({
						css: { left: "10px", top: "10px" },
						chainTo: myself
					});
					newLayer.load(function () {
						$(this).attr("width", $(this).width());
						$(this).attr("height", $(this).height());
						// trigger selection on controls to set data on attached layer
						scaler.jloScalerSet();
					});
					newLayer.attr('src',path); // load it last, allowing to size
					
					// attach layer to all controls for easy access
					myself.chainTo(newLayer);
					scaler.chainTo(newLayer);
					positioner.chainTo(newLayer);
					
					myself.data('updated').call(myself, name); // pass file name onto oter elements for labels
				},
				error: myself.jloErrorMsg,
				after: function() { o.after.call(myself) }
			});
			
			myself.click(function() {
				var myself = $(this);
				myself.addClass('selected').show();
				myself.parent().show(); // show parent and self, because control click could have been externally triggered while hidden
				myself.parent().siblings().hide();
				myself.siblings().removeClass('selected').hide();
			});
			
			/* END CUSTOM FUNCTIONALITY <---------------------------------------------------------------- */

			myself.bind('click', function() { $(this).data('clicked').call(this) }); // call custom function for after its clicked
			if(o.chainClick){$(this).bind('click',function(e,bc){bc?bc.push(this):bc=[this];$($(this).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);
		});
	}
	// Set some defaults
	$.fn.jloImageControl.defaults = {
		id: 'image-control',
		className: 'layer-controls',
		title: 'Image Control',
		addLabel: false,
		thumb_size: 75,
		css: {}, // default style object
		chainTo: Array(), // array of elements that this plugin is attached to - allows chaining events from one to the next
		chainClick: true, // will fire click event on chained elements when it is clicked
		chainDisplay: false, // will show/hide chained elements when this is shown/hidden
		chainRemove: false, // will remove chained elements if this one removed
		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
