// Control the application flow and available functions

function UIHelper() { };

UIHelper.Init = function() {
    //alert("UIHelper.Init");

    UIHelper.MapCheckCount = 0;
    UIHelper.CheckIfMapInitAvailable();
};

UIHelper.SetMapInitTimer = function() {
    UIHelper.MapCheckCount++;
    if (UIHelper.MapCheckCount > 10) {
        UIHelper.GetUISettings();
    } else {
        UIHelper.Timer = setTimeout("UIHelper.CheckIfMapInitAvailable()", 500);
    }
};

UIHelper.CheckIfMapInitAvailable = function() {
    var map = $find("Map1");

    if (map) {
        // Map object is available
        UIHelper.GetUISettings();
    } else {
        // Buy a little time to see if map has loaded
        UIHelper.SetMapInitTimer();
    }
};

UIHelper.GetUISettings = function() {
    //alert("UIHelper.GetUISettings" + UIHelper.MapCheckCount);
    if (UIHelper.MapCheckCount > 1) {
        $("#browser-timeout").html("Map recheck = " + UIHelper.MapCheckCount);
        $("#browser-timeout").show();
    }

    $.ajax(
    	{
    	    type: "GET",
    	    url: "Data.aspx",
    	    data: "page=uihelper&version=" + $(".version").html(),
    	    dataType: "json",
    	    error: UIHelper.AjaxError,
    	    success: UIHelper.DefineLiterals
    	});
};

UIHelper.DefineLiterals = function(data, status) {
    //alert("UIHelper.DefineLiterals = " + status);
    if (data.status == "error") {
        UIHelper.ShowStatusMessage(data.message, "error");
        return;
    }

    UIHelper.RequiresLogin = (data.LoginEnabled == "true");
    if (UIHelper.RequiresLogin) UIHelper.LoginSummary = data.LoginSummary;

    UIHelper.DensityMapEnabled = (data.DensityMapEnabled == "true");
    UIHelper.RepeatCallsEnabled = (data.RepeatCallsEnabled == "true");
    UIHelper.WhatTabAutoLoad = (data.WhatTabAutoLoad == "true");
    UIHelper.WhatTabFoldersOpen = (data.WhatTabFoldersOpen == "true");
    UIHelper.WhatTabDefintions = (data.WhatTabDefintions == "true");

    UIHelper.QueryTabName = data.QueryTabName;
    UIHelper.HowDisplay = data.Display;
    UIHelper.HowMapTypeDisplay = data.PinMapChoice;
    UIHelper.PinMapSummary = data.PinMapSummary;
    UIHelper.RepeatCallsSummary = data.RepeatCallsSummary;
    UIHelper.DensityMapSummary = data.DensityMapSummary;

    UIHelper.CyberWatchEnabled = (data.CyberWatchEnabled == "true");
    UIHelper.CyberWatchTabName = data.CyberWatchTabName;
    UIHelper.CyberWatchSummary = data.CyberWatchTabSummary;

    UIHelper.ReportTabName = data.ReportTabName;
    UIHelper.ReportSummary = data.ReportTabSummary;
    UIHelper.ReportStyle = data.ReportStyle;

    UIHelper.PrintTabName = data.PrintTabName;
    UIHelper.PrintSummary = data.PrintTabSummary;

    UIHelper.SummaryWhatNothingSelected = data.SummaryWhatNothingSelected;
    UIHelper.SummaryWhereNothingSelected = data.SummaryWhereNothingSelected;
    UIHelper.SummaryWhenNothingSelected = data.SummaryWhenNothingSelected;

    UIHelper.NameAndPasswordRequired = data.NameAndPasswordRequired;
    UIHelper.ProcessingLogin = data.ProcessingLogin;
    UIHelper.LoginFailed = data.LoginFailed;
    UIHelper.LoginUser = data.LoginUser;
    UIHelper.LoginRole = data.LoginRole;
    UIHelper.LoggingOut = data.LoggingOut;
    UIHelper.LogoutComplete = data.LogoutComplete;
    UIHelper.LoadingCyberWatch = data.LoadingCyberWatch;
    UIHelper.LoadingWhat = data.LoadingWhat;
    UIHelper.LoadingWhere = data.LoadingWhere;
    UIHelper.LoadingWhen = data.LoadingWhen;
    UIHelper.LoadingHow = data.LoadingHow;
    UIHelper.ProcessingUpdate = data.ProcessingUpdate;
    UIHelper.RefreshingMapForChartGrid = data.RefreshingMapForChartGrid;
    UIHelper.ProcessingChartDrilldown = data.ProcessingChartDrilldown;
    UIHelper.ProcessingGridDrilldown = data.ProcessingGridDrilldown;
    UIHelper.ResettingMap = data.ResettingMap;

    UIHelper.InactiveIdleText = data.Idle;
    UIHelper.InactiveMinutesText = data.Minutes;
    UIHelper.InactiveTimeoutText = data.Timeout;

    UIHelper.BuildingChart = data.BuildingChart;
    UIHelper.MaxLimitChart = data.MaxLimitChart;
    UIHelper.BuildingGrid = data.BuildingGrid;
    UIHelper.MaxLimitGrid = data.MaxLimitGrid;
    UIHelper.IdentifyDensity = data.IdentifyDensity;
    UIHelper.IdentifyRepeat = data.IdentifyRepeat;
    UIHelper.IdentifyPoints = data.IdentifyPoints;

    UIHelper.WhatQuery = $("#WhatQuery").val("");
    UIHelper.WhereQuery = $("#WhereQuery").val("");
    UIHelper.WhenQuery = $("#WhenQuery").val("");

    UIHelper.QuerySummary = UIHelper.PinMapSummary;
    UIHelper.QueryIcon = "images/UI/ico-pin-map.jpg";
    UIHelper.ChartIDs = "";
    UIHelper.GridIDs = "";
    UIHelper.IsLinkMap = false;
    UIHelper.CurrentQueryID = "";
    UIHelper.CyberWatchPreview = false;
    UIHelper.SilverlightReports = null;
    UIHelper.TotalQueryRecs = 0;
    UIHelper.QueryMaxExceeded = false;
    UIHelper.LoginName = "";
    UIHelper.StartExtent = "";

    // Enable the How functions
    if (UIHelper.DensityMapEnabled || UIHelper.RepeatCallsEnabled) $("#how-input-button").show();

    // Enable map caches and bookmarks if there are more than one
    if ($("#lstMapCaches").attr("length") > 1) $("#map-cache-tab").show();
    if ($("#lstBookMarks").attr("length") > 1) $("#bookmarks-tab").show();

    // The Pan function is the default (can't change), but it is not highlighted. The following hack highlights it.
    // This stuff may not work in the future.
    var toolbarName = "mapToolBar";
    var f = document.forms[docFormID];
    // *******************************
    // 9.3.1 now defaults to the first tool bar item, so for now, this no longer seems necessary.
    //    f.elements[Toolbars[toolbarName].currentToolField].value = "MapPan";
    //    // Select the tool
    //    f.elements[Toolbars[toolbarName].selectTool()];
    // *******************************
    // Disable Identify
    mapToolBar_Items["MapIdentify"].disabled = true;
    mapToolBar_Items["ZoomToSelected"].disabled = true;
    // Refresh the toolbar
    f.elements[Toolbars[toolbarName].refreshGroup()];
    f.elements[Toolbars[toolbarName].refreshCommands()];

    // Setup for either login or mapping
    UIHelper.SiteSetup(UIHelper.RequiresLogin);

    // Show zoom and scale bars
    if (data.MapZoomBar == "true") $("#map-zoom-container").show();

    // If not logging in it's straight to the Queries tab, unless this is a CyberWatch confirmation or CyberWatch map
    //alert("QueryType = " + $("#QueryType").val());
    if (!UIHelper.RequiresLogin) {
        var zoomHome = true;  // Whether or not to zoom to the home extent after the map is initialized
        if ($("#QueryType").val() == "") {
            UIHelper.SetActiveTab("#queries-tab");
            if (UIHelper.WhatTabAutoLoad) UIHelper.SetActiveInputContent("what");
        } else {
            var vals = $("#QueryType").val().split("|");
            if (vals[0] == "cwm") {
                zoomHome = false;
                UIHelper.IsLinkMap = true;
                UIHelper.SetActiveTab("#queries-tab");
                UIHelper.ProcessMapLinkRequest(vals[1]);
            } else if ((vals[0] == "cwc") || (vals[0] == "cwu")) {
                CW.Action = vals[0];
                CW.ConfirmationID = vals[1];
                UIHelper.SetActiveTab("#cyberwatch-tab");
            } else {
                // Unknown query string, just start app but don't open WHAT
                UIHelper.SetActiveTab("#queries-tab");
            }
        }
        // Adjust the initial map extent after the browser (and map area) have been resized
        if (zoomHome) UIHelper.ZoomToHomeExtent();
    }

    UIHelper.TimeoutTotal = 1;  // The total needs to eventually exceed the max, not equal it
    UIHelper.TimeoutMaximum = data.MapTimeout * 60000; // 60000 = 1 minute (config setting is minutes)
    UIHelper.TimeoutInterval = 300000;  // 5 minutes = 300000, 18 minutes = 1080000
    UIHelper.TimeoutESRI = 1140000;  // 19 minutes (trigger it before ESRI's 20 minute session
    UIHelper.Timer = setTimeout("UIHelper.Timeout()", UIHelper.TimeoutInterval);

    //**************************************************************************************************
    //UIHelper.SilverlightReportLayerSelected()
    //**************************************************************************************************
};

