/***********************************************************************************
The functions listed below are related to GeoZone Module in Google V3 Maps.
***********************************************************************************/

// Global variables
var map;
var polyShape;
var polyLineColor = "#3355ff";
var polyFillColor = "#335599";
var polyPoints = new Array();
var markers = new Array();
var report = document.getElementById("status");
var contextmenu;
var circleUnits;
var timeouts = [];
var geoType;
var Rec_bounds;
var poly_bounds;
var isview = 0;
var sGeoName = '';
var maxMarkers = 5;
var centerCoordinate = new google.maps.LatLng(23.805450, 78.486328);
var mapClick = true;
var polyBounds = new google.maps.LatLngBounds();
var zoomIndex = new Array();
var isCanceled = false;
var IsEditable = true;
Rec_bounds = new google.maps.LatLngBounds();
var orgCenter = null;
var orgZoomLevel = null;
var infoWindow;
// Alerts.

var maxGeozoneMarkers = 'Geozones are restricted to have only <#maxMarkers#> points !';
var drawPolygonGeozone = 'Please draw the geozone by clicking on the map !';
var drawRectGeozone = 'Please draw the rectangle by click on map & dragging !';
var enterCategoryName = 'Enter the Category Name !';
var categoryNameExists = 'Category name already exists !'
var categorySaved = "Category has been saved successfully !";
var categoryUpdated = "Category has been updated successfully !"
var categoryCannotDelete = "Cannot delete the category as it is assigned to geozone(s) !";
var categoryConfirmDelete = "Are you sure you want to delete this entry?";
var NoofGeozonePlots = "Please draw the geozone by clicking with Minimum of Three points on the map.";
window.onresize = function(event) {
    var holderControl = document.getElementById("content");
    if (holderControl != null) {
        document.getElementById('map').style.width = (holderControl.clientWidth - 10 - (document.getElementById('search-box').clientWidth)) + 'px';
        if (document.body.clientHeight < 875) {
            document.getElementById('map').style.height = (875 - 375) + 'px';
            document.getElementById('search-box').style.height = (875 - 375) + 'px';
        }
        else {
            document.getElementById('map').style.height = (document.body.clientHeight - 375) + 'px';
            document.getElementById('search-box').style.height = (document.body.clientHeight - 375) + 'px';
        }
    }
}

// Set the alert messages from the Resource File
function SetAlertMessages(maxGeozoneMarkersAlert, drawPolygonGeozoneAlert, drawRectGeozoneAlert,
        enterCategoryNameAlert, categoryNameExistsAlert, categorySavedAlert, categoryUpdatedAlert,
        categoryCannotDeleteAlert, categoryConfirmDeleteAlert, Geozone_NoofPlots) {

    maxGeozoneMarkers = maxGeozoneMarkersAlert;
    drawPolygonGeozone = drawPolygonGeozoneAlert;
    drawRectGeozone = drawRectGeozoneAlert;
    enterCategoryName = enterCategoryNameAlert;
    categoryNameExists = categoryNameExistsAlert;
    categorySaved = categorySavedAlert;
    categoryUpdated = categoryUpdatedAlert;
    categoryCannotDelete = categoryCannotDeleteAlert;
    categoryConfirmDelete = categoryConfirmDeleteAlert;

    NoofGeozonePlots = Geozone_NoofPlots;
}

