 // Global flags
var sdbIntervalID = 0;
var _loading = false;
var _historyInit = false;
var _fromTransition = false;
var _pageloadXHR = null;

// Analytics variables
//var _gaProfileID = "UA-13115890-1"; // NOTE: This is for gyrohsr10.gyrohsrclients.com!
var _gaProfileID = "UA-8447208-1";
//var _domain = "http://174.143.146.33"; // NOTE: change after launch
var _domain = "http://www.gyrohsr.com";
var pageTracker = _gat._getTracker(_gaProfileID);

// Global defaults
$.easing.def = "easeInOutQuint";

/****************************** PORTAL SWF FUNCTIONS ******************************/

// The portal can be shown in two sizes/positions: large (centered), or small (in the upper left corner).
// This function makes transitioning between these two states happen.
showPortalSWF = function(size, on) {
    if (!on) on = "none";
    // Load flash movie
    if (!$("#innerFlashCntnr").is("object")) {
        if (swfobject.hasFlashPlayerVersion("9.0.0")) {
            swfobject.embedSWF("/flash/CirclesCombined.swf", "innerFlashCntnr", "99%", "99%", "9.0.0", "", {
                xmlPath: "/flash/xml/configCombined.xml",
                circleTopColor: "#000000",
                circleBottomColor: "#000000",
                textTopColor: "#cf2f0a",
                textBottomColor: "#cf2f0a",
                textTop: "PEOPLE",
                textBottom: "IDEAS",
                topPath: (ie6() ? "/people/" : "/#/people/"),
                bottomPath: (ie6() ? "/ideas/" : "/#/ideas/")
            }, {
                wmode: "transparent",
                quality: "high",
                allowScriptAccess: "sameDomain"
            });
        }
        else {
            // Build alternate version of portal as a slideshow of images
            // TODO: Make this a carousel instead of a single static image
            $("#peoplePortalCarousel").empty();
            $("#ideasPortalCarousel").empty();
            var randomPeopleIdx = 0; // We'll use zero here as a signal to turn that circle "on"
            if (on != "top") randomPeopleIdx = Math.floor(Math.random() * 12) + 1;
            var randomIdeasIdx = 0;
            if (on != "bottom") randomIdeasIdx = Math.floor(Math.random() * 12) + 1;
            if (size == "Small") {
                $("<a>People</a>").attr("href", (ie6() ? "/people/" : "/#/people/")).addClass("peoplePortalCarouselImgSmall").css("background-image", "url(/images/portal/137px/people/" + randomPeopleIdx + ".png)").appendTo($("#peoplePortalCarousel"));
                $("<a>Ideas</a>").attr("href", (ie6() ? "/ideas/" : "/#/ideas/")).addClass("ideasPortalCarouselImgSmall").css("background-image", "url(/images/portal/137px/ideas/" + randomIdeasIdx + ".png)").appendTo($("#ideasPortalCarousel"));
            }
            else if (size == "Large") {
                $("<a>People</a>").attr("href", (ie6() ? "/people/" : "/#/people/")).addClass("peoplePortalCarouselImgLarge").css("background-image", "url(/images/portal/225px/people/" + randomPeopleIdx + ".png)").appendTo($("#peoplePortalCarousel"));
                $("<a>Ideas</a>").attr("href", (ie6() ? "/ideas/" : "/#/ideas/")).addClass("ideasPortalCarouselImgLarge").css("background-image", "url(/images/portal/225px/ideas/" + randomIdeasIdx + ".png)").appendTo($("#ideasPortalCarousel"));
            }
        }
    }
    else {
        setCircleOn(on);
    }
    
    if (!$("#innerFlashCntnr").is(":visible")) {
        // If this is the first view of the portal, just fade it in at its proper position
        $("#flashCntnr").removeClass("flashSmall").removeClass("flashLarge").addClass("flash" + size).fadeIn();
    }
    else {
        // Check to see if we're already at the target size - to prevent unnecessary animation
        if (!$("#flashCntnr").hasClass("flash" + size)) {
            // If not in IE6, resize SWF and move it as appropriate
            if (!ie6()) {
                if (size == "Large") {
                    // Make it large and position it in the center
                    $("#flashCntnr").css({
                        width: 150,
                        height: 307,
                        top: 118,
                        left: 50,
                        marginLeft: 0
                    }).animate({
                        width: 250,
                        height: 512,
                        top: 20,
                        left: $("#iCntnr").width() / 2,
                        marginLeft: -125
                    }, 700, "easeOutQuint", function() { $(this).removeClass("flashSmall").addClass("flashLarge"); });
                }
                else {
                    // Make it small and position it in the upper left
                    $("#flashCntnr").css({
                        width: 250,
                        height: 512,
                        top: 20,
                        left: $("#iCntnr").width() / 2,
                        marginLeft: -125
                    }).animate({
                        width: 150,
                        height: 307,
                        top: 118,
                        left: 50,
                        marginLeft: 0
                    }, 700, "easeOutQuint", function() { $(this).removeClass("flashLarge").addClass("flashSmall"); });
                }
                if (size == "Large") {
                    $("#flashCntnr").animate({width: 250});
                }
                else {
                    $("#flashCntnr").animate({width: 150});
                }
            }
            else {
                $("#flashCntnr").removeClass("flashSmall").removeClass("flashLarge").addClass("flash" + size);
            }
        }
    }
}

// from http://painteddigital.com/2008/05/19/calling-flash-as3-functions-from-javascript/
getFlashMovieObject = function(movieName) {
    if (window.document[movieName]) {
        return window.document[movieName];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[movieName])
            return document.embeds[movieName];
    }
    return document.getElementById(movieName);
}

setCircleOn = function(on) {
    if (!on) on = "none";
    var flash = getFlashMovieObject("innerFlashCntnr");
    if (flash.selectCircle)
        try {
            flash.selectCircle(on);
        } catch (ex) { }
}

// This function is called by the swf when it's finished loading
// This is to combat a bug due to the history plugin of setCircleOn being called before the swf is fully loaded
flashLoaded = function() {
    if (location.href.indexOf("/people") > -1) {
        setCircleOn("top");
    }
    else if (location.href.indexOf("/ideas") > -1) {
        setCircleOn("bottom");
    }
}

