var oGMap = null;
var objGIconZoom = null;

var boolPan = true;
var boolZoomEnd = false;
var boolZoomExtent = false;
var decZoomExtentStartPoint = null;
var decZoomExtentEndPoint = null;
var objZoomExtentMarker = null;
var objZoomExtentPolygon = null;

var charts = null;
var oldBounds;
var newBounds;

var objCurrentPoly = null;

var strCurrentPoly = "";

var boolShowDetails = false;

//JH
//if (_mSvgEnabled) { setTimeout("DelGmnoprint();",500) };

function initializeGoogleMaps()
{
    // Initialize and display the Google map.
    if (GBrowserIsCompatible())
    {
        if (oGMap == null)
        {
            // Create a new Google map object associated to the <div>.
            oGMap = new GMap2(document.getElementById("map"), {backgroundColor: "silver"});

            // Display the map with some controls.
            oGMap.addControl(new GLargeMapControl());
            oGMap.addControl(new GMapTypeControl(true));
            oGMap.addControl(new GScaleControl());
            <!--oGMap.addMapType(G_SATELLITE_3D_MAP);-->

            var objOverview = new GOverviewMapControl(new GSize(100,100));
            oGMap.addControl(objOverview);
            objOverview.show();

            oGMap.setMapType(G_HYBRID_MAP);

            // Set the minimum zoom level.
            G_HYBRID_MAP.getMinimumResolution = function(){return 1};
            G_SATELLITE_MAP.getMinimumResolution = function(){return 1};
            G_NORMAL_MAP.getMinimumResolution = function(){return 1};

            // Initialize the zooming features.
            oGMap.disableDoubleClickZoom()
            oGMap.disableScrollWheelZoom();
            oGMap.enableContinuousZoom();

            oGMap.draggableCursor

            // Initialize map center point.
            initializeMapCenter();

            // Add listeners for zoom extent.
            GEvent.addListener(oGMap, "mousemove", function(oPoint){doZoomExtent(oPoint)});
            GEvent.addListener(oGMap, "moveend", function(){doMapMoveEnd()});
            GEvent.addListener(oGMap, "zoomend", function(){doMapZoomEnd()});

            // Create a transparent icon for drawing zoom extent.
            objGIconZoom = new GIcon({image: "./images/transparent.gif"});
            objGIconZoom.iconSize = new GSize(10, 10);
            objGIconZoom.iconAnchor = new GPoint(5, 5);
            objGIconZoom.maxHeight = 0.1;
            objGIconZoom.dragCrossImage = "";
            objGIconZoom.dragCrossSize = new GSize(0, 0);
        }

        // Default the toolbar to be in draw zoom extent mode.
        setZoomExtentState(document.getElementById("imgZoomExtent"));

        // Add the chart data.

        if (grabParamUrl('browser').toUpperCase() == "ENCCHARTINDEX"){
            doMapZoomEnd(); //Will take into concideration the zoom level to disable and enable layers it will call getChart function after
        }else{
            getCharts(); //These sites do not need the Zooming ability
        }
    }
    else
    {
        // Display a warning if the browser was not compatible.
        alert(strErrorGoogleCompatible);
    }
}

// Verify that the min and max extend does not cross the
// International Date Line (IDL).
function isValidMinMax(pMin, pMax)
{
    return (pMax.lat() > pMin.lat()) && (pMax.lng() > pMin.lng());
}

// Reset the map to display all of Canada.
function resetMap()
{
    oGMap.setCenter(new GLatLng(60.59, -97.03), 3);
}

// Reset the map to display all of Canada.
function zoomToBounds(pBounds)
{
    oGMap.setCenter(pBounds.getCenter(), oGMap.getBoundsZoomLevel(pBounds));
}

function zoomToRegion(pPointZoom)
{
    var arryString = pPointZoom.split(",", 3);

    var iLat = parseFloat(arryString[0]);
    var iLng = parseFloat(arryString[1]);
    var iZoom = parseFloat(arryString[2]);

    // Set the zoom level and pan to the region of interest.
    oGMap.setZoom(iZoom);
    oGMap.panTo(new GLatLng(iLat, iLng));
}

function setPanState(pImgTool)
{
    // if the user clicks on the pan tool again, exit execution.
    if (boolPan)
        return false;

    // Track the state of the pan mode.
    boolPan = !boolPan;

    // Change the border color of the pan tool.
    highlightTool(pImgTool, "onclick");

    // Reset the draw zoom extent tool.
    highlightTool(document.getElementById("imgZoomExtent"), "onmouseout");
    boolZoomExtent = !boolZoomExtent;

    // Enable map dragging and remove the zoom marker.
    oGMap.enableDragging();
    oGMap.removeOverlay(objZoomExtentMarker);
    objZoomExtentMarker = null;
}

