// Global variables
var LoadTime = null;
var maptype = "normal.day";
var map;
var behavior = null;
var ui = null;
var mapEvents = null;
var polyShape;
var polyLineColor = "#3355ff";
var polyFillColor = "#335599";
var polyPoints = new Array();
var polyArray = new Array();
var markers = new Array();
var report = document.getElementById("status");
var contextmenu;
var circleUnits;
var timeouts = [];
var geoType;
var Rec_bounds = new Array();
var poly_bounds;
var isview = 0;
var sGeoName = '';
var sIsGeoNameView = 0;
var maxMarkers = 5;
var centerCoordinate = new H.geo.Point(20.00, 78.00);
var poly_group = null;
var orgCenter = null;
var orgZoomLevel = null;
var VDirection = "ltr";
var landmarkInfo = null;
var canClearCircle = true;
var landmarkLatitude = '';
var landmarkLongitude = '';
var landmarkMarkers = new Array();
var landMarkCircles = new Array();
var search = '';
var chkValue = 0;
var LandMarkImage = '';
//var searchManager = new nokia.maps.advsearch.Manager();
var revGeocodeTerm;
var searchTerm;
var circle;
var centerMarker;
var circleUnits;
var circleRadius;
var triggerType;

//var platform = new H.service.Platform({
//    app_id: 'UdwAigBKPRhu01vbIGkI',
//    app_code: 'PzCfyYAsV98qvfU8gusqRg',
//    useCIT: true,
//    useHTTPS: true
//});
var platform = new H.service.Platform({
    //'apikey': '0OaPhakkm6zOHUc55oZIxP1mXOVPYk9KQdF7omnlmQo'
    'apikey': 'VWYjajXdN_OtsvW2akEG9Ys3uszv8gC1ktVFX7U-eto'
});
var defaultLayers = platform.createDefaultLayers();

var infoBubble = null;
var mapClick = true;
var IsDragStart = false;
var PrevCoordinates = null;
var CurrCoordinates = null;
var marker;
var IsDblClick = false;
var zoomIndex = new Array();

// Alerts
var getCentroid = function (path) {
    var f;
    var x = 0;
    var y = 0;
    var nPts = path.getLength();
    var j = nPts - 1;
    var area = 0;

    for (var i = 0; i < nPts; j = i++) {
        var pt1 = path.get(i);
        var pt2 = path.get(j);
        f = pt1.latitude * pt2.longitude - pt2.latitude * pt1.longitude;
        x += (pt1.latitude + pt2.latitude) * f;
        y += (pt1.longitude + pt2.longitude) * f;

        area += pt1.latitude * pt2.longitude;
        area -= pt1.longitude * pt2.latitude;
    }
    area /= 2;
    f = area * 6;
    return new H.geo.Point(x / f, y / f);
};


var defaultHandler = function (evt) {

    try {
        //var s_infoBubble = new nokia.maps.map.component.InfoBubbles();
        //var s_coord = map.pixelToGeo(evt.displayX, evt.displayY);
        alert("Geozone Name : " + evt.target.$name);
    }
    catch (err) {
        alert(err.Message);
    }

    /* Normally on certain events like double click the map zooms in 
    * we would like to prevent this behavior when clicking a 
    * Spatial object (Circle, Rectangle, Polyline or Polygon)
    */
    if (evt.target instanceof nokia.maps.map.Spatial) {
        /* Prevent other event listeners from being triggered
        * For more details see  nokia.maps.dom.Event
        */
        evt.stopImmediatePropagation();
    }
};

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 drawCirGeozone = 'Please draw the circular by click on map !';
var enterAddress = "Enter Address !";
var enterLatitude = "Enter Latitude !"
var enterLongitude = "Enter Longitude !"
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");
    var ht = $('#search-box').height() + 'px';
    if (holderControl != null) {
        document.getElementById('map').style.width = (holderControl.clientWidth - 10 - (document.getElementById('search-box').clientWidth)) + 'px';
        if (document.body.clientHeight < 875) {
            document.getElementById('search-box').style.height = 'auto';    //(875 - 375) + 'px';
            document.getElementById('map').style.height = ht;   //(875 - 375) + 'px';
        }
        else {
            document.getElementById('search-box').style.height = 'auto';    //(document.body.clientHeight - 375) + 'px';
            document.getElementById('map').style.height = ht;   //(document.body.clientHeight - 375) + 'px';
        }
    }
}

// Set the alert messages from the Resource File
function SetAlertMessages(maxGeozoneMarkersAlert, drawPolygonGeozoneAlert, drawRectGeozoneAlert, enterAddressAlert,
        enterLatitudeAlert, enterLongitudeAlert, enterCategoryNameAlert, categoryNameExistsAlert, categorySavedAlert,
        categoryUpdatedAlert, categoryCannotDeleteAlert, categoryConfirmDeleteAlert, Geozone_NoofPlots) {
    maxGeozoneMarkers = maxGeozoneMarkersAlert;
    drawPolygonGeozone = drawPolygonGeozoneAlert;
    drawRectGeozone = drawRectGeozoneAlert;
    enterAddress = enterAddressAlert;
    enterLatitude = enterLatitudeAlert;
    enterLongitude = enterLongitudeAlert;
    enterCategoryName = enterCategoryNameAlert;
    categoryNameExists = categoryNameExistsAlert;
    categorySaved = categorySavedAlert;
    categoryUpdated = categoryUpdatedAlert;
    categoryCannotDelete = categoryCannotDeleteAlert;
    categoryConfirmDelete = categoryConfirmDeleteAlert;
    NoofGeozonePlots = Geozone_NoofPlots;
}

function loadMap() {
    try {
        if (map) {
            map.removeObjects(map.getObjects());
        }
    }
    catch (Error) {

    }
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    var holderControl = document.getElementById("content");
    var ht = $('#search-box').height() + 'px';
    document.getElementById('search-box').style.width = '100%';
    if (holderControl != null) {
        document.getElementById('map').style.width = '100%';         /* Jayaram changes 0n 30-05-2016 for bootstrap convertion purpose */
        //document.getElementById('map').style.width = (holderControl.clientWidth - 10 - (document.getElementById('search-box').clientWidth)) + 'px';  /* sakthi sir */        
        if (document.body.clientHeight < 875) {
            document.getElementById('search-box').style.height = 'auto';    //(875 - 375) + 'px';
            document.getElementById('map').style.height = ht;   //(875 - 375) + 'px';
        }
        else {
            document.getElementById('search-box').style.height = 'auto';    //(document.body.clientHeight - 375) + 'px';
            document.getElementById('map').style.height = ht;   //(document.body.clientHeight - 375) + 'px';
        }
    }
    // Create the map inside the map container.    
    try {
        var mapContainer = document.getElementById('map').innerHTML;
        if (document.getElementById('map').innerHTML == "" || mapContainer.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            //infoBubble = new nokia.maps.map.component.InfoBubbles();
            map = new H.Map(document.getElementById("map"),
             defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4,
                engineType: H.map.render.RenderEngine.EngineType.P2D
            });

            // Set up events for the map:
            mapEvents = new H.mapevents.MapEvents(map); //new mapsjs.mapevents.MapEvents(map);

            //Behaviour
            behavior = new H.mapevents.Behavior(mapEvents);

            // Create the default UI components
            ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");

            ui.removeControl('scalebar');
            ui.getControl('mapsettings').setAlignment('top-left');
            ui.getControl('zoom').setAlignment('left-middle');

            IsDblClick = false;
            if (zoomIndex.length > 0) {
                map.setZoom(parseFloat(zoomIndex[0]));
                map.setCenter(zoomIndex[1]);
            }

            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value == "LanguageArNew") {
                    changeTileProvider(maptype, 'Ar');
                    LoadTime = null;
                    //map.addObserver("baseMapType", MapTypeObserver);
                }
                else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                    changeTileProvider(maptype, 'hin');
                    LoadTime = null;
                    //map.addObserver("baseMapType", MapTypeObserver);
                }
            }
            //applyFleetLayer_NV(map, platform);
        }
        else {
            //map.setZoomLevel(4, "default");
        }
    }
    catch (Error) {

    }

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

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

        if (isview == 0) {
            map.removeEventListener("tap", getCoordinate, false);
            map.removeEventListener("pointermove", mapDragRectangle, false);
            map.removeEventListener("tap", Getlatlng);
            map.removeEventListener("tap", leftClick);
            eventOnclick = map.addEventListener("tap", leftClick);
        }
        else {
            map.removeEventListener("tap", leftClick);
        }
        geoType = 2;
    }
    else if (oUnitsMI != null && oUnitsMI.checked) {

        circleUnits = 'RC';
        map.removeEventListener("tap", leftClick, false);
        myrectangle = null;

        map.removeEventListener("tap", getCoordinate);
        map.removeEventListener("pointermove", mapDragRectangle);
        map.removeEventListener("tap", Getlatlng);
        eventOnclick = map.addEventListener("tap", getCoordinate);
        eventOnMove = map.addEventListener("pointermove", mapDragRectangle);

        if (isview == 0) {
            //eventOnclick = GEvent.addListener(map, 'click', mapClickRectangle);
        }

        dragRectangle = false;
        geoType = 1;
    }
    else {
        circleUnits = 'CR';
        myrectangle = null;
        map.removeEventListener("tap", getCoordinate);
        map.removeEventListener("mousemove", mapDragRectangle);
        map.removeEventListener("tap", leftClick);
        map.removeEventListener("tap", Getlatlng);
        if (isview == 0) {
            eventOnclick = map.addEventListener("tap", Getlatlng);
        }
        geoType = 3;
    }

    function dblClick() {
        try {
            map.removeEventListener(eventOnclick);
            if (oUnitsKM != null && oUnitsKM.checked) {
                markers.length = markers.length - 1;
                markers.splice(markers.length, 1);
                map.removeObject(marker);
                drawPoly(0);
            }
            else if (oUnitsMI != null && oUnitsMI.checked) {
                first = '';
                dragRectangle = false;
                map.removeEventListener("tap", getCoordinate);
                map.removeEventListener("pointermove", mapDragRectangle);
                eventOnclick = map.addEventListener("tap", getCoordinate);
                eventOnMove = map.addEventListener("pointermove", mapDragRectangle);
            }
        }
        catch (Error) {
        }
    }
    if (isview == 0) {
        if (!IsDblClick) {
            //If double click event is already assigned skip reassigning of event.
            map.addEventListener("dbltap", dblClick);
            IsDblClick = true;
        }
        //);

        if (document.getElementById('hdnMapZoomLevel').value != "") {
            map.setZoom(parseFloat(eval(document.getElementById('hdnMapZoomLevel').value)));
        }
    }


    // === create the context menu div ===
    contextmenu = document.createElement("div");
    contextmenu.style.visibility = "hidden";
    contextmenu.style.background = "#ffffff";
    contextmenu.style.border = "1px solid #8888FF";

    contextmenu.innerHTML = '<a href="javascript:zoomIn()"><div class="context">&nbsp;&nbsp;Zoom in&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:zoomOut()"><div class="context">&nbsp;&nbsp;Zoom out&nbsp;&nbsp;</div></a>';

    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (mapTypeHolder.value) {
            case 'N': map.setBaseLayer(defaultLayers.raster.normal.map); break;
            case 'H': map.setBaseLayer(defaultLayers.raster.satellite.map); break;
            case 'T': map.setBaseLayer(defaultLayers.raster.terrain.map); break;
        }
        //applyFleetLayer_NV(map, platform);
    }
}