flashNavigate = function(url) {
    if (!ie6() && location.href.indexOf("/blog/") == -1) {
        _fromTransition = true;
        hash = url.replace(/^.*#/, '').replace("http://" + location.host, '');
        $.historyLoad(hash);
        trackEvent("Portal Click", hash, location.href);
        return false;
    }
    trackEvent("Portal Click", url, location.href);
    location.href = url;
}

/****************************** HISTORY FUNCTIONS ******************************/

setupHistory = function() {
    if (!_historyInit) {
        $.historyInit(pageload, "/", function() {
            _historyInit = true;
        });
    }
}

pageload = function(hash) {
    if (location.pathname != "/") {
        location.href = "/" + (hash ? "#" + hash: "");
    }
    else {
        if (!hash) hash = "/";
        if (!_fromTransition) {
            $("#content").empty();
        }
        var qs = querystringFromHash(hash);
        if ($.browser.msie) {
            hash = encodeURIComponent(hash);
        }
        var p = qs.params;
        if (typeof p.length == "undefined") { p = null; }
        if (_pageloadXHR) {
            _pageloadXHR.abort();
            _pageloadXHR = null;
        }
        $("#content").stop(true, true);
        hash = decodeURIComponent(hash); // Fix a problem in IE6 - this gets double-encoded for some reason
        var ajaxSettings = {
            url: hash,
            success: function(data, status, xhr) {
                // Snag the incoming data and hide it for now.
                var inContent = $("#content", data);

                // If a transition link wasn't clicked, just simply load this data into the content <div>
                if (!_fromTransition) {
                    $("#content").append(inContent.children());
                    resizeContent();
                }
                else {
                    var inCC = $(".contentCntnr", inContent);
                    var inImg = $("#imgCntnr img:first", inContent);
                    var inTrx = $(".transitionCntnr", inCC);
                    if (inCC[0]) inCC.hide();
                    if (inTrx[0]) inTrx.hide();

                    var outContent = $("#content:visible");
                    var outCC = $(".contentCntnr .transitionCntnr:first", outContent).parents(".contentCntnr");
                    if (outCC[0]) outCC.siblings(".contentCntnr").remove();
                    var outTrx = $(".transitionCntnr", outCC);

                    // If About This Design is showing, hide it
                    if ($(".sdb:visible", outContent)[0]) {
                        toggleSDB({ data: { id: $($(".sdb:visible")[0]).attr("id") } });
                    }

                    // If we have transition information, do the transition thing.
                    if (inCC[0] && inTrx[0] && outCC[0] && outTrx[0]) {

                        try {
                            // Compare background images - if they're the same, don't transition
                            var outImgSrc = $("#imgCntnr img:first", outContent).attr("src");
                            var inImgSrc = inImg.attr("src");

                            // Remove existing imgCntnr and sdbInfoCntnr
                            outCC.siblings().remove();

                            // Now all that's left is contentCntnr, which contains the background image, and its child, transitionCntnr, which contains the content.
                            // Fade out transitionCntnr's children.
                            outTrx.children().fadeOut(function() {
                                // Remove transitionCntnr.
                                outTrx.remove();

                                // Add the new content children to the content <div>.
                                outContent.append(inContent.children());

                                // If the background image is changing, animate the existing contentCntnr off the left-hand side of the content <div>.
                                if (outImgSrc != inImgSrc) {
                                    inCC.css({ width: 0, left: 1000 }).show().animate({ width: 1000, left: 0 });
                                    outCC.animate({ width: 0 }, function() {
                                        // Remove the outgoing content.
                                        $(this).remove();
                                        // Fade in the new content
                                        if (!inTrx.is(":animated"))
                                            inTrx.fadeIn(function() {
                                                resizeContent();
                                                inCC.show();
                                            });
                                    });
                                }
                                else {
                                    // Just fade in the new content
                                    outCC.append(inTrx);
                                    if (!inTrx.is(":animated"))
                                        inTrx.fadeIn(function() {
                                            resizeContent();
                                            inCC.remove();
                                        });
                                }
                            });
                        }
                        catch (ex) {
                            if (console) console.log(ex);
                            // Just do a quick swap of content
                            outContent.empty().append(inContent.children());
                            resizeContent();
                        }
                    }
                    else {
                        // Just do a quick swap of content
                        outContent.empty().append(inContent.children());
                        resizeContent();
                    }
                }

                // Update the title tag
                var titlere = /<title>(.*?)<\/title>/;
                var titlegroups = titlere.exec(data);
                if (titlegroups && titlegroups.length > 1) {
                    document.title = titlegroups[1];
                }
                else {
                    document.title = 'GyroHSR'; // TODO: Updated text?
                }

                $("#screenDesignedByCntnr a").text("About This Design");
                Cufon.replace("#screenDesignedByCntnr a", { fontFamily: "Gotham" });

                _fromTransition = false; // Reset this flag
                _pageloadXHR = null; // Request is over
            },
            dataType: "html"
        }

        if (p) ajaxSettings.data = p;

        _pageloadXHR = $.ajax(ajaxSettings);
    }
}

resizeContent = function() {
    var h = 0;
    if ($(".transitionCntnr")[0]) h = $(".transitionCntnr:last").height();
    var h2 = $(".contentCntnr:first").height();
    $("#content").animate({ height: Math.max(h, h2) });
}

/****************************** DOCUMENT READY HANDLERS ******************************/

// all
all_docready_pre = function() {
   // Bind anchor tags to load through the history plugin
   if (!ie6()) {
        $("a.transition").unbind("click").bind("click", function() {
            _fromTransition = true;
            hash = this.href.replace(/^.*#/, '').replace("http://" + location.host, '');
            $.historyLoad(hash);
            return false;
        });
   }
   
    // Reset navigation items' on-states
    $("#header li, #footerNav li, #copyrightNav li").removeClass("on");
    Cufon.replace("#header li, #footerNav li, #copyrightNav li", { fontFamily: "Gotham" });

    // Add on-click events to all external links
    $("a").each(function() {
        var href = this.href;
        var domainre = new RegExp("^" + _domain.replace(".", "\\."));
        if (!href.match(domainre) && href.indexOf("javascript:") == -1) {
            $(this).unbind("click").bind("click", function() {
                trackExternalClick(href, location.href);
                return true;
            });
        }
    });
}

all_docready_post = function() {
    
}

// index
index_docready = function() {
    all_docready_pre();

    // Some nice visuals
    if (!$("#logoCntnr").is(":visible")) {
        $("#logoCntnr").hide().slideDown();
    }

    // Fade in each social media icon
    $("#fbLink a").fadeIn("fast", function() {
        $("#twLink a").fadeIn("fast", function() {
            $("#flLink a").fadeIn("fast", function() {
                $("#rssLink a").fadeIn("fast");
            });
        });
    });

    // Fade in the News and Insights content
    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Large");
    });

    all_docready_post();
}

// people
people_docready = function() {
    all_docready_pre();
    
    // Fade in the body copy and people grid
    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small", "top");
    });

    // Set up rollovers for the "by visuals" cells
    if ($(".peopleByVisualsCell")[0]) {
        $("#peopleByVisualsScrollCntnr").hide();
        loadPBVCells();
    }
    else if ($(".peopleList")[0]) {
        $(".peopleList li a").hide().bind("click", function() {
            // Set a cookie value indicating that the link was clicked from "list" view
            $.cookies.set("peopleview", "list");
        });
        fadeInPBLItems(0);
    }

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#peopleBodyCopyCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#peopleBodyCopyCntnr p").addClass("whitetext");
        Cufon.refresh("#peopleBodyCopyCntnr p");
        if ($(".peopleList")[0]) {
            $(".peopleList li").addClass("whitetext");
            Cufon.refresh(".peopleList li a");
        }
    }

    // Set nav on state
    setGlobalNavOn("#globalPeopleLink");

    all_docready_post();
}