function setZoomExtentState(pImgTool)
{
    // if the user clicks on the draw zoom extant tool again, exit execution.
    if (boolZoomExtent)
        return false;

    // Track the state of the zoom extent and pan mode.
    boolZoomExtent = !boolZoomExtent;

    // Change the border color of the draw zoom extent tool.
    highlightTool(pImgTool, "onclick");

    // Reset the pan tool.
    highlightTool(document.getElementById("imgPan"), "onmouseout");
    boolPan = !boolPan;

    oGMap.getContainer().style.cursor = "crosshair";

    // Create a marker that will be dragged with mouse movement.
    objZoomExtentMarker = new GMarker(new GLatLng(0, 0), {icon: objGIconZoom, title: strMarkerTitle, draggable: true});

    // Disable map dragging and add the zoom marker.
    oGMap.disableDragging();
    oGMap.addOverlay(objZoomExtentMarker);

    // Add events for dragging the zoom marker.
    GEvent.addListener(objZoomExtentMarker, "dragstart", function(){doDragStartZoomExtent()});
    GEvent.addListener(objZoomExtentMarker, "drag", function(){doDragZoomExtent()});
    GEvent.addListener(objZoomExtentMarker, "dragend", function(){doDragEndZoomExtent()});
}

// Zoom the map by 1 level.
function doSingleZoom(pDirection)
{
    // If pDirection > 0 then zoom the map in, otherwise zoom out.
    if (pDirection > 0)
        oGMap.zoomIn();
    else
        oGMap.zoomOut();
}

function doZoomExtent(oPoint)
{
    // Reposition the zoom marker.
    if ((boolZoomExtent) && (objZoomExtentMarker != null))
        objZoomExtentMarker.setLatLng(oPoint);
}

// Begin the zoom extent box.
function doDragStartZoomExtent()
{
    decZoomExtentStartPoint = objZoomExtentMarker.getPoint();
}

// Draw the zoom extent box.
function doDragZoomExtent()
{
    if (decZoomExtentEndPoint != objZoomExtentMarker.getPoint())
    {
        // Get the zoom extent end point.
        decZoomExtentEndPoint = objZoomExtentMarker.getPoint();

        // Draw a zoom polygon. Remove the old one first.
        if (objZoomExtentPolygon)
            oGMap.removeOverlay(objZoomExtentPolygon);

        objZoomExtentPolygon = new GPolygon([decZoomExtentStartPoint, new GLatLng(decZoomExtentStartPoint.lat(), decZoomExtentEndPoint.lng()), decZoomExtentEndPoint, new GLatLng(decZoomExtentEndPoint.lat(), decZoomExtentStartPoint.lng()), decZoomExtentStartPoint], "white", 3, 1, "white", .4);

        oGMap.addOverlay(objZoomExtentPolygon);
    }
}

// End the zoom extent box.
function doDragEndZoomExtent()
{
    // Set the new center and zoom level to the extent.
    oGMap.setCenter(objZoomExtentPolygon.getBounds().getCenter(), oGMap.getBoundsZoomLevel(objZoomExtentPolygon.getBounds()));

    // Remove the zoom polygon.
    oGMap.removeOverlay(objZoomExtentPolygon);
    objZoomExtentPolygon = null;
}

// Save the map information in the session when the map has changed
// zoom level or pan position.
function doMapMoveEnd()
{
    // Create a new XML HTTP object for AJAX operation.
    var oTempXmlHttp = getNewXmlHTTPObject();

    //GLog.write("repositioning ==> centerx=" + oGMap.getCenter().lng() + "&centery=" + oGMap.getCenter().lat() + "&zoom=" + oGMap.getZoom());

    // Call the server side code to update the session.
    if (!isXmlHTTPNull(oTempXmlHttp))
        doXMLRequest(oTempXmlHttp, "./jsp/serverCode.jsp?centerx=" + oGMap.getCenter().lng() + "&centery=" + oGMap.getCenter().lat() + "&zoom=" + oGMap.getZoom()+ "&browser="+gblStrBrowserMode, "post", true, "", "", "");

    // Reset the current polyline(s) of interest.
    if (strCurrentPoly != "")
        closeDivPopup();

    // Get charts on. --> Felix
    getCharts();
}

/************************************************************
doMapZoomEnd()
Parameters: zoom
   The google map zoom level

Author: Felix de Bie
Date: Nov 27/2008

Description:

This controls the layer visiblity in the legend based on the
google zoom level. When a zoom is performed it checks to see
if the layer should be disbaled. If it is enabled, then it
unchecks it and disables it.

It maintains the layer checked state if the zoom does not
change the disable state.
************************************************************/