// Included by Kumuthini. L on 30-Jan-09
function mapTypeChanged() {
    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (map.getCurrentMapType()) {
            case 'N': map.setBaseLayer(defaultLayers.raster.normal.map); break;
            case 'H': map.setBaseLayer(defaultLayers.raster.satellite.map); break;
            case 'T': map.setBaseLayer(defaultLayers.raster.terrain.map); break;
        }
        //applyFleetLayer_NV(map, platform);
    }
}

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);
}

//Function for drawing a polygon.
function leftClick(overlay, point) {
    if (mapClick) {
        if (!point || point == '') {
            point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
            //map.pixelToGeo(overlay.displayX, overlay.displayY);
        }
        if (point) {
            maxMarkers = document.getElementById('hdnMaxGeozoneMarkers').value;

            if (isview == 0) {
                if (markers.length > 0) {
                    var temp = markers[markers.length - 1].getGeometry().lat + ',' + markers[markers.length - 1].getGeometry().lng;
                    var p = point.lat + ',' + point.lng;
                    if (temp == p) {
                        map.removeObject(marker);
                        markers.length = markers.length - 1;
                        markers.splice(markers.length, 1);
                    }
                }


                if ((markers.length + 1) > maxMarkers) {
                    //alert("Geozones are restricted to have only " + maxMarkers + " points !");
                    TrinetraCustomAlerts(maxGeozoneMarkers.replace("<#maxMarkers#>", maxMarkers));
                    return false;
                }
            }

            // Make markers draggable
            if (isview == 0) {

                marker = new H.map.Marker(point, {});
                marker.draggable = true;
            }
            else {
                marker = new H.map.Marker(point, {});
                marker.draggable = true;
            }

            markers.push(marker);
            map.addObject(marker);

            if (isview == 0) {
                marker.addEventListener("dragstart", function (evt) { behavior.disable(); }, false);
                marker.addEventListener("drag", function (evt) {
                    // Get the marker itself.
                    //var marker = evt.dataTransfer.getData("application/map-drag-object");
                    // Get the offset of the mouse relative to the top-left corner of the marker.
                    //var offset = evt.dataTransfer.getData("application/map-drag-object-offset");

                    //CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX - offset.x + marker.anchor.x, evt.currentPointer.viewportY - offset.y + marker.anchor.y);
                    CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                    //map.pixelToGeo(evt.displayX - offset.x + marker.anchor.x, evt.displayY - offset.y + marker.anchor.y);
                    PrevCoordinates = evt.target.getGeometry();
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                });

                marker.addEventListener("dragend", function (evt) {
                    behavior.enable();
                    // Get the marker itself.
                    //var marker = evt.dataTransfer.getData("application/map-drag-object");

                    // Get the offset of the mouse relative to the top-left corner of the marker.
                    //var offset = evt.dataTransfer.getData("application/map-drag-object-offset");

                    //CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX - offset.x + marker.anchor.x, evt.currentPointer.viewportY - offset.y + marker.anchor.y);
                    CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                    PrevCoordinates = evt.target.getGeometry();
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                    //marker.setImage("mapIcons/m-over-square.png");
                });

                marker.addEventListener("pointerout", function () {
                });

                // Second click listener to remove the square
                marker.addEventListener("tap", function (evt) {
                    // Find out which square to remove
                    for (var n = 0; n < markers.length; n++) {
                        //var MarkerCoord = 
                        if (markers[n].getGeometry() == evt.target.getGeometry()) {
                            map.removeObject(markers[n]);
                            mapClick = false;
                            break;
                        }
                    }
                    markers.splice(n, 1);
                    drawPoly(0);
                });
            }
            drawPoly(0);
        }
    }
    mapClick = true;
}

var polyArray = new Array();
var polyStrip = new H.geo.LineString();
function drawPoly(type) {
    try {

        if (polyShape != null) {
            poly_group.removeObjects(poly_group.getObjects());
        }

        polyPoints.length = 0;
        polyArray.length = 0;
        polyStrip = new H.geo.LineString();
        for (i = 0; i < markers.length; i++) {
            if (IsDragStart) {
                //markers[i].coordinate = markers[i].coordinate == PrevCoordinates ? CurrCoordinates : markers[i].coordinate;
                markers[i].setGeometry(markers[i].getGeometry() == PrevCoordinates ? CurrCoordinates : markers[i].getGeometry());
            }

            polyPoints.push(markers[i].getGeometry());
            polyStrip.pushPoint(markers[i].getGeometry());
            //var appendvalues = markers[i].coordinate.lat + ',' + markers[i].coordinate.lng + '#';
            var appendvalues = markers[i].getGeometry().lat + ',' + markers[i].getGeometry().lng + '#';
            polyArray.push(appendvalues);
        }

        // 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 filClr = "rgba(65,105,225,0.5)";//"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
        var lneClr = "rgba(0,0,128,1)"; //#3355ff - Normal Geozone #FF0000 - Restricted Geozone #2E8B57 - UnRestricted Geozone

        if (type == 1) {
            filClr = "#F145";
            lneClr = "#FF0000";
        }
        else if (type == 2) {
            filClr = "#2E45";
            lneClr = "#2E8B57";
        }

        polyShape = new H.map.Polygon(polyStrip, {
            //$name: sGeoName,
            style: { strokeColor: lneClr, lineWidth: .4, fillColor: filClr }
        });

        // On mouse click we fire off the default event handler
        //polyShape.addListener("click", defaultHandler);
        if (isview == 1) {
            polyShape.setData(sGeoName);
            polyShape.addEventListener(
              'tap',
              function (e) {
                  ui.removeBubble(infoBubble);
                  var coord = map.screenToGeo(e.currentPointer.viewportX, e.currentPointer.viewportY);
                  infoBubble = new H.ui.InfoBubble(coord,
                      //getCentroid(e.target.getPath()),
                      { content: 'Geozone Name : ' + e.target.getData() });
                  ui.addBubble(infoBubble);
                  //                  infoBubble.openBubble(
                  //                  'Geozone Name : ' + sGeoName,
                  //                  getCentroid(e.target.getPath())
                  //                );
                  //                  nokia.maps.dom.EventTarget(bubble.node).addEventListener('tap', function(e) {
                  //                      infoBubble.closeAll();
                  //                  });
              }
            );
        }

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

        poly_group = new H.map.Group();
        poly_group.addObject(polyShape);
        map.addObject(poly_group);
    }
    catch (e) {
        //alert(e);
    }
}

