(function ($) {
  $.fn.infiniteScroll = function () {
    return this.each(function () {
      
      var $wrapper = $(this),
		  $slider = $wrapper.find('> ul'),
		  $items = $slider.find('> li'),
		  canvasWidth = $wrapper.outerWidth(),
		  totalWidth = 0,
		  timePerPixel = 20,
		  scrollWidth;
	
	  
	  // Klonar in elementen en gång till
	  $slider.append($items.clone().addClass('second'));
	  $items.addClass('first');
	  $slider.append($items.clone());
	  $items.remove();

	  // Räknar ut totala bredden
	  $('li.first').each(function (){
	  	totalWidth += $(this).outerWidth() + 4;
	  });

	  // Räknar ut scrollbredden
	  scrollWidth = (2 * totalWidth - canvasWidth);
	  
	  // Scrollar
	  startSlide();
	  
	  

	  function startSlide() {
	  	$wrapper.animate({scrollLeft: scrollWidth}, (scrollWidth * timePerPixel), 'linear', repeat);
	  }

	  function repeat() {
	  	var $first  = $('li.first'),
	  		$second = $('li.second'),
	  		scrollRes = $wrapper.scrollLeft();

	  	$slider.append($first.clone().addClass('second').removeClass('first'));

	  	$first.remove();

	  	$wrapper.scrollLeft(scrollWidth - totalWidth);
	  	

	  	startSlide();
	  	$second.removeClass('second').addClass('first');
	  }
    });
  };
})(jQuery);
