﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
/// <reference path="jquery-ui-1.8.7.min.js" />
/// <reference path="jquery.ba-bbq.js" />

$(document).ready(function () {

    // old browser message - TODO: determine what we consider 'unsupported'
    if ($("#OldBrowserInner").is(":visible")) {
        var cookie = readCookie("old-browser-no-thanks");
        if (cookie == "no-thanks") {
            $("#OldBrowserInner").hide();
        }
        else {
            var upgradeLink = "http://google.com/chrome";
            if ($.browser.msie) {
                upgradeLink = "http://microsoft.com/ie";
            } else if ($.browser.mozilla) {
                upgradeLink = "http://getfirefox.com";
            } else if ($.browser.webkit) {
                var isChrome = /chrome/.test(navigator.userAgent.toLowerCase());
                if (isChrome) {
                    upgradeLink = "http://google.com/chrome";
                }
                else {
                    upgradeLink = "http://apple.com/safari";
                }
            }
            $("#OldBrowserInner a.upgrade").attr("href", upgradeLink);

            $("#OldBrowserInner").css("margin-top", "-150px")
                .delay(1000)
                .animate({ "margin-top": "0px" }, 800, 'easeOutBounce');
            $("#OldBrowserInner .no-thanks").click(function () {
                $("#OldBrowserInner")
                    .animate({ "margin-top": "-150px" }, 800, 'easeInBounce');
                createCookie("old-browser-no-thanks", "no-thanks", 365);
            });
        }
    }

    //====== Preload Images ======//
    $.preloadImages(
        "/Images/nav1.1.png",
        "/Images/nav2.1.png",
        "/Images/nav3.1.png",
        "/Images/nav1.2.png",
        "/Images/nav2.2.png",
        "/Images/nav3.2.png",
        "/Images/nav1.3.png",
        "/Images/nav2.3.png",
        "/Images/nav3.3.png");

    //====== Main Navigation ======//
    var SelectedNav;
    var ExposedSubNav;
    var TimeOutNav;

    var xoff = 0, yoff = 0;
    var isIE6 = $.browser.msie && $.browser.version.substr(0, 1) < 7;
    var isIE7 = $.browser.msie && $.browser.version.substr(0, 1) == 7 && (7 >= document.documentMode); // yes, IE8+ in compat mode with the IE8+ layout engine reports a user agent of IE7...
    if (isIE6 || isIE7) {
        xoff = -126;
        yoff = 57;
        yoff = 32;
        $("#Header #Navigation .sub-nav")
            .css("margin-top", "0")
        // IE 6/7 needs a non-standard format for the clip specification, and an extra 15px at the top.  Smart IE...
            .css("clip", "rect(15px 100px 1000px 0px)");
    }

    if (isIE6) {
        /* PNG-8 of background is mostly transparent with blocks of white - we're just going to cheat and go to a solid color here */
        $("#Navigation > ul > li .sub-nav-container").css("background-color", "#F9F8F7");
        $("#Navigation > ul > li .sub-nav-container .sub-nav-menu").css("background", "transparent");
    }

    $("#Navigation .sub-nav-menu").each(function (index) {
        //        if (index == 0) {
        //            $(this).css("width", "88px");
        //            $(this).closest(".sub-nav").css("margin-left", (16 + xoff) + "px");
        //        }
        //        else 
        // adjust to the first option not having a menu anymore
        if (index == 0) {
            $(this).css("width", "88px");
            $(this).closest(".sub-nav").css("width", "96px");
            $(this).closest(".sub-nav").css("margin-left", (16 + xoff) + "px");
        }
        else if (index == 1) {
            $(this).css("width", "86px");
            $(this).closest(".sub-nav").css("width", "94px");
            var ml = (12 + xoff);
            // don't ask me why, but this is off a bit in IE7 and only IE7...
            if (isIE7) { ml += 6; }
            $(this).closest(".sub-nav").css("margin-left", ml + "px");
        }
        else if (index == 2) {
            $(this).css("width", "92px");
            $(this).closest(".sub-nav").css("width", "100px");
            var ml = (12 + xoff);
            // don't ask me why, but this is off a bit in IE7 and only IE7...
            if (isIE7) { ml -= 1; }
            $(this).closest(".sub-nav").css("margin-left", ml + "px");
        }
    });
    $("#Navigation > ul > li .sub-nav-container").each(function () {
        $(this).data("CollapsedTop", $(this).height());
        $(this).css("margin-top", "-" + ($(this).height() + yoff) + "px");
    });
    var ResetToInitialImages = function () {
        $("#Navigation > ul > li > a").each(function () {
            //$(this).children(".nav-img").attr("src", "/Images/" + $(this).attr("id") + ".png");
            if ($(this).closest("li").hasClass("selected")) {
                $(this).children(".nav-img").attr("src", "/Images/" + $(this).attr("id") + "s.png");
            }
            else {
                $(this).children(".nav-img").attr("src", "/Images/" + $(this).attr("id") + ".png");
            }
        });
    };
    var ShowMenu = function (menu) {
        menu.stop(true, true).show().animate({ "margin-top": (0 + yoff) + "px" }, 200)
            .effect('bounce', { distance: 3 }, 70); // this feels better than 'easeOutBounce' on the above
    };
    var HideMenu = function (menu, callback) {
        menu.stop(true, true).animate({ "margin-top": (-menu.data("CollapsedTop") + yoff) + "px" }, 100, 'easeInBounce', function () {
            menu.hide();
            callback();
        });
    };
    $("#Navigation > ul > li > a").mouseover(function () {
        clearTimeout(TimeOutNav);
        var CurrentNav = $(this);
        if (SelectedNav != undefined) {
            if ($(CurrentNav).attr("id") != $(SelectedNav).attr("id")) {
                SelectedNav = CurrentNav;
                if ($(ExposedSubNav).length != 0) {
                    var newSubNav = $(CurrentNav).next().find(".sub-nav-container");
                    HideMenu($(ExposedSubNav), function () {
                        $("#Navigation > ul > li > a").each(function () {
                            $(this).children(".nav-img").attr("src", "/Images/" + $(this).attr("id") + "." + CurrentNav.attr("id").substring(3) + ".png");
                        });
                        // only do this if noone has messed with what our new menu will be (which happens on rapid mouse-overs)
                        if (newSubNav == ExposedSubNav) {
                            ShowMenu(newSubNav);
                        }
                    });
                    // Updated ExposedSubNav now, rather than after the above animation completes - this way if we get rapid mouseovers, the right menu gets handled
                    ExposedSubNav = newSubNav;
                } else {
                    $("#Navigation > ul > li > a").each(function () {
                        $(this).children(".nav-img").attr("src", "/Images/" + $(this).attr("id") + "." + CurrentNav.attr("id").substring(3) + ".png");
                    });
                    ExposedSubNav = $(CurrentNav).next().find(".sub-nav-container");
                    ShowMenu($(ExposedSubNav));
                }
            }
        } else {
            SelectedNav = CurrentNav;
            $("#Navigation > ul > li > a").each(function () {
                $(this).children(".nav-img").attr("src", "/Images/" + $(this).attr("id") + "." + CurrentNav.attr("id").substring(3) + ".png");
            });
            ExposedSubNav = $(CurrentNav).next().find(".sub-nav-container");
            ShowMenu($(ExposedSubNav));
        }
    });
    $("#Navigation .sub-nav-container").mouseover(function () {
        clearTimeout(TimeOutNav);
    });
    $("#Navigation > ul > li > a").mouseout(function () {
        TimeOutNav = setTimeout(function () {
            var CurrentNav = $(this);
            if ($(ExposedSubNav).length != 0) {
                HideMenu($(ExposedSubNav), function () {
                    ResetToInitialImages();
                });
                ExposedSubNav = undefined;
                SelectedNav = undefined;
            } else {
                ResetToInitialImages();
                ExposedSubNav = undefined;
                SelectedNav = undefined;
            }
        }, 200);
    });
    $("#Navigation .sub-nav-container").mouseout(function () {
        TimeOutNav = setTimeout(function () {
            var CurrentNav = $(this);
            if ($(ExposedSubNav).length != 0) {
                HideMenu($(ExposedSubNav), function () {
                    ResetToInitialImages();
                });
                ExposedSubNav = undefined;
                SelectedNav = undefined;
            } else {
                ResetToInitialImages();
                ExposedSubNav = undefined;
                SelectedNav = undefined;
            }
        }, 200);
    });
});