function zoomToPoly() {
    if (polyShape && polyPoints.length > 0) {
        map.getViewModel().setLookAtData({
            bounds: polyShape.getBoundingBox()
        });
        //map.setViewBounds(polyShape.getBounds());
    }
}

function clearPoly() {
    // Remove polygon and reset arrayse
    //if (map) map.removeObjects(map.getObjects());
    if (polyShape != null) {
        poly_group.removeObjects(poly_group.getObjects());
    }
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    landMarkCircles.length = 0;
    //Clear Rectangle Geozone
    r1 = null;
    if (myrectangle != null) {
        map.removeObject(myrectangle);
        myrectangle = null;
    }
    document.getElementById('hdnCoordinates').value = "";
    maintainZoomLevel();
    //if(IsDblClick = true)    
    loadMap();
    var rdoID = document.getElementById('unitsCIR');
    var isIE = CheckBrowser();
    if (rdoID != null && rdoID.checked) {
        if (document.getElementById('txtRadius') != null) {
            document.getElementById('txtRadius').setAttribute((isIE ? 'className' : 'class'), (isIE ? "form-control ControlShow" : "form-control ControlShowFF"))
        }
        if (document.getElementById('Image1') != null) {
            document.getElementById('Image1').setAttribute(isIE ? 'className' : 'class', (isIE ? "ControlShow" : "ControlShowFF"))
        }
        if (document.getElementById('Label5') != null) {
            document.getElementById('Label5').setAttribute(isIE ? 'className' : 'class', (isIE ? "ControlShow" : "ControlShowFF"))
        }
    }
    else {
        if (document.getElementById('txtRadius') != null) {
            document.getElementById('txtRadius').setAttribute(isIE ? 'className' : 'class', "ControlHide")
        }
        if (document.getElementById('Image1') != null) {
            document.getElementById('Image1').setAttribute(isIE ? 'className' : 'class', "ControlHide")
        }
        if (document.getElementById('Label5') != null) {
            document.getElementById('Label5').setAttribute(isIE ? 'className' : 'class', "ControlHide")
        }
    }
    map.setCenter(centerCoordinate);
    map.setZoom(4);
}

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 += '</br>' + drawRectGeozone;
                }
                else {
                    alertMsg = drawRectGeozone;
                }
            }
        }
    }
    else if (circleUnits == "CR") {
        if (polyArray.length > 0 && alertMsg == 'NoError') {
            drawShapes();
        }
        else {
            if (polyArray.length == 0) {
                if (alertMsg != 'NoError') {
                    alertMsg += '</br>' + drawCirGeozone;
                }
                else {
                    alertMsg = drawCirGeozone;
                }
            }
        }
    }

    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) {
    TrinetraCustomAlerts(arg);
}
function ReceiveServerDataGeozone(arg, context) {
    TrinetraCustomAlerts(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;
    //sIsGeoNameView = isGeoView;
    //$find('modalMap').show();
    document.getElementById('pnlManageGeozoneHolder').style.display = "block";
    document.getElementById('pnlGeozoneDetailsList').style.display = "none";


    IsDblClick = false; //To reassign the Double click event to the map.

    clearPoly();
    var collectdata = new Array();
    //poly_bounds = new GLatLngBounds();

    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 H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
        leftClick('', point);
    }
    zoomToPoly();
}

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

    clearPoly();

    //Rec_bounds = new GLatLngBounds();
    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 H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));
        var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
        mapClickRectangle('', point);
    }
    zoomToPoly();
}

function cirGeozones(latlng, isView, geoName) {
    var isIE = CheckBrowser();
    isview = isView;
    sGeoName = geoName;
    //sIsGeoNameView = isGeoView;
    //$find('modalMap').show();
    document.getElementById('pnlManageGeozoneHolder').style.display = "block";
    document.getElementById('pnlGeozoneDetailsList').style.display = "none";

    //clearPoly();

    //Rec_bounds = new GLatLngBounds();
    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 H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));
        var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
        ShowAddress(point.lat, point.lng);
    }
    //zoomToPoly();
}

//TO toggle the Radio buttons
function toggle(rdoID) {

    var isIE = CheckBrowser();
    r1 = null;
    if (rdoID == 'unitsMI') {
        if (document.getElementById('unitsKM') != null) {
            document.getElementById('unitsKM').checked = false;
        }
        if (document.getElementById('unitsMI') != null) {
            document.getElementById('unitsMI').checked = true;
        }
        if (document.getElementById('unitsCIR') != null) {
            document.getElementById('unitsCIR').checked = false;
        }
        if (document.getElementById('txtRadius') != null) {
            document.getElementById('txtRadius').setAttribute(isIE ? 'className' : 'class', "ControlHide")
        }
        if (document.getElementById('Image1') != null) {
            document.getElementById('Image1').setAttribute(isIE ? 'className' : 'class', "ControlHide")
        }
        if (document.getElementById('Label5') != null) {
            document.getElementById('Label5').setAttribute(isIE ? 'className' : 'class', "ControlHide")
        }
    }
    else if (rdoID == 'unitsKM') {
        if (document.getElementById('unitsKM') != null) {
            document.getElementById('unitsKM').checked = true;
        }
        if (document.getElementById('unitsMI') != null) {
            document.getElementById('unitsMI').checked = false;
        }
        if (document.getElementById('unitsCIR') != null) {
            document.getElementById('unitsCIR').checked = false;
        }
        if (document.getElementById('txtRadius') != null) {
            document.getElementById('txtRadius').setAttribute(isIE ? 'className' : 'class', "ControlHide");
        }
        if (document.getElementById('Image1') != null) {
            document.getElementById('Image1').setAttribute(isIE ? 'className' : 'class', "ControlHide");
        }
        if (document.getElementById('Label5') != null) {
            document.getElementById('Label5').setAttribute(isIE ? 'className' : 'class', "ControlHide");
        }
    }
    else {
        if (document.getElementById('unitsKM') != null) {
            document.getElementById('unitsKM').checked = false;
        }
        if (document.getElementById('unitsMI') != null) {
            document.getElementById('unitsMI').checked = false;
        }
        if (document.getElementById('unitsCIR') != null) {
            document.getElementById('unitsCIR').checked = true;
        }
        if (document.getElementById('txtRadius') != null) {
            document.getElementById('txtRadius').setAttribute((isIE ? 'className' : 'class'), (isIE ? "form-control ControlShow" : "form-control ControlShowFF"));
        } if (document.getElementById('Image1') != null) {
            document.getElementById('Image1').setAttribute(isIE ? 'className' : 'class', (isIE ? "ControlShow" : "ControlShowFF"));
        } if (document.getElementById('Label5') != null) {
            document.getElementById('Label5').setAttribute(isIE ? 'className' : 'class', (isIE ? "ControlShow" : "ControlShowFF"));
        }
    }

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

var icon;
function Findplace(lat, lng) {

    //icon = new GIcon(G_DEFAULT_ICON);
    //map.clearOverlays();
    //icon = new GIcon(icon, '../images/poi_viewer_house.gif');
    //map.objects.clear();

    icon = '../images/poi_viewer_house.gif';
    var point = new H.geo.Point(parseFloat(lat), parseFloat(lng));
    map.setCenter(point);

    //var lndmarker = new GMarker(point, { draggable: false, icon: icon });
    var lndmarker = new H.map.Marker(point, {
        icon: new H.map.Icon(icon, new H.math.Point(12, 27))
    });
    map.addObject(lndmarker);
    //map.setViewBounds(lndmarker.getBounds());
    map.setViewBounds(point.getBounds());
    if (map.getZoom() > 15) map.setZoom(15); //zoom out if too close
}

//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
        if ($find('modalMap')) $find('modalMap').hide();
    }
}

function CloseModal() {
    if ($find('modalMap')) $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) {
        TrinetraCustomAlerts(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();
        TrinetraCustomAlerts(categoryNameExists);
        return;
    }
    if (type == 'Add') {
        TrinetraCustomAlerts(categorySaved);
    }
    if (type == 'Edit') {
        TrinetraCustomAlerts(categoryUpdated);
    }
    var pnlCategory = document.getElementById("pnlGeozoneCategory");
    pnlCategory.style.display = "none";
    setFocusToControl('ddlCategory');
}