function loadMap() {
    try {
        //GUnload();
        if (myrectangle) myrectangle.setMap(null);
        if (polyShape) polyShape.setMap(null);
    }
    catch (Error) {
    }
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    var holderControl = document.getElementById("content");
    /* Commented by Jeyanthi on 27-Jul-10 for restricting vertialcal scroll
    document.getElementById('search-box').style.width = 240 + 'px';       
    End*/
    //Rec_bounds = new google.maps.LatLngBounds();
    document.getElementById('search-box').style.width = 260 + 'px';
    if (holderControl != null) {
        if (document.body.clientHeight < 875) {
            document.getElementById('map').style.height = (875 - 375) + 'px';
            document.getElementById('search-box').style.height = (875 - 375) + 'px';
        }
        else {
            document.getElementById('map').style.height = (document.body.clientHeight - 375) + 'px';
            document.getElementById('search-box').style.height = (document.body.clientHeight - 375) + 'px';
        }
        document.getElementById('map').style.width = (holderControl.clientWidth - 10 - (document.getElementById('search-box').clientWidth)) + 'px';
    }

    //map = new GMap2(document.getElementById("map"), { draggableCursor: 'auto', draggingCursor: 'move' });
    //map.setOptions(

    //if (!map) {
    Rec_bounds = new google.maps.LatLngBounds();
    map = new google.maps.Map(document.getElementById("map"),
            {
                center: centerCoordinate,
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                //                panControl: true,
                //                zoomControl: true,
                //                zoomControlOptions: {
                //                    style: google.maps.ZoomControlStyle.LARGE
                //                },
                //                mapTypeControl: true,
                //                scaleControl: false,
                overviewMapControl: true
            });
    //}
    //map.setOptions({ draggableCursor: 'auto', draggingCursor: 'move' });

    if (zoomIndex.length > 0 && isCanceled != true) {
        //map.setCenter(zoomIndex[1]);
        map.setZoom(zoomIndex[0]);
        map.setCenter(zoomIndex[1], zoomIndex[0]);
        Array.clear(zoomIndex);
        //        map.setCenter(MapView[0], MapView[1]);
        //        map.setZoom(MapView[1]);
    }

    var oUnitsMI = document.getElementById('unitsMI');
    var oUnitsKM = document.getElementById('unitsKM');

    if (oUnitsKM.checked) {
        circleUnits = 'PL';

        if (isview == 0) {
            eventOnclick = google.maps.event.addListener(map, "click", leftClick);
        }
        geoType = 2;
    }
    else {
        circleUnits = 'RC';
        myrectangle = null;
        eventOnclick = google.maps.event.addListener(map, "click", getCoordinate);
        eventOnMove = google.maps.event.addListener(map, 'mousemove', mapDragRectangle);
        if (isview == 0) {
            //eventOnclick = GEvent.addListener(map, 'click', mapClickRectangle);
        }

        dragRectangle = false;
        geoType = 1;
    }


    function dblClick() {
        //google.maps.event.addDomListener(map, 'dblclick', function() {
        try {

            google.maps.event.clearListeners(map, eventOnclick);
            //GEvent.removeListener(eventOnMove);

            // doubleClick();

            //map.zoomIn();
            if (oUnitsKM.checked) {
                //map.removeOverlay(markers[markers.length - 1]);
                markers[markers.length - 1].setMap(null);
                markers.length = markers.length - 1;
                markers.splice(markers.length, 1);

                drawPoly();
                eventOnclick = google.maps.event.addListener(map, "click", leftClick);
            }
            else {
                first = '';
                dragRectangle = false;
                //eventOnclick = GEvent.addListener(map, "click", mapClickRectangle);
                eventOnclick = google.maps.event.addListener(map, "click", getCoordinate);
                eventOnMove = google.maps.event.addListener(map, 'mousemove', mapDragRectangle);
                //map.removeOverlay(myrectangle);
                Rec_bounds = new google.maps.LatLngBounds();
            }
        }
        catch (Error) {
        }
        //});
    }

    if (isview == 0) {
        //        google.maps.event.clearListeners(map, 'dblclick');
        //        google.maps.event.addDomListener(map, 'dblclick', dblClick);
    }

    // Included by Kumuthini. L on 30-Jan-09
    google.maps.event.addListener(map, "maptypechanged", mapTypeChanged);
    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (mapTypeHolder.value) {
            case 'N': map.setMapTypeId(google.maps.MapTypeId.ROADMAP); break;
            case 'S': map.setMapTypeId(google.maps.MapTypeId.SATELLITE); break;
            case 'H': map.setMapTypeId(google.maps.MapTypeId.HYBRID); break;
            case 'T': map.setMapTypeId(google.maps.MapTypeId.TERRAIN); break;
            default: map.setMapTypeId(google.maps.MapTypeId.ROADMAP); break;

            //            case 'N': map.setMapType(G_NORMAL_MAP); break;                                                                                
            //            case 'S': map.setMapType(G_SATELLITE_MAP); break;                                                                                
            //            case 'H': map.setMapType(G_HYBRID_MAP); break;                                                                                
            //            case 'T': map.setMapType(G_PHYSICAL_MAP); break;                                                                                
        }
    }
    //GEvent.addDomListener(object,'dblclick',function() {  });
}

