/*  
*	Filename: 	js_swapimage.js 
*	Author: 	Joel Salisbury
*	Date:		July 2008
*	For:		University of Connecticut 
*	Purpose:	Loops through array of preloaded images and displays them at intervals.
* 	Release: 10-01-08
*	quid erat demonstrandum
*/

var transition;
var picture;
var images;
var arrayOfImageObjects;
var currentIndex = 0;
var interval;
var fade;

function $(id) {
	return document.getElementById(id);
}

function changeBackground(id, background, type) {
	if (type == "image") { //If an image is specified
		$(id).style.background="url("+background+")";
	}
	else {
		if (type == "color") { //If user specifies a color
			$(id).style.background = background;
		}
	}
}

function StartImageRotation(images, interval, trans) {
    transition = trans;
    images = images;
    arrayOfImageObjects = preloadImages();

    var randomnumber = Math.floor(Math.random() * (arrayOfImageObjects.length + 1))

    interval = interval; //seconds
    interval *= 1000;
    picture = 'picture';
    $(picture).src = arrayOfImageObjects[0].src;
    changeBackground('homeSS', arrayOfImageObjects[1].src, 'image');

    switch (transition) {
    case 'fade':
        fade = new Spry.Effect.Fade('picture', {
            duration: 1000,
            from: 100,
            to: 0,
            toggle: true
        });
		
        setInterval('fade.start()', interval); // the fade will happen every (interval) seconds
		setInterval('swapBackground()', (interval * 2) + 1000);
        setInterval('swapImage()', (interval * 2)); //the image only changes after the background has been displayed for (interval) seconds
       

        break;

    default:
        setInterval('swapImage()', interval);
        break;
    }

}

function preloadImages() {
    array = new Array();

    for (var i = 0; i < images.length; i++) {
        array[i] = new Image();
        array[i].src = images[i];
    }
    return array;
	
	
}

function swapImage() {
    if (transition != null) {
        if ((currentIndex + 2) >= arrayOfImageObjects.length) {
            currentIndex = 0;
        } else currentIndex += 2;
    } else {

        if ((currentIndex + 1) >= arrayOfImageObjects.length) {
            currentIndex = 0;
        } else currentIndex++;
    }
    $(picture).src = arrayOfImageObjects[currentIndex].src;
}

function swapBackground() {
	
	
    if ((currentIndex + 1) == arrayOfImageObjects.length) {
        var nextIndex = 0;

    } else nextIndex = currentIndex + 1;
    changeBackground('homeSS', arrayOfImageObjects[nextIndex].src, 'image');
}