var iss;
var jss = -1;
var pss = images.length;

var DURATION = 4;
var FADE = 2;

var manual = false;

var preLoad = new Array();
for (iss = 0; iss < pss; iss++) {
  preLoad[iss] = new Image();
//  preLoad[iss].src = IMAGES_DIRECTORY + images[iss].file;
}

// load first few to cache initial slides until preloads catch up
preLoadImage(0);
preLoadImage(1);
preLoadImage(2);

function preLoadImage(index) {
  if ((index < pss) && (preLoad[index].src.length == 0))
    preLoad[index].src = images[index];
}

function preLoadAll() {
  for (var i = 0; i < pss; i++)
    preLoadImage(i);
}

function control(how) {
  return controlTo(how, jss);
}

function controlTo(how, direct) {
  var stopX = false;
  jssLast = jss;
  if (how=="A") { jss = jss + 1; }
  if (how=="F") { jss = jss + 1; if (!manual) stopX = true; }
  if (how=="B") { jss = jss - 1; if (!manual) stopX = true; }
  if (how=="D") { jss = direct; if (!manual) stopX = true; }
  if ((jss == pss - 1) && !manual) stopX = true;
  if (jss >= pss) jss = 0;
  if (jss < 0) jss = pss - 1;

  if (jss < pss) {
    if (document.all) {
      document.images.imagePresentation.style.filter="blendTrans(duration="+FADE+")";
      document.images.imagePresentation.filters[0].Apply();
    }

    preLoadImage(jss);
    document.getElementById("imagePresentation").src = preLoad[jss].src;
    preLoadImage(jss + 1);

    if (document.all) document.images.imagePresentation.filters[0].Play();
  }

  if (stopX)
    doPlay();
  if (how != "D")
    return stopX;
}

function checkArrows(keyCode) {
  if (keyCode == 60)
    control("B");
  else if (keyCode == 62)
    control("F");
}

document.onkeypress = function (evt) {
  var keyCode = 
    document.layers ? evt.which :
    document.all ? event.keyCode :
    document.getElementById ? evt.keyCode : 0;
  checkArrows(keyCode);
  return true;
}

function doPlay() {
  setPlayButton();
  if (manual)
    startTimer();
  else
    stopTimer();
  manual = !manual;
}

function setPlayButton() {
  if (document.getElementById) {
    document.getElementById("play").value = manual ? "        Pause Slideshow        " : "        Start Slideshow        ";
    document.getElementById("play").title = manual ? "Pause" : "AutoPlay";
  }
}

var timerID = 0;
var tStart = null;

function startTimer() {
  control("A");
  tStart = new Date();
  timerID = setTimeout("updateTimer()", 1000);
}

function stopTimer() {
  clearTimer();
  tStart = null;
}

function clearTimer() {
  if (timerID) {
    clearTimeout(timerID);
    timerID = 0;
  }
}

function updateTimer() {
  var stopX = false;
  clearTimer();
  var tDate = new Date();
  var tDiff = tDate.getTime() - tStart.getTime();
  tDate.setTime(tDiff);
  if (tDate.getSeconds() >= DURATION) {
    tStart = new Date();
    stopX = control("A");
  }
  if (!stopX)
    timerID = setTimeout("updateTimer()", 1000);
}
