﻿var primaryNavTimer;
var primaryNavDisableTimer = false;

$("ul.primaryNav li").live({
    mouseenter: function() {
        clearTimeout(primaryNavTimer);

        if (!primaryNavDisableTimer) {
            $("ul.primaryNav li").not($(this).parents("li")).removeClass("hover");

            $(this).addClass("hover");
        }
    },
    mouseleave: function() {
        var listItem = $(this);

        if (!primaryNavDisableTimer) {
            primaryNavTimer = setTimeout(function() {
                listItem.removeClass("hover");
            }, 500);
        }
    }
});

$(document).ready(function() {
    // Initialize content sliders
    {
        var contentSliderCount = 0;

        $("div.contentSlider").each(function() {
            var id = $(this).attr("id") !== undefined && $(this).attr("id") !== "" ? $(this).attr("id") : "contentSlider_" + contentSliderCount;

            $(this).attr("id", id);

            window[id] = new blSlider("div#" + id + " > ul", {
                IsInfinite: true,
                PreviousButtonSelector: "div#" + id + " a.previous",
                NextButtonSelector: "div#" + id + " a.next"
            });

            contentSliderCount++;
        });
    }

    // Initialize popup objects
    {
        var popupObjectCount = 0;

        $("a.popup").each(function() {
            var id = $(this).attr("id") !== undefined && $(this).attr("id") !== "" ? $(this).attr("id") : "popupObject_" + popupObjectCount;
            $(this).attr("id", id);

            var popupUrl = $(this).attr("href");

            window[id] = new blIframePopup("div#content", siteUrl + popupUrl + "?PopupId=" + id);

            $(this).bind("click", function(event) {
                if (event.preventDefault)
                    event.preventDefault();
                else
                    event.returnValue = false;

                popupObject = window[id];
                popupObject.Open();

                return false;
            });

            popupObjectCount++;
        });
    }

    // Initialize zoom objects
    {
        var zoomObjectCount = 0;

        $("a.zoom").each(function() {
            var id = $(this).attr("id") !== undefined && $(this).attr("id") !== "" ? $(this).attr("id") : "zoomObject_" + zoomObjectCount;
            $(this).attr("id", id);

            var imageUrl = $(this).attr("href");
            var altText = $(this).find("> img").attr("alt");
            var title = $(this).find("> img").attr("title");

            window[id] = new blIframePopup("div#content", siteUrl + "/view-image?PopupId=" + id + "&ImageUrl=" + imageUrl + (altText != null && altText != "" ? "&Alt=" + altText : "") + (title != null && title != "" ? "&Title=" + title : ""));

            $(this).bind("click", function(event) {
                if (event.preventDefault)
                    event.preventDefault();
                else
                    event.returnValue = false;

                zoomObject = window[id];
                zoomObject.Open();

                return false;
            });

            zoomObjectCount++;
        });
    }

    // Textbox default values
    {
        $("input:text, textarea").each(function() {
            var title = $(this).prop("title");

            if (title !== null && title !== "" && $.trim($(this).val()) === "") {
                $(this).addClass("default");

                $(this).val(title);
            }

            $(this).focus(function() {
                $(this).removeClass("default");

                var title = $(this).prop("title");

                if (title !== null && title !== "" && $(this).val() === title)
                    $(this).val("");
            });

            $(this).blur(function() {
                var title = $(this).prop("title");

                if (title !== null && title !== "" && $.trim($(this).val()) === "") {
                    $(this).addClass("default");
                    $(this).val(title);
                }
            });
        });
    }

    // Render RSS Feeds
    RenderRssFeeds();

    // Internal Search functionality
    {
        $("div.navBar div.search a.go").live("click", function() {
            var txtSearch = $("input#txtSearch");

            if (txtSearch.val() === "" || txtSearch.val() === txtSearch.attr("title"))
                alert("Please enter one or more search keywords");
            else
                window.location.href = searchUrl + "?k=" + txtSearch.val();
        });

        $("div.navBar div.search input#txtSearch").live("keyup", function(event) {
            if (event.keyCode === 13)
                $(this).siblings("a.go").click();
        });
    }

    // External Search functionality
    {
        $("div.externalSearch a.buttonGreen").live("click", function() {
            var externalUrl = $(this).siblings("input[name=externalUrl]").val();
            var searchTerm = $(this).siblings("input[name=search]").val();
            var defaultText = $(this).siblings("input[name=search]").attr("title");

            if ($.trim(searchTerm) !== "" && (defaultText === undefined || searchTerm !== defaultText))
                window.location.href = externalUrl + searchTerm;
            else
                alert("Please enter a search term");
        });

        $("div.externalSearch input[name=search]").live("keyup", function(event) {
            if (event.keyCode === 13)
                $(this).siblings("a.buttonGreen").click();
        });
    }
});