UIHelper.SiteSetup = function(login) {
    // Enable or disable the main tabs for login or map access
    if (!$("#report-tab a").hasClass("disabled")) $("#report-tab a").addClass("disabled");
    if (login) {
        $("#queries-tab a").addClass("disabled");
        $("#print-tab a").addClass("disabled");
        $("#analysis-summary-image").attr({ src: "images/UI/ico-login.jpg", title: "Login", alt: "Login" });
        $("#analysis-summary-paragraph").html(UIHelper.LoginSummary);
        
        $("#map-tab-holder").hide();
        $("#print-tab-holder").hide();
        $("#report-tab-holder").hide();
        $("#cyberwatch-tab-holder").hide();
        $("#login-tab-holder").show();
        
        $("#txtLoginPassword").val("");
        $("#txtLoginName").val("");
        $("#txtLoginName").focus();
        $("#queries-tab a").unbind("click");
        $("#report-tab a").unbind("click");
        $("#print-tab a").unbind("click");
        if (UIHelper.CyberWatchEnabled) $("#cyberwatch-tab a").unbind("click");
        $("form#form1").bind("keypress", function(e) { if (e.keyCode == 13) { UIHelper.ValidateLogin(); } });
    } else {
        $("form#form1").unbind("keypress");
        $("#queries-tab a").removeClass("disabled");
        $("#print-tab a").removeClass("disabled");
        $("#queries-tab a").bind("click", function(e) { UIHelper.SetActiveTab('#queries-tab'); });
        if (UIHelper.CyberWatchEnabled) {
            $("#cyberwatch-tab a").bind("click", function(e) { UIHelper.SetActiveTab('#cyberwatch-tab'); });
            $("#cyberwatch-tab").show();
        } else {
            $("#cyberwatch-tab a").addClass("disabled");
            //$("#cyberwatch-tab").hide();
        }
        $("#print-tab a").bind("click", function(e) { UIHelper.ShowPrint(); });
        $("#login-tab-holder").hide();
        $("#map-tab-holder").show();

        CVS.ResizeMap();
        CVS.BuildSummaryDisplay();
    }
};

UIHelper.ZoomToHomeExtent = function() {
    //alert("UIHelper.ZoomToHomeExtent");
    UIHelper.MapCheckCount = 0;
    UIHelper.CheckIfMapHomeExtentAvailable();
};

UIHelper.SetMapHomeExtentTimer = function() {
    UIHelper.MapCheckCount++;
    if (UIHelper.MapCheckCount > 10) {
        UIHelper.ShowStatusMessage("Map not available for home extent", "warning");
    } else {
    UIHelper.Timer = setTimeout("UIHelper.CheckIfMapHomeExtentAvailable()", 500);
    }
};

UIHelper.CheckIfMapHomeExtentAvailable = function() {
    var map = $find("Map1");

    if (map) {
        // Map object is available
        var vals;
        if (UIHelper.StartExtent == "") {
            vals = $("#HomeExtent").val().split(",");
        } else {
            vals = UIHelper.StartExtent.split(",");
        }
        var env = new ESRI.ADF.Geometries.Envelope(parseFloat(vals[0]), parseFloat(vals[1]), parseFloat(vals[2]), parseFloat(vals[3]));
        map.zoomToBox(env, false);  // false = do not animate

        if (UIHelper.MapCheckCount > 0) {
            $("#browser-timeout").html("Home recheck = " + UIHelper.MapCheckCount);
            $("#browser-timeout").show();
        }
    } else {
        // Buy a little time to see if map has loaded
        UIHelper.SetMapHomeExtentTimer();
    }
};

UIHelper.ValidateLogin = function() {
    var usr = $("#txtLoginName").val();
    var pwd = $("#txtLoginPassword").val();
    if (usr == "" || pwd == "") {
        UIHelper.HideStatusMessage(false);
        $(".login-error").html(UIHelper.NameAndPasswordRequired + ".");
        $(".login-error").show();
        return;
    }

    $(".login-error").hide();
    UIHelper.ShowStatusMessage(UIHelper.ProcessingLogin, "info");
    var d = new Date();
    $.ajax(
    	{
    	    type: "GET",
    	    url: "Data.aspx",
    	    data: "page=login&usr=" + usr + "&pwd=" + pwd + "&t=" + d.getTime(),
    	    dataType: "json",
    	    error: UIHelper.AjaxError,
    	    success: UIHelper.LoginResults
    	});
};

