// Global variables
var xMousePos = 0; // Horizontal position of the mouse on the screen
var yMousePos = 0; // Vertical position of the mouse on the screen

var boolFirstLogin = true;

// Add a listener for browsers other than Internet Explorer
if (!document.all) document.addEventListener("mousemove", captureMousePosition, true)

// Initialize the mouse move event.
document.onmousemove = captureMousePosition;

// Add an event handler for resizing of the client browser.
if (window.attachEvent)
    window.attachEvent("onresize", repositionObjects);
else if (window.addEventListener)
    window.addEventListener("resize", repositionObjects, false);
else
    window.onresize = repositionObjects;

//-------------------------------------------------------------------------------------------------------//

function initializePage()
{
    boolInitializingMap = true;

    // Initialize the sidebar functionality.
    initializeSidebar();

    // Initialize the map and get the root object of the map XML info.
    var objXMLMapRoot = initializeMap(numMapID);
    if ((objXMLMapRoot == null) && (objXMLMapRoot == undefined))
    {
        // Exit the operation if no map info is returned.
        boolInitializingMap = false;

        return;
    }

    // Process the map information.
    processMap(objXMLMapRoot);

    // Get the map name.
    var strMapName = objXMLMapRoot.getElementsByTagName("name")[0].childNodes[0].nodeValue;

    // Show the sidebar.
    showLegend(document.getElementById("divLegend"), numMapID, numDefaultScale);
    showReportableLayers(document.getElementById("divReport"), numMapID, numDefaultScale);
    showFilterableLayers(document.getElementById("divFilters"), numMapID, numDefaultScale);
    if ((document.getElementById("divDownload") != null) && (document.getElementById("divDownload") != undefined))
        showDownloadableLayers(document.getElementById("divDownload"),numMapID, numDefaultScale);
    showMyMapsSlider(document.getElementById("divMyMapsHierarchy"),numMapID, numDefaultScale);
    if ((document.getElementById("divMapHierarchy") != null) && (document.getElementById("divMapHierarchy") != undefined))
        getHierarchy(numMapID, document.getElementById("divMapHierarchy"));

    getMyMapsHierarchy(numMapID, document.getElementById("divMyMapsHierarchy"));

    // Add the filters to the WMS request.
    var strFilters = getFilters();

    // Add the Mapit layer if it is selected.
    if (isMapitSelected())
    {
        if (strFilters.trim().length > 0)
            strFilters += "|";

        // Update the filter parameter.
        strFilters += getMapitfilter();
    }

    // Perform a WMS request and add the layer(s) to the map.
    objMap.addLayers([doWMS(strMapName, getIncludedLayers().join(","), strFilters)]);

    // Set the center and zoom for the map.
    doResetMap();

    // Set the status of the "Select All" check box of the legend.
    initializeSelectAllStatus();

    // Track the default unchecked layers.
    getExcludedLayers().join(",");

    // If a disclaimer is displayed, there are no layers applied on the map.
    if (objMap.getNumLayers() == 0)
        boolShowDisclaimerStartUp = true;

    boolInitializingMap = false;
}

function doPostForm(pStrFormID, pStrWindowName, pStrUrl, pArryParams)
{
    // Create a form object.
    var objFrmForm = document.createElement("form");
    objFrmForm.setAttribute("id", pStrFormID);
    objFrmForm.setAttribute("method", "post");
    objFrmForm.setAttribute("target", pStrWindowName);
    objFrmForm.setAttribute("action", pStrUrl);

    for (var intCounter = 0; intCounter < pArryParams.length; intCounter ++)
    {
        var objTemp = pArryParams[intCounter];

        // Create hidden objects which will carry the values of each parameter that will be posted.
        var objHidTemp = document.createElement("input");
        objHidTemp.setAttribute("type", "hidden");
        objHidTemp.setAttribute("name", objTemp.split("$")[0]);
        objHidTemp.setAttribute("value", objTemp.split("$")[1]);
        objFrmForm.appendChild(objHidTemp);
    }

    // Add the form object.
    document.body.appendChild(objFrmForm);

    if (pStrWindowName.toUpperCase() != "_SELF")
    {
        // Display the report in a separate window.
        window.open("", pStrWindowName, "location=0, toolbar=0, scrollbars=1, status=1, titlebar=1, resizable=1");
    }

    // Submit the form.
    objFrmForm.submit();

    // Remove the form object.
    document.body.removeChild(objFrmForm);
}