//====== Search ======//
$(function () {
    // Configure handlers, settings
    var btn = $("#Search .button");
    var txt = $("#Search .textbox");
    var bg = $("#Search .searchbg");
    var bgLeft = $("#Search .searchbg-left");
    var bgRight = $("#Search .searchbg-right");
    var isSearchOpen = false;
    var searchTimeoutID;
    var waitTime = 4000;

    // Attach events
    $(btn).mouseover(function () { showSearch(); });
    $(btn).mouseleave(function () { clearTimeout(searchTimeoutID); searchTimeoutID = setTimeout(hideSearch, waitTime); });
    $(txt).focus(function () { clearTimeout(searchTimeoutID); });
    $(txt).focusout(function () { clearTimeout(searchTimeoutID); searchTimeoutID = setTimeout(hideSearch, waitTime); });

    // Enables or disables submit based on the presence a real search string
    $("#SearchForm").submit(function () {
        var canSubmit = (jQuery.trim($(txt).val()) != "");
        return (canSubmit);
    });

    // Shows & animates the search box visual wrapper
    function showSearch() {
        // If not currently visible, animate.  Else keep open
        if (!isSearchOpen) {
            $(bgLeft).css("width", "0px").css("height", "0px");
            $(bgRight).css("width", "0px").css("height", "0px");
            $(bgLeft).animate({ width: "14px", height: "24px" }, 230, 'linear')
                     .animate({ width: "163px" }, 600, 'linear', function () { $(txt).attr("disabled", "").focus(); });
            $(bgRight).animate({ width: "14px", height: "24px" }, 230, 'linear');

            isSearchOpen = true;
        }
        else { clearTimeout(searchTimeoutID); }

        // Delay the close
        searchTimeoutID = setTimeout(hideSearch, waitTime);
    }

    // Hides & animates the search box visual wrapper
    function hideSearch() {
        // Hide only if textbox is empty
        if (jQuery.trim($(txt).val()) == "") {
            $(txt).attr("disabled", "disabled");
            $(bgLeft).animate({ width: "14px" }, 600, 'linear', function () {
                $(bgLeft).animate({ width: "0px", height: "0px" }, 230, 'linear');
                $(bgRight).animate({ width: "0px", height: "0px" }, 230, 'linear');
            });

            isSearchOpen = false;
        }
    }
});