// people/office
office_docready = function(lat, lon, officeName, view) {
    $("#officeBodyCopyCntnr, #officeLocationCopyCntnr, #map, #directions, #officeContactUsCntnr, #officeCareers, #careersCntnr, #applyCntnr").hide();
    
    all_docready_pre();

    // Fade in the body copy and people grid
    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small", "top");
    });

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#officeBodyCopyCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#officeBodyCopyCntnr p").addClass("whitetext");
        Cufon.replace("#officeBodyCopyCntnr p", { fontFamily: "GothamBook" });
        Cufon.replace("#officeBodyCopyCntnr p a", { fontFamily: "GothamBook", hover: true });
    }
    $("#officeBodyCopyCntnr a").bind("hover", function() {
        Cufon.refresh(this);
    }, function() {
        Cufon.refresh(this);
    });

    // Link up subnav items
    $("#officeLink").bind("click", function() {
        try {
            office_fadeout_everything(function() {
                office_subnav_seton("#officeLink");
                $("#officeBodyCopyCntnr, #officeBodyCopyCntnr #mainhtml, #officeLocationCopyCntnr").stop().fadeIn();
            });
        } catch(ex) { if (console) console.log(ex); }
        return false;
    });
    $("#contactLink").bind("click", function() {
        try {
            office_fadeout_everything(function() {
                office_subnav_seton("#contactLink");
                trackEvent("Office Contact Form", "Start", officeName);
                init_contactus();
            });
        } catch(ex) { if (console) console.log(ex); }
        return false;
    });
    $("#mapLink").bind("click", function() {
        try {
            office_fadeout_everything(function() {
                office_subnav_seton("#mapLink");
                init_map(lat, lon, officeName);
            });
        } catch(ex) { if (console) console.log(ex); }
        return false;
    });
    $("#careersLink").bind("click", function() {
        try {
            office_subnav_seton("#careersLink");
            init_careers("office", officeName);
        } catch(ex) { if (console) console.log(ex); }
        return false;
    });
    $("#applyLink").bind("click", function() {
        try {
            office_subnav_seton("#careersLink");
            init_office_apply();
        } catch(ex) { if (console) console.log(ex); }
        return false;
    });

    // Show view if indicated - this is to support direct URLs (e.g. /people/paris/contact/)
    if (view == 'map') {
        office_subnav_seton("#mapLink");
        init_map(lat, lon, officeName);
    }
    else if (view == 'contact') {
        office_subnav_seton("#contactLink");
        trackEvent("Office Contact Form", "Start", officeName);
        init_contactus();
    }
    else if (view == 'careers') {
        office_subnav_seton("#careersLink");
        // Track whether the user came from the careers page vs. the office page
        var qs = querystringFromHash(location.hash);
        var from = "office";
        if (qs.get("from", "") == "careers")
            from = "careers";
        init_careers(from, officeName);
    }
    else if (view == 'apply') {
        office_subnav_seton("#careersLink");
        init_office_apply();
    }
    else {
        office_subnav_seton("#officeLink");
        $("#officeBodyCopyCntnr, #officeLocationCopyCntnr").stop().fadeIn();
    }

    setGlobalNavOn("#globalPeopleLink");

    all_docready_post();
}

// ideas
ideas_docready = function(view) {
    all_docready_pre();

    // Fade in the body copy and people grid
    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small", "bottom");
    });

    // Set up rollovers for the "by visuals" cells
    if ($(".ideasByVisualsCell")[0]) {
        $("#ideasByVisualsScrollCntnr").hide();
        loadIBVCells();
    }
    else if ($(".ideasList")[0]) {
        $("#ideasByListScrollCntnr").hide();
        loadIBLCells();
    }

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#ideasBodyCopyCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#ideasBodyCopyCntnr p").addClass("whitetext");
        Cufon.refresh("#ideasBodyCopyCntnr p");
        if ($(".ideasList")[0]) {
            $(".ideasList li").addClass("whitetext");
            Cufon.refresh(".ideasList li a");
        }
    }

    setGlobalNavOn("#globalIdeasLink");

    // If an idea is indicated in the URL, show the dialog automatically
    if (view) {
        showIdeaDialog(view);
    }

    all_docready_post();
}

// about
about_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });
    
    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#aboutBodyCopyCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#aboutBodyCopyCntnr p, #aboutBodyCopyCntnr h2").addClass("whitetext");
        Cufon.replace("#aboutBodyCopyCntnr p", { fontFamily: "GothamBook" });
        Cufon.replace("#aboutBodyCopyCntnr h2", { fontFamily: "Gotham" });
    }

    setGlobalNavOn("#globalAboutLink");

    all_docready_post();
}

// about/capabilities
capabilities_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#capabilitiesBodyCopy").parents(".contentCntnr").hasClass("whitetext")) {
        $("#capabilitiesListCntnr li, #capabilitiesBodyCopy p, #centresList li a").addClass("whitetext");
        Cufon.replace("#capabilitiesListCntnr li", { fontFamily: "Gotham" });
        Cufon.replace("#capabilitiesBodyCopy p", { fontFamily: "GothamBook" });
        Cufon.replace("#centresList li a", { fontFamily: "Gotham", hover: true });
    }

    // Set up strategic process view link
    $("#viewStrategicProcessesLink").bind("click", function() {
        trackPageview("/about/capabilities/strategicprocesses");
        $("#dialogContents").hide();
        $("#strategicProcessDialog")
            .css({
                width: 50,
                marginLeft: -25,
                height: 50,
                marginTop: -25,
                paddingLeft: 0,
                paddingRight: 0,
                paddingTop: 0,
                paddingBottom: 0
            }).fadeIn("fast")
            .animate({
                width: 956,
                marginLeft: -507,
                paddingLeft: 20,
                paddingRight: 20
            }, 300, "easeOutExpo", function() { $(this).animate({
                    height: 624,
                    marginTop: -337,
                    paddingTop: 20,
                    paddingBottom: 20
                }, 300, "easeOutExpo", function() {
                    $("#dialogContents").fadeIn();
                    Cufon.replace("#dialogContents h1", { fontFamily: "Gotham" });
                    // close animation
                    $("#strategicProcessDialogCloseBox").bind("click", function() {
                        $("#dialogContents").fadeOut(function() {
                            $("#strategicProcessDialog").animate({
                                height: 50,
                                marginTop: -25,
                                paddingTop: 0,
                                paddingBottom: 0
                            }, 300, "easeOutExpo", function() {
                                $(this).animate({
                                    width: 50,
                                    marginLeft: -25,
                                    paddingLeft: 0,
                                    paddingRight: 0
                                }, 300, "easeOutExpo", function() {
                                    $(this).fadeOut("fast");
                                });
                            });
                        });
                        return false;
                    });
                });
            });
        return false;
    });

    setGlobalNavOn("#globalAboutLink");

    all_docready_post();
}

// about/b2b
b2b_docready = function(centre) {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#centresBodyCopyCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#centresBodyCopyCntnr p").addClass("whitetext");
        Cufon.refresh("#centresBodyCopyCntnr p");
    }

    setGlobalNavOn("#globalAboutLink");

    all_docready_post();
}

// about/healthcare
healthcare_docready = function(centre) {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#centresBodyCopyCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#centresBodyCopyCntnr p").addClass("whitetext");
        Cufon.refresh("#centresBodyCopyCntnr p");
    }

    setGlobalNavOn("#globalAboutLink");

    all_docready_post();
}

// g foundation
gFoundation_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    setGlobalNavOn("#globalGFoundationLink");

    all_docready_post();
}

// clients
clients_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#clientsCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#clientsCntnr p").addClass("whitetext");
        Cufon.refresh("#clientsBodyText", { fontFamily: "GothamBook" });
    }
    
    $(".clientLogoImgCntnr").hide();
    $(".clientLogoPos0:first").show();
    $(".clientLogoPos1:first").show();
    $(".clientLogoPos2:first").show();
    setTimeout("rotateLogo(0, 1)", 1000);

    setGlobalNavOn("#globalClientsLink");

    all_docready_post();
}

// careers
careers_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    setGlobalNavOn("#globalCareersLink");

    // Track whether the user came from the contact page vs. the nav
    var qs = querystringFromHash(location.hash);
    var from = "nav";
    if (qs.get("from", "") == "contact")
        from = "contact";
    trackEvent("Careers Page Link Click", from);

    all_docready_post();
}

// insights
insights_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    setGlobalNavOn("#globalInsightsLink");

    all_docready_post();
}