function doMapZoomEnd() // --> Felix
{
    if (grabParamUrl('browser').toUpperCase() == "ENCCHARTINDEX"){

       var frmLayersDocument = document.getElementsByName("chkLegendDataLayer");
       var intMapZoom = oGMap.getZoom();
       var strLayerIds = document.getElementsByName("hidLegendLayerIDs");

      if(intMapZoom>=0){
         if (frmLayersDocument[4].disabled){
            frmLayersDocument[4].disabled=false;
            frmLayersDocument[4].checked=true;
         }
       }
       else
       {
          frmLayersDocument[4].checked=false;
          frmLayersDocument[4].disabled=true;
       };

       if(intMapZoom>=0){
          if (frmLayersDocument[3].disabled){
              frmLayersDocument[3].disabled=false;
              frmLayersDocument[3].checked=true;
          }
       }
       else
       {
          frmLayersDocument[3].checked=false;
          frmLayersDocument[3].disabled=true;
       };

       if(intMapZoom>=4){
          if (frmLayersDocument[2].disabled){
             frmLayersDocument[2].disabled=false;
             frmLayersDocument[2].checked=true;
          }
       }
       else
       {
          frmLayersDocument[2].checked=false;
          frmLayersDocument[2].disabled=true;
       };
       if(intMapZoom>=5){

          if (frmLayersDocument[1].disabled){
             frmLayersDocument[1].disabled=false;
             frmLayersDocument[1].checked=true;
          }
       }
       else
       {
          frmLayersDocument[1].checked=false;
          frmLayersDocument[1].disabled=true;
       };


       if(intMapZoom>=6){
          if (frmLayersDocument[0].disabled){
             frmLayersDocument[0].disabled=false;
             frmLayersDocument[0].checked=true;
          }
       }
       else
       {
          frmLayersDocument[0].checked=false;
          frmLayersDocument[0].disabled=true;
       };
    }
       getCharts();
}

function getZoomFromScale(pScale)
{
    if (pScale <= 20000)
        return 16;
    else if ((pScale > 20000) && (pScale <= 40000))
        return 14;
    else if ((pScale > 40000) && (pScale <= 70000))
        return 12;
    else if ((pScale > 70000) && (pScale <= 100000))
        return 8;
    else if ((pScale > 100000) && (pScale <= 300000))
        return 7;
    else if ((pScale > 300000) && (pScale <= 500000))
        return 6;
    else
        return 5;
}

function mouseoutPolyline(pPoly)
{
    if (strCurrentPoly != "")
    {
        // If the filter chart is active...
        if (pPoly.isFiltered)
            pPoly.setStrokeStyle({color: pPoly.filterColor});
        else
            pPoly.setStrokeStyle({color: pPoly.origColor});

        pPoly.redraw(true);

        if (!boolShowDetails)
            removeElement("divChartInfo");

        strCurrentPoly = "";
    }
}

function mouseoverPolyline(pPoly, pLeft, pTop)
{
    strCurrentPoly = pPoly.polyID;

    // If the filter chart is not active, store the original color.
    if (!pPoly.isFiltered)
        pPoly.origColor = pPoly.color;

    pPoly.setStrokeStyle({color: strPolylineMouseOverColor});
    pPoly.redraw(true);

    // Create a new div.
    var objDivElement = document.createElement("div");

    // Assign an ID to the div.
    objDivElement.id = "divChartInfo";
    objDivElement.name = "divChartInfo";

    // Assign a class style to the div object.
    objDivElement.className = "tooltip";

    // Position the div.
    objDivElement.style.left = pLeft + "px";
    objDivElement.style.top = pTop + "px";

    // Fill in the HTML "text" of the div object.
    if (strLang.toUpperCase() == "EN")
        objDivElement.innerHTML = pPoly.textEn;
    else if (strLang.toUpperCase() == "FR")
        objDivElement.innerHTML = pPoly.textFr;

    // Show the div.
    document.body.appendChild(objDivElement);
}

