jQuery(function () {
  
});

jQuery(window).load(function(){
  initProductListSlide();
});

function initProductListSlide(){
  var products = jQuery('#products');
  
  if(products[0]){
    var allProducts = products.find('.product'),
        pageWidth = products.outerWidth(),
        totalWidth = 0;
    for(var i = 0; i < allProducts.length; i++){
      var prod = jQuery(allProducts[i]);
      totalWidth += prod.width() + parseInt(prod.css('marginRight'));
    }
    var numberOfPages = Math.ceil(totalWidth / pageWidth) - 1;
    products.data('totalWidth', totalWidth);
    products.data('pageWidth', pageWidth);
    products.data('numberOfPages', numberOfPages);
    products.data('currentPage', 0);
    
    products.find('#slider').width(totalWidth);
    setOnOff(products.find('.prev'), 0, numberOfPages, false, true);
    setOnOff(products.find('.next'), 0, numberOfPages, true, true);
  }
}

jQuery('#products .prev:not(.off), #products .next:not(.off)').live('click', function(){
  var button = jQuery(this),
      hList = button.closest('#products'),
      slider = hList.find('#slider'),
      totalWidth = hList.data('totalWidth'),
      pageWidth = hList.data('pageWidth'),
      numberOfPages = hList.data('numberOfPages'),
      currentPage = hList.data('currentPage'),
      direction = button.hasClass('next'),
      animateOffset = 20,
      nextPage = currentPage + (direction ? 1 : -1),
      nextPosition = -(nextPage*pageWidth),
      nextMidPosition = nextPosition + (direction ? -animateOffset : animateOffset),
      isAnimating = hList.data('isAnimating');
  if(!isAnimating){
    hList.data('isAnimating', true);
    hList.data('currentPage', nextPage);
    
    
    
    slider.animate({left:nextMidPosition}, 700).animate({left:nextPosition}, 200, function(){
      setOnOff(button, nextPage, numberOfPages, direction);
      hList.data('isAnimating', false);
    });
  }
});

function setOnOff(button, nextPage, numberOfPages, direction, isInit){
  if(numberOfPages > 0 && !isInit){
    button.siblings('.off').removeClass('off');
  }
  if((direction && nextPage === numberOfPages) || (!direction && nextPage === 0)){
    button.addClass('off');
  }
}
