;
(function($){
    var list = $('#image_scroller_list');
    var nextButton = $('#next_button');
    var timerId = null;

    list.children('li').hover(function(){
        clearInterval(timerId);
        $(this).addClass('hover');
    }, function(){
        loop();
        $(this).removeClass('hover');
    });

    var nextButtonHovered = false;
    nextButton.hover(function(){
        nextButtonHovered = true;
        $(this).addClass('button_hover');
        list.children('li:first-child').next().addClass('hover');
    },function(){
        nextButtonHovered = false;
        $(this).removeClass('button_hover');
        list.children('li:first-child').next().removeClass('hover');
    });

    var isMoving = false;

    nextButton.click(function(){
        if (!isMoving){
            next(true);
        }
    });

    function next(isClick)
    {
        isMoving = true;

        if (isClick === true) {
            clearInterval(timerId);
        }

        if (!nextButtonHovered) {
            nextButton.addClass('button_hover');
        }

        var $first = list.children('li:first-child');
        $first.next().removeClass('hover');
        list.animate({left:-550}, 700, function(){
            var $element = $first.clone();
            $first.remove();
            list.css('left', 0);

            $element.hover(function(){
                clearInterval(timerId);
                $(this).addClass('hover');
            }, function(){
                loop();
                $(this).removeClass('hover');
            });

            list.append($element);

            if (nextButtonHovered) {
                list.children('li:first-child').next().addClass('hover');
            } else {
                nextButton.removeClass('button_hover');
                list.children('li:first-child').next().removeClass('hover');
            }

            isMoving = false;

            if (isClick === true) {
                loop();
            }
        });
    }

    function loop()
    {
        timerId = setInterval(next, 5000);
    }

    loop();
})(jQuery);
