
// Global variables
var LoadTime = null;
var maptype = "normal.day";
var map;
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 nokia.maps.geo.Coordinate(20.00, 78.00);
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;
//nokia.maps.util.ApplicationContext.set("authenticationToken", "4b25c0fb0d9f746bbe44a74f549b49208f1833336bb01f04");
//nokia.maps.util.ApplicationContext.set("appId", "<AppId>");

//nokia.maps.util.ApplicationContext.set("authenticationToken", "PzCfyYAsV98qvfU8gusqRg");
//nokia.maps.util.ApplicationContext.set("appId", "UdwAigBKPRhu01vbIGkI");
nokia.Settings.set("authenticationToken", "PzCfyYAsV98qvfU8gusqRg");
nokia.Settings.set("appId", "UdwAigBKPRhu01vbIGkI");
//nokia.Settings.set("secureConnection", "force");
(document.location.protocol == "https:") && nokia.Settings.set("secureConnection", "force");


//nokia.maps.Config.setDefaultsNS("map.tileprovider", {
//    "normal.baseUrl": "maps.st.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day",
//    "hybrid.baseUrl": "maps.st.nlp.nokia.com/maptile/2.1/maptile/newest/hybrid.day",
//    "satellite.baseUrl": "maps.st.nlp.nokia.com/maptile/2.1/maptile/newest/satellite.day",
//    "terrain.baseUrl": "maps.st.nlp.nokia.com/maptile/2.1/maptile/newest/terrain.day",
//    "publictransport.baseUrl": "maps.st.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day.transit",
//    "grey.baseUrl": "maps.st.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day.grey",
//    "traffic.baseUrl": "maps.st.nlp.nokia.com/traffic/6.0/tiles",
//    "trafficincidents.baseUrl": "traffic.st.nlp.nokia.com/traffic/6.0/incidents.json?"
////});
//nokia.maps.Config.setDefaultsNS("map.tileprovider", {
//    "normal.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day",
//    "hybrid.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/hybrid.day",
//    "satellite.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/satellite.day",
//    "terrain.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/terrain.day",
//    "publictransport.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day.transit",
//    "grey.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day.grey",
//    "traffic.baseUrl": "maps.nlp.nokia.com/traffic/6.0/tiles",
//    "trafficincidents.baseUrl": "traffic.nlp.nokia.com/traffic/6.0/incidents.json?"
//});

var infoBubble = new nokia.maps.map.component.InfoBubbles();
var mapClick = true;
var IsDragStart = false;
var PrevCoordinates = null;
var CurrCoordinates = null;
var marker;
var IsDblClick = false;
var zoomIndex = new Array();

//infoBubble.Bubble.prototype.defaultWidth = 300;
//infoBubble.Bubble.prototype.defaultXAlignment = 'auto';
//infoBubble.Bubble.prototype.defaultYAlignment = 'auto';

