$.fn.infiniteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.floor($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 0,
            pages = Math.ceil($items.length / visible);
			totale = $items.length;
			//alert(totale);
			$navi = $('div.navi');
			$prev = $('#prev_categoria');
			$next = $('#next_categoria');
			$activeClass = "active";
		
		$items.each(function(i) {
			//if(i>=visible)
			//$(this).fadeTo('fast',0);
			//$(this).hide();
		});
		
        $items = $slider.find('> li'); // reselect
        
		var elemento=Array();
		var i=1;
		els = $items.children().each(function(i) {
			var el = $(this);
			elemento[i]=$(this).width();
			i=i+1;
		});
		
		//els.eq(0).addClass($activeClass);
		
		
        // 4. paging function
        left=0;
		function gotoPage(page,current) {
			left += page;
			currentPage = current;
			$wrapper.find("ul").stop().animate({"left": left}, {duration:300}, function() { return false; });
            
            //return false;
        }
        
		
        // 5. Bind to the forward and back buttons
        $prev.click(function () {		
			if(currentPage==0) return false;
			else { 
				indi=currentPage - 1;
				//sposta = + elemento[indi] + 20;
				//alert(indi +" | "+ sposta);
				//els.eq(indi).show("slow");
				sposta = + els.eq(indi).width() + 55;
				return gotoPage(sposta, indi);
			}
		});
		
		$next.click(function () {
			if(currentPage==totale-1) return false;
			else {
				ava=currentPage + 1 ;
				//sposta = - elemento[ava-1] - 20;
				//alert(ava +" | "+ sposta);
				//els.eq(ava-1).hide("slow");
				sposta = - els.eq(ava-1).width() - 55;
				return gotoPage(sposta, ava);
			}
		});
        
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
			//alert("dove");
        });		
		
		
    });  
};

