(function () {

	jQuery.fn.slideshow = function (options) {

		var opts = jQuery.extend({}, jQuery.fn.slideshow.defaults, options);
		
		// If we don't have any images we should just bail now and not waste any more time setting things up
		if ( ! opts.images) {		
			return;		
		}
			
		jQuery.fn.slideshow.options = opts;
		
		// Preload images
		for (var index in opts.images) {
			var img = new Image(); 
			img.src = opts.images[index]; 
		}
		
		jQuery.fn.slideshow.image_index = opts.start_image;
		
		jQuery.fn.slideshow.elements = this;

		setTimeout(jQuery.fn.slideshow.next_image, jQuery.fn.slideshow.options.time);
	};
	
	jQuery.fn.slideshow.next_image = function (elm) {
	
		jQuery.fn.slideshow.image_index++;
	
		if (jQuery.fn.slideshow.image_index === jQuery.fn.slideshow.options.images.length) {
			jQuery.fn.slideshow.image_index = 0;			
		}
	
		jQuery.fn.slideshow.elements.each(function () {
		
			var offset = $(this).offset();
		
			var image = $(this).clone(true);			
			image.attr("src", jQuery.fn.slideshow.options.images[jQuery.fn.slideshow.image_index])
				.css("position", "absolute")
				.css("display", "none")
				.css("top", 0)
				.css("left", 0)
				.css("z-index", 0)
				.insertAfter(this)
				.fadeIn("slow");
			
			var index = jQuery.inArray(this, jQuery.fn.slideshow.elements);
			
			if (index !== -1) {
			
				jQuery.fn.slideshow.elements[index] = image;
			}
			
			$(this).fadeOut("slow", function () { $(this).remove(); });
		});
		
		setTimeout(jQuery.fn.slideshow.next_image, jQuery.fn.slideshow.options.time);		
	};
	
	jQuery.fn.slideshow.elements = {}; // Holds elements that slideshow will be placed in

	jQuery.fn.slideshow.image_index = 0; // Index of image being shown
	
	jQuery.fn.slideshow.options = {}; // Will hold the set options, after the passed options have overridden the below defaults
	
	jQuery.fn.slideshow.defaults = {
		time: 5000, // seconds for each image, in milliseconds
		start_image: 0, // Index of starting image
		images: [] // Array of images to use in slide show
	};


})(jQuery);