function blPopup(elementSelector) {
    /*
    Properties  
    */
    this.HtmlElement;

    this.BeforeOpen = null;
    this.AfterOpen = null;
    this.BeforeClose = null;
    this.AfterClose = null;

    /*
    Methods
    */
    this.Open = function() {
        if ($("div.blPopup:visible").size() === 0) {
            if ($("div.blPopupOverlay").size() == 0) {
                $("body").append("<div class=\"blPopupOverlay\" style=\"display: none;\"></div>");
            }

            var blPopupOverlay = $("div.blPopupOverlay");

            if (!blPopupOverlay.is(":visible")) {
                blPopupOverlay.css({ opacity: 0 });
                blPopupOverlay.show().animate({ opacity: 0.1 }, "fast");
            }

            blPopupOverlay.bind("click.blPopup", { "PopupInstance": this }, function(event) {
                event.data.PopupInstance.Close();
            });

            if (typeof this.BeforeOpen === "function")
                this.BeforeOpen();

            $(window).bind("resize.blPopup", { "PopupInstance": this }, function(event) {
                event.data.PopupInstance.Center();
            });

            this.HtmlElement.find("a.close").bind("click.blPopup", { "PopupInstance": this }, function(event) {
                event.data.PopupInstance.Close();
            });

            this.Center();

            this.HtmlElement.css({
                zIndex: parseInt(blPopupOverlay.css("zIndex")) + 100
            });
            this.HtmlElement.show();

            if (typeof this.AfterOpen === "function")
                this.AfterOpen();

            return false;
        }
    };

    this.Close = function(hideOverlay) {
        if (this.HtmlElement.is(":visible")) {
            if (typeof this.BeforeClose === "function")
                this.BeforeClose();

            this.HtmlElement.hide();

            this.HtmlElement.find("a.close").unbind("click.blPopup")

            $(window).unbind("resize.blPopup");

            if (typeof this.AfterClose === "function")
                this.AfterClose();

            var blPopupOverlay = $("div.blPopupOverlay");

            blPopupOverlay.unbind("click.blPopup");

            if (!(typeof hideOverlay === "boolean" && hideOverlay === false)) {
                blPopupOverlay.show().animate({ opacity: 0 }, "fast", function() {
                    blPopupOverlay.hide();
                });
            }
        }

        return false;
    };

    this.Center = function() {
        var topPosition = (($(window).height() - this.HtmlElement.height()) / 2);

        if (topPosition < 0)
            topPosition = 0;

        topPosition += $(window).scrollTop();

        var leftPosition = (($(window).width() - this.HtmlElement.width()) / 2);

        if (leftPosition < 0)
            leftPosition = 0;

        leftPosition += $(window).scrollLeft();

        this.HtmlElement.css({
            top: topPosition + "px",
            left: leftPosition + "px"
        });

        return false;
    };

    /*
    Initialization   
    */
    if (typeof elementSelector !== "string")
        throw "elementSelector must be of type string";
    else if (elementSelector == null || $.trim(elementSelector) === "")
        throw "elementSelector cannot be null or empty string";
    else if ($($.trim(elementSelector)).size() === 0)
        throw "The specified element does not exist on the page";
    else {
        this.HtmlElement = $(elementSelector);
        this.HtmlElement.css({
            position: "absolute"
        });
    }
}

function blIframePopup(parentElementSelector, url) {
    /*
    Initialization   
    */
    if (typeof parentElementSelector !== "string")
        throw "parentElementSelector must be of type string";
    else if (parentElementSelector == null || $.trim(parentElementSelector) === "")
        throw "parentElementSelector cannot be null or empty string";
    else if ($($.trim(parentElementSelector)).size() === 0)
        throw "The specified element does not exist on the page";
    else {
        var id = "blPopup_" + $("div.blPopup").size();

        var html = '';
        html += '<div id="' + id + '" class="blPopup">';
        html += '<a href="javascript: //" class="close">Close Window</a>';
        html += '<div class="loadingLarge">';
        html += '<img src="/images/loading_spinner.gif" alt="Loading..." title="Loading..." />';
        html += '</div>';
        html += '<iframe src="about: blank" frameborder="0"></iframe>';
        html += '</div>';

        $(parentElementSelector).append(html);

        var popup = new blPopup("#" + id);

        popup.Url = url;

        popup.BeforeOpen = function() {
            var iframe = this.HtmlElement.find("iframe");

            iframe.prop("src", this.Url);
            iframe.hide();

            this.HtmlElement.find("div.loadingLarge").show();
        };

        popup.AfterClose = function() {
            this.HtmlElement.find("iframe").prop("src", "about:blank");
        };

        popup.AfterLoad = function() {
            var popupInstance = this;

            var iframe = popupInstance.HtmlElement.find("iframe");

            iframe.css({
                height: "100px",
                width: "100px"
            });

            setTimeout(function() {
                popupInstance.HtmlElement.find("div.loadingLarge").hide();

                iframe.show();

                iframe.css({
                    width: iframe.contents().width() + "px",
                    height: iframe.contents().height() + "px"
                });

                popupInstance.Center();
            }, 100);
        };

        popup.BeforeUnload = function() {
            var iframe = this.HtmlElement.find("iframe");

            iframe.hide();

            this.HtmlElement.find("div.loadingLarge").show();
        };

        return popup;
    }
}

