/**
 * platform Image Loader
 * 
 * @desc Loads a list of images using jQuery
 * @author rdteam
 * @published 14/01/2009
 */
(function($) {

	/**
	 * Initialise cycle images
	 * 
	 * @var array images A list of image urls to be loaded into the element
	 * @var object options
	 * @var boolean options.debug will output log messages using "console" if
	 *      set to true.
	 */
	$.fn.platformPreloadImages = function(selector, options) {
		settings = jQuery.extend( {
			debug : false
		}, options);

		if(selector == undefined){
			selector = 'img';
		}
		state(this, 'initialise');
		
		// Attach loading class, and return element
		return this.each(function() {
			
			$(this).addClass( 'loading' );
			
			// Add images to array and remove src from images and put it into the jQuery data storage on the element
			// This is to prevent the document from loading the images
			var images = new Array();
			$(this).find(selector).each(function() {
				$(this).data('src', $(this).attr('src'));
				$(this).attr('src', '');
				images.push( this );
			})
			
			// Bind to the window load to commence loading
			$(window).bind('load', {target:this}, function(e) {
				imageStackOut( e.data.target, images );
			});
			
			
		});
	}

	/**
	 * Load an array of images into an element
	 * 
	 * @var HTMLElement element
	 * @var Array images
	 */
	var imageStackOut = function(element, images) {
		var image = images.shift();
		if (image == undefined) {
			$(element).removeClass( 'loading' );
			state( element, 'complete' );
			return false;
		}
		state( $(image).data( 'src' ), 'loadImage' );
		return $(image).bind( 'load', function() {
			state( this, 'loadImageComplete' );
			imageStackOut( element, images );
		}).attr( 'src', $(image).data( 'src' ) );
	}

	/**
	 * Trigger method
	 * 
	 * @var Object target
	 * @var Array images
	 */
	var state = function(target, state) {
		if (settings.debug && console) {
			console.log('State: ' + state + ' [' + target + ']');
		}
		if (typeof (target) == 'object') {
			$(target).trigger('on' + state, target);
		}
	}

})(jQuery);