/*
 * jQuery Sequential Loader
 * version: 1.0.0 (2010/12/20)
 * Author: Aldo Zorzi
 * http://www.fillstudio.com
 
 Usage:
	$('__ELEMENT__').sequentialLoader(
	{
		time:__time_in_milliseconds__
	});
*/
(function( $ )
{
	function SequentialLoader(element, opts)
	{
		//	DEFAULT ATTRIBUTES
		this.defaults = {
				time : 500
		};
		
		//	EXTENDS THE DEFAULT WITH CUSTOM OPTIONS
		this.options = $.extend(this.defaults, opts);
		
		//	REFERENCE FOR SCOPE
		this.instance = $(element);
		
		//	OTHER VARIABLES
		this.loading;
		this.image;
	};
	
	SequentialLoader.prototype = {
			init : function()
			{
				this.instance.removeAttr("src");
				this.instance.hide();
				this.createLoading();
			},
			createLoading : function()
			{
				this.instance.parent().append("<div class='photo_loading'></div>");
				this.loading = $('.photo_loading',this.instance.parent());
				this.loading.html('<span>Loading...</span>');
				this.loading.css({
					'z-index':'5',
					'position':'absolute'
				});
			},
			hideLoading : function()
			{
				var $this = this;
				this.loading.fadeOut(this.options.time,function(){
					$this.loading.remove();
					});
			},
			loadPhoto : function()
			{
					this.image = new Image();
					this.image = $(this.image);
					this.image.attr('src', this.options.image);
					
					var $this = this;
					this.image.load(function(){$this.onPhotoLoaded()});
			},
			onPhotoLoaded : function()
			{
				this.hideLoading();
				$(this.instance).trigger('PHOTO_LOADED');
				this.displayImage();
			},
			displayImage : function()
			{
				$(this.image).hide()
				this.instance.replaceWith(this.image);
				$(this.image).fadeIn(this.options.time);
			}
	};
	
	$.fn.sequentialLoader = function(options) 
	{
		this.img_queue = new Array();
		this.img_loader = new Array();
		
		if(this.length) 
		{
			$loader = this;
			this.index = 0;
			this.first = true;
			this.each(function() 
			{
				$loader.img_queue.push($(this).attr('src'));
				options = {image:$(this).attr('src')};
				var new_sequentialLoader = new SequentialLoader(this, options);
				$loader.img_loader.push(new_sequentialLoader);
				new_sequentialLoader.init();
				$(this).bind('PHOTO_LOADED', function(){$loader.nextPhoto()});
				if($loader.first)
				{
					new_sequentialLoader.loadPhoto();
					$loader.first = false;
				}
			});
		}
		this.nextPhoto = function()
		{
			if(this.index<=this.img_queue.length-2)
			{
				this.index++;
				this.img_loader[this.index].loadPhoto();
			}
		}
	};
	
})( jQuery );
