﻿/// <reference path="jquery-1.3.2.min.js" />

(function($) {
    $(document).ready(function() {

        var init = true;
        var mainImage = $(".projectGallery .galleryImage");
        var caption = $(".projectGallery .galleryCaption");
        var items = $(".projectThumbnails a");
        var itemCount = items.length;
        var prevBtn = $(".projectGallery .left a");
        var nextBtn = $(".projectGallery .right a");
        var currIndex = -1;
        var fullImages = new Array(); //pre load images with their relavent info


        function changeImage(jItem) {
            /// <summary>Function to swap images</summary>

            currIndex = items.index(jItem);
            prevBtn.css("visibility", "hidden");
            nextBtn.css("visibility", "hidden");
            if (currIndex > 0) {
                prevBtn.css("visibility", "visible");
            }
            if (currIndex < itemCount - 1) {
                nextBtn.css("visibility", "visible");
            }
            mainImage.fadeOut(200, function() {
                mainImage.attr("src", fullImages[currIndex].img.src);
                mainImage.fadeIn(200);
                caption.html(fullImages[currIndex].desc == "" ? "&nbsp;" : fullImages[currIndex].desc);
            });
        }

        $(items).each(function() {
            /// <summary>
            /// loop through each thumbnail item, create a value object for each and store it in an array.
            /// Also, set the click bindings and show the first image in the list.
            /// </summary>

            var id = $(this).attr("id");
            var src = $(this).nextAll("[id='gItemImage_" + id + "']").val();
            var desc = $(this).nextAll("[id='gItemDesc_" + id + "']").val();
            var img = new Image();
            img.src = src;
            fullImages.push({ id: id, img: img, desc: desc }); //create a new anonymous object into the array

            //set the main image to be the first image on startup
            if (init) {
                init = false;
                changeImage($(this));
            }
            $(this).click(function() {
                changeImage($(this));
            });
        });

        $(".projectGallery .left").click(function() {
            changeImage(items.eq(currIndex - 1));
        });
        $(".projectGallery .right").click(function() {
            changeImage(items.eq(currIndex + 1));
        });

        return false;

    });

})(jQuery);