function GetCategoryConfirmation() {
    if (document.getElementById("hdnCatAssignedStatus").value == 1) {
        TrinetraCustomAlerts(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 Getlatlng(overlay, point) {
    //  var cord = map.pixelToGeo(evt.displayX, evt.displayY);
    if (!point || point == '') {
        point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
        //    }
        var lat, lng;
        //  showControls(1);
        //    if (cord != null) {
        lat = Math.round(point.lat * 1000000) / 1000000;
        lng = Math.round(point.lng * 1000000) / 1000000;
        if (document.getElementById('hdnLatLong') != null) {
            document.getElementById('hdnLatLong').value = point.lat + ',' + point.lng;
        }
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = point.lat + ',' + point.lng;
        }
        chkValue = 0;
        document.getElementById('hdnIsLocateMe').value = 'N';
        ShowAddress(lat, lng, 'MapClickEvent');
    }
}
function getCoordinate(overlay, point) {

    if (!point || point == '') {
        point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
        //map.pixelToGeo(overlay.displayX, overlay.displayY);
    }

    if (first == '') {
        if (myrectangle != null)
        { return; }
        else {
            myrectangle = null;
        }
        dragRectangle = true;
        first = point;
    }
    else {
        //GEvent.removeListener(eventOnMove);
        second = point;
        dragRectangle = false;
        draw_rectangle(first, second);
        r1 = first;
        r2 = second;

        //new nokia.maps.geo.Coordinate(parseFloat(a.latitude), parseFloat(b.longitude)), b, new nokia.maps.geo.Coordinate(parseFloat(b.latitude), parseFloat(a.longitude))
        //Rec_bounds = new nokia.maps.geo.BoundingBox(r1, r2);
        var marker1 = r1;  //new nokia.maps.geo.Coordinate(r1); //GMarker(r1);
        var marker2 = r2;  //new nokia.maps.geo.Coordinate(r2); //GMarker(r2);

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

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

        //To store all the values and pass to Server Side
        polyArray.push(marker1.lat + ',' + marker1.lng + '#');
        polyArray.push(marker2.lat + ',' + marker2.lng + '#');
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = polyArray;
        }

        r1 = ''
        r2 = ''
        try {
            //map.setViewBounds(myrectangle.getBounds());
            map.getViewModel().setLookAtData({
                bounds: myrectangle.getBoundingBox()
            });
        }
        catch (er) {
            TrinetraCustomAlerts(er);
        }
        first = '';
        second = '';
    }
}

function ClearMap() {
    if (oUnitsKM.checked) {
        map.removeObject(markers[markers.length - 1]);
        markers.length = markers.length - 1;
        markers.splice(markers.length, 1);


        drawPoly(0);
        eventOnclick = map.addEventListener("tap", getCoordinate);
    }
    else {
        first = '';
        dragRectangle = false;
        myrectangle = null;
    }
}


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

    if (!r1) {   // First click
        r1 = point;
        myrectangle = null;
        dragRectangle = true;
    }
    else {   // Second click
        //map.objects.clear(); 
        dragRectangle = false;
        draw_rectangle(r1, point);
        r2 = point;

        //Rec_bounds = new nokia.maps.geo.BoundingBox(r1, r2);

        var marker1 = r1;
        var marker2 = r2;

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

        polyArray.length = 0;

        //To store all the values and pass to Server Side
        polyArray.push(marker1.lat + ',' + marker1.lng + '#');
        polyArray.push(marker2.lat + ',' + marker2.lng + '#');

        // Included by Kumuthini. L on 27-Jan-09
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = polyArray;
        }
        r1 = ''
        r2 = ''
        //map.setViewBounds(myrectangle.getBounds());
        map.getViewModel().setLookAtData({
            bounds: myrectangle.getBoundingBox()
        });
    }
}

function mapDragRectangle(point) {
    point = map.screenToGeo(point.currentPointer.viewportX, point.currentPointer.viewportY);
    //map.pixelToGeo(point.displayX, point.displayY);
    //point = map.point
    if (dragRectangle) {
        second = point;
        draw_rectangle(first, point);
    }
}



