/*
 * Initial implementation CR23195 S Hillman 16/10/2006
 */

/**********************************
 * Run init() when the window loads
 *********************************/

window.onload = init;

/*********************
* Declare global vars
*********************/

var mArr;
var curFrame;
var delay;
var timeoutId;
var running;
var lastFrame;

/****************************************
 * Initialise vars and run randomFrames()
 ***************************************/

function init() {
	
	mArr = createObjects(); //createObjects is defined in promolinks.js
	curFrame = 0;
	delay = 3000; // <- set refesh delay here (in milliseconds)
	timeoutId = null;
	running = true;
	lastFrame = 0;

	randomFrames();

}

/**************************************************
 * Stop rotation if running and show previous image
 *************************************************/

function goBack() {

	if(timeoutId != null) {
		clearTimeout(timeoutId);
		timeoutId = null;
	}

	if(running) {

		running = false;

		curFrame = curFrame - 2;

	} else {

		curFrame--;

	}

	if(curFrame < 0) {
		curFrame = (mArr.length - 1);
	}

	goToFrame(curFrame);

}

/**********************************************
 * Stop rotation if running and show next image
 *********************************************/

function goForward() {

	if(timeoutId != null) {
		clearTimeout(timeoutId);
		timeoutId = null;
	}

	if(running) {

		running = false;

	}

	curFrame++;

	if(curFrame == mArr.length) {
		curFrame = 0;
	}

	goToFrame(curFrame);
}

/**************************
 * show the specified frame
 *************************/

function goToFrame(target) {

	document.promoimage.src = mArr[target].src;
	document.promoimage.alt = mArr[target].alt;
	document.getElementById('promolink').href = mArr[target].href;

}

/**********************
 * Randomise the frames
 *********************/
 
 function randomFrames() {
 
 	// set max number for random number
 	var max = mArr.length;
 	
 	// random nuymber between 1 and mArr.length + 1
	var randomnumber = Math.floor(Math.random() * max);
	
	// prevent showing the same frame twice in a row
	if(lastFrame == randomnumber) {
	
		randomFrames();
		
	} else {
	
		goToFrame(randomnumber);
		lastFrame = randomnumber;
		curFrame = randomnumber;
		timeoutId = setTimeout("randomFrames()", delay);
		
	}
 }