// 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 nokia.maps.geo.Coordinate(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 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 {
        if (map) {
            map.objects.clear();
            if (document.getElementById('map').innerHTML == "" || document.getElementById('map').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
                if (map.getComponentById("ZoomBar")) map.removeComponent(map.getComponentById("ZoomBar"));
                //if (map.getComponentById("TypeSelector")) map.removeComponent(map.getComponentById("TypeSelector"));
                if (map.getComponentById("Overview")) map.removeComponent(map.getComponentById("Overview"));
                if (map.getComponentById("zoom.DoubleClick")) map.removeComponent(map.getComponentById("zoom.DoubleClick"));
                if (map.getComponentById("Behavior")) map.removeComponent(map.getComponentById("Behavior"));
                if (map.getComponentById("InfoBubbles")) map.removeComponent(map.getComponentById("InfoBubbles"));
                if (map.getComponentById("ViewControl")) map.removeComponent(map.getComponentById("ViewControl"));
            }
        }
    }
    catch (Error) {

    }
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    landmarkMarkers.length = 0;
    landMarkCircles.length = 0;
    var holderControl = document.getElementById("content");
    document.getElementById('search-box').style.width = 260 + '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('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';
        }
    }
    // 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 nokia.maps.map.Display(document.getElementById("map"), {
                //                center: centerCoordinate,
                //                zoomLevel: 4,
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoomLevel: orgZoomLevel != null ? orgZoomLevel : 4,
                components: [infoBubble, new nokia.maps.map.component.ZoomBar(),
                            new nokia.maps.map.component.TypeSelector(),
                //new nokia.maps.map.component.Overview(),
                            new nokia.maps.map.component.zoom.DoubleClick(),
                            new nokia.maps.map.component.Behavior(),
                            new nokia.maps.map.component.ViewControl(),
                            new nokia.maps.map.component.Traffic(),
                            new nokia.maps.map.component.PublicTransport(),
                            new nokia.maps.map.component.ZoomRectangle()]

            });
            IsDblClick = false;
            if (zoomIndex.length > 0) {
                map.set("zoomLevel", parseFloat(zoomIndex[0]));
                map.set("center", 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);
                }
            }

        }
        else {
            //map.setZoomLevel(4, "default");
        }
    }
    catch (Error) {

    }
    //map = new GMap2(document.getElementById("map"), { draggableCursor: 'auto', draggingCursor: 'move' });
    //map.setCenter(centerCoordinate, 4)//(new GLatLng(23.805450, 78.486328), 4);

    //map.addMapType(G_PHYSICAL_MAP);
    //var hierarchy = new GHierarchicalMapTypeControl();
    //hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", true);
    //map.addControl(hierarchy);
    //map.addControl(new GSmallMapControl());
    //map.disableDoubleClickZoom();
    //map.enableScrollWheelZoom();
    //map.enableContinuousZoom();

    //    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
    //        document.getElementById('hdnMapZoomLevel').value = newLevel;
    //        centerCoordinate = map.getCenter();
    //    }
    //    );

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

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

        if (isview == 0) {
            //eventOnclick = GEvent.addListener(map, "click", leftClick);
            //            map.removeListener(getCoordinate);
            //            map.removeListener(mapDragRectangle);
            //  map.removeAllListener();

            map.removeListener("click", getCoordinate, false);
            map.removeListener("mousemove", mapDragRectangle, false);
            map.removeListener("click", Getlatlng, false);

            map.removeListener("click", leftClick, false);
            eventOnclick = map.addListener("click", leftClick);
        }
        geoType = 2;
    }
    else if (oUnitsMI.checked) {
        circleUnits = 'RC';
        // map.removeAllListener();
        map.removeListener("click", leftClick, false);
        myrectangle = null;
        //     centerPoint = circle = null;       
        map.removeListener("click", getCoordinate, false);
        map.removeListener("mousemove", mapDragRectangle, false);
        map.removeListener("click", Getlatlng, false);

        eventOnclick = map.addListener("click", getCoordinate);
        eventOnMove = map.addListener("mousemove", mapDragRectangle);
        //eventOnclick = GEvent.addListener(map, "click", getCoordinate);
        //eventOnMove = GEvent.addListener(map, 'mousemove', mapDragRectangle);
        if (isview == 0) {
            //eventOnclick = GEvent.addListener(map, 'click', mapClickRectangle);
        }
        dragRectangle = false;
        geoType = 1;
    }
    else {
        circleUnits = 'CR';
        myrectangle = null;
        //  centerPoint = circle = null;         
        map.removeListener("click", getCoordinate, false);
        map.removeListener("mousemove", mapDragRectangle, false);
        map.removeListener("click", leftClick, false);
        map.removeListener("click", Getlatlng, false);
        eventOnclick = map.addListener("click", Getlatlng);
        geoType = 3;
    }

    //map.removeListener("dblclick", dblClick, false);

    function dblClick() {
        //map.addListener('dblclick', function() {
        try {
            map.removeListener(eventOnclick);
            //GEvent.removeListener(eventOnclick);
            if (oUnitsKM.checked) {
                markers.length = markers.length - 1;
                markers.splice(markers.length, 1);
                map.objects.remove(marker);
                drawPoly(0);
                //eventOnclick = map.addListener("click", leftClick);
                //eventOnclick = GEvent.addListener(map, "click", leftClick);
            }
            else {
                first = '';
                dragRectangle = false;
                map.removeListener("click", getCoordinate);
                map.removeListener("mousemove", mapDragRectangle);
                eventOnclick = map.addListener("click", getCoordinate);
                eventOnMove = map.addListener("mousemove", mapDragRectangle);
                //eventOnclick = GEvent.addListener(map, "click", getCoordinate);
                //eventOnMove = GEvent.addListener(map, 'mousemove', mapDragRectangle);
                //Rec_bounds = new GLatLngBounds();
            }
        }
        catch (Error) {
        }
    }
    if (isview == 0) {
        //GEvent.clearListeners(map.getDragObject(), 'dblclick');
        //GEvent.addDomListener(map, 'dblclick', function() {
        if (!IsDblClick) {
            //If double click event is already assigned skip reassigning of event.
            map.addListener("dblclick", dblClick);
            IsDblClick = true;
        }
        //);

        if (document.getElementById('hdnMapZoomLevel').value != "") {
            map.setZoomLevel(parseFloat(eval(document.getElementById('hdnMapZoomLevel').value)), "default");
            //map.setZoom(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>';

    //map.getContainer().appendChild(contextmenu);

    if (isview == 0) {
        // === listen for singlerightclick ===
        //GEvent.addListener(map, "singlerightclick", function(pixel, tile) {
        map.addListener("singlerightclick", function (pixel, tile) {
            // store the "pixel" info in case we need it later
            // adjust the context menu location if near an egde
            // create a GControlPosition
            // apply it to the context menu, and make the context menu visible
            //            clickedPixel = pixel;
            //            var x = pixel.x;
            //            var y = pixel.y;
            //            if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
            //            if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
            //            var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x, y));
            //            pos.apply(contextmenu);
            //            contextmenu.style.visibility = "visible";
        });
    }

    // Included by Kumuthini. L on 30-Jan-09
    //GEvent.addListener(map, "mapviewchangeend", mapTypeChanged);

    //map.addListener("mapviewchangeupdate", mapTypeChanged);

    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (mapTypeHolder.value) {
            case 'N': map.set("baseMapType", map.NORMAL); break;
            case 'S': map.set("baseMapType", map.SATELLITE); break;
            case 'H': map.set("baseMapType", map.HYBRID); 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() {  });
}
//------- loadMap end---------------------
// Included by Kumuthini. L on 30-Jan-09
function mapTypeChanged() {
    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (map.getCurrentMapType()) {
            case 'N': map.set("baseMapType", map.NORMAL); break;
            case 'S': map.set("baseMapType", map.SATELLITE); break;
            case 'H': map.set("baseMapType", map.HYBRID); 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 for drawing a polygon.
function leftClick(overlay, point) {
    if (mapClick) {
        if (!point || point == '') {
            point = 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].coordinate.latitude + ',' + markers[markers.length - 1].coordinate.longitude;
                    var p = point.latitude + ',' + point.longitude;
                    if (temp == p) {
                        map.objects.remove(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;
                }
            }

            // Square marker icons
            //var square = new GIcon(G_DEFAULT_ICON);
            //var square = "mapIcons/square.png";

            //addIcon(square);

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

                marker = new nokia.maps.map.StandardMarker(
                                    point,
                                    {
                                        //icon: square,
                                        draggable: true
                                    }
                                );
                //display.objects.add(rect);

                //marker = new GMarker(point, { icon: square, draggable: true, bouncy: false, dragCrossMove: true });
            }
            else {
                marker = new nokia.maps.map.StandardMarker(
                                    point,
                                    {
                                        //icon: square,
                                        draggable: true
                                        //dragCrossMove: false
                                    }
                                );
                //marker = new GMarker(point, { icon: square, draggable: false, bouncy: false, dragCrossMove: false });
            }

            markers.push(marker);
            map.objects.add(marker);

            if (isview == 0) {

                //GEvent.addListener(marker, "drag", function() {
                marker.addListener("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.pixelToGeo(evt.displayX - offset.x + marker.anchor.x, evt.displayY - offset.y + marker.anchor.y);
                    PrevCoordinates = evt.currentTarget.coordinate;
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                });

                //GEvent.addListener(marker, "mouseover", function() {
                marker.addListener("dragend", 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.pixelToGeo(evt.displayX - offset.x + marker.anchor.x, evt.displayY - offset.y + marker.anchor.y);
                    PrevCoordinates = evt.currentTarget.coordinate;
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                    //marker.setImage("mapIcons/m-over-square.png");
                });

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

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

                marker.addListener("click", function (evt) {
                    // Find out which square to remove
                    for (var n = 0; n < markers.length; n++) {
                        //var MarkerCoord = 
                        if (markers[n].coordinate == evt.currentTarget.coordinate) {
                            //map.removeOverlay(markers[n]);
                            map.objects.remove(markers[n]);
                            mapClick = false;
                            break;
                        }
                    }
                    markers.splice(n, 1);
                    drawPoly(0);
                });
            }
            drawPoly(0);
        }
    }
    mapClick = true;
}

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

    if (polyShape)
        map.objects.remove(polyShape);

    polyPoints.length = 0;
    polyArray.length = 0;
    landMarkCircles.length = 0;
    landmarkMarkers.length = 0;
    //markers.length = 0;

    //document.getElementById("coords").innerHTML = "";
    for (i = 0; i < markers.length; i++) {
        if (IsDragStart) {
            markers[i].coordinate = markers[i].coordinate == PrevCoordinates ? CurrCoordinates : markers[i].coordinate;
        }

        //polyPoints.push(markers[i].getLatLng());
        polyPoints.push(markers[i].coordinate);
        //var appendvalues = markers[i].getLatLng().toUrlValue() + '#';
        var appendvalues = markers[i].coordinate.latitude + ',' + markers[i].coordinate.longitude + '#';
        polyArray.push(appendvalues);
        //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 filClr = "#2387";  //"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
    var lneClr = "#3355ff"; //#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 nokia.maps.map.Polygon(polyPoints, {
        $name: sGeoName,
        pen: { strokeColor: lneClr, lineWidth: .3 },
        brush: { color: filClr }
    });

    // On mouse click we fire off the default event handler
    //polyShape.addListener("click", defaultHandler);
    if (isview == 1) {
        polyShape.addListener(
              'click',
              function (e) {
                  infoBubble.openBubble(
                  'Geozone Name : ' + sGeoName,
                  getCentroid(e.target.path)
                );
                  nokia.maps.dom.EventTarget(bubble.node).addListener('click', function (e) {
                      infoBubble.closeAll();
                  });
              }
            );
    }

    //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.objects.add(polyShape);
}