UIHelper.LoginResults = function(data, status) {
    //alert("UIHelper.LoginResults = " + status);
    if (data.status == "error") {
        $(".login-error").html(data.message);
        $(".login-error").show();
        UIHelper.ShowStatusMessage(UIHelper.LoginFailed, "error");
        return;
    }
    UIHelper.LoginName = data.Name
    UIHelper.StartExtent = data.HomeExtent;

    $("#user-info").html(UIHelper.LoginUser + ": " + data.DisplayName + "&nbsp;&nbsp;&nbsp;&nbsp;" + UIHelper.LoginRole + ": " + data.Role);
    $("#top-area .user-info").show();
    $("#query-map-tab-button").removeClass("active");
    $("#browser-timeout").hide();

    //alert("HomeExtent -->" + data.HomeExtent + "<--, not blank = " + (data.HomeExtent != ""));
    //if (data.HomeExtent != "") $("#HomeExtent").val(data.HomeExtent);

    UIHelper.SiteSetup(false);
    UIHelper.ZoomToHomeExtent();
    UIHelper.SetActiveTab("#queries-tab");
    if (UIHelper.WhatTabAutoLoad) UIHelper.SetActiveInputContent("what");
};

UIHelper.LogoutHasCompleted = function() {
    //alert("UIHelper.LogoutHasCompleted");
    $("#top-area .user-info").hide();
    UIHelper.LoginName = "";
    UIHelper.SiteSetup(true);
    UIHelper.ShowStatusMessage(UIHelper.LogoutComplete, "success");
    //UIHelper.SetActiveTab("#queries-tab");
};

UIHelper.SetActiveTab = function(TabID) {
    // toggle the main map function
    switch (TabID) {
        case "#queries-tab":
            // Is the tab already active?
            if ($("#query-map-tab-button").hasClass("active")) return;

            // Clear any messages
            UIHelper.HideStatusMessage(false);

            // Show the map area and hide the other areas
            $("#print-tab-holder").hide();
            $("#report-tab-holder").hide();
            $("#cyberwatch-tab-holder").hide();
            $("#map-tab-holder").show();

            // Show query function tabs (hidden by CyberWatch preview)
            $(".top-row-buttons").show();
            $("#summary-tab").show();
            $("#cyberwatch-preview-tab").hide();

            // Activate the tab
            $("#query-map-tab-button").addClass("active");

            // Deactivate other tabs
            $("#print-tab-button").removeClass("active");
            $("#report-tab-button").removeClass("active");
            $("#cyberwatch-tab-button").removeClass("active");

            // Set the summary image and description
            $("#analysis-summary-image").attr({ src: UIHelper.QueryIcon, title: UIHelper.QueryTabName, alt: UIHelper.QueryTabName });
            $("#analysis-summary-paragraph").html(UIHelper.QuerySummary);

            if (UIHelper.CyberWatchPreview) {
                UIHelper.CyberWatchPreview = false;
                UIHelper.UpdateMap();
            }

            break;

        case "#cyberwatch-tab":
            // Is the tab already active?
            if ($("#cyberwatch-tab-button").hasClass("active")) return;

            // Show the cyberwatch area and hide the other areas
            $("#map-tab-holder").hide();
            $("#print-tab-holder").hide();
            $("#report-tab-holder").hide();
            $("#cyberwatch-tab-holder").show();

            // Activate the tab
            $("#cyberwatch-tab-button").addClass("active");

            // Deactivate other tabs
            $("#query-map-tab-button").removeClass("active");
            $("#print-tab-button").removeClass("active");
            $("#report-tab-button").removeClass("active");

            // Set the summary image and description
            $("#analysis-summary-image").attr({ src: "images/UI/ico-cyberwatch.jpg", title: UIHelper.CyberWatchTabName, alt: UIHelper.CyberWatchTabName });
            $("#analysis-summary-paragraph").html(UIHelper.CyberWatchSummary);

            UIHelper.HideStatusMessage(true);

            if (!CW.IsLoaded) {
                UIHelper.ShowStatusMessage(UIHelper.LoadingCyberWatch, "info");
                CVS.ShowCyberWatch();
            }

            break;

        case "#report-tab":
            // Is the tab already active?
            if ($("#report-tab-button").hasClass("active")) return;

            // Clear any messages
            UIHelper.HideStatusMessage(false);

            // Show the report area and hide the other areas
            $("#map-tab-holder").hide();
            $("#print-tab-holder").hide();
            $("#cyberwatch-tab-holder").hide();
            $("#report-tab-holder").show();

            // Activate the tab
            $("#report-tab-button").addClass("active");

            // Deactivate other tabs
            $("#query-map-tab-button").removeClass("active");
            $("#print-tab-button").removeClass("active");
            $("#cyberwatch-tab-button").removeClass("active");

            // Set the summary image and description
            $("#analysis-summary-image").attr({ src: "images/UI/ico-reports.gif", title: UIHelper.ReportTabName, alt: UIHelper.ReportTabName });
            $("#analysis-summary-paragraph").html(UIHelper.ReportSummary);

            break;

        case "#print-tab":
            // Is the tab already active?
            if ($("#print-tab-button").hasClass("active")) return;

            // Clear any messages
            UIHelper.HideStatusMessage(false);

            // Show the print area and hide the other areas
            $("#map-tab-holder").hide();
            $("#report-tab-holder").hide();
            $("#cyberwatch-tab-holder").hide();
            $("#print-tab-holder").show();

            // Activate the tab
            $("#print-tab-button").addClass("active");

            // Deactivate other tabs
            $("#query-map-tab-button").removeClass("active");
            $("#report-tab-button").removeClass("active");
            $("#cyberwatch-tab-button").removeClass("active");

            // Set the summary image and description
            $("#analysis-summary-image").attr({ src: "images/UI/ico-print.jpg", title: UIHelper.PrintTabName, alt: UIHelper.PrintTabName });
            $("#analysis-summary-paragraph").html(UIHelper.PrintSummary);

            break;
    }
};

UIHelper.SetActiveInputContent = function(input) {
    var id = "#" + input + "-input-button";

    // Is the tab already active?
    if ($(id).hasClass("active")) {
        UIHelper.HideInputContent(input);
        return;
    }

    switch (input) {
        case "what":

            UIHelper.HideInputContent("how", false);
            UIHelper.HideInputContent("where", false);
            UIHelper.HideInputContent("when", false);

            if (WHAT.IsLoaded) {
                WHAT.ShowContent();
            } else {
                UIHelper.ShowStatusMessage(UIHelper.LoadingWhat, "info");
                CVS.ShowWhat();
            }

            break;

        case "where":

            UIHelper.HideInputContent("how", false);
            UIHelper.HideInputContent("what", false);
            UIHelper.HideInputContent("when", false);

            if (WHERE.IsLoaded) {
                WHERE.ShowContent();
            } else {
                UIHelper.ShowStatusMessage(UIHelper.LoadingWhere, "info");
                CVS.ShowWhere();
            }

            break;

        case "when":

            UIHelper.HideInputContent("how", false);
            UIHelper.HideInputContent("what", false);
            UIHelper.HideInputContent("where", false);

            if (WHEN.IsLoaded) {
                WHEN.ShowContent();
            } else {
                UIHelper.ShowStatusMessage(UIHelper.LoadingWhen, "info");
                CVS.ShowWhen();
            }

            break;

        case "how":

            if ($(".two-buttons li.item-how a").hasClass("disabled")) return;

            UIHelper.HideInputContent("what", false);
            UIHelper.HideInputContent("where", false);
            UIHelper.HideInputContent("when", false);

            if (HOW.IsLoaded) {
                HOW.DefineQueryLayers();
            } else {
                UIHelper.ShowStatusMessage(UIHelper.LoadingHow, "info");
                CVS.ShowHow();
            }

            break;
    }

    $(id).addClass($(id).attr("class") + " active");
    $(".two-buttons li.item-" + input + " a").addClass("active");
};

