/* ---------------------------------------------------------
   My New jQuery Plugin Light
   Author: Tim Kinnane www.owlandfox.com
   Pattern by: Tim Kinnane www.owlandfox.com
   Version: 1.0 2 Nov 2010
   Description: Provides a file upload control,
   file input, thumbnail and some basic functionality
--------------------------------------------------------- */
(function($){
	$.fn.jloUploader = function(options) {
		var opts = $.extend(true, {}, $.fn.jloUploader.defaults, options);
		var count = $(this).length;
		var collection = $(this);
		return this.each(function() {
			var o = $.extend({}, opts, $(this).data());
			var myself = $(this);
			o.before.call(this);
			myself.addClass(o.className).css(o.css);
			if(myself.attr('id') == "") { var idsuffix = (count > 1) ? "-"+collection.index(this) : ""; myself.attr("id", o.id+idsuffix) };
			myself.data(o);
			/* CUSTOM FUNCTIONALITY HERE ---------------------------------------------------------------> */
			
			var upInput = $('<input type="file" name="jloUploader" id="'+myself.attr('id')+'-file'+'" />').addClass("file-upload");
			var loadimg = $('<img />').attr('src', Settings.web_path+'/images/loading.gif');
			myself.append(upInput);
			myself.append(loadimg);
			loadimg.hide();
			
			upInput.change(function() {
				loadimg.show();
				upInput.upload(o.action, function(response) {
					if (response.error || response.filepath == "") {
						console.log(response.error);
						o.error.call(this, response.error);
					} else myself.data('updated').call(this, response.filepath, response.filename, response.larger);
					loadimg.hide();
				}, 'json');
			});
			
			/* 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
			o.after.call(this);
		});
	}
	$.fn.jloUploader.defaults = {
		/* CUSTOM PROPERTIES AND METHODS */
		
		action: Settings.web_path+'/inc/upload-handler.php',
		error: function(msg) { console.log(msg) },
		thumb_size: '75px',
		
		/* PATTERN DEFAULTS... */
		id: 'upload-control',
		className: 'upload-control',

		css: {},
		chainTo: [],
		chainClick: false,
		before: function() {},
		after: function() {},
		clicked: function() {},
		updated: function() {}
	}
})(jQuery); // ALL DONE