// featured insights
featured_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    //Set up carousel controls
    $(".featuredInsight, #featuredInsightScrollPrev, #featuredInsightScrollNext").hide();
    if ($(".featuredInsight")[0]) {
        $(".featuredInsight:first").fadeIn();
        checkFeaturedInsightsCarouselControls();
    }
    $("#featuredInsightScrollPrev").bind("click", function() {
        var fiPrev = $(".featuredInsight:visible").prev(".featuredInsight");
        $(".featuredInsight:visible").animate({ 
            marginLeft: 472
        }, function() {
            $(this).hide();
        });
        $(fiPrev).css({ 
            marginLeft: -472
        }).show().animate({
            marginLeft: 0
        }, function() {
            checkFeaturedInsightsCarouselControls();
        });
    });
    $("#featuredInsightScrollNext").bind("click", function() {
        var fiNext = $(".featuredInsight:visible").next(".featuredInsight");
        $(".featuredInsight:visible").animate({ 
            marginLeft: -472
        }, function() {
            $(this).hide();
        });
        $(fiNext).css({ 
            marginLeft: 472
        }).show().animate({
            marginLeft: 0
        }, function() {
            checkFeaturedInsightsCarouselControls();
        });
    });

    // Set body text to white if whitetext is indicated by the shown background image
    if ($("#featuredInsightsBodyCntnr").parents(".contentCntnr").hasClass("whitetext")) {
        $("#featuredInsightsBodyCntnr p").addClass("whitetext");
        Cufon.refresh("#featuredInsightsBodyCntnr p");
    }

    setGlobalNavOn("#globalInsightsLink");

    // Track featured insight clicks
    $(".featuredInsight a").bind("click", function() {
        trackEvent("Featured Insight Click", this.title);
    });

    all_docready_post();
}

// g foundation - who we work with
gfwho_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set up videos & carousel controls
    $(".videoPlayer, .videoDesc, #videoPrev, #videoNext").hide();
    $(".videoPlayer").each(function() {
        var href = $("a:first", $(this)).attr("href");
        var chunks = href.split("/");
        href = chunks[chunks.length - 1];
        var headline = $("a:first img:first", $(this)).attr("alt");
        $(this).flowplayer("/flash/flowplayer.commercial-3.1.5.swf", {
            key: "#@b5f584ea85b8cb7aa70",
            plugins: {
                controls: {
                    autoHide: "always",
                    hideDelay: 2000,
                    opacity: 1,
                    backgroundColor: "#000000",
                    backgroundGradient: "none",
                    timeColor: "#aaaaaa",
                    timeBgColor: "#000000",
                    durationColor: "#aaaaaa",
                    progressColor: "#cf2f0a",
                    progressGradient: "none",
                    buttonColor: "#404040",
                    buttonOverColor: "#606060",
                    bufferColor: "#404040",
                    scrubberHeightRatio: 0.6,
                    volumeSliderColor: '#ffffff',
                    tooltipColor: "#a62508"
                },
                rtmp: {
                    url: "/flash/flowplayer.rtmp-3.1.3.swf",
                    netConnectionUrl: "rtmp://s11i0i1bq8inpf.cloudfront.net/cfx/st"
                }
            },
            clip: {
                url: href,
                autoBuffering: true,
                scaling: "fit",
                onStart: function() {
                    trackEvent("G Foundation: " + headline, "Video Started", href);
                },
                onFinish: function() {
                    trackEvent("G Foundation: " + headline, "Video Completed", href);
                    this.unload();
                },
                provider: "rtmp"
            }
        });
    });
    showGFoundationVideo($(".videoPlayer:first"), $(".videoDesc:first"));
    $("#videoPrev").bind("click", function() {
        showGFoundationVideo($(".videoPlayer:visible").prev(".videoPlayer"), $(".videoDesc:visible").prev(".videoDesc"));
    });
    $("#videoNext").bind("click", function() {
        showGFoundationVideo($(".videoPlayer:visible").next(".videoPlayer"), $(".videoDesc:visible").next(".videoDesc"));
    });

    setGlobalNavOn("#globalGFoundationLink");

    all_docready_post();
}

contact_docready = function() {
    all_docready_pre();
    $("#generalContactUsCntnr, #generalContactUsCloseButton").hide();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    $("#generalRequestsLink").bind("click", function() {
        trackEvent("General Requests", "Start");
        $(".mailResponse").fadeOut();
        $("#generalContactUsCntnr, #generalContactUsCloseButton, #generalContactUsForm").fadeIn();
    });
    $("#generalContactUsCloseButton").bind("click", function() {
        $("#generalContactUsCntnr, #generalContactUsCloseButton, #generalContactUsForm, .mailResponse").fadeOut();
    });

    // Init contact us form
    var ajaxloader = $("#generalContactUsForm #ajaxLoader");
    $("#generalContactUsForm").unbind("submit").bind("submit", function() {
        ajaxloader.stop().fadeIn();
        $(this).ajaxSubmit({
            beforeSubmit: validate_general_contact_us,
            success: general_contact_success
        });
        return false;
    });

    setGlobalNavOn("#globalContactLink");

    all_docready_post();
}

fourOhFour_docready = function() {
    all_docready_pre();
    setupBGImages();
    all_docready_post();
}

privacy_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set nav on state
    setGlobalNavOn("#globalPrivacyLink");

    resizeContent();

    all_docready_post();
}

legal_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set nav on state
    setGlobalNavOn("#globalLegalLink");

    resizeContent();

    all_docready_post();
}

news_docready = function() {
    all_docready_pre();

    setupBGImages(function() {
        // Fade in flash movie
        showPortalSWF("Small");
    });

    // Set nav on state
    setGlobalNavOn("#globalInsightsLink");

    resizeContent();

    all_docready_post();
}

/****************************** PEOPLE (INDEX) HELPER METHODS ******************************/

fadeInPBVCell = function(idx) {
    // As long as idx isn't past the end of the array
    if ($(".peopleByVisualsCell").length > idx) {
        $(".peopleByVisualsCell:eq(" + idx + ")").fadeIn(800);
        setTimeout("fadeInPBVCell(" + (idx + 1).toString() + ")", 50);
    }
}

