var strSelectedTool = "zoomextent";
var boolToolbarFade = false;
var boolLoadMapAuthor = false;

function doPrint()
{
    // Display or hide the legend when printing by removing or setting the class to "displayOnly" respectively.
    if (document.getElementById("chkPrintLegend").checked)
    {
        var objChkLegendDataLayer = document.getElementById("frmLegend").chkLegendDataLayer;
        var objChkLegendContextLayer = document.getElementById("frmLegend").chkLegendContextLayer;
        var objChkMapitLayer = document.getElementById("frmLegend").chkLegendMapitLayer;

        var strPrintLegend = "<table cellspacing='0' cellpadding='0' border='0'>";

        // Display the data header.
        strPrintLegend += "    <tr>";
        strPrintLegend += "        <td colspan='2' style='font-weight: bold'>" + document.getElementById("divHeaderData").innerHTML + "<\/td>";
        strPrintLegend += "    <\/tr>";

        // Add the mapit layer to the printable legend if applicable.
        if ((objChkMapitLayer!= undefined) && (objChkMapitLayer.checked))
        {
            strPrintLegend += "    <tr>";
            strPrintLegend += "        <td style='padding-left: 15px; padding-top: 2px''><img src='" + document.getElementById("imgMapit").src + "' title='' alt='' /><\/td>";
            strPrintLegend += "        <td style='padding-left: 4px; padding-top: 2px''>" + document.getElementById("tblRowMapit").innerHTML + "<\/td>";
            strPrintLegend += "    <\/tr>";
        }

        // Ensure that there are data layers.
        if (objChkLegendDataLayer)
        {
            // Get a count of data layer checkboxes.
            var intCheckCount = ((objChkLegendDataLayer.length == null) || (objChkLegendDataLayer.length == undefined)) ? 1 : objChkLegendDataLayer.length;

            // Loop through the data layer checkboxes and build printable legend based on selections.
            for (intCounter = 0; intCounter < intCheckCount; intCounter ++)
            {
                // Check to see if there is only 1 data layer row (1 data layer row gives an undefined length count).
                var objTempCheck = (intCheckCount == 1) ? objChkLegendDataLayer : objChkLegendDataLayer[intCounter];

                if (objTempCheck.checked)
                {
                    strPrintLegend += "    <tr>";
                    strPrintLegend += "        <td style='padding-left: 15px; padding-top: 2px'><img src='" + document.getElementById("imgData" + intCounter).src + "' title='' alt='' /><\/td>";
                    strPrintLegend += "        <td style='padding-left: 4px; padding-top: 2px'>" + document.getElementById("tblRowLegendData" + intCounter).innerHTML + "<\/td>";
                    strPrintLegend += "    <\/tr>";
                }
            }
        }

        // Add an empty row.
        strPrintLegend += "    <tr><td colspan='2' style='height: 5px'><\/td><\/tr>";

        // Display the context header.
        strPrintLegend += "    <tr>";
        strPrintLegend += "        <td colspan='2' style='font-weight: bold'>" + document.getElementById("divHeaderContext").innerHTML + "<\/td>";
        strPrintLegend += "    <\/tr>";

        // Ensure that there are context layers.
        if (objChkLegendContextLayer)
        {
            // Get a count of context layer checkboxes.
            var intCheckCount = ((objChkLegendContextLayer.length == null) || (objChkLegendContextLayer.length == undefined)) ? 1 : objChkLegendContextLayer.length;

            // Loop through the context layer checkboxes and build printable legend based on selections.
            for (intCounter = 0; intCounter < intCheckCount; intCounter ++)
            {
                // Check to see if there is only 1 context layer row (1 context layer row gives an undefined length count).
                var objTempCheck = (intCheckCount == 1) ? objChkLegendContextLayer : objChkLegendContextLayer[intCounter];

                if (objTempCheck.checked)
                {
                    strPrintLegend += "    <tr>";
                    strPrintLegend += "        <td style='padding-left: 15px; padding-top: 2px''><img src='" + document.getElementById("imgContext" + intCounter).src + "' title='' alt='' /><\/td>";
                    strPrintLegend += "        <td style='padding-left: 4px; padding-top: 2px''>" + document.getElementById("tblRowLegendContext" + intCounter).innerHTML + "<\/td>";
                    strPrintLegend += "    <\/tr>";
                }
            }
        }

        strPrintLegend += "<\/table>";

        // Show the legend on printout.
        document.getElementById("divPrintLegend").innerHTML = strPrintLegend;
        document.getElementById("divPrintLegend").className = document.getElementById("divPrintLegend").className.replace(/printNone/ig, "printable").trim();

        // Show the sidebar on printout.
        document.getElementById("divPrintSliderLegend").className = document.getElementById("divPrintSliderLegend").className.replace(/printNone/ig, "printable").trim();

        // Resize the map.
        document.getElementById("divMapContent").className = document.getElementById("divMapContent").className.replace(/printFullMapWidth/ig, "printPartialMapWidth").trim();
    }
    else
    {
        // Hide the legend on printout.
        document.getElementById("divPrintLegend").className = document.getElementById("divPrintLegend").className.replace(/printable/ig, "printNone").trim();

        // Hide the sidebar on printout.
        document.getElementById("divPrintSliderLegend").className = document.getElementById("divPrintSliderLegend").className.replace(/printable/ig, "printNone").trim();

        // Resize the map.
        document.getElementById("divMapContent").className = document.getElementById("divMapContent").className.replace(/printPartialMapWidth/ig, "printFullMapWidth").trim();
    }

    // Display or hide the map information when printing by setting the class to "printable" or setting the class to "printNone" respectively.
    if (document.getElementById("chkPrintMapInfo").checked)
        document.getElementById("divPrintMapInfo").className = document.getElementById("divPrintMapInfo").className.replace(/printNone/ig, "printable").trim();
    else
        document.getElementById("divPrintMapInfo").className = document.getElementById("divPrintMapInfo").className.replace(/printable/ig, "printNone").trim();

    // Display or hide the custom title when printing by setting the class to "printable" or setting the class to "printNone" respectively.
    if (document.getElementById("chkPrintCustomTitle").checked)
    {
        document.getElementById("divPrintCustomTitle").className = document.getElementById("divPrintCustomTitle").className.replace(/printNone/ig, "printable").trim();

        // Set a custom title.
        if (document.getElementById("txtCustomTitle").value.trim().length > 0)
            document.getElementById("divPrintCustomTitleContent").innerHTML  = "<span><h5>" + document.getElementById("txtCustomTitle").value.trim() + "<\/h5><\/span>";
    }
    else
        document.getElementById("divPrintCustomTitle").className = document.getElementById("divPrintCustomTitle").className.replace(/printable/ig, "printNone").trim();

    // Display or hide the custom description when printing by setting the class to "printable" or setting the class to "printNone" respectively.
    if (document.getElementById("chkPrintCustomDescription").checked)
    {
        document.getElementById("divPrintCustomDescription").className = document.getElementById("divPrintCustomDescription").className.replace(/printNone/ig, "printable").trim();

        // Set a custom description.
        if (document.getElementById("txtCustomDescription").value.trim().length > 0)
            document.getElementById("divPrintCustomDescriptionContent").innerHTML  = "<span>" + document.getElementById("txtCustomDescription").value.trim() + "<\/span>";
    }
    else
        document.getElementById("divPrintCustomDescription").className = document.getElementById("divPrintCustomDescription").className.replace(/printable/ig, "printNone").trim();

    // Show the browser's print dialog box.
    window.print();

    closePrintPopUp();
}