function draw_rectangle(a, b) {

    if (myrectangle != null) { map.removeObject(myrectangle); }

    if (a != null && b != null) {

        if (b.lng > a.lng) {
            myrectangle = new H.map.Rect(new H.geo.Rect(parseFloat(a.lat), parseFloat(a.lng), parseFloat(b.lat), parseFloat(b.lng)), {
                //new H.map.Polygon([a, new H.geo.Point(parseFloat(a.latitude), parseFloat(b.longitude)), b, new H.geo.Point(parseFloat(b.latitude), parseFloat(a.longitude))], {
                //$name: sGeoName,
                style: { strokeColor: "rgba(0,0,128,1)", lineWidth: 1, fillColor: "rgba(65, 105, 225, 0.5)" } //stroke color : "#fd942d" fill color : "#859CB3"
            });
        }
        else {
            myrectangle = new H.map.Rect(new H.geo.Rect(parseFloat(a.lat), parseFloat(b.lng), parseFloat(b.lat), parseFloat(a.lng)), {
                //new H.map.Polygon([a, new H.geo.Point(parseFloat(a.latitude), parseFloat(b.longitude)), b, new H.geo.Point(parseFloat(b.latitude), parseFloat(a.longitude))], {
                //$name: sGeoName,
                style: { strokeColor: "rgba(0,0,128,1)", lineWidth: 1, fillColor: "rgba(65, 105, 225, 0.5)" } //stroke color : "#fd942d" fill color : "#859CB3"
            });
        }

        // On mouse click we fire off the default event handler
        //myrectangle.addListener("click", defaultHandler);
        if (isview == 1) {
            myrectangle.setData(sGeoName);
            myrectangle.addEventListener(
              'tap',
              function (e) {
                  ui.removeBubble(infoBubble);
                  var coord = map.screenToGeo(e.currentPointer.viewportX, e.currentPointer.viewportY);
                  infoBubble = new H.ui.InfoBubble(coord,
                      //getCentroid(e.target.getPath()),
                      { content: 'Geozone Name : ' + e.target.getData() });
                  ui.addBubble(infoBubble);
                  //                  infoBubble.openBubble(
                  //                  'Geozone Name : ' + sGeoName,
                  //                  getCentroid(e.target.getPath())
                  //                );
                  //                  nokia.maps.dom.EventTarget(bubble.node).addListener('click', function(e) {
                  //                      infoBubble.closeAll();
                  //                  });
              }
            );
        }
        if (isview != 1) {
            myrectangle.draggable = true;
            map.addObject(myrectangle);
            myrectangle.addEventListener('pointerenter', function (evt) {
                var currentStyle = myrectangle.getStyle(),
                    newStyle = currentStyle.getCopy({
                        strokeColor: 'rgb(255, 0, 0)',
                        lineWidth: 5
                    });
                // show outline
                myrectangle.setStyle(newStyle);
            }, true);

            myrectangle.addEventListener('pointerleave', function (evt) {
                var currentStyle = myrectangle.getStyle(),
                    newStyle = currentStyle.getCopy({
                        strokeColor: "rgba(0,0,128,1)",
                        lineWidth: 1
                    }),
                    timeout = (evt.currentPointer.type == 'touch') ? 1000 : 0;

                rectTimeout = setTimeout(function () {
                    myrectangle.setStyle(newStyle);
                }, timeout);


                document.body.style.cursor = 'default';
            }, true);

            // event listener for rectangle group to change the cursor if mouse position is over the outline polyline (resizing is allowed)
            myrectangle.addEventListener('pointermove', function (evt) {
                var pointer = evt.currentPointer,
                    objectTopLeftScreen = map.geoToScreen(evt.target.getGeometry().getBoundingBox().getTopLeft()),
                    objectBottomRightScreen = map.geoToScreen(evt.target.getGeometry().getBoundingBox().getBottomRight()),
                    draggingType = '';

                // only set cursor and draggingType if target is outline polyline
                if (evt.target != myrectangle) {
                    return;
                }

                // change document cursor depending on the mouse position
                if (pointer.viewportX < (objectTopLeftScreen.x + 4)) {
                    document.body.style.cursor = 'ew-resize'; // mouse position is at left side
                    draggingType = 'left';
                } else if (pointer.viewportX > (objectBottomRightScreen.x - 4)) {
                    document.body.style.cursor = 'ew-resize'; // mouse position is at right side
                    draggingType = 'right';
                } else if (pointer.viewportY < (objectTopLeftScreen.y + 4)) {
                    document.body.style.cursor = 'ns-resize'; // mouse position is at top side
                    draggingType = 'top';
                } else if (pointer.viewportY > (objectBottomRightScreen.y - 4)) {
                    document.body.style.cursor = 'ns-resize'; // mouse position is at the bottom side
                    draggingType = 'bottom';
                } else {
                    document.body.style.cursor = 'default'
                }

                if (draggingType == 'left') {
                    if (pointer.viewportY < (objectTopLeftScreen.y + 4)) {
                        document.body.style.cursor = 'nwse-resize'; // mouse position is at the top-left corner
                        draggingType = 'left-top';
                    } else if (pointer.viewportY > (objectBottomRightScreen.y - 4)) {
                        document.body.style.cursor = 'nesw-resize'; // mouse position is at the bottom-left corner
                        draggingType = 'left-bottom';
                    }
                } else if (draggingType == 'right') {
                    if (pointer.viewportY < (objectTopLeftScreen.y + 4)) {
                        document.body.style.cursor = 'nesw-resize'; // mouse position is at the top-right corner
                        draggingType = 'right-top';
                    } else if (pointer.viewportY > (objectBottomRightScreen.y - 4)) {
                        document.body.style.cursor = 'nwse-resize'; // mouse position is at the bottom-right corner
                        draggingType = 'right-bottom';
                    }
                }

                myrectangle.setData({ 'draggingType': draggingType });
            }, true);
            // disable the map's behavior if resizing started so map doesn't pan in the situation
            // when we try to set rect size to 0 or negative and mouse cursor leaves the map object
            myrectangle.addEventListener('dragstart', function (evt) {
                if (evt.target === myrectangle) {
                    behavior.disable();
                }
            }, true);

            // event listener for rect group to resize the geo rect object if dragging over outline polyline
            myrectangle.addEventListener('drag', function (evt) {
                var pointer = evt.currentPointer,
                    pointerGeoPoint = map.screenToGeo(pointer.viewportX, pointer.viewportY);
                currentGeoRect = myrectangle.getGeometry().getBoundingBox(),
                objectTopLeftScreen = map.geoToScreen(currentGeoRect.getTopLeft()),
                objectBottomRightScreen = map.geoToScreen(currentGeoRect.getBottomRight());

                // if pointer is over outline, resize the geo rect object
                if (evt.target instanceof H.map.Rect) {
                    var currentTopLeft = currentGeoRect.getTopLeft(),
                        currentBottomRight = currentGeoRect.getBottomRight(),
                        newGeoRect,
                        outlineLinestring;

                    // update rect's size depending on dragging type:
                    switch (myrectangle.getData()['draggingType']) {
                        case 'left-top':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lng >= currentBottomRight.lng || pointerGeoPoint.lat <= currentBottomRight.lat) {
                                return;
                            }
                            newGeoRect = H.geo.Rect.fromPoints(pointerGeoPoint, currentGeoRect.getBottomRight());
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(pointerGeoPoint.lat + ',' + pointerGeoPoint.lng + '#');
                            polyArray.push(currentGeoRect.getBottomRight().lat + ',' + currentGeoRect.getBottomRight().lng + '#');
                            break;
                        case 'left-bottom':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lng >= currentBottomRight.lng || pointerGeoPoint.lat >= currentTopLeft.lat) {
                                return;
                            }
                            currentTopLeft.lng = pointerGeoPoint.lng;
                            currentBottomRight.lat = pointerGeoPoint.lat;
                            newGeoRect = H.geo.Rect.fromPoints(currentTopLeft, currentBottomRight);
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(currentTopLeft.lat + ',' + currentTopLeft.lng + '#');
                            polyArray.push(currentBottomRight.lat + ',' + currentBottomRight.lng + '#');
                            break;
                        case 'right-top':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lng <= currentTopLeft.lng || pointerGeoPoint.lat <= currentBottomRight.lat) {
                                return;
                            }
                            currentTopLeft.lat = pointerGeoPoint.lat;
                            currentBottomRight.lng = pointerGeoPoint.lng;
                            newGeoRect = H.geo.Rect.fromPoints(currentTopLeft, currentBottomRight);
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(currentTopLeft.lat + ',' + currentTopLeft.lng + '#');
                            polyArray.push(currentBottomRight.lat + ',' + currentBottomRight.lng + '#');
                            break;
                        case 'right-bottom':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lng <= currentTopLeft.lng || pointerGeoPoint.lat >= currentTopLeft.lat) {
                                return;
                            }
                            newGeoRect = H.geo.Rect.fromPoints(currentGeoRect.getTopLeft(), pointerGeoPoint);
                            //console.log('right-bottom------> ' + currentGeoRect.getTopLeft(), pointerGeoPoint);
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(currentGeoRect.getTopLeft().lat + ',' + currentGeoRect.getTopLeft().lng + '#');
                            polyArray.push(pointerGeoPoint.lat + ',' + pointerGeoPoint.lng + '#');
                            break;
                        case 'left':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lng >= currentBottomRight.lng) {
                                return;
                            }
                            currentTopLeft.lng = pointerGeoPoint.lng;
                            newGeoRect = H.geo.Rect.fromPoints(currentTopLeft, currentGeoRect.getBottomRight());
                            //console.log('left------> ' + currentTopLeft, currentGeoRect.getBottomRight());
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(currentTopLeft.lat + ',' + currentTopLeft.lng + '#');
                            polyArray.push(currentGeoRect.getBottomRight().lat + ',' + currentGeoRect.getBottomRight().lng + '#');
                            break;
                        case 'right':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lng <= currentTopLeft.lng) {
                                return;
                            }
                            currentBottomRight.lng = pointerGeoPoint.lng;
                            newGeoRect = H.geo.Rect.fromPoints(currentGeoRect.getTopLeft(), currentBottomRight);
                            // console.log('right------> ' + currentGeoRect.getTopLeft(), currentBottomRight);
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(currentGeoRect.getTopLeft().lat + ',' + currentGeoRect.getTopLeft().lng + '#');
                            polyArray.push(currentBottomRight.lat + ',' + currentBottomRight.lng + '#');
                            break;
                        case 'top':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lat <= currentBottomRight.lat) {
                                return;
                            }
                            currentTopLeft.lat = pointerGeoPoint.lat;
                            newGeoRect = H.geo.Rect.fromPoints(currentTopLeft, currentGeoRect.getBottomRight());
                            //console.log('top------> ' + currentTopLeft, currentGeoRect.getBottomRight());
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(currentTopLeft.lat + ',' + currentTopLeft.lng + '#');
                            polyArray.push(currentGeoRect.getBottomRight().lat + ',' + currentGeoRect.getBottomRight().lng + '#');
                            break;
                        case 'bottom':
                            // we don't allow resizing to 0 or to negative values
                            if (pointerGeoPoint.lat >= currentTopLeft.lat) {
                                return;
                            }
                            currentBottomRight.lat = pointerGeoPoint.lat;
                            newGeoRect = H.geo.Rect.fromPoints(currentGeoRect.getTopLeft(), currentBottomRight);
                            //console.log('bottom------> ' + currentGeoRect.getTopLeft(), currentBottomRight);
                            polyArray.length = 0;
                            //To store all the values and pass to Server Side
                            polyArray.push(currentGeoRect.getTopLeft().lat + ',' + currentGeoRect.getTopLeft().lng + '#');
                            polyArray.push(currentBottomRight.lat + ',' + currentBottomRight.lng + '#');
                            break;
                    }

                    // set the new bounding box for rect object
                    myrectangle.setBoundingBox(newGeoRect);

                    // extract first point of the outline LineString and push it to the end, so the outline has a closed geometry
                    outlineLinestring = myrectangle.getGeometry().getExterior();
                    outlineLinestring.pushPoint(outlineLinestring.extractPoint(0));
                    myrectangle.setGeometry(outlineLinestring);

                    // prevent event from bubling, so map doesn't receive this event and doesn't pan
                    evt.stopPropagation();
                }
            }, true);

            // event listener for rect group to enable map's behavior
            myrectangle.addEventListener('dragend', function (evt) {
                // enable behavior
                behavior.enable();
            }, true);
        }
        else {
            map.addObject(myrectangle);
        }
        //poly_group = new H.map.Group();
        //poly_group.addObject(myrectangle);   
    }
}

//To reload the Map by removing the drawn Overlays
function reload() {
    map.removeObject(myrectangle);
}

// End of Rectangle geozone script

function clearArray() {
    //Array.clear(zoomIndex);
    map.setZoom(orgZoomLevel != null ? orgZoomLevel : 4);
    map.setCenter(orgCenter != null ? orgCenter : centerCoordinate);
}

function maintainZoomLevel() {
    if (map) {
        Array.clear(zoomIndex);
        zoomIndex.push(map.getZoom());
        zoomIndex.push(map.getCenter());
    }
}

