Caroussel = function (container, nb_elts) {
  var self = this;
  this.container = $(container);
  this.max_position = nb_elts - 1;
  this.position = 0;
  this.onchange_listeners = [];
  this.container.observe('click', function(evt) {
    var target = evt.findElement('.caroussel-prev,.caroussel-next');
    if (!Object.isElement(target)) {
      return;
    }
    if (target.hasClassName('caroussel-prev')) {
      self.show(self.position - 1);
    }
    else {
      self.show(self.position + 1);
    }
    evt.stop();
  });
  this.pe_caroussel = new PeriodicalExecuter(this.next.bind(this), 6);
}

Caroussel.prototype.show = function (position) {
  if (this.pe_caroussel) this.pe_caroussel.stop();
  if (position == this.position) {
    return;
  }
  if (position < 0) {
    position = this.max_position;
  }
  if (position > this.max_position) {
    position = 0;
  }
  this.onchange_listeners.each(function (cb) {
    cb(position);
  });
  this.position = position;
  this.pe_caroussel = new PeriodicalExecuter(this.next.bind(this), 6);
}

Caroussel.prototype.next = function () {
  this.show(this.position + 1);
}

Caroussel.prototype.on = function (evt, fct) {
  if (evt == 'change' && typeof fct == "function") {
    this.onchange_listeners.push(fct);
  }
}
