﻿jQuery(function ($) {
    $('.BannerItemsTemplate').each(function () {
        var template = $(this);
        var list2 = $(this).find('.RightSection');
        var animateDelay = 1000;
        var timerset = 7000;
        var fadeDelay = 2000;
        var list = $(this).find('.LeftSection');
        var moveLeftButton = $(this).find('.MoveLeftButton');
        var moveRightButton = $(this).find('.MoveRightButton');
        var ItemsCount = list.find('>li').length;
        list.find('>li:gt(0)').hide();
        list2.find('>li:gt(0)').hide();
        var animateRight = function () {
            moveRightButton.unbind('click');
            list.find('>li:lt(2)').show();
            list.find('>li:gt(1)').hide();
            list2.find('>li:eq(1)').fadeIn(fadeDelay);
            list2.find('>li:eq(0)').fadeOut(fadeDelay);
            
            var inc = -543;
            list.animate({
                left: '+=' + inc
            }, {
                'duration': animateDelay,
                'complete': function () {
                    list.find('>li:lt(1)').appendTo(list);
                    list.find('>li:gt(0)').hide();
                    list2.find('>li:eq(0)').hide();
                    list2.find('>li:eq(0)').appendTo(list2);
                    list.css('left', '0');
                    moveRightButton.click(animateRight);
                }
            });
        };

        var animateLeft = function () {
            moveLeftButton.unbind('click');
            list.find('>li:gt(' + (ItemsCount - 2) + ')').remove().prependTo(list).show();
            list2.find('>li:eq(0)').fadeOut(fadeDelay);
            list2.find('>li:eq(' + (ItemsCount - 1) + ')').prependTo(list2).fadeIn(fadeDelay);
            list.css('left', '-543px');
            var inc = 543;
            list.animate({
                left: '+=' + inc
            }, {
                'duration': animateDelay,
                'complete': function () {
                    list.find('>li:gt(0)').hide();
                    list2.find('>li:eq(' + (ItemsCount - 1) + ')').hide();
                    list.css('left', '0');
                    moveLeftButton.click(animateLeft);
                }
            });
        };
        moveLeftButton.click(animateLeft);
        moveRightButton.click(animateRight);
        var timer = setInterval(animateRight, timerset);
        template.hover(function () {
            clearTimeout(timer);
        }, function () {
            timer = setInterval(animateRight, timerset);
        });
    });
});