// Included by Kumuthini. L on 30-Jan-09
function mapTypeChanged() {
    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (map.getCurrentMapType()) {
            case 'N': map.setMapTypeId(google.maps.MapTypeId.ROADMAP); break;
            case 'S': map.setMapTypeId(google.maps.MapTypeId.SATELLITE); break;
            case 'H': map.setMapTypeId(google.maps.MapTypeId.HYBRID); break;
            default: map.setMapTypeId(google.maps.MapTypeId.TERRAIN); break;

            //            case G_NORMAL_MAP: mapTypeHolder.value = 'N'; break;                                                                                 
            //            case G_SATELLITE_MAP: mapTypeHolder.value = 'S'; break;                                                                                 
            //            case G_HYBRID_MAP: mapTypeHolder.value = 'H'; break;                                                                                 
            //            case G_PHYSICAL_MAP: mapTypeHolder.value = 'T'; break;                                                                                 
        }
    }
}

var timeout;
var clickCoords;

function mapClick(overlay, coordinates) {
    if (overlay != null)
    // Click wasn't on "empty" map space, so don't go any further
        return;

    if (timeout == null) {
        // The first click we've had recently => start a timeout for the lookup
        clickCoords = coordinates;
        leftClick('', coordinates);
        timeout = setTimeout('doubleClick()', 500);
    }
    else {
        // Second click means it's a double-click, so cancel the lookup timeout
        //clearTimeout(timeout)
        //timeout = null;
    }
};

