var topSeconds = 8;				// Start a new fade 8 seconds after the current one is completely done.
var topSpeed = topSeconds * 1000;		// Seconds -> milliseconds.
var topFadeSteps = 100;				// Fade more every 10th of a second.
var topFadeSpeed = 4 * 10 * 100 / topFadeSteps;	// Take 4 seconds to fad in a new image.

var topFade = -1;				// We aren't in the middle of a fade.

var nTopImgs = 12;				// Modify this if more images are added.
var topImgs = new Array(nTopImgs);		// Be ready to store all the images.
var topCur = 0;					// HTML loads in image 0 to begin with.

function setOpacity(el, o) {
    /*
     * One of these two options should work, depending on the browser.
     * The other will be ignored, or at worst, result in an error at the browser error console.
     */
    el.style.opacity = o / 100.0;
    el.style.filter = 'alpha(opacity=' + o + ')';
}

function topShow() {
  var imgOpacity;
  var ran;
  /*
   * If we are starting a new fade,
   * select a random image,
   * put it on top,
   * and start to fade it in.
   */
  if (topFade < 0) {
    do {
      ran = Math.floor(nTopImgs*Math.random());
    } while (ran == topCur);
    topCur = ran;
    document.topImgFade.src = topImgs[ran].src;
    topFade = 100;
    setTimeout(topShow, topFadeSpeed);
  }
  else { 
    /*
     * Continue to fade the top image in over the bottom image.
     */
    topFade -= 100.0 / topFadeSteps;
    if (topFade >= 0) {
      setOpacity(document.topImg, topFade);
      setTimeout(topShow, topFadeSpeed);
    }
    else {
      /*
       * New top image is completely faded in over the old bottom image.
       * Now it should be the bottom image as well.
       * Start a new cycle.
       */
      document.topImg.src = document.topImgFade.src;
      setOpacity(document.topImg, 100);
      setTimeout(topShow, topSpeed);
    }
  }
}

/*
 * Preload all the images to prevent jumpy, erratic behavior, waiting on a slow server.
 */
function topShowPreLoad() {
  for (i = 0 ; i < nTopImgs ; i++) {
    topImgs[i] = new Image();
    topImgs[i].src = "/images/top" + i + ".jpg";
  }
  /*
   * Once everything is loaded, start the show.
   */
  setTimeout(topShow, topSpeed);
}