loadPBVCells = function() {
    $(".peopleByVisualsCell").hide();
    $(".peopleByVisualsCell").each(function() {
        var a = $("<a href='" + $("a", this).attr("href") + "' class='desc'>" + $("a", this).attr("title") + "</a>");
        a.bind("click", function() {
            // Set a cookie value indicating that the link was clicked from "visuals" view
            $.cookies.set("peopleview", "visuals");
            // Do the transition thing
            _fromTransition = true;
            hash = this.href.replace(/^.*#/, '').replace("http://" + location.host, '');
            $.historyLoad(hash);
            return false;
        });
        a.appendTo($(this));
    });
    $(".peopleByVisualsCell a.cell").bind("mouseenter", function() {
        $(".desc:visible").fadeOut("fast");
        $($(this).siblings(".desc")[0]).fadeIn("fast");
    });
    $(".desc").bind("mouseleave", function() {
        $(this).fadeOut("fast");
    });
    Cufon.replace(".desc", { fontFamily: "Gotham" });
    fadeInPBVCell(0);
    if (!$("#peopleByVisualsScrollCntnr").is(":visible"))
        $("#peopleByVisualsScrollCntnr").fadeIn(1500);

    // Set up carousel links
    var ul = $("#peopleByVisualsCntnr ul");
    $("#peopleByVisualsScrollCntnr a").bind("click", function() {
        $.get(this.href, function(data) {
            // Fade out existing cells
            var loading = false;
            $(".peopleByVisualsCell").fadeOut("fast", function() {
                if (!loading) {
                    loading = true; // Ensures that this only gets run once since the fadeOut callback executes once per cell
                    var scrollCntnr = $("#peopleByVisualsScrollCntnr");
                    // Clear the ul
                    ul.empty();
                    // Get destination page's cells
                    var ulNew = $("#peopleByVisualsCntnr ul", data);
                    ulNew.children().hide();
                    ul.append(ulNew.children());
                    scrollCntnr.replaceWith($("#peopleByVisualsScrollCntnr", data));
                    loadPBVCells();
                }
            });
        });
        return false;
    })
}

fadeInPBLItems = function(idx) {
    // As long as idx isn't past the end of the array
    if ($(".peopleList li a").length > idx) {
        $(".peopleList li a:eq(" + idx + ")").fadeIn(800);
        setTimeout("fadeInPBLItems(" + (idx + 1).toString() + ")", 50);
    }
}

/****************************** OFFICE HELPER METHODS ******************************/

office_subnav_seton = function(sel) {
    $("#subnav li a").removeClass("on");
    $(sel).addClass("on");
    Cufon.replace("#officeSubnavCntnr #subnav li a", { fontFamily: "Gotham" });
}

office_fadeout_everything = function(cb) {
    $("#officeBodyCopyCntnr #mainhtml, #map, #directions, #officeContactUsCntnr, .mailResponse, #officeLocationCopyCntnr, #officeCareers").each(function() {
        if ($(this).is(":visible")) $(this).fadeOut();
    });
    if (cb) cb();
}

init_contactus = function() {
    var ajaxloader = $("#officeContactUsForm #ajaxLoader");
    $("#officeLocationCopyCntnr").stop().fadeIn();
    $("#officeContactUsForm").unbind("submit").bind("submit", function() {
        ajaxloader.stop().fadeIn();
        $(this).ajaxSubmit({
            beforeSubmit: validate_office_contact_us,
            success: office_contact_success
        });
        return false;
    });
    $("#officeContactUsCntnr").stop().fadeIn();
}

init_map = function(lat, lon, officeName) {
    $("#map, #officeLocationCopyCntnr").stop().fadeIn();

    var latlng = new google.maps.LatLng(lat, lon);
    var opt = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("mapCanvas"), opt);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
    var balloon = new google.maps.InfoWindow({
        content: "<div class='mapBalloon'><h1>GyroHSR " + officeName + "</h1>" + $.trim(document.getElementById("address").innerHTML) + "</div>"
    });
    google.maps.event.addListener(marker, "click", function() {
        balloon.open(map, marker);
    });
    google.maps.event.addListener(balloon, 'domready', function() {
        Cufon.replace(".mapBalloon h1", { fontFamily: "Gotham" });
        Cufon.replace(".mapBalloon p", { fontFamily: "GothamBook" });
    });
    $("#directions").stop().fadeIn();
}

init_careers = function(from, officeName) {
    fadeInCareers();
    if ($("#applyCntnr").is(":visible")) {
        $("#applyCntnr").fadeOut();
    }
    $("#careersCntnr").fadeIn();
    trackEvent("Careers Click", from, officeName);
    $("#applyLink").bind("click", function() {
        trackEvent("Careers Apply", "Start", officeName);
        return true;
    });
}

init_office_apply = function() {
    fadeInCareers();
    if ($("#careersCntnr").is(":visible")) {
        $("#careersCntnr").fadeOut();
    }
    $(".officeApplyRow .newListSelected").remove();
    $("#selApplyJobRole").sSelect();
    if ($("#resumeCell div").length == 0) {
        $("#filApplyResume").filestyle({
            image: "/images/browse_btn.gif",
            imagewidth: 80,
            imageheight: 24,
            width: 160
        });
    }
    var inputTop = $("#resumeCell > input:first").position().top;
    // Adjust v-pos of select - in Safari this is off by 2 px relative to the input upload control
    var selTop = $("#jobRoleCell .selectedTxt:first").position().top;
    if (selTop != inputTop) {
        $("#jobRoleCell .selectedTxt:first").css("margin-top", (selTop - inputTop) + "px");
    }
    // Adjust v-pos of browse button - in Safari this is off by 2 px relative to the input upload control
    var btnTop = $("#resumeCell > div:first").position().top;
    if (btnTop != inputTop) {
        $("#resumeCell > div:first").css("bottom", (btnTop - inputTop) + "px");
    }

    var ajaxloader = $("#applyAjaxLoader");
    $("#officeApplyForm").unbind("submit").bind("submit", function() {
        ajaxloader.stop().fadeIn();
        $(this).ajaxSubmit({
            beforeSubmit: validate_office_apply,
            success: office_apply_success
        });
        return false;
    });
    $("#applyCntnr").fadeIn();
}

validate_office_contact_us = function() {
    var ajaxloader = $("#officeContactUsForm #ajaxLoader");
    $("#officeContactUsCntnr .invalidEmailMsg").hide();
    $("#officeContactUsCntnr .requiredField").each(function() {
        $(this).removeClass("error").unbind("blur");
        if ($.trim($(this).val()) == '') {
            $(this).addClass("error").bind("blur", function() { if ($.trim($(this).val()) != '') $(this).removeClass("error"); });
        }
    });
    // Check the e-mail address
    var email = $.trim($("#txtEmail").val());
    var re = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (!re.test(email)) {
        $("#txtEmail").addClass("error");
        $("#officeContactUsCntnr .invalidEmailMsg").show();
    }

    if ($("#officeContactUsCntnr .error")[0]) {
        ajaxloader.stop().fadeOut();
        return false;
    }
    return true;
}

validate_office_apply = function() {
    var ajaxloader = $("#applyAjaxLoader");
    $("#officeApplyCntnr .invalidEmailMsg").hide();
    $("#officeApplyCntnr .requiredField").each(function() {
        $(this).removeClass("error").unbind("blur");
        if ($.trim($(this).val()) == '') {
            $(this).addClass("error").bind("blur", function() {
                if ($.trim($(this).val()) != '')
                    $(this).removeClass("error");
            });
        }
    });
    $("#officeApplyCntnr .requiredSelectBox").each(function() {
        $(this).siblings(".newListSelected").removeClass("error").unbind("blur");
        if ($(this).val() == '-1') {
            $(this).siblings(".newListSelected").addClass("error").bind("blur", function() {
                if ($(this).val() != '')
                    $(this).siblings(".newListSelected").removeClass("error");
            });
        }
    });
    // Check the e-mail address
    var email = $.trim($("#txtApplyEmail").val());
    var re = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (!re.test(email)) {
        $("#txtApplyEmail").addClass("error");
        $("#officeApplyCntnr .invalidEmailMsg").show();
    }
    // Check the attachment filetype
    var attfile = $("#filApplyResume").val();
    var attre = /\.pdf$|\.doc$|\.docx$/;
    if (!attre.test(attfile)) {
        $("#resumeCell input.requiredField").addClass("error");
    }

    if ($("#officeApplyCntnr .error")[0]) {
        ajaxloader.stop().fadeOut();
        return false;
    }
    return true;
}

office_contact_success = function(responseText, statusText) {
    var ajaxloader = $("#officeContactUsForm #ajaxLoader");
    ajaxloader.stop().fadeOut();
    var message = $(responseText);
    $("#officeContactUsForm").fadeOut(function() {
        message.hide().appendTo($("#officeContactUsCntnr")).stop().fadeIn();
        Cufon.replace(".mailResponse h2", { fontFamily: "Gotham" });
        Cufon.replace(".mailResponse p", { fontFamily: "GothamBook" });
    });
}

office_apply_success = function(responseText, statusText) {
    var ajaxloader = $("#applyAjaxLoader");
    ajaxloader.stop().fadeOut();
    var message = $(responseText);
    $("#officeApplyForm").show().fadeOut(function() {
        message.hide().appendTo($("#officeApplyCntnr")).stop().fadeIn();
        Cufon.replace(".applyResponse h2", { fontFamily: "Gotham" });
        Cufon.replace(".applyResponse p", { fontFamily: "GothamBook" });
    });
}