//Set Center to its org country.
function SetOrgCenter(coord) {
    var point = coord.split(',')
    if (map) {
        map.setCenter(new H.geo.Point(parseFloat(point[0]), parseFloat(point[1])));
        map.setZoom(parseFloat(point[2]));
    }
    //applyFleetLayer_NV(map, platform);
    orgCenter = new H.geo.Point(parseFloat(point[0]), parseFloat(point[1]));
    orgZoomLevel = point[2];
}
/************************************************************************************/
function ShowAddress(lat, lng) {
    var image = "../images/flag_2.png";
    var marker = null;
    LandMarkImage = image;
    getAddress = null;
    chkValue = 1;
    document.getElementById('hdnIsLocateMe').value = 'Y';
    if (map) map.removeObjects(map.getObjects());
    var latlong = lat + ',' + lng;
    if (document.getElementById('hdnLatLong') != null) {
        document.getElementById('hdnLatLong').value = latlong;
    }
    if (document.getElementById('hdnCoordinates') != null) {
        document.getElementById('hdnCoordinates').value = latlong;
    }
    polyArray.length = 0;

    centerPoint = new H.geo.Point(parseFloat(lat), parseFloat(lng));
    map.setCenter(centerPoint);

    var strAddress = "";
    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }

    if (marker) map.removeObject(marker);

    var offsetX = null;
    var offsetY = null;
    if (image == "../images/flag_2.png") {
        offsetX = 2;
        offsetY = 22;
    }
    else {
        offsetX = 0;
        offsetY = 32;
    }

    marker = new H.map.Marker(centerPoint
        //, {icon: new H.map.Icon(null, {anchor: new H.math.Point(offsetX, offsetY)})}
        );
    map.addObject(marker);
    polyArray.length = 0;
    polyArray.push(latlong + '#');

    //Draw circle around the Landmark.
    drawCircle();
    //map.setViewBounds(circle.getBounds());
    map.getViewModel().setLookAtData({
        bounds: circle.getBoundingBox()
    });

    //zoom out if too close
    if (map.getZoom() > 15) map.setZoom(15);
    LandMarkImage = '';

}

var centerPoint;
function drawCircle() {
    try {
        circleRadius = document.getElementById('txtRadius').value;
        doDrawCircle();
    }
    catch (Error) {
    }
}