UIHelper.HideInputContent = function(input, slide) {
    if (arguments.length > 1) {
        $("#" + input + "-content").hide();
    } else {
        $("#" + input + "-content").slideUp("fast");
    }

    var tabID = "#" + input + "-input-button";

    if ($(tabID)) {
        if ($(tabID).attr("class").indexOf(" active") >= 0) {
            var inactiveClass = $(tabID).attr("class").replace(" active", "");

            $(tabID).removeClass(inactiveClass + " active");
            $(tabID).addClass(inactiveClass);
        }
        $(".two-buttons li.item-" + input + " a").removeClass("active");
    }

};

UIHelper.ShowInfo = function(info, title) {
    var url = "Data.aspx?page=" + info;
    var target = document.getElementById("info-content");

    UIHelper.HideAllInputContent();

    if (this.ShowInfo.arguments.length == 2) {
        $("#info-title").html(title);
    } else {
        $("#info-title").html(info);
    }
    $("#info-content").html("");
    //$("#info-content-holder").slideDown("normal");
    $("#info-content-holder").show("drop", {}, 500);

    _dynoLoader._loadXmlDocument(url, target, null, null, false);
};
UIHelper.HideInfo = function() {
    //$("#info-content-holder").slideUp("fast");
    $("#info-content-holder").hide("drop", {}, 500);
};

UIHelper.ToggleTab = function(tab) {
    $("#" + tab + "-tab").slideToggle("fast");
};

UIHelper.HideTabContent = function(TabID) {
    var dropDownElement = "#" + TabID + "-drop-down";
    var parentTabElement = "#" + TabID + "-tab";
    var imageElement = null;

    if ($(parentTabElement + " a span.up-down").hasClass("up-down")) {
        imageElement = $(parentTabElement + " a span.up-down");
        imageElement.removeClass("up-down");
        imageElement.addClass("down-up");
        //$(dropDownElement).slideUp('fast');
        $(dropDownElement).hide();
    }
};

UIHelper.ShowTabContent = function(TabID) {
    var dropDownElement = "#" + TabID + "-drop-down";
    var parentTabElement = "#" + TabID + "-tab";
    var imageElement = null;

    if ($(parentTabElement + " a span.down-up").hasClass("down-up")) {
        imageElement = $(parentTabElement + " a span.down-up");
        imageElement.removeClass("down-up");
        imageElement.addClass("up-down");
        $(dropDownElement).slideDown('fast');
    }
};

UIHelper.ToggleTabContent = function(TabID) {
    var dropDownElement = "#" + TabID + "-drop-down";
    var parentTabElement = "#" + TabID + "-tab";
    var imageElement = null;

    if ($(parentTabElement + " a span.up-down").hasClass("up-down")) {
        imageElement = $(parentTabElement + " a span.up-down");
        imageElement.removeClass("up-down");
        imageElement.addClass("down-up");
        $(dropDownElement).slideUp('fast');
    } else if ($(parentTabElement + " a span.down-up").hasClass("down-up")) {
        imageElement = $(parentTabElement + " a span.down-up");
        imageElement.removeClass("down-up");
        imageElement.addClass("up-down");
        $(dropDownElement).slideDown('fast');
    }
};

UIHelper.ExpandSummaryItem = function(SummaryItemID) {
    var dropDownElement = "#" + SummaryItemID + "-drop-down";
    var headingElement = "#" + SummaryItemID + "-heading";

    $(dropDownElement).slideToggle('fast');
    $(headingElement).toggleClass('expand');
};

UIHelper.ShowIdentifyResults = function() {
    UIHelper.HideTabContent("toc");
    UIHelper.HideTabContent("overview-map");
    UIHelper.HideTabContent("map-cache");
    UIHelper.HideTabContent("bookmarks");
    //UIHelper.HideTabContent("charts");
    UIHelper.HideTabContent("summary");

    $("#identify-tab").show();
    UIHelper.ShowTabContent("identify");
};

UIHelper.ShowBrowserInfo = function() {
    UIHelper.HideAllInputContent();

    BROWSER.GetInfo();
    var s = "Browser = " + BROWSER.Name
		  + "<br/>Version = " + BROWSER.Version
          + "<br/>Cookies = " + BROWSER.Cookies
		  + "<br/>Platform = " + BROWSER.Platform;

    $("#info-title").html("Browser Information");
    $("#info-content").html(s);
    //$("#info-content-holder").slideDown("normal");
    $("#info-content-holder").show("drop", {}, 500);
};

UIHelper.ShowErrorInfo = function(title, content) {
    UIHelper.HideAllInputContent();

    $("#info-title").html(title);
    $("#info-content").html(content);
    $("#info-content-holder").show("drop", {}, 500);
};