function blSlider(elementSelector, options) {
    /*
    Properties  
    */
    this.HtmlElement;
    this.PreviousButton;
    this.NextButton;
    this.AnimationSpeed = 500;
    this.IsInfinite = true;

    /*
    Methods
    */
    this.MoveSlider = function(newPosition) {
        var sliderInstance = this;

        this.HtmlElement.animate({ left: newPosition + "px" }, this.AnimationSpeed, function() {
            if (sliderInstance.IsInfinite) {
                var position = sliderInstance.HtmlElement.position().left;

                if (position === 0)
                    sliderInstance.HtmlElement.css("left", -1 * sliderInstance.HtmlElement.width() / 3);
                //                                else if (position === (-1 * sliderInstance.HtmlElement.width()) + sliderInstance.HtmlElement.parent().width())
                //                                    sliderInstance.HtmlElement.css("left", (-1 * ((sliderInstance.HtmlElement.find("> li").size() / 3) - 1)) * sliderInstance.HtmlElement.parent().width());
                //                else if (Math.abs(position) + sliderInstance.HtmlElement.parent().width() >= sliderInstance.HtmlElement.width()) {
                //                    sliderInstance.HtmlElement.css("left", 0);
                //                }
            }
            else {
                sliderInstance.SetButtons();
            }
        });
    };

    this.Previous = function() {
        var containerWidth = this.HtmlElement.parent().width();
        var sliderWidth = this.HtmlElement.width();

        if (this.IsInfinite) {
            if (Math.abs(this.HtmlElement.position().left) <= sliderWidth / 3)
                this.HtmlElement.css("left", (this.HtmlElement.position().left - (sliderWidth / 3)) + "px");
        }

        var currentPosition = parseInt(this.HtmlElement.css("left"));
        var newPosition = currentPosition + containerWidth;

        if (!this.IsInfinite) {
            if (newPosition > sliderWidth)
                newPosition = sliderWidth;
            else if (newPosition > 0)
                newPosition = 0;
        }

        if (newPosition !== currentPosition && Math.abs(newPosition) < sliderWidth && !this.HtmlElement.is(":animated"))
            this.MoveSlider(newPosition);
    };

    this.Next = function() {
        var containerWidth = this.HtmlElement.parent().width();
        var sliderWidth = this.HtmlElement.width();

        if (this.IsInfinite) {
            if (this.HtmlElement.width() - Math.abs(this.HtmlElement.position().left) <= sliderWidth / 3)
                this.HtmlElement.css("left", (this.HtmlElement.position().left + (sliderWidth / 3)) + "px");
        }

        var currentPosition = parseInt(this.HtmlElement.css("left"));
        var newPosition = currentPosition - containerWidth;

        if (Math.abs(newPosition) > sliderWidth)
            newPosition = -1 * sliderWidth;
        else if (sliderWidth - Math.abs(newPosition) < containerWidth)
            newPosition = -1 * (sliderWidth - containerWidth);

        if (newPosition !== currentPosition && Math.abs(newPosition) < sliderWidth && !this.HtmlElement.is(":animated"))
            this.MoveSlider(newPosition);
    };

    this.SetButtons = function(pageLoad) {
        var containerWidth = this.HtmlElement.parent().width();
        var sliderWidth = this.HtmlElement.width();
        var currentPosition = parseInt(this.HtmlElement.css("left"));

        if (this.PreviousButton != null) {
            if (currentPosition >= 0)
                this.PreviousButton.addClass("disabled");
            else
                this.PreviousButton.removeClass("disabled");
        }

        if (this.NextButton != null) {
            if (Math.abs(currentPosition) + containerWidth >= sliderWidth)
                this.NextButton.addClass("disabled");
            else
                this.NextButton.removeClass("disabled");
        }
    };

    /*
    Initialization   
    */
    if (typeof elementSelector !== "string")
        throw "elementSelector must be of type string";
    else if (elementSelector === null || $.trim(elementSelector) === "")
        throw "elementSelector cannot be null or empty string";
    else if ($($.trim(elementSelector)).size() === 0)
        throw "The specified element does not exist on the page";
    else {
        if (options != null) {
            if (typeof options.IsInfinite === "boolean")
                this.IsInfinite = options.IsInfinite;

            if (options.PreviousButtonSelector != null) {
                if (typeof options.PreviousButtonSelector !== "string")
                    throw "PreviousButtonSelector must be of type string";
                else if ($.trim(options.PreviousButtonSelector) === "")
                    throw "PreviousButtonSelector cannot be null or empty string";
                else if ($($.trim(options.PreviousButtonSelector)).size() === 0 && $(elementSelector).find("> li").size() > 1)
                    throw "The specified element does not exist on the page";
                else {
                    this.PreviousButton = $(options.PreviousButtonSelector);

                    this.PreviousButton.live("click", { "SliderInstance": this }, function(event) {
                        event.data.SliderInstance.Previous();
                    });
                }
            }

            if (options.NextButtonSelector != null) {
                if (typeof options.NextButtonSelector !== "string")
                    throw "NextButtonSelector must be of type string";
                else if ($.trim(options.NextButtonSelector) === "")
                    throw "NextButtonSelector cannot be null or empty string";
                else if ($($.trim(options.NextButtonSelector)).size() === 0 && $(elementSelector).find("> li").size() > 1)
                    throw "The specified element does not exist on the page";
                else {
                    this.NextButton = $(options.NextButtonSelector);

                    this.NextButton.live("click", { "SliderInstance": this }, function(event) {
                        event.data.SliderInstance.Next();
                    });
                }
            }
        }

        this.HtmlElement = $(elementSelector);

        var sliderWidth = 0;

        this.HtmlElement.find("> li").each(function() {
            sliderWidth += $(this).outerWidth(true);
        });

        if (this.IsInfinite) {
            if (sliderWidth > this.HtmlElement.parent().width()) {
                var listItems = this.HtmlElement.find("> li");

                listItems.clone().prependTo(this.HtmlElement);
                listItems.clone().appendTo(this.HtmlElement);

                sliderWidth *= 3;
            }
        }

        this.HtmlElement.width(sliderWidth);

        if (this.IsInfinite) {
            if (this.HtmlElement.width() > this.HtmlElement.parent().width())
                this.HtmlElement.css("left", -1 * this.HtmlElement.width() / 3);
        }

        this.SetButtons();
    }
}

