var Slideshow = new Class({
  _slides: [],
  _count: 0,
  _total: 0,
  _timeout: null,

  initialize: function(element) {
    this._slides = element.getElements('li');

    this._total = this._slides.length;

    //return if no child elements were found
	if(this._total == 0) return;

    // show first element  
    this.animate(this._slides[this._count], 0);

    // navigation
    element.getElement('.previous').addEvent('click', function() {                        
      this.previous();            
    }.bind(this));
    
    element.getElement('.next').addEvent('click', function() {
      this.next();
    }.bind(this));    
  },

  previous: function() {
    this.animate(this._slides[this._count], 1);
    
    if (this._count == 0) {
      this._count = this._total;
    }
    
    this.animate(this._slides[this._count-1], 0);          
      this._count--;  
  },

  next: function() {
    this.animate(this._slides[this._count], 1);
    
    if (this._count+1 == this._total) {
      this._count = -1;
    }
    
    this.animate(this._slides[this._count+1], 0);
    
    this._count++;   
  },

  animate: function(element, hide) {
    var fxOptions = {
      onComplete: (function () {
        if (!this._timeout) {
          // only set a new timeout if the current timeout is empty
          this._timeout = window.setTimeout(this.next.bind(this), 5000);
        }
      }).bind(this)
    }

    var myFx = new Fx.Tween(element, fxOptions);

    window.clearTimeout(this._timeout);
    
    // to avoid timeout madness
    this._timeout = null;

    if (hide == 1) {
      myFx.start('opacity', 1, 0);
    } else {
      myFx.start('opacity', 0, 1);    
    }    
  }
});

document.addEvent('domready', function() {
  new Slideshow($('carrousel'));
});
