/*!
 * @copyright 2010 Advanced Care Solutions
 * @author Mervin McDougall <mmcdougall@acsedge.com>
 */
var ImageRotator = Class.create({
  initialize: function(params) {
    // The interval is set in milliseconds so 10000 stands for 10 seconds.
    // the fade duration is set in seconds so 1.0 seconds stands for 1 second.
    var defaults = {imageContainer: 'flashbox', interval:10000, fadeDuration:1.0}
    if (params) {
      defaults = Object.extend(defaults, params);
    }

    this.imageContainer = $(defaults.imageContainer);
    this.interval       = defaults.interval;
    this.fadeDuration   = defaults.fadeDuration;

    this.imageItems       = this.imageContainer.descendants();
    this.imageItemsLength = this.imageItems.length;
    if (this.imageItemsLength < 2) {
      return;
    }

    this.topImage = this.imageItems[0];
    // Set the image container to position relative and set the height and width.
    this.imageContainer.setStyle({
      position:'relative',
      width: this.topImage.width + 'px',
      height: this.topImage.height + 'px'
    });
    // Set the position, top and left attributes of all images within the image
    // container
    this.imageItems.invoke('setStyle', {position:'absolute', top:'0', left:'0'} );
    this.topImageStyle = {zIndex:'2'};
    this.topImage.setStyle(this.topImageStyle);

    this.bottomImage      = this.imageItems[1];
    this.bottomImageStyle = {zIndex:'1', display:'block'};
    this.bottomImage.setStyle(this.bottomImageStyle);

    this.nextPtr = 1;
    setInterval(this.fadeImage.bind(this), this.interval);
  },

  fadeImage: function() {
    this.topImage.fade({duration:this.fadeDuration, afterFinish:this.swapImage.bind(this)});
  },

  swapImage: function() {
    this.topImage = this.bottomImage;
    this.topImage.setStyle(this.topImageStyle);
    this.nextPtr++;
    if (this.nextPtr > this.imageItemsLength - 1) {
      this.nextPtr = 0;
    }
    this.bottomImage = this.imageItems[this.nextPtr];
    this.bottomImage.setStyle(this.bottomImageStyle);
  }
});


document.observe('dom:loaded', function(){
  new ImageRotator({interval:6000, imageContainer:'flashbox', fadeDuration:1.0});
});