
CarrouselHelper = Class.create({
  initialize: function(element_, items_, callback_, options_) {

    this.preloaded_ = [];
    this.element = element_.identify();
    this.preloading_ = items_.pluck('foto_url');

    this.items = items_;

    this.options = $H( {
	    'minClicks': 3,
	    'interval': 1.0,
	    'useCallback': true,
	    'startPos': 0
    } ).update(options_ || {});

    this.pos = 1;
    this.prev = 0;
    this.currentClick = this.options.get('startPos');
    this.isAnimating = false;
    this.callback = callback_.bind(this);

    this.start();
  },
  timerEvent: function() {

	if (! this.getElement()) { this.stop(); return }

	if (document.images && this.preloading_.length) {
		var url_ = this.preloading_.shift();

		img_ = new Image();
		img_.src = url_;

		this.preloaded_.push(img_);
	}

	this.currentClick++;

	if (this.currentClick > this.options.get('minClicks'))
	{
		if (this.isAnimating || ! this.options.get('useCallback')) return;
		this.isAnimating = true;
		this.currentClick = 0;

		this.prev = this.pos;
		this.pos++;
		if (this.pos > this.items.length-1) this.pos = 0;

		this.callback(this.pos, this.prev);
	}
  },
  isReadyAnimating: function() {
	this.isAnimating = false;
  },
  getElement: function() {
      return $(this.element);
  },
  getItem: function(iIndex) {
      return this.items[iIndex];
  },
  getItems: function() {
      return this.items;
  },
  stop: function() {
      if (this.fxI) window.clearInterval(this.fxI); this.fxI = false;
  },
  start: function() {
      this.stop();
      this.fxI = window.setInterval(this.timerEvent.bind(this), this.options.get('interval') * 1000);
  },
  setPosition: function(pos, draw) {
      this.pos = pos;
      this.currentClick = 0;

      if (draw) {
	  this.isAnimating = false;
	  this.callback(this.pos, this.prev);
	  this.start();
      }
  },
  getPosition: function() {
      return this.pos;
  }
});
