

var isMovingRight = true;

/**
 * If has next rpoduct to display
 */
function hasNextProduct(){
    return !$(".promo_product_box .product:last").is(":visible");
}

/**
 * If has prev product to display
 */
function hasPrevProduct(){
    return !$(".promo_product_box .product:first").is(":visible");
}


function moveRight(){    
    if(!hasNextProduct()) return;

    var toHide = $(".promo_product_box .product:visible:first");
    var toShow = $(".promo_product_box .product:visible:last").next(".product");
    
    toHide.fadeOut("normal",function(){
        toShow.fadeIn("slow");
    });

}

function moveLeft(){
    if(!hasPrevProduct()) return;

    var toHide = $(".promo_product_box .product:visible:last");
    var toShow = $(".promo_product_box .product:visible:first").prev(".product");


    toHide.fadeOut("normal",function(){
        toShow.fadeIn("slow");
    });

}

function moving(){    
    $("#progresBar").animate({
        'background-position' : '0px'
        }, 10000, function() {
            $("#progresBar").css('background-position','-53px');
            if(isMovingRight){
                if(hasNextProduct()){
                    moveRight();
                }else{
                    isMovingRight = false;
                    moveLeft();
                }
            }else{
                if(hasPrevProduct()){
                    moveLeft();
                }else{
                    isMovingRight = true;
                    moveRight();
                }
            }

            moving();
    });

}


$(document).ready(function(){
    
    $("#prev_promoted_product").click(function(event){
        event.preventDefault();
        isMovingRight = false;
        moveLeft();
    });

    $("#next_promoted_product").click(function(event){
        event.preventDefault();
        isMovingRight = true;
        moveRight();
    });

    moving();

});