function clickPolyline(pPoly, pLeft, pTop)
{
    // Check to see if the polyline selected is the same one that is highlighted.
    if (strCurrentPoly != pPoly.polyID)
    {
        // If a map pan was performed and the polyline was highlighted,
        // strCurrentPoly would have been reset with the closeDivPopup function.
        // If that is the case, no resetting of strCurrentPoly can be performed.
        if (strCurrentPoly != "")
        {
            // If not, then unhighlight the currently highlighted polyline...
            var objTemp = window[strCurrentPoly];

            // If the filter chart is active...
            if (objTemp.isFiltered)
                objTemp.setStrokeStyle({color: objTemp.filterColor});
            else
                objTemp.setStrokeStyle({color: objTemp.origColor});
            objTemp.redraw(true);
        }

        // ...highlight the selected polyline instead.
        strCurrentPoly = pPoly.polyID;

        // If pPoly is filtered then do not set the origColor.
        if (!pPoly.isFiltered)
            pPoly.origColor = pPoly.color;
    }

    pPoly.setStrokeStyle({color: strPolylineClickColor});
    pPoly.redraw(true);

    // Remove the div (if exists).
    removeElement("divChartInfo");

    //Check if width will fit assuming its 400 width from css file class:table.details
    if (pLeft + 400 > window.document.body.clientWidth)
    {
        pLeft = pLeft - 400;

        //Check if there is enough space on the left to show if not forces right
        if (pLeft < 0 )
            pLeft = pLeft + 400;
    }

    //Checks the Height  - JH
    if (pTop + 350 > window.document.body.clientHeight)
    {
        pTop = pTop - 300; // 300 is an assumption of the height of the div that will be generated

        //verify if there is space on top to show the div if not force div to go bottom
        if (pTop < 0 )
            pTop = pTop + 300
    }

    // Create a new XML HTTP object for AJAX operation.
    var oTempXmlHttp = getNewXmlHTTPObject();

    // Call the server side code to update the session.
    if (!isXmlHTTPNull(oTempXmlHttp))
        doXMLRequest(oTempXmlHttp, "./jsp/showDataDetails.jsp?id=" + pPoly.contentKey + "&browser="+gblStrBrowserMode, "post", false);

    // Create a new div.
    var objDivElement = document.createElement("div");

    // Assign an ID to the div.
    objDivElement.id = "divChartInfo";
    objDivElement.name = "divChartInfo";

    // Assign a class style to the div object.
    objDivElement.className = "tooltip";

    // Position the div.
    objDivElement.style.left = pLeft + "px";
    objDivElement.style.top = pTop + "px";

    // Fill in the HTML "text" of the div object.
    objDivElement.innerHTML = "<div style='width: 400px'>" + oTempXmlHttp.responseText + "</div>";

    // Show the div.
    document.body.appendChild(objDivElement);

    // Add the same information in the divPrintChartInfo element.
    document.getElementById("divPrintChartInfo").innerHTML = "<div class='sidebarHeading' style='align:left;'>" + strPrintChartDetailHeader;
    document.getElementById("divPrintChartInfo").innerHTML = document.getElementById("divPrintChartInfo").innerHTML + "</div>";
    document.getElementById("divPrintChartInfo").innerHTML = document.getElementById("divPrintChartInfo").innerHTML + "<div class='sideBarContent' id='divPrintChart' name='divPrintChart'>";
    document.getElementById("divPrintChartInfo").innerHTML = document.getElementById("divPrintChartInfo").innerHTML + oTempXmlHttp.responseText;
    document.getElementById("divPrintChartInfo").innerHTML = document.getElementById("divPrintChartInfo").innerHTML + "</div></div>";

    oTempXmlHttp = null;

    boolShowDetails = true;
}

// Handle mouse over event for polylines.
function handlePolyline(pContentKey, pTextEn, pTextFr, pPoly, pLeft, pTop, pAction)
{
    pPoly.polyID = "v" + pContentKey;
    pPoly.contentKey = pContentKey;
    pPoly.textEn = pTextEn;
    pPoly.textFr = pTextFr;

    if (pAction == "mouseout")
        mouseoutPolyline(pPoly);
    else if (pAction == "mouseover")
        mouseoverPolyline(pPoly, pLeft, pTop);
    else if (pAction == "click")
        clickPolyline(pPoly, pLeft, pTop);
}

function closeDivPopup()
{
    // Modify the current polyline (if exists).
    if (strCurrentPoly != "")
    {
        // Unhighlight the polyline.
        var objTemp = window[strCurrentPoly];

        // If the filter chart is active...
        if (objTemp.isFiltered)
            objTemp.setStrokeStyle({color: objTemp.filterColor});
        else
            objTemp.setStrokeStyle({color: objTemp.origColor});
        objTemp.redraw(true);

        removeElement("divChartInfo");
        strCurrentPoly = "";

        boolShowDetails = false;
    }

    // Remove the div object.
    removeElement("divChartInfo");

    // Set the flag to show that details are off.
    if (boolShowDetails)
        boolShowDetails = false;

    document.getElementById("divPrintChartInfo").innerHTML = "";
}