function zoomToPoly() {

    if (polyShape && polyPoints.length > 0) {
        //var bounds = polyShape.getBounds();

        //map.setCenter(polyShape.getBoundingBox(), "default");
        map.zoomTo(polyShape.getBoundingBox(), false);

        //map.setCenter(bounds.getCenter());        
        //map.setZoom(map.getBoundsZoomLevel(bounds));
        //map.setCenter(poly_bounds.getCenter(), map.getBoundsZoomLevel(poly_bounds) - 1); 
    }
}

function clearPoly() {
    // Remove polygon and reset arrayse
    if (map)
        map.objects.clear();
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    landMarkCircles.length = 0;
    //Clear Rectangle Geozone
    r1 = null;
    if (myrectangle != null) {
        map.objects.remove(myrectangle);
        myrectangle = null;
    }
    document.getElementById('hdnCoordinates').value = "";
    maintainZoomLevel();
    //if(IsDblClick = true)
    loadMap();
    var rdoID = document.getElementById('unitsCIR');
    if (rdoID.checked) {
        document.getElementById('ddlRadius').style.display = "block";
        document.getElementById('Image1').style.display = "block";
        document.getElementById('Label5').style.display = "block";
    }
    else {
        document.getElementById('ddlRadius').style.display = "none";
        document.getElementById('Image1').style.display = "none";
        document.getElementById('Label5').style.display = "none";
    }
}

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