//====== Top Banner ======//
$(function () {
    // Configure handlers, settings
    var bannerTimeoutID;
    var BannerIsOpen = false;
    var ComeInsideHandle = $('div#TopBannerComeInside');
    var BannerWindow = $('div#TopBannerWindow');
    var BannerWrapper = $('div.TopBannerWrapper');
    var GoBackHandle = $('div#TopBannerGoBack');

    // Attach events
    ComeInsideHandle.click(function () { openBanner(); });
    GoBackHandle.click(function () { closeBanner(); });

    // Start vibration
    queueBannerVibration();

    // Animate the bar left to right (open)
    function openBanner() {
        clearTimeout(bannerTimeoutID);
        BannerWrapper.show();
        BannerIsOpen = true;
        BannerWindow.css("left", "-989px");
        BannerWindow.show();
        BannerWindow.animate(
            {
                left: '0px'
            }, 450, 'linear',
            function () { switchHandleToClose(); }
        );
    }

    // Animate the bar right to left (close)
    function closeBanner() {
        BannerIsOpen = false;
        BannerWindow.animate(
            {
                left: '-960px'
            }, 450, 'linear',
            function () {
                switchHandleToOpen();
                BannerWindow.hide();
                BannerWrapper.hide();
                queueBannerVibration();
            }
        );
    }

    // Switch handle from open to close
    function switchHandleToClose() {
        ComeInsideHandle.css("width", "0px");
        GoBackHandle.animate({ right: "-35" }, 50, 'linear',
                             function () {
                                 GoBackHandle.css("background-image", "url('/images/topBannerClose-sprite.png')");
                             })
                    .animate({ right: "0" }, 500, 'easeOutBounce', function () { });
    }

    // Switch handle from close to open
    function switchHandleToOpen() {
        ComeInsideHandle.animate({ width: "35px" }, 500, 'easeOutBounce', function () { });
        GoBackHandle.css("background-image", "url('/images/topBannerOpen-sprite.png')");
    }

    // Shows random bounce opens to entice the user to click
    function queueBannerVibration() {
        // Abort if open
        if (BannerIsOpen) return;

        // Do effect every 5-10 seconds
        delay = (Math.floor(Math.random() * 5) + 5) * 1000
        bannerTimeoutID = setTimeout(function () { vibrateBanner(); }, delay);
    }

    // Vibrate the banner/handle
    function vibrateBanner() {
        ComeInsideHandle.animate({ width: "55px" }, 800, "easeOutQuart", function () { })
                        .animate({ width: "35px" }, 500, "easeOutBounce", function () { });

        queueBannerVibration();
    }
});