function doubleClick() {
    // Double-click functionality goes in here, using clickCoords 
    // alert('double click testt');
    //GEvent.removeListener(eventOnclick);

    if (document.getElementById('unitsMI').checked && document.getElementById('hdnCoordinates').value != "") {
        var coordinates = document.getElementById('hdnCoordinates').value;
        coordinates = coordinates.replace(/#/g, "&").replace("&,", "&").replace(/,/g, "#");

        RecGeozones(coordinates, isview);
    }
};


function pageLoad(sender, args) {
    if (!args.get_isPartialLoad()) {
        // add our handler to the document's
        // keydown event
        $addHandler(document, "keydown", onKeyDown);
    }
}
function onKeyDown(e) {
    if (e && e.keyCode == Sys.UI.Key.esc) {
        // if the key pressed is the escape key, dismiss the dialog
        contextmenu.style.visibility = "hidden";
    }
}
function addIcon(icon) {
    // Add icon attributes 
    icon.dragCrossSize = new GSize(0, 0);
}
//var marker;
//var icon1 = new G_DEFAULT_ICON();
function leftClick(overlay, point) {
    if (!point || point == '') {
        point = overlay.latLng;  //map.pixelToGeo(overlay.displayX, overlay.displayY);
    }

    if (point) {
        maxMarkers = document.getElementById('hdnMaxGeozoneMarkers').value;

        if (isview == 0) {
            // Included by Kumuthini. L
            if ((markers.length + 1) > maxMarkers) {
                //alert("Geozones are restricted to have only " + maxMarkers + " points !");
                alert(maxGeozoneMarkers.replace("<#maxMarkers#>", maxMarkers));
                return false;
            }
        }

        // Square marker icons


        //        var square = new GIcon(G_DEFAULT_ICON);
        //        //square.image = "mapIcons/square.png";
        //        addIcon(square);
        var marker;
        // Make markers draggable
        if (isview == 0) {
            marker = new google.maps.Marker({
                position: point,
                //map: map,
                draggable: true,
                animation: google.maps.Animation.DROP
            });
            //marker = new GMarker(point, { icon: square, draggable: true, bouncy: false, dragCrossMove: true });
        }
        else {

            marker = new google.maps.Marker({
                position: point,
                //map: map,
                draggable: false,
                animation: google.maps.Animation.DROP
            });
            //marker = new GMarker(point, { icon: square, draggable: false, bouncy: false, dragCrossMove: false });
        }

        markers.push(marker);
        //map.addOverlay(marker);
        marker.setMap(map);

        if (isview == 0) {
            google.maps.event.addListener(marker, "drag", function() {
                drawPoly();
            });

            //            google.maps.event.addListener(marker, "mouseover", function() {
            //                //marker.setImage("mapIcons/m-over-square.png");
            //            });

            //            google.maps.event.addListener(marker, "mouseout", function() {
            //                //marker.setImage("mapIcons/square.png");
            //            });

            // Second click listener to remove the square
            google.maps.event.addListener(marker, "click", function() {

                // Find out which square to remove
                for (var n = 0; n < markers.length; n++) {
                    if (markers[n] == marker) {
                        //map.removeOverlay(markers[n]);
                        markers[n].setMap(null);
                        break;
                    }
                }
                markers.splice(n, 1);
                drawPoly();
            });
        }

        drawPoly();
    }
}

/** @this {google.maps.Polygon} */
function showArrays(event) {

    // Since this polygon has only one path, we can call getPath()
    // to return the MVCArray of LatLngs.
    var vertices = this.getPath();

    var contentString = '<b>Bermuda Triangle polygon</b><br>' +
      'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
      '<br>';

    // Iterate over the vertices.
    for (var i = 0; i < vertices.getLength(); i++) {
        var xy = vertices.getAt(i);
        contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
        xy.lng();
    }

    // Replace the info window's content and position.
    infoWindow.setContent("<b>Geozone </b></br>" + sGeoName);
    infoWindow.setPosition(event.latLng);

    infoWindow.open(map);
}

var polyArray = new Array();
function drawPoly() {

    if (polyShape) polyShape.setMap(null);  //map.removeOverlay(polyShape);
    polyPoints.length = 0;
    polyArray.length = 0;
    //markers.length = 0;

    //document.getElementById("coords").innerHTML = "";
    for (i = 0; i < markers.length; i++) {
        polyPoints.push(new google.maps.LatLng(markers[i].position.lat(), markers[i].position.lng()));
        var appendvalues = new google.maps.LatLng(markers[i].position.lat(), markers[i].position.lng()) + '#';
        polyArray.push(appendvalues.replace("(", "").replace(")", ""));
        //document.getElementById("coords").innerHTML += i+": "+markers[i].getLatLng().toUrlValue(6)+"<br>";
    }

    // Included by Kumuthini. L on 27-Jan-09
    document.getElementById('hdnCoordinates').value = polyArray;

    // Close the shape with the last line or not
    //polyPoints.push(markers[0].getLatLng());
    var polyOptions = {
        strokeColor: polyLineColor,
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: polyFillColor,
        fillOpacity: 0.3,
        path: polyPoints
    }
    polyShape = new google.maps.Polygon(polyOptions);
    infoWindow = new google.maps.InfoWindow();
    // Add a listener for the click event.
    google.maps.event.addListener(polyShape, 'click', showArrays);

    //polyShape = new GPolygon(polyPoints, polyLineColor, 3, .8, polyFillColor, .3);
    var unit = " km&sup2;";
    //var area = polyShape.getArea() / (1000 * 1000);

    if (markers.length <= 2) {
        //report.innerHTML = "&nbsp;";
    }
    else if (markers.length > 2) {
        //report.innerHTML = area.toFixed(3)+ unit;
    }
    //map.addOverlay(polyShape);
    polyShape.setMap(map);
}

function zoomToPoly() {

    if (polyShape && polyPoints.length > 0) {
        //var bounds = polyShape.getBounds();
        //        map.setCenter(bounds.getCenter());
        //        map.setZoom(map.getBoundsZoomLevel(bounds));
        //polyBounds(
        map.fitBounds(poly_bounds);
        //map.setCenter(poly_bounds.getCenter(), map.getBoundsZoomLevel(poly_bounds) - 1); 
    }
}

function clearPoly() {
    // Remove polygon and reset arrays
    //map.clearOverlays();
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    //Clear Rectangle Geozone
    r1 = null;
    //    if (myrectangle != null) {
    //        //map.removeOverlay(myrectangle);
    //        myrectangle.setMap(null);
    //        myrectangle = null;
    //    }
    document.getElementById('hdnCoordinates').value = "";
    maintainZoomLevel();
    loadMap();
}

function view() {
    // Modified by Kumuthini. L on 29-Jan-09
    var alertMsg = ValidateGeozoneEntries();

    if (circleUnits == "PL") {
        if (polyPoints.length > 2 && alertMsg == 'NoError') {
            drawShapes();
        }
        else {
            if (polyPoints.length == 0) {
                if (alertMsg != 'NoError') {
                    alertMsg += '</br>' + drawPolygonGeozone;
                }
                else {
                    alertMsg = drawPolygonGeozone;
                }
            }
            else {
                if (alertMsg != 'NoError') {
                    alertMsg += '</br>' + NoofGeozonePlots;
                }
                else {
                    alertMsg = NoofGeozonePlots;
                }
            }
        }

    }
    else if (circleUnits == "RC") {
        if (polyArray.length > 0 && alertMsg == 'NoError') {
            drawShapes();
        }
        else {
            if (polyArray.length == 0) {
                if (alertMsg != 'NoError') {
                    alertMsg += '\n' + drawRectGeozone;
                }
                else {
                    alertMsg = drawRectGeozone;
                }
            }
        }
    }

    if (alertMsg != 'NoError') {
        TrinetraCustomAlerts(alertMsg);
        return false;
    }

    return true;
}

function drawShapes() {
    polyArray.push('$' + document.getElementById('txtGeozoneName').value + '#');
    polyArray.push(document.getElementById('txtGeozoneDesc').value + '#');
    polyArray.push(geoType + '#');
    polyArray.push(document.getElementById('ddlDirection').value + '#');
    polyArray.push(document.getElementById('ddlSeverity').value + '#');
    polyArray.push(document.getElementById('ddlCategory').value + '#');
    document.getElementById('hdnPoly').value = polyArray;
    clearPoly();
}

function ReceiveServerData(arg, context) {
    alert(arg);
}
function ReceiveServerDataGeozone(arg, context) {
    alert(arg);
}

function clear() {
    //map.clearOverlays();
}
function hideContext() {
    contextmenu.style.visibility = "hidden";
}
// === functions that perform the context menu options ===
function zoomIn() {
    // perform the requested operation
    map.zoomIn();
    // hide the context menu now that it has been used
    contextmenu.style.visibility = "hidden";
}
function zoomOut() {
    // perform the requested operation
    map.zoomOut();
    // hide the context menu now that it has been used
    contextmenu.style.visibility = "hidden";
}
//]]>
var fdata;
var ldata;
function ShowGeozones(latlng, isView, geoName) {
    var isIE = CheckBrowser();
    isview = isView;
    sGeoName = geoName;
    //$find('modalMap').show();
    document.getElementById('pnlManageGeozoneHolder').style.display = "block";
    document.getElementById('pnlGeozoneDetailsList').style.display = "none";

    clearPoly();
    var collectdata = new Array();
    poly_bounds = new google.maps.LatLngBounds();

    var lt = latlng.split('&');

    for (var i = 0; i < lt.length; i++) {

        var lng;
        lng = lt[i].split('#');
        //polyPoints.push(new GLatLng(lng[0],lng[1]));
        var point = new google.maps.LatLng(lng[0].replace("(", " "), lng[1].replace(")", ""));
        leftClick('', point);
        poly_bounds.extend(point);
    }
    zoomToPoly();
}

function RecGeozones(latlng, isView, geoName) {
    var isIE = CheckBrowser();
    isview = isView;
    sGeoName = geoName;
    IsEditable = isView == "1" ? false : true;
    //$find('modalMap').show();
    document.getElementById('pnlManageGeozoneHolder').style.display = "block";
    document.getElementById('pnlGeozoneDetailsList').style.display = "none";

    //clearPoly();
    myrectangle = null;
    loadMap();

    Rec_bounds = new google.maps.LatLngBounds();
    polyPoints.length = 0;
    polyArray.length = 0;

    var collectdata = new Array();
    var lt = latlng.split('&');

    for (var i = 0; i < lt.length; i++) {

        var lng;
        lng = lt[i].split('#');

        polyPoints.push(new google.maps.LatLng(lng[0].replace("(", " "), lng[1].replace(")", "")));
        var point = new google.maps.LatLng(lng[0].replace("(", " "), lng[1].replace(")", ""));
        mapClickRectangle('', point);
    }
    //zoomToPoly();                
}

//TO toggle the Radio buttons
function toggle(rdoID) {
    //var id = document.getElementById(rdoID);
    //alert(id);
    r1 = null;
    if (rdoID == 'unitsMI') {
        document.getElementById('unitsKM').checked = false;
        document.getElementById('unitsMI').checked = true;
    }
    else {
        document.getElementById('unitsKM').checked = true;
        document.getElementById('unitsMI').checked = false;
    }

    document.getElementById('hdnCoordinates').value = "";
    document.getElementById('ddlLandMark').selectedIndex = 0
    maintainZoomLevel();
    loadMap();
}

var icon;
function Findplace(lat, lng) {
    icon = new google.maps.MarkerImage('../images/poi_viewer_house.gif',
           new google.maps.Size(32, 32),
           new google.maps.Point(0, 0),
           new google.maps.Point(16, 32));

    //icon = new GIcon(G_DEFAULT_ICON);
    //map.clearOverlays();
    if (myrectangle) myrectangle.setMap(null);
    if (polyShape) polyShape.setMap(null);

    //icon = new GIcon(icon, '../images/poi_viewer_house.gif');
    //icon.iconSize = new GSize(32, 32);
    var point = new google.maps.LatLng(lat, lng);
    //map.setCenter(point, 14);
    //map.fitBounds(point)
    map.setCenter(point, 14);
    map.setZoom(14);
    var lndmarker = new google.maps.Marker({ position: point, draggable: false, icon: icon });
    //var lndmarker = new GMarker(point, { draggable: false, icon: icon });
    lndmarker.setMap(map);  //map.addOverlay(lndmarker);
}

//To hide the PopupExtender when ESC key is Pressed
function onKeyDown(e) {
    if (e && e.keyCode == Sys.UI.Key.esc) {
        // if the key pressed is the escape key, dismiss the dialog                
        $find('modalMap').hide();
    }
}

function CloseModal() {
    $find('modalMap').hide();
}

function OpenModalPopup(ModalId) {
    var popup = $find(ModalId);
    popup.show();
    loadMap();
}

function enablePostBack() {
    clear();
}

function CategoryValidation() {
    var categoryName = RemoveSpaces(document.getElementById("txtCategoryName"));

    if (categoryName.length == 0) {
        alert(enterCategoryName);
        document.getElementById("txtCategoryName").style.backgroundColor = 'lightyellow';
        document.getElementById("txtCategoryName").focus();
        return false;
    }
    else {
        document.getElementById("txtCategoryName").style.backgroundColor = 'white';
        return true;
    }
}

// Included by Kumuthini. L on 06-Jan-09
// Function to load the Geozone Category Popup
function LoadCategoryPopup() {
    var isIE = CheckBrowser();
    var pnlCategory = document.getElementById("pnlGeozoneCategory");
    pnlCategory.style.display = "block";
    document.getElementById("txtCategoryName").focus();
}

// Included by Kumuthini. L on 06-Jan-09
// Function to close the Geozone Category Popup
function CloseCategoryPopup(type) {
    if (type == 'Duplicate') {
        LoadCategoryPopup();
        alert(categoryNameExists);
        return;
    }
    if (type == 'Add') {
        alert(categorySaved);
    }
    if (type == 'Edit') {
        alert(categoryUpdated);
    }
    var pnlCategory = document.getElementById("pnlGeozoneCategory");
    pnlCategory.style.display = "none";
    setFocusToControl('ddlCategory');
}

function GetCategoryConfirmation() {
    if (document.getElementById("hdnCatAssignedStatus").value == 1) {
        alert(categoryCannotDelete);
        return false;
    }
    else {
        return confirm(categoryConfirmDelete);
    }
}

// Rectangle Geozone script

// JScript File
var r1 = null;
var r2 = null;
var myrectangle;
var dragRectangle;
var first = '';
var second = '';

function getCoordinate(overlay, point) {
    // Included by Kumuthini. L on 07-May-10
    //    if (document.getElementById('hdnCoordinates') != null && document.getElementById('hdnCoordinates').value != '') {
    //        return;
    //    }
    if (!point || point == '') {
        point = overlay.latLng;  //map.pixelToGeo(overlay.displayX, overlay.displayY);
    }
    if (first == '') {
        if (myrectangle != null)
        { return; }
        else {
            myrectangle = null;
        }
        dragRectangle = true;
        first = point;
    }
    else {
        //GEvent.removeListener(eventOnMove);
        dragRectangle = false;
        IsEditable = true;
        draw_rectangle(first, second);

        r1 = first;
        r2 = second;
        //alert(r1 + '-' + r2);
        Rec_bounds = new google.maps.LatLngBounds();

        Rec_bounds.extend(r1);
        Rec_bounds.extend(r2.latLng);

        var marker1 = new google.maps.Marker({ position: r1 });
        var marker2 = new google.maps.Marker({ position: r1 });

        //var marker1 = new GMarker(r1);
        //var marker2 = new GMarker(r2);

        //To store the coordinates
        polyPoints.push(r1 + '#');
        polyPoints.push(r2 + '#');

        // Included by Kumuthini. L on 02-Feb-09
        polyArray.length = 0;

        //To store all the values and pass to Server Side
        polyArray.push(new google.maps.LatLng(marker1.position.lat().replace("(", ""), marker1.position.lng().replace(")", "")) + '#');
        polyArray.push(new google.maps.LatLng(marker2.position.lat().replace("(", ""), marker2.position.lng().replace(")", "")) + '#');

        // Included by Kumuthini. L on 27-Jan-09
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = polyArray;
        }

        r1 = ''
        r2 = ''
        map.fitBounds(Rec_bounds);
        //map.setCenter(Rec_bounds.getCenter(), map.getBoundsZoomLevel(Rec_bounds) - 1);
        first = '';
        second = '';
    }
}


