var imgRotate = null;

registerEvent(window, "load", initImgRotate);

function initImgRotate() {
  //log("initImgRotate");
  imgRotate = new ImgRotate("sponsorsImg", 7);
  
  /*
  // check for imgRotateIndex cookie
  var cks = document.cookie;
  //log("initImgRoate: cks='" + cks + "'");
  var i = cks.indexOf("imgRotateIndex=");
  if (i != -1) {
    i += "imgRotateIndex=".length;
    var end = cks.indexOf(";", i);
    if (end == -1)
      end = cks.length;
    imgRotate.i = cks.substring(i, end);
    //log("cookie found, update imgRotate.i=" + imgRotate.i);
  }
  */
  
  var sponsors = document.getElementById("sponsors");
  if (sponsors) {
    registerEvent(sponsors, "mouseover", sponsorsCaptionOn);
    registerEvent(sponsors, "mouseout", sponsorsCaptionOff);
  }
  
  setTimeout(imgRotate.rotate, imgRotate.pauseIntvs[1.0]);  
}

function sponsorsCaptionOn(e) {
  var caption = document.getElementById("sponsorsCaption");
  if (caption)
    caption.style.visibility = "visible";
}

function sponsorsCaptionOff(e) {
  var caption = document.getElementById("sponsorsCaption");
  if (caption)
    caption.style.visibility = "hidden";
}

function ImgRotate(imgId, nImages) {
  this.state = 0;
  this.n = nImages;
  this.i = 1;
  this.img = document.getElementById(imgId);
  this.img.style.opacity = 1.0;
  this.intv = 1; // milliseconds, 50 ms (20 fps) is very smooth
  this.pauseIntvs = [
    1000,1000, // platinum
    1000,1000, // gold
    1000,1000,// silver
    1000,1000, // bronze
    
  ];
}

ImgRotate.prototype.setNextImg = function() {
  this.i = (this.i % this.n) + 1;
  this.img.src = "images/sponsors" + this.i + ".jpg";
  document.cookie = "imgRotateIndex=" + this.i + ";max-age=" + 50;
}

ImgRotate.prototype.rotate = function() {
  //log("rotate: state=" + imgRotate.state);

  var nextIntv = imgRotate.intv;

  switch (imgRotate.state) {
  
  case 0:
    if (fadeout(imgRotate.img)) {
      imgRotate.setNextImg();
      imgRotate.state = 1;
    }
    break;
    
  case 1:
    if (fadein(imgRotate.img)) {
      imgRotate.state = 0;
      nextIntv = imgRotate.pauseIntvs[imgRotate.i-1];
    }
    break;
  }
  
  setTimeout(imgRotate.rotate, nextIntv);
}

function fadeout(img) {
  //log("fadeout");
  var opc = parseFloat(img.style.opacity);
  //log("opc=" + opc);
  opc -= 1.15;
  setOpacity(img, opc);
  return (opc <= 0.0);
}

function fadein(img) {
  //log("fadein");
  var opc = parseFloat(img.style.opacity);
  //log("opc=" + opc);
  opc += 1.05;
  setOpacity(img, opc);
  return (opc >= 1.0);
}
