
var SlideShow = Class.create();

SlideShow.prototype = { 

  ACTIVE_CLASS: 'active',

  initialize: function(element, options) { 
    this.id = element;
    this.settings = Object.extend({ 
      frequency: 5,
      effectOptions: { duration: 1, fps: 50 } 
    }, options || {})
    this.template = new Template('<div class="slide" style="display: none"><a href="#{href}"><img src="#{url}" /></a><span>#{caption}</span></div>');
    Event.observe(document, 'dom:loaded', this.startup.bind(this));
  }, 

  startup: function() {
    this.element = $(this.id);
    this.settings.slides.each(this.add, this);
    this.slides = this.element.getElementsBySelector('div.slide');
    this.activate(this.slides.first());
    this.start();
  },

  add: function(slide) {
    slide.href = slide.href || "#"
    this.element.insert(this.template.evaluate(slide));
  },
  
  start: function() {
    this._periodical = new PeriodicalExecuter(this.cycle.bind(this), this.settings.frequency);
  },

  stop: function() {
    this._periodical.stop();
  },

  activate: function(slide) {
    if(slide) {
      if(this._current) {
        new Effect.Fade(this._current, this.settings.effectOptions);
        new Effect.Appear(slide, this.settings.effectOptions);
      } else
        slide.show();
    }
    this._current = slide;
  },

  next: function() {
    return this._current.next('div.slide') || this.slides.first();
  },

  cycle: function() { 
    if(this.slides.length > 1)
      this.activate(this.next());
  } 

} 

