// -----------------------------------------------------------------------------------
// THIS CLASS EXTENDS JQUERY SO THAT AN IMAGE PRELOADER CAN BE ADDED TO ANY ELEMENT
// COPYRIGHT 2010+: SCOTT THOMPSON, ALL RIGHTS RESERVED
// -----------------------------------------------------------------------------------
 jQuery.fn.image_preloader = function(options) {
	
	//__CONSTRUCTOR
	return this.each(function(index, item) {
		
		//=== SETTINGS + DEFAULTS
		this.settings = jQuery.extend({
			onFinish: function () {}	//called when all the images have finished loading, and the original HTML has been restored
		}, options);
		
		//=== VARIABLES
		
		//save the original html ready to be restored when finished loading the images
		this.original_html = $(item).html();
		this.$container = $(item);
		this.total_preloaded = 0;
		
		//extract all the images ready to preload
		this.images = this.$container.find('img');
		
		//if there are no images to load, no need to load the preloader!
		if (this.images.length < 1) {
			//callback
			this.settings.onFinish(this.$container);
			return;
		}
		
		//NOW START USING THE VARIABLES
		
		//replace the original html, with the preloader html
		this.$container.html('<div class="image_preloader_loading"><div style="padding:15px;"><b style="font-size:16px;">loading slideshow...</b><br /><br /><br /><span style="font-size:10px;color:#666666;font-weight:bold;">0 of '+this.images.length+' (0% complete)</span></div></div>');
		
		//stupid function closures
		var _this = this;
		
		//load the images 1 by 1
		return this.images.each(function(index, img) {
			
			var img_preloader = new Image();
			
			//stupid function closures, ahhhhh
			var __this = _this;
			
			// once image is preloaded, resize image container
			img_preloader.onload = function(){
				
				//loaded the image, so update the preloaders status
				__this.total_preloaded++;
				__this.$container.find('span').text(__this.total_preloaded+' of '+__this.images.length+' ('+Math.round(__this.total_preloaded/__this.images.length*100)+'% complete)');
				
				//destroy the preloader?
				if (__this.total_preloaded == __this.images.length) {
					
					//replace the preloader with the original html
					__this.$container.html(__this.original_html);
					
					//callback
					__this.settings.onFinish(__this.$container);
					
				}
			};
			
			img_preloader.src = img.src;
			
		});
		
	});
	
};