function RecClick(evt) {
    if (dragRectangle) {
        dragRectangle = false;
        IsEditable = true;
        draw_rectangle(first, second);

        r1 = first;
        r2 = second;

        Rec_bounds = new google.maps.LatLngBounds();

        Rec_bounds.extend(r1);
        Rec_bounds.extend(r2);

        var marker1 = new google.maps.Marker({ position: r1 });
        var marker2 = new google.maps.Marker({ position: r2 });

        //var marker1 = new GMarker(r1);
        //var marker2 = new GMarker(r2);

        //To store the coordinates
        polyPoints.push(r1 + '#');
        polyPoints.push(r2 + '#');

        // Included by Kumuthini. L on 02-Feb-09
        polyArray.length = 0;

        //To store all the values and pass to Server Side
        var mark1 = new google.maps.LatLng(marker1.position.lat(), marker1.position.lng()) + '#';
        var mark2 = new google.maps.LatLng(marker2.position.lat(), marker2.position.lng()) + '#';

        polyArray.push(mark1.replace("(", "").replace(")", ""));
        polyArray.push(mark2.replace("(", "").replace(")", ""));

        // Included by Kumuthini. L on 27-Jan-09
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = polyArray;
        }

        r1 = ''
        r2 = ''
        map.fitBounds(Rec_bounds);
        //map.setCenter(Rec_bounds.getCenter(), map.getBoundsZoomLevel(Rec_bounds) - 1);
        first = '';
        second = '';
        //google.maps.event.clearListeners(myrectangle, RecClick);
    }
    else {   // Replace the info window's content and position.
        if (infowindow) {
            infowindow.close();
        }
        infoWindow = new google.maps.InfoWindow();
        infoWindow.setContent("<b>Geozone : </b></br>" + sGeoName);
        infoWindow.setPosition(myrectangle.getBounds().getCenter());
        infoWindow.open(map);
    }
}