function logMsg(pStrMsg, pStrLevel, pStrModuleName, pStrCallbackProc)
{
    // If the looger is disabled, then exit the procedure.
    if (!boolLoggerActive)
        return;

    pStrMsg = pStrMsg.replace(/\r\n/g, "").replace(/</g, "~lt~").replace(/>/g, "~gt~").replace(/\#/g, "%23");

    // Truncate the mesage if it is too long.
    if (pStrMsg.length > 1500)
        pStrMsg = pStrMsg.substr(0, 768) + "...";

    var strUrl = "./jsp/logger.jsp";
    var strUrlParams = "msg=" + pStrMsg + "&level=" + pStrLevel + "&module=" + pStrModuleName + "&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", true, "application/x-www-form-urlencoded", pStrCallbackProc, "loggingCallback(pObjXmlHTTP)");

    oTempXmlHttp = null;
}

function loggingCallback(pObjXML)
{
    // If there was an error when writing to the log file, alert the error message.
    if (pObjXML.responseText.split("|")[0] != 0)
        alert(pObjXML.responseText.split("|")[1]);
}

function showSidebar()
{
    showLegend(document.getElementById("divLegend"), numMapID, objMap.getScale());
    showReportableLayers(document.getElementById("divReport"), numMapID, objMap.getScale());
    showFilterableLayers(document.getElementById("divFilters"), numMapID, objMap.getScale());
    if ((document.getElementById("divDownload") != null) && (document.getElementById("divDownload") != undefined))
        showDownloadableLayers(document.getElementById("divDownload"),numMapID, objMap.getScale());
    showMyMapsSlider(document.getElementById("divMyMapsHierarchy"),numMapID, objMap.getScale());
    if ((document.getElementById("divMapHierarchy") != null) && (document.getElementById("divMapHierarchy") != undefined))
        getHierarchy(numMapID, document.getElementById("divMapHierarchy"));

    getMyMapsHierarchy(numMapID, document.getElementById("divMyMapsHierarchy"));
}

function captureMousePosition(e)
{
    if (!e)
        var e = window.event;

    // Capture the mouse position.
    if (e.pageX || e.pageY)
    {
        xMousePos = e.pageX;
        yMousePos = e.pageY;
    }
    else if (e.clientX || e.clientY)
    {
        xMousePos = e.clientX + document.documentElement.scrollLeft;
        yMousePos = e.clientY + document.documentElement.scrollTop;
    }

    // Show mouse position in browser status bar.
    //window.status = "xMousePos=" + xMousePos + ", yMousePos=" + yMousePos;
}

function processKeyPress(pEvent, pStrFunction)
{
    var strKeyCode;

    if (window.event) // IE
        strKeyCode = pEvent.keyCode;
    else if (pEvent.which) // Netscape/Firefox/Opera
        strKeyCode = pEvent.which;

    if ((strKeyCode == 13) && (pStrFunction))
        eval(pStrFunction);
}

function removeElement(pElementID)
{
    var objElement = document.getElementById(pElementID);

    // Remove the child element (if it exists) from the parent.
    if (objElement)
        objElement.parentNode.removeChild(objElement);
}

function removePopUp(pPopUpName)
{
    // Remove the modal div (if exists).
    if (document.getElementById("divModal"))
        removeElement("divModal");

    removeElement(pPopUpName);
}

// Creates the help window
function showHelpDiv(pID, pHtml, pLeft, pTop)
{
    // Create a new div.
    var oHelpDiv = document.createElement("div");

    // Assign an ID to the div.
    oHelpDiv.id = pID;
    oHelpDiv.name = pID;
    oHelpDiv.style.left = "0px";
    oHelpDiv.style.top = "0px";

    oHelpDiv.innerHTML = pHtml;

    // Assign a class style to the div object.
    addClassName(oHelpDiv, "popUpHelp");

    document.body.appendChild(oHelpDiv);

    positionObject(oHelpDiv, pLeft, pTop);
}

