var timeDelay = 3; // change delay time in seconds
var curImageIndex = -1;
var imageList = null;
var timerID = null;

timeDelay *= 1000;

function getImageListToRotate() {
  if (null == imageList) {
    var url = "/getImagesToRotate.php";
    var loader =  new net.ContentLoader(url, "", setImageList, onLoaderError);
  }
}

function onLoaderError(err) {
   alert("Loader Error: " + err);
}

function setImageList() {
  //alert(this.req.responseText);
  //var obj = eval('(' + this.req.responseText + ')');
  imageList = JSON.parse(this.req.responseText);
  //alert(obj.images[0].title);
  updateRotatingImage();
  
}

function startRotatingImages() {
   timerID = setInterval("updateRotatingImage()", timeDelay);
}

function updateRotatingImage() {
  var el = document.getElementById('rotatingImage');

  if (null != el) {
    if (null != imageList) {

      if (curImageIndex < imageList.images.length-1) {
        curImageIndex++;
      } else {
        curImageIndex = 0;
      }

      var info = imageList.images[curImageIndex];

      //var html = "<a href=./details.php?image=" + info.id + "&amp;terms=index>" + 
      //           "<img src=images/large/" + info.file + ".jpg alt='" + info.title + "'" + 
      //           "border=0, height=" + info.height + " width=" + info.width + "></a>";

      //var html = "<img src=\"images/large/" + info.file + ".jpg\">";

      var html = "<a href=\"./details.php?image=" + info.id + "&amp;terms=index\">" +
                 "<img src=\"images/large/" + info.file + ".jpg\"" + 
                   " width=\"" + info.width + "\"" +
                   " height=\"" + info.height + "\"" +
                   " alt=\"" + info.title + "\"" +
                   " border=0" +
                 "></a>";


      // Firefox:
      // el.innerHTML = html;

      var oldChild = document.getElementById("tmpImage");
      var newChild = document.createElement("tmpImage");
      newChild.id = "tmpImage";
      newChild.innerHTML = html;

      if (null != oldChild) {
        //alert("Replace Child\n" + html);
        el.replaceChild(newChild, oldChild);
      } else {
        //alert("Append Child\n" + html);
        el.appendChild(newChild);
      }
      
    }
  } else {
    timerID = setInterval("updateRotatingImage()", 600000);
  }
}

// Called when the browser leaves the page
function onPageExit(pageName) {
   // stop the timer
   if (null != timerID) {
     clearInterval(timerID);
   }
}

// Called when the browser opens the page
function onPageLoad(pageName) {
  document.mysearch.terms.focus();
  if (pageName == "home") {
    getImageListToRotate();
    startRotatingImages();
  }
}

