Wd.Frontend.Rotations = new function(){

  var self = this;
  var count = 0;
  var current = 0;
  var zindex;
  var caption;
  var timer;
  var delay = 6000;
  var animating = false;

  this.init = function(){

    caption = $('#WdRotationCaption');
    count = $('.WdRotationBanner').length;
    zindex = count + 1;
    
    $('#WdRotationControls').delegate('li', 'click', self.clickHandler);
    
    // Hide all others and click first control
    $('#WdRotationBanners li:nth-child(1n+2)').hide();
    $('#WdRotationControl_0').click();
  };

  this.setDelay = function(newDelay){
    delay = parseInt(newDelay);
  };

  this.clickHandler = function(){
    if(animating){
      return;
    }
    window.clearTimeout(timer);
    timer = window.setTimeout(self.goNext, delay);
    var clicked = $(this);
    var id;
    if(clicked.hasClass('WdRotationControlNext')){
      id = parseInt(current)+1;
      if(id >= count){
        id = 0;
      }
    }
    else if(clicked.hasClass('WdRotationControlPrevious')){
      id = parseInt(current)-1;
      if(id < 0){
        id = count - 1;
      }
    }
    else{
      id = clicked.text();
    }
    self.goToBanner(id);
  };

  this.goToBanner = function(id){
    animating = true;
    $('.WdRotationControlActive').removeClass('WdRotationControlActive');
    $('#WdRotationControl_'+id).addClass('WdRotationControlActive');
    $('#WdRotationBanner_'+id).remove().appendTo('#WdRotationBanners').fadeIn(400, function(){
      animating = false;
      $('.WdRotationBanner').not('#WdRotationBanner_'+id).hide();
    });    
    caption.html( $('#WdRotationBanner_' + id + ' img').attr('title') );
    current = id;
  };

  this.goNext = function(){
    $('#WdRotationControlNext').click();
  };
  
  this.goPrevious = function(){
    $('#WdRotationControlPrevious').click();
  };
};
