//
// 1) Make sure a "ROTATORS" array is defined in page *before* this script is included;
// 2) Make sure that "rotator" is the id and name of the rotator table on the page;
// 3) Change the TIMEOUT value below to reflect the number of seconds between rotating rotators
//
var TIMEOUT = 6;
var ROTATOR_ID = "rotator_";

// variables
var timerID = 0;
var tStart = null;
var rotator = new Array(ROTATORS.length);

// preload array
var preLoad = new Array(ROTATORS.length);

// present the first rotator and start times
function startTimer() {
  for (var i = 0; i < ROTATORS.length; i++)  {
    rotator[i] = ROTATORS[i].length;
	preLoad[i] = new Array(ROTATORS[i].length);
    doPreLoad(i, nextRotator(i));
    doRotator(i);
  }
  tStart = new Date();
  timerID = setTimeout("updateTimer()", 1000);
}

// clear the timer
function clearTimer() {
  if (timerID) {
    clearTimeout(timerID);
    timerID = 0;
  }
}

// a second has passed; is it time for a new rotator?
function updateTimer() {
  clearTimer();
  var tDate = new Date();
  var tDiff = tDate.getTime() - tStart.getTime();
  tDate.setTime(tDiff);
  if (tDate.getSeconds() >= TIMEOUT) {
    tStart = new Date();
    for (var i = 0; i < ROTATORS.length; i++) {
      doRotator(i);
	}
  }
  timerID = setTimeout("updateTimer()", 1000);
}

// preload an image
function doPreLoad(i, j) {
  if (preLoad[i][j] == null) {
    preLoad[i][j] = new Image();
	preLoad[i][j].src = ROTATORS[i][j];
  }
}

// present the next rotator
function doRotator(i) {
  var img = document.getElementById(ROTATOR_ID + (i + 1));
  if (img != null) {
    rotator[i] = nextRotator(i);
//  img.style.backgroundImage = 'url('+ROTATORS[rotator]+')';
    img.src = ROTATORS[i][rotator[i]];
    doPreLoad(i, nextRotator(i));
  }
}

// returns the value of the next rotator
function nextRotator(i) {
  return (rotator[i] >= ROTATORS[i].length - 1) ? 0 : rotator[i] + 1;
}
