$(document).ready(function() {
  
  //get values for carousel elements
  var itemWidth = $('div.carousel > ul > li').width();
  var totItems = $('div.carousel > ul > li').size();
  var winWidth = $('div.carousel').width();
  
  //calculate looping constraints
  var itemShown = parseInt(winWidth / itemWidth);
  var loopPos = totItems * itemWidth * -1;
  
  //size the ul
  var reelWidth = (totItems + itemShown) * itemWidth;
  $('div.carousel > ul').css('width', reelWidth);
  
  //function to loop or move the ul
  function nextItem() {
    var currentPos = $('div.carousel > ul').position().left;
    if(currentPos == loopPos){
      $('div.carousel > ul').css({
        'left': 0
      });
      var currentPos = 0;
    }
    var nextPos = currentPos - itemWidth;
    $('div.carousel > ul').animate({
      left: nextPos
    }, 750);
  }
  
  //function timer
  function rotateItem() {
    play = setInterval(nextItem, 4000);
  }
  
  //function kill the timer
  function stopRotate() {
    clearInterval(play);
  }
  
  //animate if not all items are shown
  if(totItems > itemShown){
    
    //clone the items needed for the loop
    $('div.carousel > ul > li').slice(0,itemShown).clone().appendTo('div.carousel > ul');
  
    rotateItem();
  
    $('div.carousel > ul').hover(function(){
      stopRotate();
    }, function(){
      rotateItem();
    });
  
  }
  
});
