/*
Written by: Adam Crownoble (adam@bryan.edu)
Date: April 3 2006
Update: October 7 2008
Version: 2.0
Dependencies: MooTools 1.11
License: LGPL (http://www.gnu.org/copyleft/lesser.html)
*/

var Fader = new Class({

 initialize: function(list, randomize) {
 
  this.list = $(list);
  this.lines = $A(this.list.getElementsByTagName('li'));
  if(randomize) { this.randomize(); }
  this.lineCount = this.lines.length;
  this.currentLineIndex = 0;
  this.currentLine = this.lines[this.currentLineIndex];
  this.transitionDelay = 5;
  this.transitionTime = 1;
  this.onNext = null;

  this.list.setStyles({'position':'relative','overflow':'hidden'});

  this.lines.each(
   function(line) {
    line = $(line);
    line.setStyle('position','absolute');
    line.effect = new Fx.Style(line,'opacity',{duration: this.transitionTime*1000, wait: false});
    if(line != this.lines[0]) { line.effect.set(0); }
   }.bind(this)
  );

  if(this.lineCount > 1) { this.startTimer(); }

 },

 randomize: function() {
  var i = this.lines.length;
  if ( i == 0 ) return false;
  while ( --i ) {
   var j = Math.floor( Math.random() * ( i + 1 ) );
   var tempi = this.lines[i];
   var tempj = this.lines[j];
   this.lines[i] = tempj;
   this.lines[j] = tempi;
  }
 },

 startTimer: function() {
  this.timerID = setInterval(this.next.bind(this), (this.transitionDelay+this.transitionTime) * 1000);
 },

 stopTimer: function() {
  clearInterval(this.timerID);
 },

 fadeIn: function(line) {
  line.effect.set(0);
  line.effect.start(1);
 },
 
 fadeOut: function(line) {
  line.effect.set(1);
  line.effect.start(0);
 },

 increment: function() {
  if(this.currentLineIndex == (this.lineCount-1)) {
   this.currentLineIndex = 0;
  } else {
   this.currentLineIndex++;
  }
  this.currentLine = this.lines[this.currentLineIndex];
 },

 decrement: function() {
  if(this.currentLineIndex == 0) {
   this.currentLineIndex = this.lineCount-1;
  } else {
   this.currentLineIndex--;
  }
  this.currentLine = this.lines[this.currentLineIndex];
 },

 next: function() {

  this.stopTimer();
  this.startTimer();

  this.fadeOut(this.currentLine);
  this.increment();
  this.fadeIn(this.currentLine);

  if(this.onNext != null) {
   this.onNext(this.currentLine);
  }

 },

 previous: function() {

  this.stopTimer();
  this.startTimer();

  this.fadeOut(this.currentLine);
  this.decrement();
  this.fadeIn(this.currentLine);

  if(this.onNext != null) {
   this.onNext(this.currentLine);
  }

 }

});