fadeInCareers = function() {
    if (!$("#officeCareers").is(":visible")) {
        office_fadeout_everything();
        $("#officeCareers").fadeIn();
    }
}

/****************************** IDEAS HELPER METHODS ******************************/

fadeInIBVCell = function(idx) {
    // As long as idx isn't past the end of the array
    if ($(".ideasByVisualsCell").length > idx) {
        $(".ideasByVisualsCell:eq(" + idx + ")").fadeIn(800);
        setTimeout("fadeInIBVCell(" + (idx + 1).toString() + ")", 50);
    }
}

loadIBVCells = function() {
    $(".ideasByVisualsCell").hide();

    // Vertically center if less than three rows
    $("#ideasByVisualsCntnr").css("top", (110 + (58 * (3 - ($(".ideasByVisualsCell").length / 4)))) + "px"); // 110 is the container's default top.  58 is 1/2 of 115, the height of one of the cells.  There are three rows with four cells per row.

    $(".ideasByVisualsCell").each(function() {
        var idea = getIdeaFromHref($("a", this).attr("href"));
        var a = $("<a href='" + $("a", this).attr("href") + "' class='desc'>" + $("a", this).attr("title") + "</a>");
        a.bind("click", function() {
            if (this.href[this.href.length - 1] != "#") {
                // Set a cookie value indicating that the link was clicked from "visuals" view
                $.cookies.set("ideasview", "visuals");
                showIdeaDialog(idea);
            }
            return false;
        });
        a.appendTo($(this));
    });
    $(".ideasByVisualsCell a.cell").bind("mouseenter", function() {
        $(".desc:visible").fadeOut("fast");
        $($(this).siblings(".desc")[0]).fadeIn("fast");
    });
    $(".desc").bind("mouseleave", function() {
        $(this).fadeOut("fast");
    });
    Cufon.replace(".desc", { fontFamily: "Gotham" });
    fadeInIBVCell(0);
    if (!$("#ideasByVisualsScrollCntnr").is(":visible"))
        $("#ideasByVisualsScrollCntnr").fadeIn(1500);

    // Set up carousel links
    var ul = $("#ideasByVisualsCntnr ul");
    $("#ideasByVisualsScrollCntnr a").bind("click", function() {
        $.get(this.href, function(data) {
            // Fade out existing cells
            var loading = false;
            $(".ideasByVisualsCell").fadeOut("fast", function() {            
                if (!loading) {
                    loading = true; // Ensures that this only gets run once since the fadeOut callback executes once per cell
                    var scrollCntnr = $("#ideasByVisualsScrollCntnr");
                    // Clear the ul
                    ul.empty();
                    // Get destination page's cells
                    var ulNew = $("#ideasByVisualsCntnr ul", data);
                    ulNew.children().hide();
                    ul.append(ulNew.children());
                    scrollCntnr.replaceWith($("#ideasByVisualsScrollCntnr", data));
                    loadIBVCells();
                }
            });
        });
        return false;
    });
}

fadeInIBLItems = function(idx) {
    // As long as idx isn't past the end of the array
    if ($(".ideasList li a").length > idx) {
        $(".ideasList li a:eq(" + idx + ")").fadeIn(800);
        setTimeout("fadeInIBLItems(" + (idx + 1).toString() + ")", 50);
    }
}

loadIBLCells = function() {
    $(".ideasList li a").hide();
    
    $(".ideasList li a").each(function() {
        var idea = getIdeaFromHref($(this).attr("href"));
        $(this).bind("click", function() {
            if (this.href[this.href.length - 1] != "#") {
                // Set a cookie value indicating that the link was clicked from "list" view
                $.cookies.set("ideasview", "list");
                showIdeaDialog(idea);
            }
            return false;
        });
    });
    Cufon.replace(".ideasList li a", { fontFamily: "Gotham" });
    fadeInIBLItems(0);
    if (!$("#ideasByListScrollCntnr").is(":visible"))
        $("#ideasByListScrollCntnr").fadeIn(1500);

    // Set up carousel links
    var ul = $(".ideasList:first");
    $("#ideasByListScrollCntnr a").bind("click", function() {
        $.get(this.href, function(data) {
            // Fade out existing cells
            var loading = false;
            $(".ideasList li a").fadeOut("fast", function() {
                if (!loading) {
                    loading = true; // Ensures that this only gets run once since the fadeOut callback executes once per cell
                    var scrollCntnr = $("#ideasByListScrollCntnr");
                    // Clear the ul
                    ul.empty();
                    // Get destination page's cells
                    var ulNew = $(".ideasList:first", data);
                    ulNew.children("a").hide();
                    ul.append(ulNew.children());
                    scrollCntnr.replaceWith($("#ideasByListScrollCntnr", data));
                    loadIBLCells();
                }
            });
        });
        return false;
    });

    // Set up hovers
    $(".ideasList li").hover(function() {
        $(".ideasListLogoLink div", $(this)).css("background-position", "0 -110px");
        $(".ideasListTextLink", $(this)).css("background-color", "#000000").css("color", "#ffffff");
        Cufon.replace($(".ideasListTextLink:first", $(this)), { fontFamily: "Gotham", hover: true, color: "#ffffff", backgroundColor: "#000000" });
    }, function() {
        $(".ideasListLogoLink div", $(this)).css("background-position", "0 0");
        $(".ideasListTextLink", $(this)).css("background-color", "#ffffff").css("color", "#cf2f0a");
        Cufon.replace($(".ideasListTextLink:first", $(this)), { fontFamily: "Gotham", hover: true, color: "#cf2f0a", backgroundColor: "#ffffff" });
    });
}

getIdeaFromHref = function(href) {
    var hrefchunks = href.split("/");
    var chunks = new Array();
    for (var i = 0; i < hrefchunks.length; i++) {
        if ($.trim(hrefchunks[i]) != "") {
            chunks.push(hrefchunks[i]);
        }
    }
    return chunks.length == 0 ? "" : chunks[chunks.length - 1];
}

