/**
 * Expects a ticker element containing children items
 * Animates a ticker by slicing the original collection of items
 * into sections and rotating those sections.
 * The current position is stored in a cookie so that the position
 * can be persisted accross pages.
 * Requires jquery.js, jquery.cookie.js 
 */
jQuery.fn.ticker = function(params) {
  var ticker = this;
  // Element references 
  var items = ticker.children();
  var t1 = $('<div style="float:left"></div>'), t2 = t1.clone();
  // Create the wrapper who's width must exceed the length of t1 and t2 combined
  var wrapper = t1.clone().width(2000).append(t1).append(t2);
  // Position and increment info
  var counter = 0, increment = 5;
  var paused;
  
  // Remove items and add wrapper to ticker
  ticker.empty().append(wrapper);
  
  ticker.mouseover(function() {
    paused = true;
  }).mouseout(function() {
    paused = false;
  });
  
  function populateDiv(div) {
    // copy required items to div
    var newCounter = counter + increment;
    var newItems = items.slice(counter, newCounter);
    div.empty().append(newItems.clone());
    // check counter doesn't exceed items length
    counter = (newCounter > items.length) ? 0 : newCounter;
  }
  
  // populate first
  populateDiv(t1);
  
  function animate(t1, t2) {
    populateDiv(t2);
    // Would use $(...).animate(...) but can't pause
    var i = setInterval(function() {
      // allow pausing
      if (paused) return;
      // Can't access scrollLeft through jQuery - must expliitly check if it is available
      if (!ticker.length) return; 
      ticker[0].scrollLeft++; 
      // Check for end condition
      if (ticker[0].scrollLeft >= t1.width()) {
        // Clear current interval timer
        clearInterval(i);
        // Setup for next call
        ticker[0].scrollLeft = 0;
        wrapper.append(t1);
        // Call
        animate(t2, t1);
      }
    }, params.travelocity * 1000);
  }
  
  // start ticker
  animate(t1, t2);
};

