// configuration options

var slideshow =	$("slideshow");	// id of the slideshow element
var slideDuration =	2.0; // in seconds
var transitionDuration = 2.0; // in seconds
var imageAltTag = 'J.Win Jewelry'; // alt tag
var shouldShuffle = true; // true or false

// don't mess with the stuff below

var theImages;
function startSlideshow(images){ 
	theImages = images;
	if (shouldShuffle)
    	theImages.shuffle();
	
	// set up the first image
	insertImage(theImages.first(), true);
}

function displayWithTimeout() {
	setTimeout(displaySlide, slideDuration * 1000);
}

var currentArrayIndex = 0;
function displaySlide() {
	if (currentArrayIndex + 1 > theImages.size()) {
		currentArrayIndex = 0;
	}
	
	insertImage(theImages[currentArrayIndex], true);
	preloadNextImage();
	currentArrayIndex++;
}

function insertImage(src, animated) {
	var theElement = new Element('img', { 'src': src, 'alt': imageAltTag});
	var previousElement = slideshow.down();
	if (animated) {
		theElement.hide();
		slideshow.insert(theElement);
		new Effect.Appear(theElement, {duration : transitionDuration, afterFinish:function(){
			if (previousElement) {
				previousElement.remove();
			}
			displayWithTimeout();
		}});
	}
	else {
		slideshow.update(theElement);
		displayWithTimeout();
	}
}

Array.prototype.shuffle = function(){
	this.sort(function() {return 0.5 - Math.random()})
}

function preloadNextImage() {
    preloadImages([theImages[currentArrayIndex + 1]]);
}

function preloadImages(array) {
    if (document.images) {
        var preload_image_object = new Image();
        array.each(function(image){
            preload_image_object.src = image;
        });
    }
}