
var Slideshow = new Class({
  Implements: [Options, Events],
  options: {
    duration: 5000,
    slideClass: 'slideshow-slide',
    onSlideUpdated: function() {},
    onStatusUpdated: function() {}
  },
  initialize: function(elm, options) {
    this.setOptions(options);
    
    this.elm = $(elm);
    this.position = 0;
    this.playing = false;
    this.timer = null;
    
    this.frames = this.elm.getElements('.' + this.options.slideClass);
    
    if(this.frames.length <= 1)
    {
      return;
    }
    
    this.frames.set('opacity', 0);
    
    this.frames.each(function(frame) {
      frame.set('tween', { onComplete: 
        function() { this.frameFinished(); }.bind(this) });
    }.bind(this));
    
    this.start();
    
  },
  start: function() {
    this.fireEvent('slideUpdated', this.position);
    this.playing = true;
    this.frames[this.position].tween('opacity', 1);    
    this.fireEvent('statusUpdated', this.playing);
  },
  next: function() {
    this.goTo((this.position + 1));
  },
  back: function() {
    this.goTo((this.position - 1));
  },
  goTo: function(frame) {

    if(frame == this.position) return;
    
    this.clearShow();
    
    this.frames[this.position].tween('opacity', 0);
        
    this.position = frame;
    
    if(this.position > (this.frames.length - 1)) {
      this.position = 0;
    }
    
    if(this.position < 0) {
      this.position = (this.frames.length - 1);
    }
    
    this.start();
    
  },
  pause: function() {
    this.clearShow();
    this.fireEvent('statusUpdated', this.playing);
  },
  clearShow: function() {
    this.playing = false;
    clearInterval(this.timer);
    clearTimeout(this.timer);
    
  },
  frameFinished: function() {
    if(this.playing) {
      clearTimeout(this.timer);
      clearInterval(this.timer);
      this.timer = setTimeout(function(){ this.next(); }.bind(this), 
          this.options.duration);
    }
  }
});