function doDrawCircle() {
    try {
        //if (circle && canClearCircle) {
        //    map.removeObject(circle);
        //}
        var center = map.getCenter();
        var circlePoints = Array();

        with (Math) {
            var d = circleRadius / 6378.8;
            d = d / 1000;

            var lat1 = (PI / 180) * (!canClearCircle ? landmarkLatitude : center.lat); // radians
            var lng1 = (PI / 180) * (!canClearCircle ? landmarkLongitude : center.lng); // radians

            for (var a = 0; a < 361; a++) {
                var tc = (PI / 180) * a;
                var y = asin(sin(lat1) * cos(d) + cos(lat1) * sin(d) * cos(tc));
                var dlng = atan2(sin(tc) * sin(d) * cos(lat1), cos(d) - sin(lat1) * sin(y));
                var x = ((lng1 - dlng + PI) % (2 * PI)) - PI; // MOD function

                var point = new H.geo.Point(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                circlePoints.push(point);
            }

            if (d < 1.5678565720686044) {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                style: { strokeColor: "rgba(0, 0, 128, 1)", lineWidth: 1, fillColor: "rgba(65, 105, 225, 0.5)" } // "#C69ACC" }
                            }
                        );
            }
            else {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                style: { strokeColor: "rgba(0, 0, 128, 1)", lineWidth: 1, fillColor: canClearCircle ? '#000000' : "rgba(65, 105, 225, 0.5)" } //'#C69ACC' }
                            }
                        );
            }
            landMarkCircles.push(circle);
            if (triggerType != 'LocateMeBtnEvent')
                map.addObject(circle);

            //----------------Circle Resize  code --------------------------------//
            if (isview == 0) {
                circle.draggable = true;

                circle.addEventListener('pointerenter', function (evt) {
                    var currentStyle = circle.getStyle(),
                     newStyle = currentStyle.getCopy({
                         strokeColor: 'rgb(255, 0, 0)'
                     });
                    circle.setStyle(newStyle);
                }, true);
                circle.addEventListener('pointerleave', function (evt) {
                    var currentStyle = circle.getStyle(),
                        newStyle = currentStyle.getCopy({
                            strokeColor: "#5270B2", lineWidth: 4
                        }),
                        timeout = (evt.currentPointer.type == 'touch') ? 1000 : 0;

                    circleTimeout = setTimeout(function () {
                        circle.setStyle(newStyle);
                    }, timeout);
                    document.body.style.cursor = 'default';
                }, true);

                circle.addEventListener('pointermove', function (evt) {
                    if (evt.target instanceof H.map.Circle) {
                        document.body.style.cursor = 'pointer';
                    } else {
                        document.body.style.cursor = 'default'
                    }
                }, true);
                circle.addEventListener('drag', function (evt) {
                    var pointer = evt.currentPointer,
                        distanceFromCenterInMeters = circle.getCenter().distance(map.screenToGeo(pointer.viewportX, pointer.viewportY));

                    // if resizing is alloved, set the circle's radius
                    if (evt.target instanceof H.map.Circle) {
                        if (round(distanceFromCenterInMeters) <= 10000) {
                            circle.setRadius(distanceFromCenterInMeters);


                            var outlineLinestring = circle.getGeometry().getExterior();

                            // extract first point of the outline LineString and push it to the end, so the outline has a closed geometry
                            outlineLinestring.pushPoint(outlineLinestring.extractPoint(0));
                            circle.setGeometry(outlineLinestring);
                        }
                        // prevent event from bubling, so map doesn't receive this event and doesn't pan
                        evt.stopPropagation();
                        document.getElementById('txtRadius').value = round(circle.getRadius());
                    }
                }, true);
                //--------------------------------Circle Resize  code  End-----------------------------------------------------------//
            }

        }
    }
    catch (Error) {
        alert(Error);
    }
}
function drawCircle_LandmarkPage(landmarkEntries, isLandmarkEnable, IsView) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    isview = IsView
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        for (var n = 0; n < landmarkMarkers.length; n++) {
            map.removeObject(landmarkMarkers[n]);
        }
        landmarkMarkers.splice(n, 1);
        for (var c = 0; c < landMarkCircles.length; c++) {
            map.removeObject(landMarkCircles[c]);
        }
        landMarkCircles.splice(c, 1);
    }
    for (var iterator = 0; iterator < lanmarkInformation.length; iterator++) {
        if (lanmarkInformation[iterator] == "") {
            break;
        }
        else {
            var landmarkinfo = lanmarkInformation[iterator].split("~#~");
            centerPoint = new H.geo.Point(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
            //centerPoint = new GLatLng(landmarkinfo[0], landmarkinfo[1]);
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new H.map.Marker(centerPoint);
            var lndTemplate = '<div style="text-align:left;"><table style="direction:  VDirection  " class=\'InfoBubble\' cellpadding=\'5\' cellspacing=\'2\'><tr><td colspan=3><b><u> VLandmarkLocationDetails </u></b></td><tr><td><b> VOrgCoordinates </b></td><td>:</td><td>landmarkLatitude landmarkLongitude</td></tr><tr><td><b> VAddress </b></td><td>:</td><td> landmarkinfo[4] </td></tr></table></div>';
            if (isLandmarkEnable) {
                var lndMarks = flagMarker_LandmarkPage(centerPoint, landmarkinfo[3], landmarkinfo[4], landmarkinfo[0], 'green', 1, lndTemplate)
                landmarkMarkers.push(lndMarks);
                map.addObject(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) {
                doDrawCircle();
                triggerType = "ViewOrEditEvent";
            }
            map.setZoom(6);
            //map.setViewBounds(circle.getBounds());
            map.getViewModel().setLookAtData({
                bounds: circle.getBoundingBox()
            });
        }

    }
    if (document.getElementById('hdnCoordinates') != null) {
        document.getElementById('hdnCoordinates').value = landmarkLatitude + ',' + landmarkLongitude;
        polyArray.push(document.getElementById('hdnCoordinates').value + ',#');
    }
}
function flagMarker_LandmarkPage(point, lndName, lndAddr, time, id, i_No, content) {
    lndImage = document.getElementById('hdnLandmarkImage').value != "" ? String(document.getElementById('hdnLandmarkImage').value) : '../images/flag_2.svg';
    //if (document.getElementById('hdnLandmarkImage') != null && document.getElementById('hdnLandmarkImage').value != "") {
    //    lndImage = String(document.getElementById('hdnLandmarkImage').value);
    //}

    loadMap();

    var marker = new H.map.Marker(point
        //, { icon: new H.map.Icon(null, { anchor: new H.math.Point(2, 22) }) }
        );
    marker.addEventListener(
              'tap',
              function (e) {
                  ui.removeBubble(infoBubble);
                  var coord = map.screenToGeo(e.currentPointer.viewportX, e.currentPointer.viewportY);
                  infoBubble = new H.ui.InfoBubble(coord,
                      //getCentroid(e.target.getPath()),
                      { content: 'Geozone Name : ' + lndName });
                  ui.addBubble(infoBubble);
                  //                  infoBubble.openBubble(
                  //                  'Geozone Name : ' + sGeoName,
                  //                  getCentroid(e.target.getPath())
                  //                );
                  //                  nokia.maps.dom.EventTarget(bubble.node).addListener('click', function(e) {
                  //                      infoBubble.closeAll();
                  //                  });
              }
            );
    return marker;
}


/*******************************************************************************************/
/***********************************Maps in Arabic******************************************/
function changeTileProvider(MapType, PasLang) {
    if (LoadTime == null) {
        var server_rr = 0;
        var token = "PzCfyYAsV98qvfU8gusqRg";
        var appId = "UdwAigBKPRhu01vbIGkI";
        var Plang = "Ar";

        if (PasLang == "Ar") {
            Plang = "ARA";
        }
        else {
            Plang = "hin";
        }
        var baseMapProvider = new nokia.maps.map.provider.ImgTileProvider({
            label: "normal.day",
            descr: "Nokia Base Map tile provider",
            width: 256,
            height: 256,
            min: 0,
            max: 23,
            getUrl: function (level, row, col) {
                server_rr++;
                if (server_rr > 4)
                    server_rr = 1;

                //                return ["https://",
                //					server_rr,
                //					".maps.st.nlp.nokia.com/maptile/",
                //					"2.1",
                //					"/",
                //					"maptile",
                //					"/",
                //					"newest",
                //					"/",
                //					MapType,
                //					"/",
                //					level,
                //					"/",
                //					col,
                //					"/",
                //					row,
                //					"/",
                //					"256",
                //					"/",
                //					"png",
                //					"?lg=",
                //					"ARA",
                //					"&token=",
                //					token,
                //					"&app_id=",
                //					appId
                //					].join("");
                return ["https://",
                					server_rr,
                					".maps.nlp.nokia.com/maptile/",
                					"2.1",
                					"/",
                					"maptile",
                					"/",
                					"newest",
                					"/",
                					MapType,
                					"/",
                					level,
                					"/",
                					col,
                					"/",
                					row,
                					"/",
                					"256",
                					"/",
                					"png",
                					"?lg=",
                					Plang,
                					"&token=",
                					token,
                					"&app_id=",
                					appId
                ].join("");
            }
        });
        // very evil to overwrite the base provider for minimap provider
        // nokia.maps.map.js.nokiaTileProviders.base[0] = baseMapProvider;
        LoadTime = 1;
        map.set("baseMapType", baseMapProvider);
    }
    else {
        LoadTime = null;
    }
}

//Map type change event.
var MapTypeObserver = function (obj, key, newValue, oldValue) {
    var TypeofMap = null;
    switch (newValue.uri) {
        case 'normal': TypeofMap = 'N'; maptype = 'normal.day'; break;
        case 'hybrid': TypeofMap = 'H'; maptype = 'hybrid.day'; break;
        case 'terrain': TypeofMap = 'T'; maptype = 'terrain.day'; break;
    }
    if (document.getElementById("hdnlang") != null) {
        if (document.getElementById("hdnlang").value == "LanguageArNew") {
            changeTileProvider(maptype, 'Ar');
        }
        else if (document.getElementById("hdnlang").value == "LanguageHindi") {
            changeTileProvider(maptype, 'hin');
        }
    }
};
/***********************************End of Maps in Arabic******************************************/

/****************************************Locate Me Functionality****************************************/

function PlotAddress() {
    //    if (document.getElementById("txtLocationName").value == "" || document.getElementById("txtLocationName").value == "Name") {
    //        alert(enterLocationName);
    //        document.getElementById("txtLocationName").focus();
    //        return false;
    //    }
    var Restriction = document.getElementById('hdnRestriction').value;
    var plotType = document.getElementById('ddlType');
    var street = document.getElementById('txtstreet');
    var latitude = document.getElementById('txtlat');
    var longitude = document.getElementById('txtlong');

    if (Restriction == '0') {
        TrinetraCustomAlerts(LandmarkMax);
        return false;
    }

    if (plotType.value == "addr") {
        if (street.value == "" || street.value == "Address") {
            TrinetraCustomAlerts(enterAddress);
            street.focus();
            return false;
        }
    }
    else if (plotType.value = "ltlng") {
        if (latitude.value == "" || latitude.value == "Latitude") {
            TrinetraCustomAlerts(enterLatitude);
            latitude.focus();
            return false;
        }
        if (longitude.value == "" || longitude.value == "Longitude") {
            TrinetraCustomAlerts(enterLongitude);
            longitude.focus();
            return false;
        }
    }

    ShowAddress(latitude.value, longitude.value, 'LocateMeBtnEvent');
    return true;
}

function showControls(typeid) {
    try {
        if (typeid == '0') {

            document.getElementById('txtlat').value = '';
            document.getElementById('txtlong').value = '';
            document.getElementById('spLatlng').style.display = 'none';
            document.getElementById('spAddr').style.display = 'block';
        }
        else {
            document.getElementById('ddlType').value = 'ltlng';
            document.getElementById('spLatlng').style.display = 'block';
            document.getElementById('spAddr').style.display = 'none';
        }
    }
    catch (Error) {
    }
}

function ShowAddress(lat, lng, triggertype) {
    var image = "../images/flag_2.png";
    LandMarkImage = image;
    triggerType = triggertype;

    if (triggertype == "LocateMeBtnEvent") {
        if (document.getElementById('ddlType').value == 'addr') {
            //if (poly_group != null)
            //    poly_group.removeObjects(poly_group.getObjects());
            if (geoType == 2)
                clearPoly();
            if (map) {
                map.removeObjects(map.getObjects());

                search = FrameAddress();

                //Set the Advance Search manager to the variable
                geo = platform.getGeocodingService();

                //======= GeoCode Callback function ======
                geo.geocode({ 'searchText': search },
                function (serviceResponse) {
                    var locations = serviceResponse.Response.View[0].Result;
                    if (locations != null && locations.length > 0) {
                        if (locations.length > 1) {
                            document.getElementById("message").innerHTML = "Did you mean:";
                            // Loop through the results
                            for (var i = 0; i < locations.length; i++) {
                                var p = locations[i].Location.DisplayPosition;
                                document.getElementById("message").innerHTML += "<br>" + (i + 1) + ": <a href='#' onclick='place("
                                    + p.Latitude + "," + p.Longitude + "); return false;'>" + FormAddressList(locations[i].Location) + "<\/a>";
                            }
                            if (triggertype == "MapClickEvent") {
                                AddressSuggestionPanelVisibility(false);
                                LocateMapCoordinates(lat, lng);
                            }
                            else {
                                AddressSuggestionPanelVisibility(true);
                                map.setCenter(new H.geo.Point(-1.757537, 92.460937));
                            }
                        }
                        else {
                            document.getElementById("message").innerHTML = "";
                            var p = locations[0].Location.DisplayPosition;

                            if (document.getElementById('hdnLatLong') != null) {
                                document.getElementById('hdnLatLong').value = p.Latitude + ',' + p.Longitude;
                            }
                            Findplace(p.Latitude, p.Longitude, '', 50, 0);
                            LandMarkImage = '';
                        }
                    }
                    else {
                        if (document.getElementById("hdnlang") != null) {
                            if (document.getElementById("hdnlang").value == "LanguageArNew") {

                                TrinetraCustomAlerts('لا يمكن أن تجد "' + search + '" ');

                            }
                            else if (document.getElementById("hdnlang").value == "LanguageEn") {
                                TrinetraCustomAlerts('Could not find "' + search + '" ');
                            }

                            else {
                                TrinetraCustomAlerts('नहीं मिल सका "' + search + '" ');
                            }
                        }
                        //loadForLandMark();
                    }
                }, function () {
                    if (document.getElementById("hdnlang") != null) {
                        if (document.getElementById("hdnlang").value == "LanguageArNew") {
                            TrinetraCustomAlerts('لا يمكن أن تجد "' + search + '" ');
                        }
                        else if (document.getElementById("hdnlang").value == "LanguageEn") {
                            TrinetraCustomAlerts('Could not find "' + search + '" ');
                        }
                        else {
                            TrinetraCustomAlerts('नहीं मिल सका "' + search + '" ');
                        }
                    }
                    //loadForLandMark();
                });
            }
            //else {
            //}
        }
        else {
            LocateMapCoordinates(lat, lng);
        }
    }
    else {
        LocateMapCoordinates(lat, lng);
    }
}

function LocateMapCoordinates(lat, lng) {
    var image = "../images/flag_2.png";
    LandMarkImage = image;
    var marker = null;
    getAddress = null;
    chkValue = 1;

    document.getElementById('hdnIsLocateMe').value = 'Y';
    //if (geoType == 3) {     //remove map objects directly if its Circular Geozone
    //    if (map)
    //        map.removeObjects(map.getObjects());
    //}
    //else {                  //remove map objects after clearing group objects if its Polygon or Rectangle Geozone
    //if (poly_group != null)
    //poly_group.removeObjects(poly_group.getObjects());
    if (geoType == 2)
        clearPoly();
    if (map)
        map.removeObjects(map.getObjects());
    //}

    var latlong = lat + ',' + lng;

    if (document.getElementById('hdnLatLong') != null) {
        document.getElementById('hdnLatLong').value = latlong;
    }
    if (document.getElementById('hdnCoordinates') != null) {
        document.getElementById('hdnCoordinates').value = latlong;
    }

    centerPoint = new H.geo.Point(parseFloat(lat), parseFloat(lng));
    map.setCenter(centerPoint);

    var strAddress = "";
    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }

    if (marker) map.removeObject(marker);

    var offsetX = null;
    var offsetY = null;
    if (image == "../images/flag_2.png") {
        offsetX = 2;
        offsetY = 22;
    }
    else {
        offsetX = 0;
        offsetY = 32;
    }

    marker = new H.map.Marker(centerPoint
        //, {icon: new H.map.Icon(null, {anchor: new H.math.Point(offsetX, offsetY)})}
        );
    map.addObject(marker);

    polyArray.length = 0;
    if (triggerType != 'LocateMeBtnEvent')
        polyArray.push(latlong + '#');

    //Draw circle around the Landmark.
    drawCircle();
    // map.setViewBounds(circle.getBounds());
    map.getViewModel().setLookAtData({
        bounds: circle.getBoundingBox()
    });
    //zoom out if too close
    if (map.getZoom() > 15) map.setZoom(15);
    LandMarkImage = '';
}




