window.addEvent('domready', function() {
  new Diaporama();
});

var Diaporama =  new Class({
  slides: [],
  last_index: -1,
  cur_index: 0,
  next_index: 1,
  prev_index: -1,
  timer: null,

  initialize: function() {
    if($('ticker')){
      this.slides = $$('.slide');
      this.last_index = this.slides.length-1;
      if (this.last_index > 0) {
        this.cur_index = 0;
        this.next_index = 1;
        this.prev_index = this.last_index;
        $('slides-next').addEvent('click',function(e){
          e.stop();
          this.stop();
          this.start();
          this.next();
          //console.log('next:'+this.next_index+' / prev:'+this.prev_index);
        }.bind(this));
        $('slides-prev').addEvent('click',function(e){
          e.stop();
          this.stop();
          this.start();
          this.previous();
          //console.log('next:'+this.next_index+' / prev:'+this.prev_index);
        }.bind(this));

        this.start();

      } else {
        $('slides-prev').addEvent('click',function(e){
          e.stop();
        });
        $('slides-next').addEvent('click',function(e){
          e.stop();
        });
      }
    }
  },

  next: function() {
    this.slides[this.cur_index].fade('out');
    this.slides[this.next_index].fade('in');
    this.cur_index = this.next_index;
    if (this.cur_index == this.last_index) {
      this.next_index = 0;
    } else {
      this.next_index = this.next_index+1;
    }
    if (this.cur_index == 0) {
      this.prev_index = this.last_index;
    } else {
      this.prev_index = this.cur_index-1;
    }
  },

  previous: function() {
    this.slides[this.cur_index].fade('out');
    this.slides[this.prev_index].fade('in');
    this.cur_index = this.prev_index;
    if (this.cur_index == this.last_index) {
      this.next_index = 0;
    } else {
      this.next_index = this.next_index+1;
    }
    if (this.cur_index == 0) {
      this.prev_index = this.last_index;
    } else {
      this.prev_index = this.prev_index-1;
    }
  },

  stop: function() {
    if (!this.timer) return false;
    this.timer = $clear(this.timer);
    return true;
  },

  start: function(force) {
    if (this.timer) return false;
    if (force) { this.next(); }
    this.timer = this.next.periodical(3500, this);
    return true;
  }


});

