jQuery(document).ready(function () {

    webselectCarousel = null;

    var carouselArray = [
    //{ url: "/img/site/portfolio_intro.jpg", title: "splash" }
        { url: "/img/carousel/splash1.png", title: "splash" },
        { url: "/img/carousel/splash2.png", title: "splash" },
        { url: "/img/carousel/splash3.png", title: "splash" },
        { url: "/img/carousel/splash4.png", title: "splash" }
    ];

    var pauseLength = 4;

    // For loading
    var isActive = false;
    // For transitions
    var isActive2 = false;

    function carouselInit(carousel, state) {
        if (state == 'init') {
            webselectCarousel = carousel;
        }

        carousel.clip.unbind();
        carousel.buttonNext.unbind();
        carousel.buttonPrev.unbind();

        // Disable autoscrolling if the user clicks the prev or next button.
        carousel.buttonNext.bind('click', function () {
            //console.log("stopping");
            //carousel.startAuto(0);
            carousel.stopAuto();
        });
        carousel.buttonPrev.bind('click', function () {
            //console.log("stopping");
            //carousel.startAuto(0);
            carousel.stopAuto();
        });

        // Pause autoscrolling if the user moves the cursor over the clip.
        carousel.clip.hover(function () {
            carousel.stopAuto();
            //console.log("stop auto");
        }, function () {
            carousel.startAuto();
            //console.log("start auto");
        });

        // Add a fake clip that will show a preloader.
        // We have to wait for the Init, otherwise 'jcarousel-clip' doesn't exist,
        // however this means that each time we load new data a duplicate of this
        // clip will be made. To prevent this, we only create it if it doesn't exist.
        if (!$(".portfolio_loader").length) {
            $('.jcarousel-clip').prepend("<div class=\"portfolio_loader\"></div>");
        }

        // And another for the info panel.
        if (!$(".portfolio_info").length && carouselArray.length > 0 && carouselArray[0].title != "splash") {
            $('.jcarousel-clip').prepend("<div class=\"portfolio_info\"><p class=\"name\">{name}</p><p class=\"link\"><a href=\"#\">{url}</a></p><p class=\"more\"><a href=\"#\">more info <img src=\"/img/site/small_arrow.gif\" /></a></p></div>");
            $(".portfolio_info .more a").click(function (event) {
                event.preventDefault();
                toggleDescription("in");
            });
        }

        // And one more for the description panel.
        if (!$(".portfolio_description").length) {
            $('.jcarousel-clip').prepend("<div class=\"portfolio_description\"><div class=\"desc_inner\"><div class=\"desc_close\"></div><p class=\"name\">{name}</p><p class=\"link\"><a href=\"#\">{url}</a></p><div class=\"hr\">&nbsp;</div><div class=\"desc_body\"><p>{description}</p></div><div class=\"buttons\"><a class=\"desc_close2\" href=\"#\"><img src=\"/img/site/info_close.gif\" /></a><a class=\"link2\" href=\"#\"><img src=\"/img/site/info_link.gif\" /></a></div></div>");
            $(".portfolio_description .desc_close").click(function (event) {
                toggleDescription("out");
            });
            $(".portfolio_description .desc_close2").click(function (event) {
                event.preventDefault();
                toggleDescription("out");
            });
        }

        // Create the timeline, but clear it first incase this isn't the first,
        // time the Init is being called.
        $("#carousel_timeline").empty();

        // Add a button for every item in the carousel.
        if (carouselArray.length > 1) {
            for (i = 0; i < carousel.options.size; i++) {
                $("#carousel_timeline").append("<a id=\"button_" + (i + 1) + "\" href=\"#\">" + (i + 1) + "<\/a>");
            }
        }

        // Bind a function to each of those buttons.
        $('#carousel_timeline a').bind('click', function (event) {
            event.preventDefault();
            //carousel.startAuto(0);
            carousel.stopAuto();
            carousel.scroll(jQuery.jcarousel.intval($(this).html()));
        });

        // Center the timeline.
        var timeline_width = 704;
        var timeline_button_width = 8;
        var timeline_button_margin = 20;
        var timeline_buttons_width = ((timeline_button_width + timeline_button_margin) * carousel.options.size) - timeline_button_margin;
        $("#carousel_timeline").css("padding-left", ((timeline_width / 2) - (timeline_buttons_width / 2)) + "px");

    };

    // Update the timeline.
    function carouselTimelineUpdate(carousel, state, idx) {
        $("#carousel_timeline a").removeClass("selected");
        $("#carousel_timeline a#button_" + idx).addClass("selected");
        isActive2 = false;
    };

    function animationLock() {
        isActive2 = true;
    }

    function carouselLoadCallback(carousel, state) {
        for (var i = carousel.first; i <= carousel.last; i++) {
            if (carousel.has(i)) {
                continue;
            }

            if (i > carouselArray.length) {
                break;
            }

            carousel.add(i, getItemHTML(carouselArray[i - 1]));
        }
    };

    function getItemHTML(item) {
        return '<img src="' + item.url + '" width="700" height="300" alt="' + item.url + '" />';
    };

    jQuery(document).ready(function () {
        jQuery('#webselect_carousel').jcarousel({
            size: carouselArray.length,
            auto: pauseLength,
            wrap: "both",
            scroll: 1,
            animation: 1000,
            easing: "easeInOutExpo",
            initCallback: carouselInit,
            itemVisibleInCallback: { onBeforeAnimation: animationLock, onAfterAnimation: carouselTimelineUpdate },
            //itemVisibleOutCallback: { onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); } },
            itemLoadCallback: { onBeforeAnimation: carouselLoadCallback }
        });
    });

    function toggleDescription(direction) {
        $(".desc_inner").animate(
            { right: ((direction == "in") ? "0" : "-352px") },
            1000,
            'easeInOutExpo',
            function () {
                if (direction == "out") {
                    $(".portfolio_info").css("z-index", "3");
                    $(".portfolio_description").css("z-index", "2");
                }
            }
        );

        if (direction == "in") {
            $('.jcarousel-clip .portfolio_info').fadeOut();
            $(".portfolio_info").css("z-index", "2");
            $(".portfolio_description").css("z-index", "3");
        } else {
            $('.jcarousel-clip .portfolio_info').fadeIn();
        }
    }

    function hideDescriptionQuick() {
        $(".desc_inner").stop(true, true);
        $(".desc_inner").css("right", "-352px");
        $(".portfolio_info").css("z-index", "3");
        $(".portfolio_description").css("z-index", "2");
    }

    $(".portfolio_item").click(function (event) {
        event.preventDefault();

        if (!isActive && !isActive2) {

            isActive = true;

            webselectCarousel.stopAuto();

            $("#currently_viewing").remove();
            $("#portfolio_thumbs li").removeClass("selected");
            $(this).parent().addClass("selected");
            $(this).parent().append("<div id=\"currently_viewing\"></div>");

            $.scrollTo("#left_col", 1000, { easing: 'easeInOutExpo' });

            var folder = $(this).attr("id");

            $('.jcarousel-clip .portfolio_loader').fadeIn(function () {
                carouselArray = [];

                hideDescriptionQuick();

                $(".jcarousel-skin-webselect .jcarousel-container-horizontal").css("background-image", "none");

                $.ajax({
                    url: '/ajax_portfolio.aspx?folder=' + folder,
                    type: 'POST',
                    dataType: 'json',
                    error: function (request, status, error) { alert(error); },
                    success: function (json, status, request) {

                        $.each(json.images, function (i, image) {
                            carouselArray.push({ url: "/img/lib/lge/" + image.imageid + ".jpg", title: image.caption });
                        });

                        webselectCarousel.size(carouselArray.length);
                        webselectCarousel.reset();

                        $('.jcarousel-clip .portfolio_info .name').html(json.name);
                        $('.jcarousel-clip .portfolio_info .link a').html(json.url);
                        $('.jcarousel-clip .portfolio_info .link a').attr("href", "http://" + json.url);
                        $('.jcarousel-clip .portfolio_info').show();

                        $('.jcarousel-clip .portfolio_description .desc_inner .name').html(json.name);
                        $('.jcarousel-clip .portfolio_description .desc_inner .link a').html(json.url);
                        $('.jcarousel-clip .portfolio_description .desc_inner .link a').attr("href", "http://" + json.url);
                        $('.jcarousel-clip .portfolio_description .desc_inner a.link2').attr("href", "http://" + json.url);
                        $('.jcarousel-clip .portfolio_description .desc_inner .desc_body').html(json.description);

                        $('.jcarousel-clip .portfolio_loader').fadeOut(function () {
                            isActive = false;
                        });

                    }
                });

            });
        }

    });

});
