var Slideshow = Class.create();
Object.extend(Slideshow.prototype, {
  initialize: function(element, duration) {
    this.element     = $(element);
    this.duration    = duration || 4;
    this.slides      = element.getElementsBySelector("li");
    this.activeSlide = this.slides.first();
    this.start();
  },
  
  start: function() {
    if (this.interval) return;
    this.interval = window.setInterval(this.next.bind(this), this.duration * 1000);
  },
  
  stop: function() {
    if (!this.interval) return;
    window.clearInterval(this.interval);
    delete this.interval;
  },
  
  next: function() {
    var nextSlide = this.slides[(this.slides.indexOf(this.activeSlide) + 1) % this.slides.length];
    new Effect.Parallel([
      new Effect.Fade(this.activeSlide, { sync: true }),
      new Effect.Appear(nextSlide, { sync: true })
    ], {
      afterFinish: function() { 
        this.activeSlide = nextSlide;
      }.bind(this),
      
      duration: 1.5
    });
  }
});


Event.observe(window, "load", function() {
  $$(".slideshow").each(function(element) {
    var slideshow = new Slideshow(element);
    element.observe("click", function() {
      slideshow.stop();
      slideshow.next();
    });
  });
});
