/*
 Параметры
*/
var quality=30; // качество (1-30), влияет на загруженность процессора
var timeout=3000; // время задержки в милисекундах
// Системные переменные
var autoscrolling = true;
var block=false;
function infiniteCarouselInit()
{
	$('.infiniteCarousel').mouseover(function ()
    //$('#gb').mouseover(function ()
	{
		autoscrolling = false;
		block=true;
	}).mouseout(function () 
    {
		block=false;
		setTimeout(function () 
  	    {
			if (block==false) autoscrolling = true;
		}, timeout);
	});
	
	$('.infiniteCarousel').infiniteCarousel();	
}

$.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'),
		    speed=1, // Скорость движения. Возможны отрицательные значения - движение в обратную сторону
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
			$items2 = $slider.find('> li'),
            $single = $items.filter(':first'),

            singleWidth = $single.outerWidth(),
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesnt include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);

        //alert(visible);
       
        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
		pagesGo = Math.ceil(($items.length+2) / visible);
		
		if (pagesGo>1)
		{
			$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
			$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
			$items = $slider.find('> li'); // reselect
			$wrapper.scrollLeft(singleWidth * visible);
			$wrapper.css("padding","0 0 0 70px");
		}
		else
		{
			$wrapper.scrollLeft(0);
			$wrapper.css("padding","0 0 0 0");
		}
		
		pages2 = Math.ceil($items.length / visible);

        // 3. Set the left position to the first 'real' item
        

        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
				
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 500, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                }

                currentPage = page;
				//$("#vst").val($wrapper.scrollLeft());
            });

            return false;
        }
		

        $wrapper.after('<a class="arrow back"></a><a class="arrow forward"></a>');

        // 5. Bind to the forward and back buttons
        $('a.back', this).click(function () 
		{
			if (pagesGo>1)
			{
				return gotoPage(currentPage - 1);
			}
			else return false;
        });

        $('a.forward', this).click(function () 
		{
			if (pagesGo>1)
			{
				return gotoPage(currentPage + 1);
			}
			else return false;
        });
		
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });			

		$(this).bind('next', function () 
		{
			pr();
		});	
		
		function pr()
		{
			if (pagesGo>1)
			{
			if ($wrapper.scrollLeft()==0)
			{
				$wrapper.scrollLeft(($items.length - visible*2) * singleWidth);
			}
			else if ($wrapper.scrollLeft()<($items2.length+visible) * singleWidth)
			{
				$wrapper.scrollLeft($wrapper.scrollLeft()+speed);
			}
			else 
			{
				//autoscrolling = false;
				//$wrapper.scrollLeft(0);
				 $wrapper.scrollLeft(singleWidth * visible);
			}
			}
			//$("#vst").val(pagesGo);
			//$("#vst").val($wrapper.scrollLeft());
		}
		
		
    });
};

$(document).ready(function () {

infiniteCarouselInit();

	setInterval(function () 
    {
		if (autoscrolling)
		{
			$('.infiniteCarousel').trigger('next');
		}
	}, quality);  

});
