// 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 gblStrBrowserMode = getURLParam('browser');// Gets the browser mode for the application
// 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;

// -------------------------------------------------------------------------------------------------------//

//JH
function DelGmnoprint() {
    var sd = document.getElementsByTagName('svg');

        for (var n = 0 ; n < sd.length ; n++ ) {
            if (sd[n].parentNode.className == 'gmnoprint') {
                sd[n].parentNode.className = '';
            }
        }
    setTimeout("DelGmnoprint();",100);
}

//Javascript grab parameter in url 
function grabParamUrl( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function initializePage()
{
    // Initialize the page.
    // Create a new XML HTTP object for AJAX operation.
    var oTempXmlHttp = getNewXmlHTTPObject();

    var strUrl = "./jsp/showSidebarLegend.jsp?mapID=" + numMapID + "&startup=true&lang=" + strLang + "&browser=" + gblStrBrowserMode;

    //GLog.write("fetching legend ==> " + strUrl);

    // Create AJAX call to retrieve the legend.
    if (!isXmlHTTPNull(oTempXmlHttp))
        doXMLRequest(oTempXmlHttp, strUrl, "post", false);

    document.getElementById("divLegendContent").innerHTML = oTempXmlHttp.responseText;
    document.getElementById("btnGenerateReport").disabled = (objChartArray.length == 0);

    oTempXmlHttp = null;

    // Position the loading animation.
    document.getElementById("loadingDivMap").style.left = ((document.getElementById("map").offsetWidth - 220) / 2) + "px";
    document.getElementById("loadingDivMap").style.top = ((document.getElementById("map").offsetHeight - 19) / 2) + "px";

    // Initialize Google Maps.
    initializeGoogleMaps();
}

function logMsg(pStrMsg, pStrLevel, pStrModuleName)
{
    var strUrl = "./jsp/logger.jsp?msg=" + pStrMsg + "&level=" + pStrLevel + "&module=" + pStrModuleName + "&lang=" + strLang + "&browser="+gblStrBrowserMode;

    // Create a new XML HTTP object for AJAX operation.
    var oTempXmlHttp = getNewXmlHTTPObject();

    // Process the AJAX request.
    if (!isXmlHTTPNull(oTempXmlHttp))
        doXMLRequest(oTempXmlHttp, strUrl, "post", true, "", "", "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 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 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 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 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;
}
//This function serves to grab an url parameter effortlessly
//For example, if you have an url like the following : http://localhost:8080/googleBrowser/index.jsp?browser=BSBCollections
//And you want to get the parameter "browser", you would do the following:
//var strBrowserMode = getURLParam('browser');
function getURLParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
String.prototype.ltrim = function() { return this.replace(/^\s + /, ""); };
String.prototype.rtrim = function() { return this.replace(/\s + $/, ""); };
String.prototype.trim = function() { return this.ltrim().rtrim(); };