//====== Accordion ======//
var accordionIntroTimeoutID;
function AddAccordionChrome() {
    // Add styling
    $("#accordion .ui-accordion-header").add("#accordion .ui-accordion-content").each(function () {
        $(this).html("<table class='accordionTable' border='0' cellpadding='0' cellspacing='0'>\
        <tr>\
            <td class='accordionTopLeft'></td>\
            <td class='accordionTopEdge'></td>\
            <td class='accordionTopRight'></td>\
        </tr>\
        <tr>\
            <td class='accordionLeftEdge'></td>\
            <td class='accordionBody'>" + $(this).html() + "</td>\
            <td class='accordionRightEdge'></td>\
        </tr>\
        <tr>\
            <td class='accordionBottomLeft'></td>\
            <td class='accordionBottomEdge'></td>\
            <td class='accordionBottomRight'></td>\
        </tr>\
    </table>");
    });

    // Move close icon
    $("<span class='ui-icon'/>").appendTo("#accordion .ui-accordion-content .accordionBody").click(function () {
        var body = $(this).closest(".accordion-body");
        var toOpen = body.next().next();
        if (toOpen.length == 0) {
            // closing the last one, we want to open the first one
            toOpen = body.parent().children(".accordion-body").eq(0);
        }
        if (toOpen.length == 0) {
            return false;
        }
        toOpen.prev().find(".ui-icon").trigger('click');
    });
}

function OnAccordionChangeStart(event, ui) {

}

function OnAccordionChange(event, ui) {
    var id = ui.newHeader.attr("id");
    //    AccordionLog("OnAccordionChangeStart firing for " + id);
    //    $.History.setHash("#/" + id);

    if (window.location.hash == "" && id == ui.newHeader.parent().children().eq(0).attr("id")) {
        // we have an empty hash, and we're navigating to the first item
        // current hash is good - no need to mess with it
    }
    else {
        $.bbq.pushState("#/" + id);
    }

}


//====== Utility Functions ======//
jQuery.preloadImages = function () {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}


//====== General Functions ======//
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

//function AccordionLog(message) {
//    $("<p/>").text(message).appendTo("#accordion-log");
//}

