Control.Carousel = Class.create({
  options: {
    direction      : "horizontal",
    previousButton : "previous_button",
    nextButton     : "next_button",
    scrollInc      : "auto"
  },
    
  initialize: function(element, options) {
    Object.extend(this.options, options || {});
    this.element = $(element);
    this.container   = this.element.firstDescendant();
    this.elements    = this.container.childElements();
    this.elementSize = this.elements.first().getDimensions();

    this.previousButton = $(this.options.previousButton);
    this.nextButton     = $(this.options.nextButton);
    
    this.cssAttribute = 'left';
    this.dimAttribute = 'width';
    
    //this.nbVisible = this.element.getDimensions()[this.dimAttribute] / this.elementSize[this.dimAttribute];
	this.nbVisible = 1;

    if (this.options.scrollInc == "auto")
      this.options.scrollInc = this.nbVisible;
      
    $A([this.previousButton, this.nextButton]).each(function(button) {
      button.observe("click", this.scroll.bind(this, (button == this.nextButton ? 1 : -1) * this.options.scrollInc))	
            .observe("mouseover", function() {button.addClassName("over")}.bind(this))
            .observe("mouseout",  function() {button.removeClassName("over")}.bind(this));
    }.bind(this));
    
    this.position = 0;
    this.updateButtons();
  },
 
  // Private function 
  scroll: function(nbElements) {   
    if (this.animating)
      return; 
      
    if (this.position + nbElements < 0)
      nbElements = -this.position;

    if (this.position + nbElements + this.nbVisible >= this.elements.length)
      nbElements = this.elements.length - nbElements - this.position ;

    if (nbElements != 0) {
      this.elementSize = this.elements.first().getDimensions();
      this.animating = true;
      this.position += nbElements;
      
      var position = parseInt(this.container.getStyle(this.cssAttribute));
      position -= nbElements * this.elementSize[this.dimAttribute];

      // if (Prototype.Browser.Safari2)
        this.container.morph(this.cssAttribute + ": " + position + "px", {duration: 0.4, afterFinish: function() {delete this.animating}.bind(this)});
      // else {
      //   this.container.fade({to: 0.5, duration: 0.2, queue: "end"});
      //   this.container.morph(this.cssAttribute + ": " + position + "px", {duration: 0.4, queue: "end"});
      //   this.container.appear({from:0.5, duration: 0.2, queue: "end", afterFinish: function() {delete this.animating}.bind(this)});
      // }
      
      this.element.fire("carousel:scrolled", {shift: nbElements})
      this.updateButtons();
    }
  },

  // Private functions
  updateButtons: function() {
    this.previousButton[this.position == 0 ? "addClassName" : "removeClassName"]("disabled")
    this.nextButton[this.position == this.elements.length - this.nbVisible ? "addClassName" : "removeClassName"]("disabled")
  }
});