function updateDivPopUpContent(pStrInnerHtmlContent, pStrPopUpName)
{
    if (document.getElementById(pStrPopUpName))
        document.getElementById(pStrPopUpName + "_content").innerHTML = pStrInnerHtmlContent;

    return document.getElementById(pStrPopUpName);
}

function createDivPopUp(pStrInnerHtmlTitle, pStrInnerHtmlContent, pStrPopUpName, pStrClassName, pBoolDraggable, pBoolModal)
{
    // Remove the div if exists already.
    removeElement(pStrPopUpName);

    // Remove the modal div if exists already.
    if (!pBoolModal)
        removeElement("divModal")

    // Create a div to make the popup appear to be modal.
    if ((pBoolModal) && (!document.getElementById("divModal")))
    {
        var divPopUpModal = document.createElement("div");

        divPopUpModal.id = "divModal";
        divPopUpModal.name = "divModal";
        divPopUpModal.style.display = "none";
        addClassName(divPopUpModal,  "modal displayOnly");

        // Add the div to the document object.
        document.body.appendChild(divPopUpModal);

        divPopUpModal.style.display = "";
    }

    var divPopUpContainer = document.createElement("div");
    var divPopUpTitle = document.createElement("div");
    var divPopUpContent = document.createElement("div");

    // Assign a name to the div if specified.
    if (pStrPopUpName != null)
    {
        divPopUpContainer.id = pStrPopUpName;
        divPopUpContainer.name = pStrPopUpName;
    }

    addClassName(divPopUpContainer, "displayOnly popUpDefault");

    // Assign a class name to the div if specified.
    if (pStrClassName != null)
        addClassName(divPopUpContainer, pStrClassName)

    divPopUpContainer.style.overflow = "hidden";
    divPopUpContainer.style.padding = "0px";

    var strTitleHTML = "";

    // Add the title to the title div if specified.
    if (pStrInnerHtmlTitle != null)
    {
        strTitleHTML += "<table style='width: 100%' cellpadding='0' cellspacing='0' border='0'>";
        strTitleHTML += "   <tr>";
        strTitleHTML += "       <td id='" + pStrPopUpName + "_draggable' name='" + pStrPopUpName + "_draggable' style='padding: 2px 4px 2px 4px; cursor: default'>";
        strTitleHTML += "          <div style='float: left'>" + pStrInnerHtmlTitle + "<\/div>";
        strTitleHTML += "      <\/td>";
        strTitleHTML += "       <td style='width: 1px; padding: 2px 4px 2px 4px; cursor: default'>";
        strTitleHTML += "           <div style='line-height: 12px; float: right'>" + createCloseButton("onclick", "removePopUp(&quot;" + pStrPopUpName + "&quot;)") + "<\/div>";
        strTitleHTML += "       <\/td>";
        strTitleHTML += "   <\/tr>";
        strTitleHTML += "<\/table>";
    }

    divPopUpTitle.innerHTML = strTitleHTML;
    divPopUpTitle.id = pStrPopUpName + "_title";
    divPopUpTitle.name = pStrPopUpName + "_title";
    addClassName(divPopUpTitle, "popUpTitle");

    // Add the content to the content div.
    divPopUpContent.innerHTML = pStrInnerHtmlContent;
    divPopUpContent.id = pStrPopUpName + "_content";
    divPopUpContent.name = pStrPopUpName + "_content";
    addClassName(divPopUpContent, "popUpContent");

    // Add the title and content divs to the container div.
    divPopUpContainer.appendChild(divPopUpTitle);
    divPopUpContainer.appendChild(divPopUpContent);

    positionObject(divPopUpContainer, 0, 0);

    // Add the div to the document object.
    document.body.appendChild(divPopUpContainer);

    // Make the div draggable if specified.
    if ((pBoolDraggable) && (pStrPopUpName != null))
        new Draggable(pStrPopUpName, {handle: pStrPopUpName + "_draggable"});
    else if (!pBoolDraggable)
        divPopUpTitle.style.display = "none";

    return divPopUpContainer;
}