showIdeaDialog = function(idea) {
    trackPageview("/ideas/" + idea);
    // Fill the dialog container with the results of an ajax call
    $("#ideasDialog #dialogContents").remove();
    // open animation
    var targetWidth = 735;
    var targetMarginLeft = -485;
    var targetPaddingLeft = 210;
    var targetPaddingRight = 25;
    var targetHeight = 620;
    var targetTop = 15;
    var targetPaddingTop = 25;
    var targetPaddingBottom = 25;

    // IE6 double-padding math garbage
    if (ie6()) {
        targetWidth = targetWidth + targetPaddingLeft + targetPaddingRight;
        targetHeight = targetHeight + targetPaddingTop + targetPaddingBottom;
    }


    $.ajax({
        url: "/include/ideas/ideas-dialog.php",
        data: { i: idea },
        error: function(xhr, status, error) {
            if (xhr.status == "404") {
                location.href = "/404/";
            }
        },
        success: function(data, status, xhr) {
            $("#ideasDialog")
            .css({
                width: 50,
                marginLeft: -25,
                height: 50,
                top: 278,
                paddingLeft: 0,
                paddingRight: 0,
                paddingTop: 0,
                paddingBottom: 0
            }).fadeIn("fast")
            .animate({
                width: targetWidth,
                marginLeft: targetMarginLeft,
                paddingLeft: targetPaddingLeft,
                paddingRight: targetPaddingRight
            }, 300, "easeOutExpo", function() { $(this).animate({
                    height: targetHeight,
                    top: targetTop,
                    paddingTop: targetPaddingTop,
                    paddingBottom: targetPaddingBottom
                }, 300, "easeOutExpo", function() {
                    $("#ideasDialogAjaxLoader", this).fadeIn();
                    $("#dialogContents", data).hide();
                    $("#ideasDialog").empty().append($(data));
                    $("#ideasDialogHorizExpandableCntnr").hide();
                    $(".ideasSlide").hide();
                    Cufon.replace("#ideasDialogHead h1, .ideasSlide h1, .ideasSlide p, #ideasDialogHorizBody p, #ideasDialogCaseSummaryVertCntnr p", { fontFamily: "GothamBook" });
                    Cufon.replace("#ideasDialogHead h1 strong, .ideasSlide h1 strong, .ideasSlide h2, #ideasDialogHorizBody h2, #caseSummaryHorizLink, #ideasDialogHorizCapabilities li, #ideasDialogCaseSummaryVertCntnr h1, #ideasDialogCaseSummaryVertCntnr h2, #ideasDialogCaseSummaryVertCntnr li", { fontFamily: "Gotham" });
                    Cufon.replace(".ideasDialogSlideshowLink", { hover: true, fontFamily: "Gotham" });
                    $("#dialogContents").fadeIn();
                    // AddThis Share link
                    addthis.button("#ideasDialogShareButton");
                    // External link click tracking
                    $(".ideasDialogSlideshowLink").bind("click", function() {
                        trackExternalClick(this.href, "/ideas/" + idea);
                    });
                    // Case study link
                    if ($("#caseSummaryHorizLink")[0]) {
                        // Horizontal mode
                        $("#caseSummaryHorizLink").bind("click", function() {
                            if ($("#ideasDialogHorizBody").is(":visible")) {
                                $("#ideasDialogHorizExpandableCntnr").slideUp("easeOutExpo");
                                $("#caseSummaryHorizLink").removeClass("caseSummaryLinkOn").addClass("caseSummaryLinkOff");
                            }
                            else {
                                $("#ideasDialogHorizExpandableCntnr").slideDown("easeOutExpo");
                                $("#caseSummaryHorizLink").removeClass("caseSummaryLinkOff").addClass("caseSummaryLinkOn");
                            }
                        });
                    }
                    else if ($(".ideasSlide")[0]) {
                        $(".ideasSlide:first").fadeIn();

                        // Bind slide navigation controls
                        checkIdeasSlideshowCarouselControls();
                        $("#ideasSlideshowPrev").bind("click", function() {
                            if (!$(".ideasSlide:visible").is(":animated") && !$(".ideasSlide:visible").is(":first-child")) {
                                var prev = $(".ideasSlide:visible").prev(".ideasSlide");
                                hideIdeaVideo();
                                $(".ideasSlide:visible").animate({
                                    marginLeft: 620
                                }, function() {
                                    $(this).hide();
                                });
                                $(prev).css({
                                    marginLeft: -620
                                }).show().animate({
                                    marginLeft: 0
                                }, function() {
                                    checkIdeasSlideshowCarouselControls();
                                });
                            }
                        });
                        $("#ideasSlideshowNext").bind("click", function() {
                            if (!$(".ideasSlide:visible").is(":animated") && !$(".ideasSlide:visible").is(":last-child")) {
                                var next = $(".ideasSlide:visible").next(".ideasSlide");
                                hideIdeaVideo();
                                $(".ideasSlide:visible").animate({
                                    marginLeft: -620
                                }, function() {
                                    $(this).hide();
                                });
                                $(next).css({
                                    marginLeft: 620
                                }).show().animate({
                                    marginLeft: 0
                                }, function() {
                                    checkIdeasSlideshowCarouselControls();
                                })
                            }

                        });
                    }
                    // close animation
                    $("#ideasDialogCloseBox").unbind("click").bind("click", function() {
                        $("#ideasDialog #dialogContents").fadeOut(function() {
                            $("#ideasDialog #dialogContents").remove();
                            $("#ideasDialog").animate({
                                height: 50,
                                top: 278,
                                paddingTop: 0,
                                paddingBottom: 0
                            }, 300, "easeOutExpo", function() {
                                $(this).animate({
                                    width: 50,
                                    marginLeft: -25,
                                    paddingLeft: 0,
                                    paddingRight: 0
                                }, 300, "easeOutExpo", function() {
                                    $(this).fadeOut("fast");
                                });
                            });
                        });
                    });
                    $("#ideasDialogAjaxLoader", this).fadeOut();
                });
            });
        }
    });
}

checkIdeasSlideshowCarouselControls = function() {
    if ($(".ideasSlide:visible").is(":first-child")) {
        $("#ideasSlideshowPrev").hide();
    }
    else {
        $("#ideasSlideshowPrev").show();
    }
    if ($(".ideasSlide:visible").is(":last-child")) {
        $("#ideasSlideshowNext").hide();
    }
    else {
        $("#ideasSlideshowNext").show();
    }
}

hideIdeaVideo = function() {
    // Hides any playing videos in the current slide
    if ($(".ideasSlide:visible object")[0]) {
        var player = flowplayer($("object:visible").parent("a").attr("id"));
        if (player) {
            player.unload();
        }
    }
}

/****************************** CENTRES OF EXCELLENCE HELPER METHODS ******************************/

centres_subnav_seton = function(sel) {
    $("#subnav li a").removeClass("on");
    $("#centresPageList li a").removeClass("on");
    $(sel).addClass("on");
    Cufon.replace("#subnav li a", { fontFamily: "Gotham", hover: true });
    Cufon.replace("#centresPageList li a", { fontFamily: "Gotham", hover: true });
}

centres_fadeout_everything = function(cb) {
    $("#centresBodyCopyCntnr div").each(function() {
        if ($(this).is(":visible")) { $(this).fadeOut(); }
        if (cb) cb();
    })
}

/****************************** CLIENTS HELPER METHODS ******************************/

rotateLogo = function(pos, idx) {
    var vis = $(".clientLogoPos" + pos + ":visible")[0];
    $(vis).fadeOut(150, function() {
        var nextLogo = $(".clientLogoPos" + pos + ":eq(" + idx + ")");
        var totalCount = $(".clientLogoPos" + pos).length;
        $(nextLogo).fadeIn(300, function() {
            pos = (pos + 1) % 3;
            if (pos == 0) {
                idx = (idx + 1) % totalCount;
                setTimeout("rotateLogo(" + pos + "," + idx + ")", 1000);
            }
            else {
                setTimeout("rotateLogo(" + pos + "," + idx + ")", 20);
            }
        });
    });
}

/****************************** G FOUNDATION - WHO WE WORK WITH HELPER METHODS ******************************/

checkGFWhoVideoCarouselControls = function() {
    // IE6 gets a different video play button
    if (ie6()) {
        $(".videoPlayBtn").each(function() {
            this.src = "/images/videoPlayBtn_ie6.gif";
            this.width = 101;
            this.height = 101;
        });
    }

    if ($(".videoPlayer:visible").is(":first-child")) {
        $("#videoPrev").hide();
    }
    else {
        $("#videoPrev").show();
    }
    if ($(".videoPlayer:visible").is(":last-child")) {
        $("#videoNext").hide();
    }
    else {
        $("#videoNext").show();
    }
}

showGFoundationVideo = function(vid, desc) {
    if ($(".videoPlayer:visible").length > 0) {
        $("#gfWhoVideoPlayerCntnr, .videoPlayer:visible, .videoDesc:visible").fadeOut(function() {
            $f("*").each(function() { this.unload(); }); // Unload any running players
            desc.fadeIn();
            $("#gfWhoVideoPlayerCntnr").fadeIn();
            vid.fadeIn(function() {
                checkGFWhoVideoCarouselControls();
            });
        });
    }
    else {
        desc.fadeIn();
        vid.fadeIn(function() {
            checkGFWhoVideoCarouselControls();
        });
    }
}

