/**
 * Generic cross-fader, expects the following structure:
 * <div class="crossfader-container" id="my-crossfader">
 *   <div class="crossfade-element">
 *     ....
 *   </div>
 *   <div class="crossfade-element" style="display: none;">
 *     ....
 *   </div>
 * </div>
 * <script>
 *    var fader = Crossfade.Fader.new('my-crossfader', { autoplay: true, pause: 5 })
 *    fader.select(0);
 *    etc...
 * </script>
 * 
 * @author Konstantin Gredeskoul kig@infectious.com
 */

if (typeof Crossfade == "undefined") { var Crossfade = {}; }

Crossfade.Fader = Class.create({

  initialize: function(containerId, options) {
    var fader = this;
    this.container = $(containerId);
    this.sections = $$('#' + containerId + ' .crossfade-element');
    this.current = 0;
    this.queue_id = containerId;

    if (options) {
      this.options = options;
    }
    else {
      this.options = {
        autoplay: false,
        pause: 4
      };
    }
    
    // start autoplay
    if (this.options.autoplay == true) {
      this.autoplay = new PeriodicalExecuter(function(pe){
        fader.next();
      }, options.pause || 3);
    }
    
    Event.observe(window, 'load', function(event) {
      fader.resizeContainer();
    })
  },

  select: function(index){
    if (index == this.current) return;
    if (index >= this.sections.length || index < 0) return;

    // cancel any currently playing transitions
    var queue = Effect.Queues.get(this.queue_id);
    queue.each(function(effect) { effect.cancel(); });

    current_element = this.sections[this.current];

    if (current_element && current_element.visible()) {
      Effect.Fade(current_element, {
        duration: 0.5,
        from: 1.0,
        to: 0.0,
        queue: { scope: this.queue_id }
      });
    }
        
    Effect.Appear(this.sections[index], {
      duration: 0.5,
      from: 0.0,
      to: 1.0,
      queue: { scope: this.queue_id}
    });
    
    this.current = index;
    this.resizeContainer();
    
  },
  
  next: function() {

    next = this.current + 1;
    if (next >= this.sections.length && this.options.stopAfterRotation) {
      this.autoplay.stop();
      return
    }
    if (next >= this.sections.length) next = 0;
    this.select(next);
  },
	
	previous: function() {
   	previous = this.current - 1;
    if (previous < 0 ) previous = this.sections.length - 1;
    this.select(previous);
  },

  stopAutoPlay : function () {
    this.autoplay.stop();  
  },

  resizeContainer: function() {
    h = (this.sections[this.current].height + 5);
    if (h < 10) h = 296;
	this.container.height = h + "px";
  }  
  
});