function RecGeozones(latlng, isView, geoName) {
    var isIE = CheckBrowser();
    if (circle) map.objects.remove(circle);
    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 nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1])));
        var point = new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
        mapClickRectangle('', point);
    }
    zoomToPoly();
}

//TO toggle the Radio buttons
function toggle(rdoID) {
    var isIE = CheckBrowser();
    r1 = null;
    if (rdoID == 'unitsMI') {
        document.getElementById('unitsKM').checked = false;
        document.getElementById('unitsMI').checked = true;
        document.getElementById('unitsCIR').checked = false;
        document.getElementById('ddlRadius').style.display = "none";
        document.getElementById('Image1').style.display = "none";
        document.getElementById('Label5').style.display = "none";
    }
    else if (rdoID == 'unitsKM') {
        document.getElementById('unitsKM').checked = true;
        document.getElementById('unitsMI').checked = false;
        document.getElementById('unitsCIR').checked = false;
        document.getElementById('ddlRadius').style.display = "none";
        document.getElementById('Image1').style.display = "none";
        document.getElementById('Label5').style.display = "none";
    }
    else {
        document.getElementById('unitsKM').checked = false;
        document.getElementById('unitsMI').checked = false;
        document.getElementById('unitsCIR').checked = true;
        document.getElementById('ddlRadius').style.display = "block";
        document.getElementById('Image1').style.display = "block";
        document.getElementById('Label5').style.display = "block";
    }

    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';
    //icon.iconSize = new GSize(32, 32);
    var point = new nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng)); //new GLatLng(lat, lng);
    map.setCenter(point, "default");

    //var lndmarker = new GMarker(point, { draggable: false, icon: icon });
    var lndmarker = new nokia.maps.map.Marker(point, {
        draggable: false,
        icon: icon,
        anchor: new nokia.maps.util.Point(12, 27)
    });
    map.objects.add(lndmarker);
    map.zoomTo(lndmarker.getBoundingBox(), false);
    if (map.zoomLevel > 15) map.set("zoomLevel", 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.pixelToGeo(overlay.displayX, overlay.displayY);
        //    }
        var lat, lng;
        //  showControls(1);
        //    if (cord != null) {
        lat = Math.round(point.latitude * 1000000) / 1000000;
        lng = Math.round(point.longitude * 1000000) / 1000000;
        if (document.getElementById('hdnLatLong') != null) {
            document.getElementById('hdnLatLong').value = point.latitude + ',' + point.longitude;
        }
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = point.latitude + ',' + point.longitude;
        }
        chkValue = 0;
        document.getElementById('hdnIsLocateMe').value = 'N';
        ShowAddress(lat, lng);
    }
}
function getCoordinate(overlay, point) {
    if (marker)
        map.objects.remove(marker);
    // Included by Kumuthini. L on 07-May-10
    //    if (document.getElementById('hdnCoordinates') != null && document.getElementById('hdnCoordinates').value != '') {
    //        return;
    //    }
    map.objects.clear();
    if (!point || point == '') {
        point = 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.latitude + ',' + r1.longitude + '#');
        polyPoints.push(r2.latitude + ',' + r2.longitude + '#');

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

        //To store all the values and pass to Server Side


        polyArray.push(marker2.latitude + ',' + marker2.longitude + '#');
        if (document.getElementById('hdnCoordinates') != null) {
            document.getElementById('hdnCoordinates').value = polyArray;
        }

        r1 = ''
        r2 = ''
        //map.setCenter(Rec_bounds.getCenter(), map.getBoundsZoomLevel(Rec_bounds) - 1);
        try {
            map.zoomTo(myrectangle.getBoundingBox(), false, "default");
        }
        catch (er) {
            TrinetraCustomAlerts(er);
        }
        //map.zoomTo(Rec_bounds.getBoundingBox(), false, "default");
        first = '';
        second = '';
    }
}

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


        drawPoly(0);
        //eventOnclick = GEvent.addListener(map, "click", getCoordinate);
        eventOnclick = map.addListener("click", 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(); //clearOverlays();
        //GEvent.removeListener(eventOnClick);
        dragRectangle = false;
        draw_rectangle(r1, point);
        r2 = point;

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

        //        var marker1 = new GMarker(r1);
        //        var marker2 = new GMarker(r2);
        var marker1 = r1;  //new nokia.maps.geo.Coordinate(r1); //GMarker(r1);
        var marker2 = r2;

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

        polyArray.length = 0;

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

        // 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.zoomTo(Rec_bounds, false, "default");
        map.zoomTo(myrectangle.getBoundingBox(), false, "default");

    }
}