function ClearMap() {
    if (oUnitsKM.checked) {
        //eventOnclick =  GEvent.addListener(map, "click", leftClick);
        map.removeOverlay(markers[markers.length - 1]);
        markers.length = markers.length - 1;
        markers.splice(markers.length, 1);


        drawPoly();
        eventOnclick = google.maps.event.addListener(map, "click", getCoordinate);
    }
    else {
        first = '';
        dragRectangle = false;
        myrectangle = null;
    }
}


function mapClickRectangle(overlay, point) {
    if (point == null) { return; }

    if (!r1) {   // First click
        r1 = point;
        if (myrectangle) myrectangle.setMap(null);
        myrectangle = null;
        dragRectangle = true;
    }
    else {   // Second click
        //map.clearOverlays();
        //GEvent.removeListener(eventOnClick);
        dragRectangle = false;
        draw_rectangle(r1, point);
        r2 = point;
        Rec_bounds.extend(r1);
        Rec_bounds.extend(r2);


        var marker1 = new google.maps.Marker({ position: r1 });
        var marker2 = new google.maps.Marker({ position: r2 });

        //To store the coordinates
        polyPoints.push(r1 + '#');
        polyPoints.push(r2 + '#');

        // Included by Kumuthini. L on 02-Feb-09
        polyArray.length = 0;

        var mark1 = new google.maps.LatLng(marker1.position.lat(), marker1.position.lng()) + '#';
        var mark2 = new google.maps.LatLng(marker2.position.lat(), marker2.position.lng()) + '#';

        //To store all the values and pass to Server Side
        polyArray.push(mark1.replace("(", "").replace(")", ""));
        polyArray.push(mark2.replace("(", "").replace(")", ""));


        //        polyArray.push(new google.maps.LatLng(marker1.position.lat(), marker1.position.lng()) + '#');
        //        polyArray.push(new google.maps.LatLng(marker2.position.lat(), marker2.position.lng()) + '#');

        // Included by Kumuthini. L on 27-Jan-09
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = polyArray;
        }

        r1 = ''
        r2 = ''
        //map.setCenter(Rec_bounds.getCenter(), map.getBoundsZoomLevel(Rec_bounds) - 1);
        map.fitBounds(Rec_bounds);

        // commented by christopher s on 01-sep-09 for avoid improper alert while adding rec type
        //polyPoints.length = 0;
        //polyArray.length = 0;
        //markers.length = 0;
    }
}