function closePrintPopUp()
{
    // Remove the div.
    removePopUp("divPrintOptionsPopUp");
}

function showPrintOptions(pStrPopUpTitle)
{
    var strCustomTitle = document.getElementById("divPrintCustomTitleContent").innerHTML.replace(/<\/?span>/ig, "").replace(/<\/?h5>/ig, "");
    var strCustomDescription = document.getElementById("divPrintCustomDescriptionContent").innerHTML.replace(/<\/?span>/ig, "");

    strCustomTitle += "|" + (document.getElementById("divPrintCustomTitle").className.toUpperCase().indexOf("PRINTABLE") >= 0);
    strCustomDescription += "|" + (document.getElementById("divPrintCustomDescription").className.toUpperCase().indexOf("PRINTABLE") >= 0);

    var boolMapInfo = (document.getElementById("divPrintMapInfo").className.toUpperCase().indexOf("PRINTABLE") >= 0);
    var boolLegend = (document.getElementById("divPrintSliderLegend").className.toUpperCase().indexOf("PRINTABLE") >= 0);

    var strUrl = "./jsp/showPrintOptionsForm.jsp";
    var strUrlParams = "title=" + strCustomTitle + "&description=" + strCustomDescription + "&legend=" + boolLegend + "&mapInfo=" + boolMapInfo + "&lang=" + strLang;

    // Create a new XML HTTP object for AJAX operation.
    var oTempXmlHttp = getNewXmlHTTPObject();

    // Process the AJAX request.
    if (!isXmlHTTPNull(oTempXmlHttp))
        doXMLRequest(oTempXmlHttp, strUrl, strUrlParams, "post", false, "application/x-www-form-urlencoded");

    // Create a div containing the results.
    var objDivPrintOptionsPopUp = createDivPopUp(pStrPopUpTitle, oTempXmlHttp.responseText, "divPrintOptionsPopUp", "popUpModalDefault popUpPrintOptions", true, true)

    oTempXmlHttp = null;

    // Position the div.
    centerObjectWithin(objDivPrintOptionsPopUp, (document.body || window));
}