function mapDragRectangle(point) {
    point = 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.objects.remove(myrectangle);
    }

    if (a != null && b != null) {
        //        myrectangle = new nokia.maps.map.Rectangle(
        //                                    [a, b],
        //                                    {
        //                                        //$name: "Rectangle",
        //                                        //eventListener: myListener,
        //                                        pen: { strokeColor: "#fd942d", lineWidth: 5 },
        //                                        brush: { color: "#2387" }
        //                                        //draggable: true
        //                                    }
        //                                );


        myrectangle = new nokia.maps.map.Polygon([a, new nokia.maps.geo.Coordinate(parseFloat(a.latitude), parseFloat(b.longitude)), b, new nokia.maps.geo.Coordinate(parseFloat(b.latitude), parseFloat(a.longitude))], {
            $name: sGeoName,
            pen: { strokeColor: "#fd942d", lineWidth: 5 },
            brush: { color: "#2387" }
            //draggable: true
        });

        // On mouse click we fire off the default event handler
        //myrectangle.addListener("click", defaultHandler);
        if (isview == 1) {
            myrectangle.addListener(
              'click',
              function (e) {
                  infoBubble.openBubble(
                  'Geozone Name : ' + sGeoName,
                  getCentroid(e.target.path)
                );
                  nokia.maps.dom.EventTarget(bubble.node).addListener('click', function (e) {
                      infoBubble.closeAll();
                  });
              }
            );
        }

        map.objects.add(myrectangle);

        //map.zoomTo(myrectangle.getBoundingBox(), "default");
        //first = '';
        //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);
        //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() {
    map.objects.remove(myrectangle);
}