function mapDragRectangle(point) {
    if (dragRectangle) {
        second = point.latLng;
        IsEditable = false;
        draw_rectangle(first, point.latLng);
    }
}

function draw_rectangle(a, b) {
    if (myrectangle != null) {
        myrectangle.setMap(null);  //map.removeOverlay(myrectangle);
    }

    var rec = new google.maps.LatLngBounds();
    rec.extend(a);
    rec.extend(b);
    if (a != null && b != null) {

        myrectangle = new google.maps.Rectangle();
        var rectOptions = {
            strokeColor: "#fd942d",
            strokeOpacity: 0.7,
            strokeWeight: 5,
            fillColor: "#96bdfe",
            fillOpacity: 0.7,
            bounds: rec,
            editable: IsEditable
        };
        myrectangle.setOptions(rectOptions);

        myrectangle.setMap(map);

        google.maps.event.addListener(myrectangle, 'click', RecClick);

        if (IsEditable) {
            google.maps.event.addListener(myrectangle, 'bounds_changed', function(Bounds) {

                //To store all the values and pass to Server Side
                Array.clear(polyArray);
                var latlng = myrectangle.getBounds().toUrlValue().split(',');
                polyArray.push(latlng[2] + "," + latlng[1] + '#');
                polyArray.push(latlng[0] + "," + latlng[3] + '#');

                //                polyArray.push(myrectangle.getBounds().getSouthWest().toUrlValue() + '#');
                //                polyArray.push(myrectangle.getBounds().getNorthEast().toUrlValue() + '#');

                // Included by Kumuthini. L on 27-Jan-09
                if (document.getElementById('hdnCoordinates') != null) {
                    document.getElementById('hdnCoordinates').value = myrectangle.getBounds().getSouthWest().toUrlValue() + "#" + myrectangle.getBounds().getNorthEast().toUrlValue();
                }
            });
        }


        //myrectangle = new GPolygon(new Array(a, new GPoint(a.x, b.y), b, new GPoint(b.x, a.y), a), '#fd942d', 5, 0.5, '#96bdfe', .7);
        //myrectangle = new GPolygon(new Array((35.16707280202653, -90.06179809570312),new GPoint((35.16707280202653, -89.85855102539062)),(35.16931803601131, -89.85855102539062),new GPoint(35.16931803601131, -90.06179809570312),(35.16707280202653, -90.06179809570312)),'#fd942d',1,1,'#96bdfe',.5);
        //map.addOverlay(myrectangle);
        //        var collectdata = new GLatLngBounds();
        //        collectdata.extend(new GLatLng(a.y, a.x));
        //        collectdata.extend(new GLatLng(b.y, b.x));
        //        map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata));
    }
}

//To reload the Map by removing the drawn Overlays
function reload() {
    myrectangle.setMap(null);   //map.removeOverlay(myrectangle);
}
//This function is used for navTeq, to maintain the same kind of code in server side this function is been included in Google Script(Don't delete this).
function clearArray() {
    Array.clear(zoomIndex);
    zoomIndex.push(4);
    zoomIndex.push(centerCoordinate);
    isCanceled = true;
    //    zoomIndex.push(map.zoom);
    //    zoomIndex.push(new google.maps.LatLng(map.center.lat(), map.center.lng()));
}

function maintainZoomLevel() {
    if (map) {
        Array.clear(zoomIndex);
        zoomIndex.push(map.zoom);
        zoomIndex.push(new google.maps.LatLng(map.center.lat(), map.center.lng()));
    }
}

//Set Center to its org country.
function SetOrgCenter(coord) {
    var point = coord.split(',')
    if (map) {
        map.setCenter(new google.maps.LatLng(parseFloat(point[0]), parseFloat(point[1])), parseFloat(point[2]));
    }
    orgCenter = new google.maps.LatLng(parseFloat(point[0]), parseFloat(point[1]));
    orgZoomLevel = point[2];
}

// End of Rectangle geozone script