

(function($){
	
	if (!Array.prototype.shuffle) {
		Array.prototype.shuffle	= function () {
			var l = this.length;
			while (l--) {
				var r = Math.floor(Math.random() * (l + 1));
				var s = this[r];
				this.splice(r, 1);
				this.push(s);
			}
			return this;
		};
	}
	
	$.slideimage = function (options) {
		
		$.slideimage.options	= $.extend({}, $.slideimage.defaults, options || {});
		$.slideimage.init($(this));
		return this;
		
		return this.each(function(){
			$.slideimage.init($(this)).show();
		});
	};
	
	$.extend($.slideimage, {
		defaults	: {
			images	: [],
			onfinish: function(){},
			delay	: 6,
			fade	: 3.5,
			zIndex	: -5
		},
		options		: {},
		init		: function (elements) {
			$(elements).hide();
			$(elements).each(function(){
				$.slideimage.options.images.push($(this));
			});
			$.slideimage.start();
			return this;
		},
		start		: function () {
			
			var currentSlide	= 0;
			var options			= $.slideimage.options;
			options.images.shuffle();
			$(options.images[currentSlide]).css({zIndex:options.zIndex}).delay(400).fadeIn("slow");
			
			$.slideimage.slideInterval	= setInterval(function(){
				if (currentSlide < options.images.length - 1) {
					lastSlide	= currentSlide;
					currentSlide++;
				} else {
					options.onfinish($.slideimage.slideInterval);
					currentSlide= 0;
					lastSlide	= options.images.length - 1;
				}
				
				$(options.images[lastSlide]).css({zIndex:options.zIndex - 1}).fadeOut(options.fade * 1000);
				$(options.images[currentSlide]).css({zIndex:options.zIndex}).fadeIn(options.fade * 1000);
				
			}, options.delay * 1000);
			
			return this;
		},
		stop		: function () {
			clearInterval($.slideimage.slideInterval);
		}
	});
	
	$.fn.extend({ slideimage : $.slideimage });
	
})(jQuery);