function RenderRssFeeds() {
    $("div.rssFeed").each(function() {
        var isRendered = $(this).find("> input[name=isRendered]").val() === "true";

        if (!isRendered) {
            var feedUrl = $(this).find("> input[name=feedUrl]").val();
            var faviconUrl = $(this).find("> input[name=faviconUrl]").val();
            var maxResults = parseInt($(this).find("> input[name=maxResults]").val());

            if (isNaN(maxResults))
                maxResults = 0;

            $.ajax({
                type: "POST",
                url: "/edrservice/rssservice.asmx/GetRssFeed",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: "{ feedUrl: '" + feedUrl + "', maxResults: " + maxResults + " }",
                context: $(this),
                success: function(results) {
                    results = results.d;

                    var html = '<ul>';

                    for (var i = 0; i < results.length; i++) {
                        if (i == results.length - 1)
                            html += '<li class="last">';
                        else
                            html += '<li>';
                        html += '<img src="' + faviconUrl + '" alt="" />';
                        html += '<a href="' + results[i].Url + '" target="_blank">' + results[i].Title + '</a> ';
                        html += '<span class="date">' + results[i].PublishDate + '</span>';
                        html += '</li>';
                    }

                    html += '</ul>'

                    $(this).find("img.loadingSpinner").hide();

                    $(this).find("ul").remove();
                    $(this).append(html);
                },
                error: function(results) {
                    $(this).hide();
                }
            });

            $(this).find("> input[name=isRendered]").val("true");
        }
    });
}

function HierarchicalNavigation_AfterContextMenuShow(sender, eventArgs) {
    clearTimeout(primaryNavTimer);

    primaryNavDisableTimer = true;
}

function HierarchicalNavigation_AfterContextMenuHide(sender, eventArgs) {
    primaryNavDisableTimer = false;

    primaryNavTimer = setTimeout(function() {
        $("ul.primaryNav li").removeClass("hover");
    }, 500);
}
