var APP = {}, PROMO_ROTATOR;
APP.PromoRotaterInterval = 8000;
APP.QuoteRotaterInterval = 10000;

APP.PromoRotater = Backbone.View.extend({
  el: '#rotater',
  initialize: function(interval) {
    _.bindAll(this, 'rotate', 'selectItem');
    this.selectedItem = 0;
    this.rotationInterval = interval;
    this.rotate();
  },
  rotate: function(e) {
    var prev = this.selectedItem;
    if(!this._stop){
      this.selectedItem = ((this.selectedItem + 1) % 3);
      setTimeout(_.bind(function(){
        if(!this._stop){
          this.$('.rotater-item').eq(prev).fadeOut(800, _.bind(function(){
            if(!this._stop){
              this.$('a').removeClass('on');
              this.$('a').eq(this.selectedItem).addClass('on');
              this.$('.rotater-item').eq(this.selectedItem).animate({
                opacity: 'toggle'
              }, 800, 'linear', this.rotate);
            }
          }, this));
        }
      }, this), this.rotationInterval);
    }
  },
  selectItem: function(e){
    this._stop = true;
    var clickedIndex = this.$('a').index($(e.target))
    this.$('.rotater-item').hide();
    this.$('.rotater-item').eq(clickedIndex).fadeIn(200, _.bind(function(){
      this.$('a').removeClass('on');
      this.$('a').eq(clickedIndex).addClass('on');
      this.selectedIndex = clickedIndex;
    }, this));
  }
});
APP.QuoteRotater = Backbone.View.extend({
  el: '#quotes',
  initialize: function(interval) {
    _.bindAll(this, 'rotate');
    this.selectedItem = 0;
    this.rotationInterval = interval;
    this.rotate();
  },
  rotate: function() {
    var prev = this.selectedItem;
    this.selectedItem = ((this.selectedItem + 1) % this.$('.quote').length);
    this.$('.quote').eq(prev).delay(this.rotationInterval).fadeOut(800, _.bind(function(){
      this.$('.quote').eq(this.selectedItem).animate({
        opacity: 'toggle'
      }, 800, 'linear', this.rotate);
    }, this));
  }
});
$(function() {
  $('a', '#rotater').click(function(e) {
    PROMO_ROTATOR.selectItem(e);
  });
  PROMO_ROTATOR = new APP.PromoRotater(APP.PromoRotaterInterval);
  new APP.QuoteRotater(APP.QuoteRotaterInterval);
})
