var Carousel = Class.create({
  initialize: function(options) {
    var defaultOptions = {
      currentSlide: 1,
      loop: false,
      numSlides: 2,
      slideDuration: 2,
      slider: 'slider',
      transitionDuration: 1,
      width: 600
    };
    this.pe;
    Object.extend(defaultOptions, options);
    Object.extend(this, defaultOptions);
    this.name = this.name || ++Carousel.InstanceNumber;
    this.slider = $(this.slider);
    if (this.slideDuration) this.setupAutoSlide();
    
    document.observe('Slider_'+this.name+':ShiftRight', this.shiftSlide.bind(this));
    document.observe('Slider_'+this.name+':ShiftLeft', this.shiftSlide.bind(this));
    
    if (this.currentSlide == 1) document.fire('Slider_'+this.name+':MinReached');
  },
  setupAutoSlide: function() {
    this.pe = new PeriodicalExecuter(function(pe){
      if (this.currentSlide == this.numSlides && !this.loop) {
        pe.stop();
        return;
      }
      var curSlide = this.currentSlide;
      document.fire('Slider_'+this.name+':ShiftRight');
    }.bind(this), this.slideDuration);
  },
  shiftSlide: function(e) {
    var nextSlide = this.getNextSlide(e),
        w = this.width, tD = this.transitionDuration,
        afterFunction = this.updateCurrentSlide;
    this.slider.morph('left:' + (-(w*(nextSlide-1))) + 'px', {
        transition: 'easeOutSine',
        duration: tD,
        position: 'end',
        before: function() {
          document.fire('Slider_'+this.name+':ShiftBegin', {currentSlide: this.currentSlide, nextSlide: nextSlide});
        }.bind(this),
        after: function() {
          this.currentSlide = nextSlide;
          document.fire('Slider_'+this.name+':ShiftEnd', {currentSlide: this.currentSlide});
          if (this.currentSlide == this.numSlides) document.fire('Slider_'+this.name+':MaxReached');
          else if (this.currentSlide == 1) document.fire('Slider_'+this.name+':MinReached')
        }.bind(this)
    });
  },
  getNextSlide: function(e) {
    if (e.eventName == 'Slider_'+this.name+':ShiftRight') {
      if (this.currentSlide == this.numSlides){ 
        if (this.loop) return 1
        else return this.currentSlide
      }
      else return this.currentSlide+1;
    }
    else {
      if (this.currentSlide == 1) {
        if (this.loop) return this.numSlides;
        else return this.currentSlide;
      }
      else return this.currentSlide-1;
    }
  },
  showSlide: function(slideNum) {
    var left = -(this.width*(slideNum));
    this.slider.setStyle({left: left + 'px'});
    this.currentSlide = slideNum+1;
  },
  stopAutoSlide: function() {
    this.pe.stop();
  }
});

// used to identify Carousel Objects
Carousel.InstanceNumber = 0;