function doSaveMap(pNumMapID)
{
    // Set action state.
    boolSavingMap = true;

    // Verify if the user is logged in. If so, perform a save. Otherwise, prompt for login.
    if (boolLoggedIn)
        saveMap(pNumMapID);
    else
        document.getElementById("lnkLogin").click();
}

function saveMap(pNumMapID)
{
    var strUrl = "./jsp/processShareCopy.jsp";
    var strUrlParams = "mapID=" + numMapID + "&lang=" + strLang;

    // Create a new XML HTTP object for AJAX operation.
    var oTempXmlHttp = getNewXmlHTTPObject();

    // Process the AJAX request.
    if (!isXmlHTTPNull(oTempXmlHttp))
        doXMLRequest(oTempXmlHttp, strUrl, strUrlParams, "post", false, "application/x-www-form-urlencoded");

    // Show layers in the legend field.
    var strResult = oTempXmlHttp.responseText.split("|")[0];
    if (strResult == 1)
    {
        // Store the new map ID.
        numMapID = oTempXmlHttp.responseText.split("|")[1];

        // Show the popup message div.
        createDivPopUpFade(strSavedMsg, "divSaveMsgPopUp", "popUpLoginLogoutMsg", 2000, false);

        // update the "My Maps" hierarchy.
        getMyMapsHierarchy(numMapID, document.getElementById("divMyMapsHierarchy"));

        // Remove the save button.
        document.getElementById("divToolbarSaveMap").parentNode.removeChild(document.getElementById("divToolbarSaveMap"));
    }

    // Open the MyMaps hierarchy.
    showHideSliderElement("divMyMapsHierarchy", document.getElementById("divMyMapsHierarchyOpenClose"), true);

    // Set action state.
    boolSavingMap = false;
}

function doCatalogSearch()
{
    var arryBBox = objMap.getExtent().toBBOX().split(",");
    var strUrl = strCatalogSearchUrl + "?action=fromGeoBrowser&lang=" + strLang + "&minx=" + arryBBox[0] + "&miny=" + arryBBox[1] + "&maxx=" + arryBBox[2] + "&maxy=" + arryBBox[3] + "&keywords=" + strCatalogSearchParams;

    window.open(strUrl, "_blank");
}