function LocateMapCoordinatesForMap(lat, lng) {
    var image = "../images/flag_2.png";
    LandMarkImage = image;
    var marker = null;
    getAddress = null;
    chkValue = 1;

    document.getElementById('hdnIsLocateMe').value = 'Y';
    if (geoType == 2)
        clearPoly();
    if (map)
        map.removeObjects(map.getObjects());
    //}

    var latlong = lat + ',' + lng;

    var reverseGeocodingParameters = {
        prox: latlong + ",200",
        mode: 'retrieveAddresses',
        maxresults: 1,
        language: 'en'
    };
    geocoder.reverseGeocode(reverseGeocodingParameters, function (result) {
        try {
            address = result.Response.View[0].Result[0].Location.Address.Label;
        }
        catch (e) {
            console.log(e);
        }
        document.getElementById('hdnAddress').value = address;
        infoBubble = new H.ui.InfoBubble(lcPoint, { content: '<span>' + address + '</span>' });
        ui.addBubble(infoBubble);
    }, function (e) {
        console.log(e);
    });



    if (document.getElementById('hdnLatLong') != null) {
        document.getElementById('hdnLatLong').value = latlong;
    }
    if (document.getElementById('hdnCoordinates') != null) {
        document.getElementById('hdnCoordinates').value = latlong;
    }

    centerPoint = new H.geo.Point(parseFloat(lat), parseFloat(lng));
    map.setCenter(centerPoint);

    var strAddress = "";
    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }

    if (marker) map.removeObject(marker);

    var offsetX = null;
    var offsetY = null;
    if (image == "../images/flag_2.png") {
        offsetX = 2;
        offsetY = 22;
    }
    else {
        offsetX = 0;
        offsetY = 32;
    }

    marker = new H.map.Marker(centerPoint
        //, {icon: new H.map.Icon(null, {anchor: new H.math.Point(offsetX, offsetY)})}
        );
    map.addObject(marker);

    polyArray.length = 0;
    if (triggerType != 'LocateMeBtnEvent')
        polyArray.push(latlong + '#');

    //Draw circle around the Landmark.
    drawCircle();
    //map.setViewBounds(circle.getBounds());
    map.getViewModel().setLookAtData({
        bounds: circle.getBoundingBox()
    });
    //zoom out if too close
    if (map.getZoom() > 15) map.setZoom(15);
    LandMarkImage = '';
}

var address1 = null;
function FrameAddress() {
    try {
        address1 = ''

        if (document.getElementById('txtstreet').value != '') {
            if (address1 != '') {
                address1 = address1 + ' ' + document.getElementById('txtstreet').value;
            }
            else {
                address1 = document.getElementById('txtstreet').value;
            }
        }
        if (document.getElementById('txtcity').value != '' && document.getElementById('txtcity').value != "City" && document.getElementById('txtcity').value != "المدينة") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('txtcity').value;
            }
            else {
                address1 = document.getElementById('txtcity').value;
            }
        }
        if (document.getElementById('txtstate').value != '' && document.getElementById('txtstate').value != "State" && document.getElementById('txtstate').value != "الدولة") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('txtstate').value;
            }
            else {
                address1 = document.getElementById('txtstate').value;
            }
        }
        if (document.getElementById('txtCountry').value != '' && document.getElementById('txtCountry').value != "Country" && document.getElementById('txtCountry').value != "الدولة") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('txtCountry').value;
            }
            else {
                address1 = document.getElementById('txtCountry').value;
            }
        }
        return address1;
    }
    catch (Error) {
    }
}

// Frame the List of Address to show to the user for their suggession.
function FormAddressList(observedManager) {
    var temp = '';
    temp += BubbleAddress(observedManager.Address.Street) + BubbleAddress(observedManager.Address.District) + BubbleAddress(observedManager.Address.City) + BubbleAddress(observedManager.Address.State) + observedManager.Address.Country;
    return temp; //.substring(0, temp.lastIndexOf(","));
}

//Frame the bubble address
function BubbleAddress(Address) {
    return Address = (Address == null || Address == 'undefined' || Address == '') ? '' : Address + ',';
}

// ====== Plot a marker after positive reponse to "did you mean" ======
function place(lat, lng) {
    try {

        var icon = LandMarkImage;
        var point = new H.geo.Point(parseFloat(lat), parseFloat(lng));

        var offsetX = null;
        var offsetY = null;
        if (icon == "../images/flag_2.png") {
            offsetX = 2;
            offsetY = 22;
        }
        else {
            offsetX = 0;
            offsetY = 32;
        }

        //Set marker to a variable.
        var marker = new H.map.Marker(point
            //, { icon: new H.map.Icon(icon, { anchor: new H.math.Point(offsetX, offsetY) }) }
            );

        //Add marker to the map.
        map.addObject(marker);
        //Zoom out if to close.
        if (map.getZoom() > 15) map.setZoom(15);

        //var LocDesc = (document.getElementById('txtLocationDesc').value == "Description") ? "" : document.getElementById('txtLocationDesc').value;
        //var Radius = (document.getElementById('txtRadius').value == "Radius" || document.getElementById('txtRadius').value == 'الإشعاع' || document.getElementById('txtRadius').value == "0") ? 500 : document.getElementById('txtRadius').value;
        //getAddress = document.getElementById('txtLocationName').value + '#' + lat + '#' + lng + '#' + LocDesc + '#' + search + '#' + Radius + '#' /*+ document.getElementById('txtEmail').value + '#' + document.getElementById('txtSMS').value + '#'*/ + (document.getElementById('chkNotify').checked ? 1 : 0) + '#0';  /* + document.getElementById('ddlTimezone').value; */
        document.getElementById('txtlat').value = lat;
        document.getElementById('txtlong').value = lng;
        centerPoint = new H.geo.Point(parseFloat(lat), parseFloat(lng));
        document.getElementById("message").innerHTML = "";
        AddressSuggestionPanelVisibility(false);
        drawCircle();
        //map.setViewBounds(circle.getBounds());
        map.getViewModel().setLookAtData({
            bounds: circle.getBoundingBox()
        });
        LandMarkImage = '';
    }
    catch (Error) {
    }
}

function AddressSuggestionPanelVisibility(isView) {
    if (isView)
        document.getElementById("pnlAddressLocating").style.display = "block";
    else
        document.getElementById("pnlAddressLocating").style.display = "none";
    isview = 0;
}


/*Show POI's*/
function applyFleetLayer_NV(map, platform) {
    var mapTileService = platform.getMapTileService({ 'type': 'base' });

    // Create a tile layer which requests map tiles with an additional 'style'
    // URL parameter set to 'fleet':
    var parameters = { style: 'default', pois: true, ppi: '72' };

    var fleetStyleLayer = mapTileService.createTileLayer(
        'maptile',
        'normal.day',
        256,
        'png8',
        parameters);

    // Set the new fleet style layer as a base layer on the map:
    map.setBaseLayer(fleetStyleLayer);
}
/*********************************End of Locate Me Functionality******************************************/