// IMPORTANT!! All the names, arrays and IDs are case sensitive!!

var changeTime = 5000;		// Modify this value to change how often a random picture changes
var lastImageChanged = -1;
var topImages = new Array();
var sourceArrays = new Array();
var alternateTextArrays = new Array();

function initializeTopImages()
{
	var img;

	TopImage.prototype.loadImages = loadImages;
	TopImage.prototype.changeImage = changeImage;
	TopImage.prototype.loadAlternateTexts = loadAlternateTexts;
	
	for (var i in sourceArrays)
	{
		img = new TopImage(i);
		img.loadImages(sourceArrays[i]);
		img.loadAlternateTexts(alternateTextArrays[i]);
		
		// If the TopImage has any ImageLinks, display one of them
		if (img.imageSources.length > 0)
		{
			img.changeImage();
		}
		
		// If the TopImage has more than one ImageLink, make it rotate
		if (img.imageSources.length > 1)
		{
			topImages.push(img);
		}
	}
	
	// If there are any TopImages, start rotating them
	if (topImages.length > 0)
	{
		startRotation();
	}
}

function startRotation()
{
	setTimeout("rotateRandomImage()", changeTime);
}

function rotateRandomImage()
{
	lastImageChanged = rand(topImages.length, lastImageChanged);
	topImages[lastImageChanged].changeImage();
	setTimeout("rotateRandomImage()", changeTime);	
}

function rand(arrayLength, previousValue)
{
	// If there is only one item in the array, avoid endless loop by returning 0
	if (arrayLength == 1)
	{
		return 0;
	}
		
	var i = parseInt(Math.random() * arrayLength);
	
	while (i == previousValue)
	{
		i = parseInt(Math.random() * arrayLength);
	}
	
	return i;
}

// Class for storing ImageLinks for a specific 
function TopImage(i)
{
	this.currentImage = -1;
	this.imageSources = new Array();
	this.alternateTexts = new Array();
	this.imageTag = document.getElementById(imageTagArray[i]);
}

function loadImages(sourceArray)
{
	var img = new Image();
	
	for (i in sourceArray)
	{
		img.src = sourceArray[i];
		this.imageSources.push(sourceArray[i]);
	}
}

function loadAlternateTexts(textArray)
{
	for (i in textArray)
	{
		this.alternateTexts.push(textArray[i]);
	}
}

function changeImage()
{
	this.currentImage = rand(this.imageSources.length, this.currentImage);	
	this.imageTag.src = this.imageSources[this.currentImage];
	this.imageTag.alt = this.alternateTexts[this.currentImage];
}