﻿$(document).ready(function() {

    if (document.body.id == "ctl00_portfolio") {
        // A js class for portfolio items
        var PortfolioItem = function(options) {
            this._id = options.id;
            this._client = options.client;
            this._description = options.description;
            this._serviceList = options.serviceList;
            this._siteStatus = options.siteStatus;
            this._siteUrl = options.siteUrl;
            this._imageName = options.imageName;
            this._width = options.width;
            this._height = options.height;
        }

        var ClearPreview = function(fadeOut) {
            var fadeTime = fadeOut ? 1000 : 1;
            // hide the preview item info panel
            $("#item_info").fadeOut(fadeTime);

            // hide the preview panel items
            $("#ctl00_ContentPlaceHolder1_lblInstructions").fadeOut(fadeTime);
            $("#ctl00_ContentPlaceHolder1_pnlPreviewImage").fadeOut(fadeTime);
            $(".preview_link").fadeOut(fadeTime);

            // clear any existing preview item info from its panel
            window.setTimeout(function() {
                $("#item_info")
                    .find("li#url a").remove().end()
                    .find("span.placeholder").text("");
            }, fadeTime);
        }

        var HighlightThumb = function(elem) {
            // remove highlights on any selected images and parent li's...
            $("a.thumb_link").each(function() {
                if ($(this).children("img").hasClass("selected")) {
                    $(this).children("img").removeClass("selected");
                    $(this).children("img").fadeTo("slow", 0.6);
                    $(this).parents("li").removeClass("li_hover");
                }
            });

            // "select" the highlighted image and its parent li..
            $(elem)
                .addClass("selected")
                .parents("li").addClass("li_hover");
        }

        var FadeInPreview = function(data) {
            data = $(data);

            // ID will be 0 if the server couldn't find a preview image,
            // display error and exit
            // *** part of the querystring bug fix (10-20-09)
            if (parseInt(data.find("ID").text()) == 0) {
                $("#loader").hide();
                $("#ctl00_ContentPlaceHolder1_lblError").show();
                return;
            }

            // display full size preview image centered in its container using css
            var width = parseInt(data.find("Width").text());
            var height = parseInt(data.find("Height").text());
            var imgUrl = data.find("ImageName").text();
            var url = data.find("SiteUrl").text();
            $("#ctl00_ContentPlaceHolder1_pnlPreviewImage")
                .css({
                    position: "absolute",
                    width: width,
                    height: height,
                    top: "50%",
                    left: "50%",
                    margin: "-" + (height / 2) + "px 0 0 -" + (width / 2) + "px",
                    background: "url(../images/portfolio/" + imgUrl + ") no-repeat top left"
                })
                .fadeIn(1000, function() {
                    if (url != "n/a") {
                        $("a.preview_link")
                            .attr("href", url)
                            .fadeIn("slow");
                    }
                });

            // add the preview item information to the pnlItemInfo
            var itemInfo = $("#item_info");
            itemInfo.find("li#client span.placeholder").text(data.find("Client").text());
            itemInfo.find("li#services_provided span.placeholder").text(data.find("ServiceList").text());
            itemInfo.find("li#description span.placeholder").text(data.find("Description").text());
            var status = data.find("SiteStatus").text();
            if (status != "") {
                itemInfo.find("li#status span.placeholder").text(status);
                itemInfo.find("li#status").show();
            }
            else {
                $("li#status").hide();
            }
            if (url == "n/a") {
                itemInfo.find("li#url span.placeholder").text(url);
            }
            else {
                itemInfo.find("li#url")
                .append("<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>");
            }

            itemInfo.fadeIn(1000);
        }

        var AjaxCall = function(url, postdata, successCallback, errorCallback) {
            $.ajax({
                url: url,
                type: "GET",
                data: postdata,
                dataType: "xml",
                timeout: 5000,
                success: function(data) {
                    $("#loader").hide();
                    successCallback(data);
                },
                error: function() {
                    $("#loader").hide();
                    errorCallback();
                }
            });
        }

        // Remove classes from the img and li elements that basically are for creating
        // the opacity hover effects when js is disabled. jQuery will now handle this
        // below when js is enabled using fades.
        $("img.thumb").removeClass("thumb");
        $("li.thumb_li").removeClass("thumb_li");
        $("#portfolio_thumbs")
            .removeClass("overflow_auto")
            .addClass("overflow_hidden");

        // declarations
        var thumb_timeout;
        var portfolio = {};
        var current_thumb = 0;
        var thumb_count = $("a.thumb_link").length;

        // This section handles the automatic cycling of the preview images
        // when the page first loads.
        var RefreshCycle = function() {
            ClearPreview(true);
            thumb_timeout = window.setTimeout(CyclePreview, 1000);
        }

        var CyclePreview = function() {
            FadeInPreview(portfolio.items[current_thumb]);
            var active_li = $("a.thumb_link")[current_thumb];
            var active_thumb = $(active_li).children("img");
            HighlightThumb(active_thumb);
            current_thumb++;
            if (current_thumb >= thumb_count) {
                current_thumb = 0;
            }
            thumb_timeout = window.setTimeout(RefreshCycle, 5000);
        }

        var GetPortfolio = function(data) {
            data = $(data);

            $("#ctl00_ContentPlaceHolder1_lblInstructions").hide();
            portfolio.items = data.find("PortfolioItem");
            CyclePreview();
        }

        // This is the launching point for the preview section on page load. 
        // If there is a querystring in the url, the preview for that item will have been
        // loaded and the corresponding thumb then gets highlighted. If not, the automatic
        // preview cycling should begin and an ajax call is made to the server to get the
        // full portfolio which will then launch the preview cycling.
        // ** the regex and first part of if block are part of the querystring bug fix (10-20-09)
        var regex = new RegExp("[a-zA-Z]\?item=");
        if (regex.test(window.location)) {
            var qstr = window.location.search.substring(1);
            var pair = qstr.split("=");
            var num = parseInt(pair[1]);
            if (!isNaN(num)) {
                var thumb = $("img#item_" + pair[1]);
                HighlightThumb(thumb);
            }
        }
        else {
            AjaxCall(
                "../portfolio/GetAjaxPortfolio.aspx",
                { includeAll: false },
                GetPortfolio,
                function() {
                    // empty function essentially ignoring an ajax error.
                    // visitors can still click on the thumbs to get previews
                }
            );
        }

        // wire up events on the thumb links
        $("a.thumb_link")
            .hover(
        // fade to fully opaque on mouseover if not already selected
                function($e) {
                    if (!$($e.target).hasClass("selected")) {
                        $($e.target).fadeTo("slow", 1);
                    }
                },
        // fade to 60% opaque on mouseout if not already selected
                function($e) {
                    if (!$($e.target).hasClass("selected")) {
                        $($e.target).fadeTo("slow", 0.6);
                    }
                }
            )
            .click(function($e) {
                // when clicked, stop from posting back to the server...
                $e.preventDefault();

                if ($($e.target).hasClass("selected")) { return; }

                // a click on a thumb stops the auto preview image cycling
                if (thumb_timeout) {
                    window.clearTimeout(thumb_timeout);
                }

                // this var and if block is part of the querystring bug fix (10-20-09)
                var img_tag = $("#ctl00_ContentPlaceHolder1_pnlPreviewImage img");
                if (img_tag != null) {
                    img_tag.remove();
                    $("#ctl00_ContentPlaceHolder1_pnlItemInfo").hide();
                }
                $("#ctl00_ContentPlaceHolder1_lblError").hide();
                ClearPreview(false);
                $("#loader").show();

                HighlightThumb($e.target);

                // Make an ajax call to the server to get xml data for the selected image
                var url = "../portfolio/GetAjaxPortfolioItem.aspx";
                var data = { item: this.href.substring(this.href.indexOf("=") + 1) };
                AjaxCall(url, data, FadeInPreview, function() {
                    $("#loader").hide();
                    $("#ctl00_ContentPlaceHolder1_lblError").show();
                });
            });
    }
});
