var nextPage = 0;
var started = 0;
var active = null;
	
(function () {
    $.fn.infiniteCarousel = function () {
        function repeat(str, n) {
            return new Array( n ).join(str);
        }

        function desactivator(p,n){
            p.parent().css('display','none');
            p.css('opacity',0.1);
            if(started == 1)
                n.css('opacity',0.1);
            n.parent().css('display','block');
        }
       
		totalButtons = $('.barre').find('>li').length;
        
        return this.each(function () {
            itemsD = $(this).find('> div');
            items = itemsD.find('>img');
            function gotoPage(page) {
                var id = '#item_' + page;
                $('.animation_active').addClass('animation_links')
                $('.animation_active').removeClass('animation_active');
                $(id).parent().removeClass();
                $(id).parent().addClass('animation_active');
                if(started == 0)
                    started = 1;
                itemf = $(items[page]);
                nextPage = page+1;
                if(nextPage > (items.length - 1))
                                nextPage = 0;
                itemf.animate({
                    opacity: (1)
                }, 500
            );
            }

            $('a.set_item').click(function () {
                $().stop();
                autoscrolling = false;
                var id = $(this).attr('id');
                var tabTmp = id.split("_");
                id = parseInt(tabTmp[1])

                var previousPage = nextPage - 1;
                if(nextPage == 0)
                    previousPage = items.length - 1;
                itemp = $(items[previousPage]);
                
                itemn = $(items[id]);
                desactivator(itemp,itemn);

                gotoPage(id);
                autoscrolling = true;
                return false;
            });

            // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
            $(this).bind('next', function () {
                $().stop();
                var previousPage = nextPage - 1;
                if(nextPage == 0)
                    previousPage = items.length - 1;
                itemp = $(items[previousPage]);
                itemn = $(items[nextPage]);
                desactivator(itemp,itemn);
                gotoPage(nextPage);
                return false;
            });
        });
    };
})(jQuery);


