/* =======================================================
   cycle-images.js
   
   Version:   2009-07-30
   Copyright: Bakonyi Technologies GmbH - www.bakonyi.de
   License:   http://www.gnu.org/copyleft/gpl.html
   =======================================================
   A simple slide show:
   Changes the src attribute of image tag identified by
   given id every n milliseconds by cycling through an array
   of image sources.
   
   Usage:
   1) Create an array of image sources
   2) onload, create an instance of ImageCycler passing the ID of
      the image tag, the timeout interval and the array.
   3) To start/stop cycling, call toggleCycling() in the images
      onclick event handler
   ======================================================= */


/* -------------------------------------------------------
   Define class 'ImageCycler'
   ------------------------------------------------------- */
function ImageCycler( sImageID, nInterval, aImageSrc ) {

  // Public properties
  this.ImageID = sImageID;
  this.Interval = nInterval;
  this.ImageSrc = aImageSrc;

  // Public function: show image that corresponds to current index
  this.showImage = function() {
    if(nCurrentPicIdx < this.ImageSrc.length) {
      var i;
      for(i=0; i<document.images.length; i++) {
        if(document.images[i].id == this.ImageID) {
          document.images[i].src = this.ImageSrc[nCurrentPicIdx];
        }
      }
    }
  }

  // Public function: display next image on timeout/interval
  this.handleTimeout = function() {
    nCurrentPicIdx++;
    if(nCurrentPicIdx >= this.ImageSrc.length) nCurrentPicIdx = 0;
    this.showImage();
  };


  // Public function: stop or restart image cycling by clearing/setting the timeout/interval
  this.toggleCycling = function() {
    if(nTimerID) {
      clearInterval(nTimerID);
      nTimerID = 0;
    } else {
      startCycling( this );
    }
  };

  // Private function: Activate timeout/interval if there are at least two images
  function startCycling( objSelf ) {
    if(objSelf.ImageSrc.length > 1) {
      nTimerID = setInterval(function() { objSelf.handleTimeout() }, objSelf.Interval);
    }
  }
  
  // Static
  var nCurrentPicIdx = 0;   // Array index of image currently on display
  var nTimerID = 0;
  
  // Show first image
  this.showImage();

  // Install timer if there are at least two images
  startCycling( this );
  
} // End class definition


