// Index of the image to display.
var indexToDisplay = getIndexToDisplayCookieValue();

// Function to retrieve the cookie value.
function getIndexToDisplayCookieValue() {
	
	var cookieString = document.cookie;
	var equalsLocation = cookieString.indexOf("=");

	// If the cookie string exists.
	if (equalsLocation != -1)
	{
		// Find the end of the cookie string.
		var endLocation = cookieString.indexOf(";");
		if (endLocation == -1) endLocation = document.cookie.length;
		
		// Find the index to display stored in the cookie string.
	 	var indexToDisplay = cookieString.substring(equalsLocation + 1, endLocation);
		if (indexToDisplay=="" || isNaN(indexToDisplay)) {indexToDisplay = 0;}
	}
	// Otherwise
	else
	{
		indexToDisplay = 0
	}
	return indexToDisplay;
}

// Funciton to set the cookie value.
function setIndexToDisplayCookie(indexToDisplay)
{
	document.cookie="indexToDisplay=" + indexToDisplay;
}

function updateAndDisplayImage(elementID, nextElementID)
{
	// Update the index to display.
	indexToDisplay++;
	indexToDisplay = indexToDisplay%imageList.length;
	setIndexToDisplayCookie(indexToDisplay);

	// Display the image.
	displayImage(elementID, nextElementID);

}

function displayImage(elementID, nextElementID)
{
	// Display the image.
	var backgroundImage = imageList[indexToDisplay];
	document.getElementById(elementID).style.backgroundImage = "url('images/rolling/" + backgroundImage + "')";

	// Cache the next image.
	cacheNextImage(nextElementID);

	// After the timout update and display the image.
	setTimeout("updateAndDisplayImage('" + elementID + "', '" + nextElementID + "')", 5000);

}

function cacheNextImage(nextElementID)
{
	var indexToCache = indexToDisplay/1+1;
	indexToCache = indexToCache%imageList.length;
	var backgroundImage = imageList[indexToCache];
	document.getElementById(nextElementID).style.background = "url('images/rolling/" + backgroundImage + "') no-repeat center center";
}

function startRollingImage(elementID, nextElementID)
{
	//Display the first image.
	displayImage(elementID, nextElementID);
}