function sizeDivPopUpToContent(pObjDivPopUp)
{
    // Size the popup window to it contents.
    var objContent = null;
    if (navigator.appName == "Microsoft Internet Explorer")
        objContent = pObjDivPopUp.childNodes[1].childNodes[0];
    else
        objContent = pObjDivPopUp.childNodes[1].childNodes[0].nextSibling;
    pObjDivPopUp.style.width = objContent.clientWidth + 20 + "px";
}

function createDivPopUpFade(strMsg, pStrPopUpName, pStrClassName, pNumTime, boolModal)
{
    // Set a default modal state for the window, if not present.
    boolModal = ((boolModal == null) || (boolModal == undefined)) ? false : boolModal;

    // Show the popup message div.
    var objDivPopUpFade = createDivPopUp(null, strMsg, pStrPopUpName, pStrClassName, false, boolModal);

    // Position the div.
    centerObjectWithin(objDivPopUpFade, (document.body || window));

    // Show the message for a period of time (in milliseconds).
    setTimeout("Effect.Fade('" + pStrPopUpName + "', {duration: 1.0, from: 1, to: 0})", pNumTime);

    // Remove the message div.
    setTimeout("removeElement('" + pStrPopUpName + "')", (pNumTime * 2));
}

function changeButtonText(pButton, pText)
{
    pButton.value = pText;
}

function existsInArray(pContentKey, pArray)
{
    var intArrayLength = pArray.length;
    var intCounter = 0;
    var boolFound = false;

    // Loop through the array to see if pContentKey already exists.
    while ((boolFound == false) && (intCounter < intArrayLength))
    {
        if (pArray[intCounter] == pContentKey)
            boolFound = true;

        intCounter ++;
    }

    return boolFound;
}

function toggleImage(pObjObject, pStrStatus, pStrOnImageLocation, pStrOffImageLocation, pStrTitle)
{
    // Toggle the image on the object pObj.
    if (pStrStatus.toUpperCase() == "ON")
        pObjObject.style.backgroundImage = "url(" + pStrOnImageLocation + ")";
    else
        pObjObject.style.backgroundImage = "url(" + pStrOffImageLocation + ")";

    // Set the title if specified.
    if ((pStrTitle != null) && (pStrTitle != ""))
        pObjObject.title = pStrTitle;
}

function addClassName(pObjObject, pStrClassName)
{
    // If there are class names assigned, add to the list of classes. Otherwise, set the class name.
    if (pObjObject.className.trim().length > 0)
        pObjObject.className = pObjObject.className + " " + pStrClassName;
    else
        pObjObject.className = pStrClassName;
}

function centerObjectWithin(pObjectSource, pObjTarget)
{
    var numTargetWidth = 0;
    var numTargetHeight = 0;
    var numTargetScrollLeft = 0;
    var numTargetScrollTop = 0;

    // Firefox client browser width is not the same as IE.
    // All other objects are ok.
    if ((pObjTarget == document.body) || (pObjTarget == window))
    {
        numTargetWidth = document.documentElement.clientWidth;
        numTargetHeight = document.documentElement.clientHeight;

        numTargetScrollLeft = document.documentElement.scrollLeft;
        numTargetScrollTop = document.documentElement.scrollTop;
    }
    else
    {
        numTargetWidth = pObjTarget.clientWidth;
        numTargetHeight = pObjTarget.clientHeight;

        numTargetScrollLeft = (numTargetWidth.scrollLeft == null ? 0 : numTargetWidth.scrollLeft);
        numTargetScrollTop = (numTargetHeight.scrollTop == null ? 0 : numTargetWidth.scrollTop);
    }

    // Center the pObjectSource within pObjTarget.
    pObjectSource.style.left = findPosX(pObjTarget) + (((numTargetWidth - pObjectSource.clientWidth) / 2) >= 0 ? (numTargetWidth - pObjectSource.clientWidth) / 2 : 0) + numTargetScrollLeft + "px";
    pObjectSource.style.top = findPosY(pObjTarget) + (((numTargetHeight - pObjectSource.clientHeight) / 2) >= 0 ? (numTargetHeight - pObjectSource.clientHeight) / 2 : 0) + numTargetScrollTop + "px";
}

