var currentRotator = null;
var rotatorTimer = null;

$(document).ready(function() {
   // get the rotator container
   var container = $('div#home-rotator-container');
   if (container.length) {
      // get the first rotator (the currently visible one)
      // and register its handlers
      currentRotator = $(container.children()[0]);
      registerRotatorHandlers(currentRotator);
   }

   // set up the rotator timer to swap the displayed message
   // after an interval
   rotatorTimer = $.timer(6000, function(timer) {
      // move on to the next rotator
      setRotator(getNextRotator(currentRotator));
   });
   
   // when rolled over, the rotator should not change
   container.mouseover(function(evt) {
      rotatorTimer.stop();
   });
   // re-enable timed change on rollout
   container.mouseout(function(evt) {
      rotatorTimer.reset(6000);   
   });
});

// get the next rotator from the given one
function getNextRotator(rotator) {
   var next = $(rotator).next();
   if (!next.length) {
      // the next is actually the parent's first child
      next = $($(rotator).parent().children()[0]);
   }
   return next;
}

// get the next rotator by index number
function getRotatorByIndex(index) {
   return $($('div#home-rotator-container').children()[index]);
}

// register event handlers on the rotator
function registerRotatorHandlers(rotator) {
   var links = rotator.find('.home-rotator-thumbs a');
   // register a click handler on each link
   // don't call setRotator on the link with this index
   var index = $('div#home-rotator-container').children().index(rotator.get()[0]);
   
   $(links[0]).click(function(evt) {
      if (index != 3) setRotator(getRotatorByIndex(3));
      evt.preventDefault();
   });
   $(links[1]).click(function(evt) {
      if (index != 2) setRotator(getRotatorByIndex(2));
      evt.preventDefault();
   });
   $(links[2]).click(function(evt) {
      if (index != 1) setRotator(getRotatorByIndex(1));
      evt.preventDefault();      
   });
   $(links[3]).click(function(evt) {
      if (index != 0) setRotator(getRotatorByIndex(0));
      evt.preventDefault();      
   });         
}

// degister event handlers on the given rotator
function deregisterRotatorHandlers(rotator) {
   rotator.find('.home-rotator-thumbs a').unbind();   
}

// swap in the given rotator, making it current. handle 
// the transition animation and register all event handlers
function setRotator(rotator) {
   // deregister and fade out the current rotator
   deregisterRotatorHandlers(currentRotator);
   currentRotator.fadeOut(500);
   
   // register the given rotator and fade it in
   registerRotatorHandlers(rotator);
   rotator.fadeIn(1500);
   
   currentRotator = rotator;
}