// End of Rectangle geozone script

function clearArray() {
    //Array.clear(zoomIndex);
    map.set("zoomLevel", orgZoomLevel != null ? orgZoomLevel : 4);
    map.set("center", orgCenter != null ? orgCenter : centerCoordinate);
}

function maintainZoomLevel() {
    if (map) {
        Array.clear(zoomIndex);
        zoomIndex.push(map.zoomLevel);
        zoomIndex.push(map.center);
    }
}
var IsMSIE9 = null;
//Set Center to its org country.
function SetOrgCenter(coord) {
    var point = coord.split(',')
    if (map) {
        map.set('center', new nokia.maps.geo.Coordinate(parseFloat(point[0]), parseFloat(point[1])));
        map.setZoomLevel(parseFloat(point[2]), "default");
    }
    orgCenter = new nokia.maps.geo.Coordinate(parseFloat(point[0]), parseFloat(point[1]));
    orgZoomLevel = point[2];
}

function infoBubbleStyle() {
    if (!CheckBrowserForBubble()) {
        infoBubble.node.firstElementChild.style.borderRadius = "10px 10px 10px 10px";
        infoBubble.node.firstElementChild.style.boxshadow = "rgba(0,0,0,0.4)10px 10px";
        if (!IsMSIE9)
            infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.cssText = "top: 4px; right: 5px;background-position: -31px -193px;width: 16px;height: 16px;"; //background-image:url(../images/icn-action-off.gif)
        else
            infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.cssText = "top: 4px; right: 5px;background-position: -33px -198px;width: 16px;height: 16px"; //;background-image:url(../images/icn-action-off.gif)
    }
    else {
        infoBubble.node.firstChild.style.cssText = "border-radius: 10px; -moz-border-radius: 10px;-webkit-border-radius: 10px;"; //behavior: url(../border-radius-ie8.htc);"; //rgba(0,0,0,0.4)30px 30px"
        infoBubble.node.firstChild.firstChild.nextSibling.style.cssText = "top: 4px; right: 5px;background-position: -31px -193px;width: 16px;height: 16px;"; //;background-image:url(../images/icn-action-off.gif)
    }
}
function CheckBrowserForBubble() {
    var isIE = false;
    if (navigator.appName == "Microsoft Internet Explorer") {
        var version = null;
        version = navigator.appVersion.substring(0, 3);
        isIE = parseFloat(version) < 5.0 ? true : false;
        IsMSIE9 = navigator.appVersion.substring(25, 19) == "IE 9.0" ? true : false;
    }
    else {
        isIE = false;
    }
    return isIE;
}
function ShowAddress(lat, lng) {
    var image = "../images/flag_2.png";
    LandMarkImage = image;
    getAddress = null;
    chkValue = 1;
    document.getElementById('hdnIsLocateMe').value = 'Y';
    map.objects.clear();
    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 nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng));
    map.setCenter(centerPoint, "default")

    var strAddress = "";
    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }
    if (marker) map.objects.remove(marker);
    var offsetX = null;
    var offsetY = null;
    if (image == "../images/flag_2.png") {
        offsetX = 2;
        offsetY = 22;
    }
    else {
        offsetX = 0;
        offsetY = 32;
    }

    marker = new nokia.maps.map.Marker(centerPoint, {
        draggable: false,
        anchor: new nokia.maps.util.Point(offsetX, offsetY)
    });
    map.objects.add(marker);
    polyArray.length = 0;
    polyArray.push(latlong + '#');

    //Draw circle around the Landmark.
    drawCircle();
    map.zoomTo(circle.getBoundingBox(), false, "default");

    //zoom out if too close
    if (map.zoomLevel > 15) map.set("zoomLevel", 15);
    LandMarkImage = '';
}

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