function repositionObjects()
{
    // Reposition the map loading modal if visible.
    var objDivLoadingModal = document.getElementById("divLoadingMapModal");
    if (objDivLoadingModal)
        centerObjectWithin(objDivLoadingModal, document.getElementById("divMap"));

    // Reposition the progress bar if visible.
    if ((document.getElementById("divLoading")) && (document.getElementById("divLoading").style.display == ""))
        centerObjectWithin(document.getElementById("divLoading"), document.getElementById("divMap"));
}

function positionObject(pObject, pNumLeft, pNumTop)
{
    // Get the browser inner window dimensions.
    var numWindowInnerWidth = document.documentElement.clientWidth;
    var numWindowInnerHeight = document.documentElement.clientHeight;

    var numLeft = 0;
    var numTop = 0;

    // Ensure that the object is within the window limits. If not, reposition accordingly.
    if ((pNumLeft + pObject.clientWidth) > (numWindowInnerWidth + document.documentElement.scrollLeft))
        numLeft = (numWindowInnerWidth + document.documentElement.scrollLeft) - pObject.clientWidth - 5;
    else if ((pNumLeft + pObject.clientWidth) < 0)
        numLeft = 0;
    else
        numLeft = pNumLeft;

    if ((pNumTop + pObject.clientHeight) > (numWindowInnerHeight + document.documentElement.scrollTop))
        numTop = (numWindowInnerHeight + document.documentElement.scrollTop) - pObject.clientHeight - 5;
    else if ((pNumTop + pObject.clientHeight) < 0)
        numTop = 0;
    else
        numTop = pNumTop;

    // Position the pObject.
    pObject.style.left = numLeft + "px";
    pObject.style.top = numTop + "px";
}

function getElementsByClassName(classname, node)
{
    if(!node)
        node = document.getElementsByTagName("body")[0];

    var a = [];
    var re = new RegExp("\\b" + classname + "\\b");
    var els = node.getElementsByTagName("*");

    for(var i = 0, j = els.length; i < j; i ++)
        if(re.test(els[i].className))a.push(els[i]);

    return a;
}

function isChild(objParent, objChild)
{
    if (objChild != null)
    {
        while(objChild.parentNode)
        {
            if ((objChild = objChild.parentNode) == objParent)
                return true;
        }
    }
    return false;
}

function removeWhiteSpace(objNode)
{
    var strWhiteSpace = /\S/;
    for (var intCounter = 0; intCounter < objNode.childNodes.length; intCounter ++)
    {
        var objChildNode = objNode.childNodes[intCounter]

        // Verify that the childNode is a whitespace text node. If so, remove it.
        if ((objChildNode.nodeType == 3) && (!strWhiteSpace.test(objChildNode.nodeValue)))
        {
            objNode.removeChild(objNode.childNodes[intCounter])
            intCounter --
        }

        // Process other childNodes if available.
        if (objChildNode.nodeType == 1)
            removeWhiteSpace(objChildNode)
    }
}

function findPosX(obj)
{
    var curleft = 0;

    if(obj.offsetParent)
    {
        while(1)
        {
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
            break;
            obj = obj.offsetParent;
        }
    }
    else if(obj.x)
        curleft += obj.x;

    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;

    if(obj.offsetParent)
    {
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    }
    else if(obj.y)
        curtop += obj.y;

    return curtop;
}

String.prototype.ltrim = function() { return this.replace(/^\s + /, "") }
String.prototype.rtrim = function() { return this.replace(/\s + $/, "") }
String.prototype.trim = function() { return this.ltrim().rtrim() }
