//
//  fader.js
//  Fades Between Images
//

var ALL_FADERS = new Array();

var Fader = Class.create();
Fader.prototype = ({
  initialize: function (element) {
    this.element = element;
    this.interval = 3.0;
    this.delay = 5.0;
    this.transition = 0.66;
    
    this.hasPerformedInitialDelay = false;
    this.currentImage = 0;
    
    this.parseClassName(this.element.className);
    this.cacheImages();
  },
  
  parseClassName: function (className) {
    var settingParts = className.split(" ");
    for (var index = 1; index < settingParts.length; index ++) {
      var thisSetting = settingParts[index];
      var settingValue = thisSetting.split("-")[1];
      
      if (thisSetting.match(/^interval-[0-9]+$/))
        this.interval = parseFloat(settingValue) / 1000.0;
        
      else if (thisSetting.match(/^delay-[0-9]+$/))
        this.delay = parseFloat(settingValue) / 1000.0;
        
      else if (thisSetting.match(/^transition-[0-9]+$/))
        this.transition = parseFloat(settingValue) / 1000.0;
    }
  },
  
  cacheImages: function () {
    this.allImages = this.element.getElementsByTagName("img");
  },
  
  performInitialDelay: function () {
    this.hasPerformedInitialDelay = true;
    setTimeout(this.startFading.bind(this), this.delay * 1000.0);
  },
  
  imageAtIndex: function (index) {
    index = index % this.allImages.length;
    return this.allImages[index];
  },
  
  imageAtOffset: function (offset) {
    return this.imageAtIndex(this.currentImage + offset);
  },
  
  fadeOptions: function () {
    return ({ duration: this.transition });
  },
  
  startFading: function () {
    if (this.delay > 0.0 && !this.hasPerformedInitialDelay)
      return this.performInitialDelay();
    setInterval(this._fadeNextPhoto.bind(this), this.interval * 1000.0);   
  },
  
  _fadeNextPhoto: function () {
    Effect.Appear(this.imageAtOffset(1), this.fadeOptions());
    Effect.Fade(this.imageAtOffset(0), this.fadeOptions());
    
    this.currentImage = this.currentImage + 1;
    if (this.currentImage > (this.allImages.length - 1))
      this.currentImage = 0;
  }
});

function setUpFaders () {
  var allDivs = document.getElementsByTagName("div");
  for (var index = 0; index < allDivs.length; index ++) {
    var thisDiv = allDivs[index];
    if (thisDiv.className.match(/^fader/))
      ALL_FADERS[ALL_FADERS.length] = new Fader(thisDiv);
  }
}

function startFadingFaders () {
  for (var index = 0; index < ALL_FADERS.length; index ++)
    ALL_FADERS[index].startFading();
}

Event.observe(window, 'load', function () {
  setUpFaders();
  startFadingFaders();
});