/****************************** FEATURED INSIGHTS HELPER METHODS ******************************/

checkFeaturedInsightsCarouselControls = function() {
    if ($(".featuredInsight:visible").is(":first-child")) {
        $("#featuredInsightScrollPrev").hide();
    }
    else {
        $("#featuredInsightScrollPrev").show();
    }
    if ($(".featuredInsight:visible").is(":last-child")) {
        $("#featuredInsightScrollNext").hide();
    }
    else {
        $("#featuredInsightScrollNext").show();
    }
}

/****************************** CONTACT US HELPER METHODS ******************************/

validate_general_contact_us = function() {
    var ajaxloader = $("#generalContactUsForm #ajaxLoader");
    $("#generalContactUsForm .invalidEmailMsg").hide();
    $("#generalContactUsForm .requiredField").each(function() {
        $(this).removeClass("error").unbind("blur");
        if ($.trim($(this).val()) == '') {
            $(this).addClass("error").bind("blur", function() { if ($.trim($(this).val()) != '') $(this).removeClass("error"); });
        }
    });
    // Check the e-mail address
    var email = $.trim($("#txtEmail").val());
    var re = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (!re.test(email)) {
        $("#txtEmail").addClass("error");
        $("#generalContactUsForm .invalidEmailMsg").show();
    }

    if ($("#generalContactUsForm .error")[0]) {
        ajaxloader.stop().fadeOut();
        return false;
    }
    return true;
}

general_contact_success = function(responseText, statusText) {
    var ajaxloader = $("#generalContactUsForm #ajaxLoader");
    ajaxloader.stop().fadeOut();
    var message = $(responseText);
    $("#generalContactUsForm").fadeOut(function() {
        message.hide().appendTo($("#generalContactUsCntnr")).stop().fadeIn();
        Cufon.replace(".mailResponse h2", { fontFamily: "Gotham" });
        Cufon.replace(".mailResponse p", { fontFamily: "GothamBook" });
        $("#generalContactUsCloseButton").fadeIn();
        $(".requiredField").val(""); // Clear all fields
    });
}

/****************************** IGNITION BACKGROUND IMAGE FUNCTIONS ******************************/

setupBGImages = function(cb) {
    $("#imgCntnr").hide();
    var img = $("#imgCntnr img:first");
    var minHeight = 740;
    var cssHeight = $(img).css("height");
    if (!isNaN(cssHeight) && parseInt(cssHeight) > 0) minHeight = cssHeight;
    $(".contentCntnr:last").css({
       backgroundImage: "url(" + $(img).attr("src") + ")",
       backgroundRepeat: "no-repeat",
       minHeight: minHeight
    }).addClass("clearfix");
    var imgHeight = $(img).attr("height");
    if (!isNaN(imgHeight) && imgHeight > 0) {
        $("#content").css({ minHeight: imgHeight - 1 });
    }
    // IE6 min-height hack
    if (typeof document.body.style.maxHeight == "undefined") {
        $(".contentCntnr:last, #content").css({ height: $(img).attr("height") });
    }
    if ($(img).hasClass("whitetext")) $(".contentCntnr:last").addClass("whitetext");
    setScreenDesignedBy($(img).attr("id"));
    if (cb) cb();
    // Set the subnav to use white text if indicated to do so
    if ($("#subnav")[0] && $(img).hasClass("whitetext")) {
        $("#subnav li").addClass("whitetext");
    }
    Cufon.replace("#subnav li a", { hover: "true", fontFamily: "Gotham" });
}

setScreenDesignedBy = function(id) {
    if (id) {
        sdbid = "#sdb" + id.substr(2);
        $("#screenDesignedByCntnr a").unbind("click").bind("click", { id: sdbid }, toggleSDB);
        $(sdbid).children("img").remove();
        $("<img class='sdbThumbnail' src='" + $("#" + id).attr("src") + "'>").prependTo($(sdbid));
        if (sdbIntervalID > 0) {
            clearInterval(sdbIntervalID);
        }
        sdbIntervalID = setInterval("setIgnitionTimeRemaining()", 1000) ;
    }
}

setIgnitionTimeRemaining = function() {
    var igTime = parseInt($(".sdbIgnitionInternal:first").text()) + 3600;
    var now = new Date();
    var remaining = Math.floor(igTime - Math.floor(now.getTime() / 1000));

    var hh = Math.max(0, Math.floor(remaining / 3600));
    var mm = Math.max(0, Math.floor((remaining % 3600) / 60));
    var ss = Math.max(0, Math.floor((remaining % 3600) % 60));
    
    $(".sdbIgnitionDT:first").text("0" + hh + ":" + (mm < 10 ? "0" + mm : mm) + ":" + (ss < 10 ? "0" + ss: ss));
    Cufon.replace(".sdbIgnitionDT", { fontFamily: "GothamBook" });
}

toggleSDB = function(e) {
    var $el = $(e.data.id);
    if (!$el.is(":animated")) {
        if ($el.is(":visible")) {
            $el.show().css({
                height: 110
            }).animate({
                height: 1 // For some reason, animating to height=0 in IE6 causes a flicker of content.  This is OK because we hide the div in the callback function anyway.
            }, 600, "easeOutExpo", function() { $(this).hide(); });
            $("#screenDesignedByCntnr a").text("About This Design");
        }
        else {
            Cufon.replace(e.data.id);
            $el.hide().css({
                height: 0
            }).show().animate({
                height: 110
            }, 600, "easeOutExpo");
            $("#screenDesignedByCntnr a").text("Close");

            var author = $(".sdbAuthor", $el).text();
            var title = $(".sdbTitleCell", $el).text();
            var location = $(".sdbLocation", $el).text();

            trackEvent("About This Design", location, author, title);
        }
        $("#screenDesignedByCntnr a").toggleClass("on");
        Cufon.replace("#screenDesignedByCntnr a", { fontFamily: "Gotham", hover: true });
    }
    return false; // Prevent bubbling
}

/****************************** ANALYTICS METHODS *******************************/

trackPageview = function(url) {
    // Google Analytics
    //alert("trackPageview('" + url + "')");
    try {
        if (url)
            pageTracker._trackPageview(url);
        else
            pageTracker._trackPageview();
    } catch(err) {}
}

trackExternalClick = function(url, referrer) {
    trackEvent("External Link Click", url, referrer);
}

trackEvent = function(category, action, label, value) {
    if (action == null) action = '';
    if (label == null) label = '';
    if (value == null) value = '';
    //alert("trackEvent('" + category + "', '" + action + "', '" + label + "', '" + value + "')");
    // Google Analytics
    try {
        var pageTracker = _gat._getTracker(_gaProfileID);
	pageTracker._initData();
        pageTracker._trackEvent(category, action, label, value);
    } catch(err) {}
}

/****************************** MISC UTILITY METHODS ******************************/

get_ajax_loader = function() {
    return $("<img id='ajaxLoader' src='/images/ajax-loader.gif' width='32' height='32' alt='Loading...' />");
}

setGlobalNavOn = function(sel) {
    $(sel).addClass("on");
    Cufon.replace(sel, { fontFamily: "Gotham" });
}

ie6 = function() {
    return ($.browser.msie && $.browser.version == 6);
}

querystringFromHash = function(hash) {
    hash = hash.replace(/^#/, '');
    if ($.browser.msie) {
        hash = encodeURIComponent(hash);
    }
    var chunks = hash.split("?");
    if (chunks.length > 1) {
        return new Querystring(chunks[1]);
    }
    return new Querystring(hash);
}
