/**
 * Image Loader jQuery Plugin 1.0
 *
 * @author Steve Sinnwell<s@hopeglory.com>
 */
(function($) {
	$.fn.imageQueue = function(settings) {
		var images = [];
		var config = {attribute:'src'};
		if (settings) {
			$.extend(config, settings);
		}

		this._start = function() {
			$(this).triggerHandler(START);
		};

		this._progress = function(data) {
			$(this).triggerHandler(PROGRESS, data);
		};

		this._error = function() {
			$(this).triggerHandler(ERROR);
		};

		this._complete = function(data) {
			$(this).triggerHandler(COMPLETE, data);
		};

		this.load = function(index) {
			var max = images.length;

			if(index < max) {
				var img = new Image();
				var imageQueue = this;
				if(index === 0) {
					imageQueue._start();
				}
				$(img).load(function() {
					imageQueue._progress({index:(index+1), max:max});
					if(index == max-1) {
						imageQueue._complete({images:images,index:(index+1), max:max});
					}else {
						imageQueue.load(index+1);
					}
				}).error(function() {
					imageQueue._progress({index:(index+1), max:max});
					imageQueue._error();
					if(index == max-1) {
						imageQueue._complete({images:images,index:(index+1), max:max});
					}else {
						imageQueue.load(index+1);
					}
				}).attr('src', images[index]);

			};

			return this;
		};
                                 
		var START = 'loadstart'; 
		var PROGRESS = 'loadprogress'; 
		var ERROR = 'loaderror';
		var COMPLETE = 'loadcomplete';
		
		this.each(function(index, element) {
			if($(element).attr(config.attribute)) {
				images.push($(element).attr(config.attribute));
			}
		});

		return this;
	};
})(jQuery);