function doControlGroup(pObjImg, pStrOperation)
{
    // Get the zoom and pan controls from the map.
    var objZoomExtent = objMap.getControlsByClass("OpenLayers.Control.ZoomBox")[0];

    // Reset the map cursor to the default cursor.
    objMap.div.style.cursor = "default";

    // Unselect all tools in the toolbar.
    unselectGroupTools();

    if (pStrOperation.toUpperCase() == "ZOOMEXTENT")
    {
        objZoomExtent.activate();
        toggleMeasureControl("");
        hideQueryRadioButtons();

        // Change the map cursor.
        //objMap.div.style.cursor = "crosshair";

        objMap.setOptions({restrictedExtent: null});

        if (boolGetFeatureInfo)
            setGetFeatureInfoState();
    }
    else if (pStrOperation.toUpperCase() == "DRAGPAN")
    {
        objZoomExtent.deactivate();
        toggleMeasureControl("");
        hideQueryRadioButtons();

        if (boolGetFeatureInfo)
            setGetFeatureInfoState();

        objMap.setOptions({restrictedExtent: null});

        // Change the map cursor.
        //objMap.div.style.cursor = "./images/openhand.cur";
    }
    else if (pStrOperation.toUpperCase() == "MEASUREDISTANCE")
    {
        objZoomExtent.deactivate();
        toggleMeasureControl("line");
        hideQueryRadioButtons();

        if (boolGetFeatureInfo)
            setGetFeatureInfoState();

        objMap.setOptions({restrictedExtent: null});

        // Change the map cursor.
        //objMap.div.style.cursor = "pointer";
    }
    else if (pStrOperation.toUpperCase() == "MEASUREAREA")
    {
        objZoomExtent.deactivate();
        toggleMeasureControl("polygon");
        hideQueryRadioButtons();

        if (boolGetFeatureInfo)
            setGetFeatureInfoState();

        objMap.setOptions({restrictedExtent: null});

        // Change the map cursor.
        //objMap.div.style.cursor = "pointer";
    }
    else if (pStrOperation.toUpperCase() == "GETFEATUREINFO")
    {
        objZoomExtent.deactivate();
        toggleMeasureControl("");
        showQueryRadioButtons();

        //if the field is side menu is hidden then show, we need it to be able to select the layer to query on.
        if (document.getElementById("divSidebar").style.display.toUpperCase() == "NONE")
        {
            var objToolBarShowSidebar = document.getElementById("divToolbarHideShowSidebar")
            doHideShowSidebar(objToolBarShowSidebar);
        }

        if (!boolGetFeatureInfo)
            setGetFeatureInfoState();

        // Change the map cursor.
        //objMap.div.style.cursor = "pointer";
    }

    // Reset the getFeatureInfo request..
    resetAllQueryButtons();
    removePopUp("divGetFeatureInfoPopUp");
    strQueryLayer = "";
    strQueryLayerTitle = "";

    // Show that the control is selected.
    pObjImg.setAttribute("class", "toolbarControlsActive");
    pObjImg.setAttribute("className", "toolbarControlsActive");

    strSelectedTool = pStrOperation;
}

function doResetMap()
{
    // Set the center and zoom for the map.
    doSetCenter(numDefaultLon, numDefaultLat, numDefaultScale);
}

function unselectGroupTools()
{
    // Reset the display of all controls in the group.
    var arryDivControlGroup = document.getElementsByName("imgToolbarControlGroup");
    for (var intCounter = 0; intCounter < arryDivControlGroup.length; intCounter ++)
    {
        arryDivControlGroup[intCounter].setAttribute("class", "toolbarControls");
        arryDivControlGroup[intCounter].setAttribute("className", "toolbarControls");
    }
}

function fadeToolbar(pObjToolbar, pOpacityLevel, pStrAction, e)
{
    if ((pStrAction.toUpperCase() == "IN") && (!boolToolbarFade))
    {
        new Effect.Opacity(pObjToolbar, { from: pOpacityLevel, to: 1, duration: 0.5 });
        boolToolbarFade = true;
    }
    else if ((pStrAction.toUpperCase() == "OUT") && (boolToolbarFade))
    {
        var objTarget = (e.toElement || e.relatedTarget);

        if ((objTarget == null) || (objTarget == undefined))
            boolToolbarFade = false;
        else if(!isChild(pObjToolbar, objTarget) && (pObjToolbar != objTarget))
        {
            new Effect.Opacity(pObjToolbar, { from: 1, to: pOpacityLevel, duration: 0.5 });
            boolToolbarFade = false;
        }
    }
}

function setGetFeatureInfoState()
{
    // Set the getFeatureInfo state.
    boolGetFeatureInfo = !boolGetFeatureInfo;

    // Reset the map cursor to the default cursor.
    objMap.div.style.cursor = "default";

    // Get the click controls from the map.
    var objClick = objMap.getControlsBy("id", "OpenLayers.Control.Click")[0];

    if (!boolGetFeatureInfo)
    {
        strQueryLayer = "";
        strQueryLayerTitle = "";

        objClick.deactivate();
    }
    else
        objClick.activate();
}
