(function(){

	jQuery.fn.slideshow = function(settings) {
		settings = $.extend({
			images: null,
			width: 573,
			height: 382,
			interval: 8,
			rand: true,
			randStart: true,
			prefix: ''
		}, settings);

		var snapwindow = $(this);
		
		// Remove all child elements
		snapwindow.children().remove();
		
		snapwindow.css({
			position: 'relative',
			width: settings.width + 'px',
			height: settings.height + 'px'
		});

		var oldSnap = $('<div></div>').css({ 
			position: 'absolute', 
			top: 0, 
			left: 0,
			width: settings.width + 'px',
			height: settings.height + 'px'
		});
		
		oldSnap.appendTo(snapwindow);

		var lastImage = null, 
		    preloader = new Image(),
		    current   = null,
		    index     = null;
		
		preloader.snapElements = [snapwindow, oldSnap];

		preloader.onload = function() {
			this.snapElements[0].css({  
				background: 'transparent url(' + lastImage + ') no-repeat' 
			});
			this.snapElements[1].fadeOut('slow');
		}

		var getRand  = function() {
			return Math.floor(Math.random() * settings.images.length);
		};
		
		var getImage = function() {
			// Check if random mode or random start position is enabled 
			if (settings.rand || (current === null && settings.randStart)) {
				// Make sure that random picture is not same as the last one
				do { var index = getRand(); } while(current == index);

				current = index;
			}
			else 
				current = (current < settings.images.length - 1) ? current + 1 : 0;

			if (lastImage != null)
				oldSnap.css({ background: 'transparent url(' + lastImage + ') no-repeat' }).show();
			
			lastImage = settings.prefix + settings.images[current];
			preloader.src = lastImage;
		};
		// Get first picture
		getImage();
		setInterval(getImage, settings.interval * 1000);
		
	}


})();
