/**
 * Slideshow
 * 
 * Made by Jorn - Info.nl
 * 
 * DEPENDANCIES
 * MooTools v1.11 with: Fx.Style, Fx.Elements, Element.Selectors
 * 
 * IE6 REQUIREMENT
 * The images (slides) inside the containing div need to have a fixed width and
 * height set to work in IE6.
 */
var Slideshow = new Class({
  slides     : [],
  slideTimer : null,
  fadeFx     : [],
  currentSlideIndex : 0,
  
  options : {
    timeout    : 2000, // time to wait untill next slide
    duration   : 1000, // duration of the switching slides effect
    autostart  : false
  },
  
  initialize: function(slideContainer, options){
    $(slideContainer).getChildren().each(function(slide, i){ // put slides in object array
      
      this.slides[i] = slide; // add slide to object array
      this.fadeFx.include(new Fx.Style(slide, 'opacity', {duration:this.options.duration}).set(0)); // effect
    }.bind(this));
    
    if( this.slides.length < 1 ){ // check if there are images
      alert('no children found in div#'+ slideContainer);
      return false;
    }
    
    this.setOptions(options); // customise options
    this.fadeFx[this.currentSlideIndex].set(1);
    
    if( this.options.autostart ) this.start();
  },
  
  start: function(){
    this.slideTimer = (function(){ this.showNext(); }).delay(this.options.timeout, this);
  },
  
  stop: function(){
    this.slideTimer = $clear(this.slideTimer);
  },
  
  showNext: function(){
    if( $chk(this.currentSlideIndex) && this.currentSlideIndex < this.slides.length - 1 ){
      this._doSlide(this.currentSlideIndex + 1); // show next slide
    }else
    if( $chk(this.currentSlideIndex) ){
      this._doSlide(0); // wrap on last slide
    }
    
    this.start();
  },
  
  _doSlide: function(newSlideIndex){
    var oldSlideIndex = this.currentSlideIndex;
    var oldSlide = this.slides[oldSlideIndex];
    var newSlide = this.slides[newSlideIndex];
    
    this.fadeFx[newSlideIndex].start(1);
    this.fadeFx[oldSlideIndex].start(0).chain(function(){
      
      this.currentSlideIndex = newSlideIndex;
    }.bind(this));
  }
  
});
Slideshow.implement(new Options, new Events); // End SlideShow.class