$(document).ready(function() {
    switchImg();
    carousel();
    productsList();
});

function switchImg() {

    $('#productImgNav a').click(function() {
        var $newImgSrc = this.href;
        $('#productImgNav a').each(function() { $(this).removeClass('selected') });
        $(this).addClass('selected');
        $("#carouselDetail .active").removeClass('active').addClass('last-active')
        var $next = $('[src=' + $newImgSrc + ']');
        if ($next.length > 0) {
            $next.addClass('active');
        } else {
            $("#carouselDetail").append('<img src="' + $newImgSrc + '" class="active" />');
        }
        $("#carouselDetail .active").css({ opacity: 0.0 })
        $("#carouselDetail .active").animate({ opacity: 1.0 }, 1000, function() {
            $("#carouselDetail img").removeClass('last-active');
        })
        return false;
    });
}

function carousel() {
    var cl = 1;
    var $first = $('#slideshow a:first').attr('href');
    $('<img src="' + $first + '" />').load(start);
    function start() {
        $('#slideshow a').each(function() {
            var $lia = this.href;
            if (cl == 1) {
                $("#slideshow").append('<img alt="' + $lia + '" class="active" src="' + $lia + '" />')

            } else {
                $("#slideshow").append('<img alt="' + $lia + '" class="' + $(this).attr('class') + '" />')
            }
            cl += 1;
        })
        if (cl > 2) { setInterval("slideSwitch()", 5000);}
    }
}

function productsList() {
    $(".products").hover(function() {
        $(this).fadeTo("fast", 0.8);
    }, function() {
        $(this).fadeTo("fast", 1.0);
    });

}

function slideSwitch() {
    var $active = $('#slideshow img.active');
    if ($active.length == 0) $active = $('#slideshow img.active');
    var $next = $active.next().length ? $active.next() : $('#slideshow img:first');
    $('<img src="' + $next.attr('alt') + '" />').load(nextImg);
    function nextImg() {
        $next.attr('src', $next.attr('alt'));
        $active.addClass('last-active');
        $next.css({ opacity: 0.0 })
        .addClass('active')
        .animate({ opacity: 1.0 }, 1500, function() {
            $active.removeClass('active last-active');
        })
    }
}