function doDrawCircle() {
    try {
        if (circle && canClearCircle) {
            map.objects.remove(circle);
        }
        var center = map.center;
        var circlePoints = new Array();
        with (Math) {
            //if (circleUnits == 'KM') { 
            var d = circleRadius / 6378.8; // radians
            d = d / 1000;

            var lat1 = (PI / 180) * (!canClearCircle ? landmarkLatitude : center.latitude); // radians
            var lng1 = (PI / 180) * (!canClearCircle ? landmarkLongitude : center.longitude); // 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 nokia.maps.geo.Coordinate(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                circlePoints.push(point);
            }
            if (d < 1.5678565720686044) {
                circle = new nokia.maps.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                pen: { strokeColor: "#5270B2", lineWidth: 2 },
                                brush: { color: "#A4A7" }
                            }
                        );
                //circle = new GPolygon(circlePoints, '#5270B2'/*#000000'*/, 2, 1, '#D8E2FA', 0.25);
            }
            else {
                circle = new nokia.maps.map.Circle(
                            centerPoint,
                //circleRadius,
                            circleRadius,
                            {
                                pen: { strokeColor: "#5270B2", lineWidth: 2 },
                                brush: { color: canClearCircle ? '#000000' : '#A4A7' }
                            }
                        );
                //circle = new GPolygon(circlePoints, canClearCircle ? '#000000' : '#D8E2FA', 2, 1);
            }
            landMarkCircles.push(circle);
            map.objects.add(circle);
            //map.zoomTo(circle.getBoundingBox(), false, "default");
            // Included code to append Landmark & MapIT for best zoom level
            if (mapPoints != null) {
                //bounds.extend(mapPoints);
            }
            else {
                //map.setZoom(map.getBoundsZoomLevel(bounds));
            }
        }

    }
    catch (Error) {
    }
}
function drawCircle_LandmarkPage(landmarkEntries, isLandmarkEnable) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        for (var n = 0; n < landmarkMarkers.length; n++) {
            map.objects.remove(landmarkMarkers[n]);
        }
        landmarkMarkers.splice(n, 1);
        for (var c = 0; c < landMarkCircles.length; c++) {
            map.objects.remove(landMarkCircles[c]);
            //map.removeOverlay(landMarkCircles[c]);
        }
        landMarkCircles.splice(c, 1);
        //landmarkMarkers = null;
    }
    for (var iterator = 0; iterator < lanmarkInformation.length; iterator++) {
        if (lanmarkInformation[iterator] == "") {
            break;
        }
        else {
            var landmarkinfo = lanmarkInformation[iterator].split("~#~");
            centerPoint = new nokia.maps.geo.Coordinate(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
            //centerPoint = new GLatLng(landmarkinfo[0], landmarkinfo[1]);
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new nokia.maps.map.Marker(centerPoint);
            //DrawCircle = marker;
            //var marker = new GMarker(new GLatLng(landmarkinfo[0], landmarkinfo[1]));
            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.objects.add(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) {
                doDrawCircle();
            }
            map.setZoomLevel(6);
            map.zoomTo(circle.getBoundingBox(), false, "default");
        }
    }
}
function flagMarker_LandmarkPage(point, lndName, lndAddr, time, id, i_No, content) {
    var icon = null; //new GIcon();
    icon = '../images/flag_2.png';
    if (document.getElementById('hdnLandmarkImage') != null && document.getElementById('hdnLandmarkImage').value != "") {
        lndImage = String(document.getElementById('hdnLandmarkImage').value);
    }
    loadMap();

    var marker = new nokia.maps.map.Marker(
    point, {
        draggable: false,
        anchor: new nokia.maps.util.Point(2, 22)
    });
    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******************************************/