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 oldLayerArray=0;
var newLayerArray;

var objCurrentPoly = null;

var strCurrentPoly = "";

var boolShowDetails = false;

//JH
var _mSvgEnabled = true;
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.hide();

            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(objZoomOld, objZoomNew){doMapZoomEnd(objZoomNew)});

            // 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.
        getCharts();
    }
    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(), "get", true, "", "");

    // Reset the current polyline(s) of interest.
    if (strCurrentPoly != "")
        closeDivPopup();

    // Get charts on. --> Felix
    getCharts();
}

function doMapZoomEnd(pZoom) // --> Felix
{
    // Refresh the legend based on zoom level.
    zoomLegend(pZoom);
}

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)
            removeDiv("divChartInfo");

        strCurrentPoly = "";
    }
}

function mouseoverPolyline(pContentKey, pChartNumber, 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.
    objDivElement.innerHTML = pPoly.chartNumber;

    // 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).
    removeDiv("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/getChartDetails.jsp?contentKey=" + pPoly.contentKey, "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, pChartNumber, pPoly, pLeft, pTop, pAction)
{
    pPoly.polyID = "v" + pContentKey;
    pPoly.contentKey = pContentKey;
    pPoly.chartNumber = pChartNumber;

    if (pAction == "mouseout")
        mouseoutPolyline(pPoly);
    else if (pAction == "mouseover")
        mouseoverPolyline(pContentKey, pChartNumber, 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);

        removeDiv("divChartInfo");
        strCurrentPoly = "";

        boolShowDetails = false;
    }

    // Remove the div object.
    removeDiv("divChartInfo");

    // Set the flag to show that details are off.
    if (boolShowDetails)
        boolShowDetails = false;

    document.getElementById("divPrintChartInfo").innerHTML = "";
}