UIHelper.ProcessMapCacheRequest = function() {
    $("#QueryType").val("cache");
    $("#WhatQuery").val($("#lstMapCaches").val());

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.ProcessBookmarkRequest = function() {
    $("#QueryType").val("book");
    $("#WhatQuery").val($("#lstBookMarks").val());

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.ProcessMapLinkRequest = function(id) {
    $("#QueryType").val("link");
    $("#WhatQuery").val(id);

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.CrystalReportLayerSelected = function() {
    //alert("UIHelper.ProcessCrystalRequest = " + $("#lstReportLayers").val());
    $("#QueryType").val("reports");
    $("#WhatQuery").val($("#lstReportLayers").val());

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.LoadSelectedCrystalReport = function(params) {
    //alert("UIHelper.LoadSelectedCrystalReport = " + params);
    $("#QueryType").val("report");
    $("#WhatQuery").val(params);

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.SwitchDrilldownTab = function(type) {
    //alert("UIHelper.SwitchDrilldownTab = " + type);
    UIHelper.ShowStatusMessage(UIHelper.RefreshingMapForChartGrid, "info");

    $("#QueryType").val(type);
    $("#WhatQuery").val(UIHelper.WhatQuery);
    $("#WhereQuery").val(UIHelper.WhereQuery);
    $("#WhenQuery").val(UIHelper.WhenQuery);

    UIHelper.HideAllInputContent();

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.UpdateMap = function() {
    if ($(".two-buttons li.item-update-map a").hasClass("disabled")) return;
    //alert("UIHelper.UpdateMap = " + UIHelper.WhatQuery);
    UIHelper.ShowStatusMessage(UIHelper.ProcessingUpdate, "info");

    $("#QueryType").val(HOW.MapType);
    $("#WhatQuery").val(UIHelper.WhatQuery);
    $("#WhereQuery").val(UIHelper.WhereQuery);
    $("#WhenQuery").val(UIHelper.WhenQuery);

    switch (HOW.MapType) {
        case "density":
            $("#HowQuery").val(HOW.QueryLayerID + "|" + HOW.UseBoundarySubset + "|" + HOW.GeographyLayerID + "|" + HOW.Classify);
            break;

        case "repeat":
            $("#HowQuery").val(HOW.QueryLayerID + "|" + HOW.UseBoundarySubset + "|" + HOW.RepeatPoints + "|" + HOW.OnlyIncludeTop);
            break;
    }

    UIHelper.HideAllInputContent();

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.UpdateChartDrilldownMap = function() {
    UIHelper.ShowStatusMessage(UIHelper.ProcessingChartDrilldown, "info");

    // Set the type of map function to perform
    $("#QueryType").val("drilldown");
    $("#WhatQuery").val(CHART.WhatQuery);
    $("#WhereQuery").val(UIHelper.WhereQuery);
    $("#WhenQuery").val(CHART.WhenQuery);

    UIHelper.HideAllInputContent();

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.UpdateGridDrilldownMap = function() {
    UIHelper.ShowStatusMessage(UIHelper.ProcessingGridDrilldown, "info");

    // Set the type of map function to perform
    $("#QueryType").val("drilldown");
    $("#WhatQuery").val(GRID.LayerQuery);
    $("#WhereQuery").val(UIHelper.WhereQuery);
    $("#WhenQuery").val(GRID.WhenQuery);

    UIHelper.HideAllInputContent();

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.UpdateCyberWatchMap = function() {
    CW.BuildWhatQuery();

    UIHelper.CyberWatchPreview = false; // Queries tab will requery if this is true. Don't want that now. Only when leaving CW tab.
    UIHelper.SetActiveTab("#queries-tab");
    UIHelper.ShowStatusMessage(UIHelper.ProcessingCyberWatch, "info");

    //alert("UIHelper.UpdateCyberWatchMap");
    // Set the type of map function to perform
    $("#QueryType").val("cyberwatch");
    $("#WhatQuery").val(CW.WhatQuery);
    $("#WhereQuery").val(CW.WhereQuery);
    $("#WhenQuery").val("");

    UIHelper.HideAllInputContent();
    $(".top-row-buttons").hide();
    $("#summary-tab").hide();

    //UIHelper.HideTabContent("identify");
    UIHelper.HideTabContent("toc");
    UIHelper.HideTabContent("overview-map");
    UIHelper.HideTabContent("map-cache");
    UIHelper.HideTabContent("bookmarks");
    //UIHelper.HideTabContent("charts");
    UIHelper.HideTabContent("summary");

    $("#cyberwatch-preview-tab").show();

    UIHelper.CyberWatchPreview = true;

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.ResetMap = function(logout) {
    //alert("UIHelper.ResetMap = " + logout);
    if (logout) {
        UIHelper.ShowStatusMessage(UIHelper.LoggingOut, "info");
        $("#QueryType").val("logout");
        $("#WhatQuery").val(UIHelper.LoginName);
        UIHelper.TotalQueryRecs = 0;
        UIHelper.ResetControls();
    } else {
        UIHelper.ShowStatusMessage(UIHelper.ResettingMap, "info");
        $("#QueryType").val("reset");
    }

    WHAT.Init();
    WHEN.Init();
    WHERE.Init();
    HOW.Init();

    UIHelper.HideAllInputContent();

    UIHelper.HideTabContent("toc");
    UIHelper.HideTabContent("overview-map");
    UIHelper.HideTabContent("map-cache");
    UIHelper.HideTabContent("bookmarks");

    $("#lstMapCaches").attr("selectedIndex", 0);
    $("#WhereQuery").val($("#lstMapCaches").val()); // Not really a where, but What is being used


    $("#status-message-box").fadeOut('fast');

    CVS.BuildSummaryDisplay();
    UIHelper.DisableUpdateMapButton(true);

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.DisableUpdateMapButton = function(yes) {
    if (yes) {
        if ($(".two-buttons li.item-update-map a").hasClass("disabled")) return;

        $(".two-buttons li.item-update-map a").removeClass("highlight");
        $(".two-buttons li.item-update-map a").addClass("disabled");
        $(".two-buttons li.item-update-map span").addClass("disabled");

        $(".two-buttons li.item-how a").addClass("disabled");
        $(".two-buttons li.item-how span").addClass("disabled");
    } else {
        $(".two-buttons li.item-update-map a").removeClass("disabled");
        $(".two-buttons li.item-update-map span").removeClass("disabled");

        $(".two-buttons li.item-how a").removeClass("disabled");
        $(".two-buttons li.item-how span").removeClass("disabled");
    }
};

UIHelper.DisableResetButton = function(yes) {
    if (yes) {
        if ($(".two-buttons li.item-reset-map a").hasClass("disabled")) return;

        $(".two-buttons li.item-reset-map a").addClass("disabled");
        $(".two-buttons li.item-reset-map span").addClass("disabled");
    } else {
        $(".two-buttons li.item-reset-map a").removeClass("disabled");
        $(".two-buttons li.item-reset-map span").removeClass("disabled");
    }
};

UIHelper.IndicatePendingChanges = function(yes) {
    if (yes) {
        if ($(".two-buttons li.item-update-map a").hasClass("highlight")) return;
        if (WHAT.IsValid) $(".two-buttons li.item-update-map a").addClass("highlight");
    } else {
        $(".two-buttons li.item-update-map a").removeClass("highlight");
    }
};

UIHelper.HideAllInputContent = function() {
    UIHelper.HideInputContent("what", false);
    UIHelper.HideInputContent("where", false);
    UIHelper.HideInputContent("when", false);
    UIHelper.HideInputContent("how", false);
};

UIHelper.ResetControls = function() {
    var toolbarName = "mapToolBar";
    var f = document.forms[docFormID];
    var type = $("#QueryType").val();

    if (UIHelper.TotalQueryRecs == 0) {
        if (f.elements[Toolbars[toolbarName].currentToolField].value == "MapIdentify") {
            f.elements[Toolbars[toolbarName].currentToolField].value = "MapZoomIn";
            // Set the javascript function that will be run for MapPan
            MapDragRectangle("Map1", "MapZoomIn", true, "");
            // Select the tool and refresh the toolbar
            f.elements[Toolbars[toolbarName].selectTool()];
        }
        mapToolBar_Items["MapIdentify"].disabled = true;
        $("#mapToolBarMapIdentify").unbind("click");
        mapToolBar_Items["ZoomToSelected"].disabled = true;

        // Hide content tabs
        $("#toc-tab").hide();
    } else {
        mapToolBar_Items["MapIdentify"].disabled = false;
        mapToolBar_Items["ZoomToSelected"].disabled = false;
        // Add a message to the Identify tool when set active
        switch (type) {
            case "density":
                $("#mapToolBarMapIdentify").bind("click", function(e) { UIHelper.ShowStatusMessage(UIHelper.IdentifyDensity, "warning"); });
                break;
            case "repeat":
                $("#mapToolBarMapIdentify").bind("click", function(e) { UIHelper.ShowStatusMessage(UIHelper.IdentifyRepeat, "warning"); });
                break;
            default:
                $("#mapToolBarMapIdentify").bind("click", function(e) { UIHelper.ShowStatusMessage(UIHelper.IdentifyPoints, "warning"); });
                break;
        }

        // Show content tabs
        $("#toc-tab").show();
    }
    f.elements[Toolbars[toolbarName].refreshGroup()];
    f.elements[Toolbars[toolbarName].refreshCommands()];

    document.getElementById("print-frame").src = "";

    // Initialize misc content
    if (UIHelper.CyberWatchPreview || UIHelper.TotalQueryRecs == 0) {
        // Disable the reports and charts
        $("#report-tab a").unbind("click");
        $("#report-tab a").addClass("disabled");
        document.getElementById("report-frame").src = "";

        $("#charts-tab").hide();
        $("#grid-tab").hide();

        if (type == "reset" && UIHelper.StartExtent != "") UIHelper.ZoomToHomeExtent();
    } else {
        // Enable the reports and charts
        $("#report-tab a").bind("click", function(e) { UIHelper.SetupReportTab(); });
        $("#report-tab a").removeClass("disabled");

        if (type == "pin" || type == "link" || type == "showchart" || type == "showgrid") {
            $("#charts-tab").show();
            $("#grid-tab").show();
        } else {
            $("#charts-tab").hide();
            $("#grid-tab").hide();
        }
    }

    $("#identify-tab").hide();
    $("#bar-chart-data").html("");
    $("#pie-chart-data").html("");
    $("#grid-data").html("");

    UIHelper.HideTabContent("charts");
    UIHelper.HideTabContent("grid");
};

UIHelper.UpdateComplete = function(statusMsg, statusType, totRecs, maxExceeded, id) {
    //alert("IHelper.UpdateComplete = " + maxExceeded);
    UIHelper.TimeoutTotal = 1;  // The total needs to eventually exceed the max, not equal it
    UIHelper.SetTimer();
    $("#browser-timeout").hide();

    UIHelper.TotalQueryRecs = totRecs;
    UIHelper.QueryMaxExceeded = (maxExceeded == "True");

    UIHelper.ShowStatusMessage(statusMsg, statusType);

    UIHelper.IndicatePendingChanges(false);

    UIHelper.CurrentQueryID = id;

    if ($("#QueryType").val() != "drilldown" &&
        $("#QueryType").val() != "newchart" &&
        $("#QueryType").val() != "newgrid") UIHelper.ResetControls();
};

UIHelper.SetTimer = function() {
    clearTimeout(UIHelper.Timer);
    UIHelper.Timer = setTimeout("UIHelper.Timeout()", UIHelper.TimeoutInterval);
};
UIHelper.Timeout = function() {
    //alert("UIHelper.Timeout");
    UIHelper.TimeoutTotal += UIHelper.TimeoutInterval;
    if (UIHelper.TimeoutTotal > UIHelper.TimeoutMaximum) {
        window.location = "Inactive.aspx";
    } else {
        UIHelper.SetTimer();
        //UIHelper.ShowStatusMessage("Timeout total = " + UIHelper.TimeoutTotal + ", Max = " + UIHelper.TimeoutMaximum, "warning");

        if (UIHelper.TimeoutTotal + UIHelper.TimeoutInterval > UIHelper.TimeoutESRI) {
            // Reset the client side timeout
            ESRI.ADF.System.__lastResponseRecievedTime = new Date();

            $("#QueryType").val("notyet");
            __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
        }
    }
};
UIHelper.TimeoutCallback = function() {
    // The timeout does a zoom to selected to force a server side map call
    // This will move the current extent, so put the map back where it was
    // Clugey, but it keeps the ADF from timing out
    //alert("UIHelper.TimeoutCallback");
    var map = $find("Map1");
    //map.stepExtentHistory(-1);

    var minsLeft = parseInt(((UIHelper.TimeoutMaximum - UIHelper.TimeoutTotal) / 60000));
    var when = new Date();
    when.setMinutes(when.getMinutes() + minsLeft);
    var hour = when.getHours();
    var min = when.getMinutes();
    var ampm = " AM";
    if (hour > 11) ampm = " PM";
    if (hour > 12) hour -= 12;
    if (min < 10) min = "0" + min;
    var msg = "Idle: " + parseInt(UIHelper.TimeoutTotal / 60000) + " minutes<br/>"
            + "Timeout at " + hour + ":" + min + ampm;

    $("#browser-timeout").html(msg);
    $("#browser-timeout").show();
};

UIHelper.ShowDelayedStatusMessage = function(statusMsg, statusType) {
    setTimeout("UIHelper.ShowStatusMessage('" + statusMsg + "','" + statusType + "')", 7000); // 7 seconds
};
UIHelper.ShowStatusMessage = function(statusMsg, statusType) {
    var closeImg = "&nbsp;&nbsp;&nbsp;<img src=\"images/ui/close_" + statusType + ".jpg\" onclick=\"$('#status-message-box').fadeOut('slow');\" title=\"close\" alt=\"close\">";

    $("#status-message-box #status-image").html(closeImg);
    $("#status-message-box #status-message").html(statusMsg);

    $("#status-message-box").removeAttr("class");
    $("#status-message-box").addClass(statusType);

    if (jQuery.browser.msie) {
        // IE 6 won't handle the class change correctly so override the style manually (lame)
        if (parseInt(jQuery.browser.version) < 7) {
            switch (statusType) {
                case "info":
                    back = "#BFD9F0";
                    borderTL = "#F3F6FF";
                    borderBR = "#9FC6E9";
                    break;

                case "warning":
                    back = "#f9f090";
                    borderTL = "#fffff0";
                    borderBR = "#F0CF00";
                    break;

                case "error":
                    back = "#ff9999";
                    borderTL = "#fff0f0";
                    borderBR = "#cf3f3f";
                    break;

                case "success":
                    back = "#c0ffc0";
                    borderTL = "#f0fff0";
                    borderBR = "#6fcf6f";
                    break;
            }
            var s = "background-color:" + back +
                    ";border-top: 2px solid " + borderTL +
                    ";border-left: 2px solid " + borderTL +
                    ";border-bottom: 2px solid " + borderBR +
                    ";border-right: 2px solid " + borderBR + ";";
            $("#status-message-box").attr("style", s);
        }
    }

    $("#status-message-box").fadeIn("fast");
};

UIHelper.HideStatusMessage = function(IsFading) {
    if (IsFading) {
        $('#status-message-box').fadeOut('fast');
    }

    $('#status-message-box').hide();
};

UIHelper.ShowPrint = function() {
    if ($("#print-tab-button").hasClass("active")) return;

    UIHelper.HideAllInputContent();

    var winSize = CVS.GetClientSize();
    $("#print-info").css("height", winSize.y - 165);
    $("#print-info").css("width", 400);
    $("#print-frame").css("height", winSize.y - 165);
    $("#print-frame").css("width", winSize.x - 165 - 25);   //Include scroll bar

    UIHelper.ShowPrintInfo();

    // Make the print tab the active one
    UIHelper.SetActiveTab("#print-tab");

    //var s = "To continue working with the incident map, click the Map Tab above."
    //UIHelper.ShowStatusMessage(s, "warning");
};

UIHelper.ShowPrintInfo = function() {
    $("#print-frame").hide();
    $("#print-info").show();
};

UIHelper.ShowPrintFrame = function() {
    $("#print-info").hide();
    $("#print-frame").show();
};

UIHelper.CreateMapImage = function() {
    $("#QueryType").val("print");
    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

UIHelper.CreatePDF = function() {
    var d = new Date();
    var obj = document.getElementById("print-frame");
    var title = document.getElementById("txtPrintTitle").value;
    var subtitle = document.getElementById("txtPrintSubTitle").value
    var url = "CreatePDF.aspx?id=" + d.getTime() + "&title=" + title + "&subtitle=" + subtitle;
    var dt = "";
    
    if (HOW.MapType != "pin") dt = HOW.Classify;
    url += "&maptype=" + HOW.MapType + "&dt=" + dt;

    UIHelper.ShowPrintFrame();

    obj.src = url;
};

UIHelper.BuildReportLayersArea = function(data) {
    // {reportcount:2,reports:{0:{id:'12', name:'onetwo'},1:{id:'34', name:'threefour'}}
    // ,chartcount:1,charts:{0:{rid:'12',lid:'ab', name:'onetwo'},1:{rid:'34',lid:'cd', name:'threefour'}}
    // ,gridcount:1,grids:{0:{rid:'12',lid:'ab', name:'onetwo'},1:{rid:'34',lid:'cd', name:'threefour'}}
    // }
    //alert("UIHelper.BuildReportLayersArea = " + data.count);
    if (data.reportcount == 0) {
        $("#report-layers-list").html("");
        $("#report-layers-area").hide();

        // Disable the reports and charts
        $("#report-tab a").unbind("click");
        $("#report-tab a").addClass("disabled");
        document.getElementById("report-frame").src = "";

        $("#charts-tab").hide();
        $("#grid-tab").hide();
        return;
    }

    var numReportLayers = data.reportcount;
    var reports = data.reports;
    var charts = data.charts;
    var grids = data.grids;
    var onchange, reportList, chartList, gridList, showList, type, idx;
    var numChartLayers, numGridLayers;

    if (UIHelper.ReportStyle == "crystal") {
        onchange = 'UIHelper.CrystalReportLayerSelected();';
    } else {
        onchange = 'UIHelper.SilverlightReportLayerSelected();';
    }

    reportList = '<select id="lstReportLayers" onchange="' + onchange + '" size="3">';
    reportList += '<option selected="selected" value="' + reports[0].id + '">' + reports[0].name + '</option>';
    for (idx = 1; idx < numReportLayers; idx++) {
        reportList += '<option value="' + reports[idx].id + '">' + reports[idx].name + '</option>';
    }
    reportList += '</select>';

    $("#report-layers-list").html(reportList);
    if (numReportLayers > 1) {
        $("#report-layers-area").show();
    } else {
        $("#report-layers-area").hide();
    }
    //alert("selected = " + $("#lstReportLayers").val());

    // Charts
    //alert("UIHelper.BuildReportLayersArea Chart count = " + data.chartcount + ", type = " + $("#QueryType").val());
    type = $("#QueryType").val();
    if (type == "pin" || type == "link" || type == "showchart") {
        showList = false;
        chartList = ""
        numChartLayers = data.chartcount;
        if (numChartLayers > 0) {
            if (numReportLayers > 1 || numChartLayers > 1) showList = true;

            if (showList) {
                UIHelper.ChartIDs = "";
            } else {
                UIHelper.ChartIDs = charts[0].rid + "|" + charts[0].lid
            }
            chartList = "<ul id=\"lstChartLayers\" class=\"chart-list\">";
            for (idx = 0; idx < numChartLayers; idx++) {
                chartList += "<li><a onclick=\"UIHelper.ChartLayerSelected('" + charts[idx].lid + "')\">" + charts[idx].name + "</a></li>";
            }
            chartList += '</ul>';
        } else {
            $("#charts-tab").hide();
        }

        $("#chart-layers-list").html(chartList);
        if (showList) {
            $("#chart-layers-area").show();
        } else {
            $("#chart-layers-area").hide();
        }
    } else if (type == "newchart") {
        UIHelper.ChartIDs = charts[0].rid + "|" + charts[0].lid
        UIHelper.GetRecsForChart();
    }

    // Grids
    //alert("UIHelper.BuildReportLayersArea Grid count = " + data.gridcount);
    if (type == "pin" || type == "link" || type == "showgrid") {
        showList = false;
        gridList = ""
        numGridLayers = data.gridcount;
        if (numGridLayers > 0) {
            if (numReportLayers > 1 || numGridLayers > 1) showList = true;

            if (showList) {
                UIHelper.GridIDs = "";
            } else {
                UIHelper.GridIDs = grids[0].rid + "|" + grids[0].lid
            }
            gridList = "<ul id=\"lstGridLayers\" class=\"chart-list\">";
            for (idx = 0; idx < numGridLayers; idx++) {
                gridList += "<li><a onclick=\"UIHelper.GridLayerSelected('" + grids[idx].lid + "')\">" + grids[idx].name + "</a></li>";
            }
            gridList += '</ul>';
        } else {
            $("#grid-tab").hide();
        }

        $("#grid-layers-list").html(gridList);
        if (showList) {
            $("#grid-layers-area").show();
        } else {
            $("#grid-layers-area").hide();
        }
    } else if (type == "newgrid") {
        UIHelper.GridIDs = grids[0].rid + "|" + grids[0].lid
        UIHelper.GetRecsForGrid();
    }

    // The show types are used when toggling from charts to grid etc.
    // Because they are drilldown implementors, they cannot both be open at the same time.
    if (type == "showchart") UIHelper.ShowCharts();
    if (type == "showgrid") UIHelper.ShowGrid();
};

UIHelper.SilverlightReportLayerSelected = function() {
    //    alert("UIHelper.SilverlightReportLayerSelected = " + $("#lstReportLayers").val() +
    //        ", Do not have object = " + (!UIHelper.SilverlightReports));
    if (!UIHelper.SilverlightReports) {
        $.ajax(
    	{
    	    type: "GET",
    	    url: "Data.aspx",
    	    data: "page=silverlightreports",
    	    dataType: "json",
    	    error: UIHelper.AjaxError,
    	    success: UIHelper.SaveSilverlightReportsObject
    	});
    } else {
        UIHelper.BuildSilverlightReportList();
    }
};
UIHelper.AjaxError = function(msg) {
    alert("UIHelper.AjaxError = " + msg);
};
UIHelper.SaveSilverlightReportsObject = function(data, status) {
    //alert("UIHelper.SaveSilverlightReportsObject = " + data.count);
    UIHelper.SilverlightReports = data;
    UIHelper.BuildSilverlightReportList();
};

UIHelper.BuildSilverlightReportList = function() {
    //alert("UIHelper.BuildSilverlightReportList lst = " + $("#lstReportLayers").val() +
    //        ", data = " + UIHelper.SilverlightReports.layers[0].layerid);
    var idx;
    var lyrID = $("#lstReportLayers").val();
    var reports = null;

    // {count: 1, layers: [{layerid: "{5ca34365-ad28-4e19-a682-01716adb13b5}", reports: [{filename: "IncidentDetail", displayname: "Incident Detail"}, {filename: "IncidentSummary", displayname: "Incident Summary"}] }] }
    for (idx = 0; idx < UIHelper.SilverlightReports.count; idx++) {
        if (UIHelper.SilverlightReports.layers[idx].layerid == lyrID) {
            reports = UIHelper.SilverlightReports.layers[0].reports
            break;
        }
    }

    if (reports == null) {
        $("#reports-list").html("No reports found");
        return;
    }

    alert("UIHelper.BuildSilverlightReportList reports.length = " + reports.length);

    var s = "<ul id=\"lstAvailableReports\" class=\"report-list\">";
    for (idx = 0; idx < reports.length; idx++) {
        s += "<li><a onclick=\"UIHelper.ShowSilverlightReport('" + reports[idx].filename + "')\">" + reports[idx].displayname + "</a></li>";
    }
    s += '</ul>';

    $("#reports-list").html(s);
};

UIHelper.BuildCrystalReportList = function(data) {
    // {count:3,reportID:xyz,items:{0:{id:'12', name:'onetwo'},1:{id:'34', name:'threefour'}}}
    //alert("UIHelper.BuildCrystalReportList = " + data.count);
    var numReports = data.count;
    var reportID = data.reportID;
    var items = data.items;

    var s = "<ul id=\"lstAvailableReports\" class=\"report-list\">";
    for (var idx = 0; idx < numReports; idx++) {
        s += "<li><a onclick=\"UIHelper.LoadSelectedCrystalReport('" + reportID + "|" + items[idx].id + "|" + items[idx].name + "')\">" + items[idx].name + "</a></li>";
    }
    s += '</ul>';

    $("#reports-list").html(s);
};

UIHelper.SetupReportTab = function() {
    if (UIHelper.ReportStyle == "crystal") {
        UIHelper.CrystalReportLayerSelected();
    } else {
        UIHelper.SilverlightReportLayerSelected();
    }

    UIHelper.HideAllInputContent();

    //    var winSize = CVS.GetClientSize();

    //    $('#report-frame').css('height', CVS.IFrameHeight);
    //    $('#report-frame').css('width', winSize.x - 225);

    // This function should only be run the first time the report tab is clicked
    // after a new query has been run. Change the report tab function from initializing
    // to just making the tab visible (active)
    $("#report-tab a").unbind("click");
    $("#report-tab a").bind("click", function(e) { UIHelper.SetActiveTab('#report-tab'); });

    UIHelper.SetActiveTab('#report-tab');
};
UIHelper.ShowSilverlightReport = function(rid) {
    var d = new Date();

    //    UIHelper.ShowStatusMessage("Loading Report Viewer...", "info");
    //    CVS.ShowReport();

    var obj = document.getElementById("report-frame");
    var url = "http://localhost/ReportViewerService/Report.aspx?dt=" + d.getTime() +
        "&h=" + (CVS.IFrameHeight - 20) + "&q=" + UIHelper.CurrentQueryID + "&l=" + $("#lstReportLayers").val() + "&r=CrimeDetail";
    alert("Silverlight url=" + url + ", obj=" + obj);
    obj.src = url;
};
UIHelper.ShowCrystalReport = function(name) {
    var d = new Date();

    var obj = document.getElementById("report-frame");
    var url = "CrystalReport.aspx?id=" + d.getTime();

    //alert("url=" + url + ", obj=" + obj);
    obj.src = url;
};
UIHelper.ShowCharts = function() {
    //alert("UIHelper.ShowCharts = " + $("#charts-tab").css("display"));
    if ($("#charts-tab a span.up-down").hasClass("up-down")) {
        // Closing the chart tab, put the map back to the original query
        UIHelper.UpdateMap();
    } else {
        if (UIHelper.QueryMaxExceeded) {
            $("#pie-chart-header").html("<p>" + UIHelper.MaxLimitChart + "</p>");
            $("#bar-chart-header").html("");
            $("#chart-layers-area").hide();
            $("#all-dates-link").hide();
        } else {
            if ($("#grid-tab a span.up-down").hasClass("up-down")) {
                // Can't do charts if grid is open
                UIHelper.HideTabContent("grid");
                UIHelper.SwitchDrilldownTab("showchart");
                return;
            }
            if (UIHelper.ChartIDs == "") {
                $("#pie-chart-header").html("");
                $("#bar-chart-header").html("");
                $("#all-dates-link").hide();
            } else {
                UIHelper.GetRecsForChart();
            }
        }
    }
    UIHelper.ToggleTabContent("charts");
};
UIHelper.GetRecsForChart = function() {
    $("#pie-chart-header").html("<p>" + UIHelper.BuildingChart + "</p>");
    $("#QueryType").val("chart");
    $("#WhatQuery").val(UIHelper.ChartIDs);
    $("#WhenQuery").val(UIHelper.WhenQuery);

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};
UIHelper.ChartLayerSelected = function(lyrID) {
    CHART.LayerID = lyrID;
    $("#pie-chart-header").html("<p>" + UIHelper.BuildingChart + "</p>");
    $("#QueryType").val("newchart");
    $("#WhatQuery").val(WHAT.GetLayerQuery(lyrID));
    $("#WhenQuery").val(UIHelper.WhenQuery);

    //alert("UIHelper.ChartLayerSelected WhatQuery = " + $("#WhatQuery").val());

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};
UIHelper.ShowGrid = function() {
    //alert("UIHelper.ShowGrid = " + $("#grid-tab").css("display"));
    if ($("#grid-tab a span.up-down").hasClass("up-down")) {
        // Closing the temporal grid tab, put the map back to the original query
        UIHelper.UpdateMap();
    } else {
        if (UIHelper.QueryMaxExceeded) {
            $("#grid-header").html("<p>" + UIHelper.MaxLimitGrid + "</p>");
            $("#grid-layers-area").hide();
            $("#grid-links").hide();
            $("#grid-stats").hide();
        } else {
            if ($("#charts-tab a span.up-down").hasClass("up-down")) {
                // Can't do grid if charts are open
                UIHelper.HideTabContent("charts");
                UIHelper.SwitchDrilldownTab("showgrid");
                return;
            }
            if (UIHelper.GridIDs == "") {
                $("#grid-header").html("");
            } else {
                UIHelper.GetRecsForGrid();
            }
        }
    }
    UIHelper.ToggleTabContent("grid");
};
UIHelper.GetRecsForGrid = function() {
    $("#grid-header").html("<p>" + UIHelper.BuildingGrid + "</p>");
    $("#QueryType").val("grid");
    $("#WhatQuery").val(UIHelper.GridIDs);
    $("#WhenQuery").val(UIHelper.WhenQuery);

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};
UIHelper.GridLayerSelected = function(lyrID) {
    CHART.LayerID = lyrID;
    $("#grid-header").html("<p>" + UIHelper.BuildingGrid + "</p>");
    $("#QueryType").val("newgrid");
    $("#WhatQuery").val(WHAT.GetLayerQuery(lyrID));
    $("#WhenQuery").val(UIHelper.WhenQuery);

    //alert("UIHelper.GridLayerSelected WhatQuery = " + $("#WhatQuery").val());

    __doPostBack('btnUpdateMap', '')    // Not sure this is valid, but it works
};

