﻿var CarouselAnimating = false ;

$(function ()
{
    var carousel = $(".carousel") ;
    var productsParent = carousel.children ("#CarouselProducts") ;
    var carouselProducts = productsParent.children () ;
    if (carouselProducts.length <= 4)
    {
        carousel.children ("img.arrow").hide () ;
    }
    else
    {
        carousel.children ("img.arrow").click (function ()
        {
            switch ($(this).attr("id"))
            {
            case "CarouselLeft":
                CarouselAction (productsParent, "left") ;
                break ;

            case "CarouselRight":
                CarouselAction (productsParent, "right") ;
                break ;
            }
        }) ;
    }
    carouselProducts.click (function ()
    {
        if (typeof (OnCarouselClick) != 'undefined')
            OnCarouselClick ($(this)) ;
    }) ;
}) ;

function CarouselAction (products, action)
{
    if (CarouselAnimating) return ;

    CarouselAnimating = true ;
    var images = products.children () ;
    if (action == "left")
    {
        var last = images.last () ;
        products.prepend (last) ;
        images = products.children () ;
        images.css ("left", "-162px") ;
    }
    images.animate ({left: (action == "right") ? '-162px' : "0px"}, { duration : 500, complete : function ()
    {
        if (action == "right")
            products.append (images[0]) ;
        images.css ("left", "0px") ;
        CarouselAnimating = false ;
    } }) ;
}
