/***********************************************************************************
The functions listed below are related to Vehicle tracking Feature in here Maps.
***********************************************************************************/
var maptype = "normal.day";
var LoadTime = null;
var timerInterval;
var map = null;
var map1 = null;
var map2 = null;
var map3 = null;
var map4 = null;
var map5 = null;
var map6 = null;
var map7 = null;
var map8 = null;
var map9 = null;

var behavior = null;
var ui = null;
var mapEvents = null;
var mapBckup = null;
var polyline = null;
var history_latlng = null;
var centerCoordinate = new H.geo.Point(20.00, 78.00);
var markersContainer = null;
var isViewLatLong = 0;
var mapItMarkers;
var bubbles;
var MapView = new Array();
var MapViewFullScreen = new Array();
var orgCenter = null;
var orgZoomLevel = null;
var polyLineColor = "#3355ff";
var polyFillColor = "#279923";  //"#335599";
var polyPoints = new Array();
var polyShapeArray = new Array();
var polyArray = new Array();
var markers = new Array();
var polyShape;
var contextmenu;
var ctxtMenu;
var circleUnits;
var timeouts = [];
var geoType, Geozonetype;
var Rec_bounds = new Array();
var poly_bounds;
var isview = 0;
var sGeoName = '';
var PlayBack = {};
var playBackArray = new Array();
var busMarker;
var PlayBackZoom = new Array();
var playAlarm = new Array();
var clusterPoint = new Array();
var clusterPoint_Monitor = new Array();
var clusterProvider = null; //H.clustering.ClusterProvider;
var objectLayer = null;
var objectLayer_monitor = null;
var clusterBackup = new Array();
var clusterBackup_Monitor = new Array();
var isShowLandmarkPlotter = 0;
var isShowGeozonePlotter = false;
var isCreateLandmark = false;
var isCreateGeozone = false;
var kmlGenerator;
var resultContainer;

// Legend Icons
var VAllLandmark = "Landmark";
var VCurrLocation = "Curr. Location";
var VIgnitionOn = "Ignition On";
var VIgnitionOff = "Ignition Off";
var VMoving = "Others";
var VIdling = "Idling";
var VAlarms = "Alarms";
var VDetails = "Details";
var VOtherinfo = "Other Info";
var VDateTime = "Date & Time";
var VMessage = "Message";
var VAddress = "Address";
var VLegendAlign = "left";
var VLandmark = "Landmark";
var VSleep = "Sleep Mode";
var VOthers = "Moving";
var VLegendHeader = "Legends";
var VLegendToolTip = "click to show / hide legends";
var VDirection = "ltr";
var VShowRoute = 'Show Route';
var VAllGeozone = "Show Geozone";

//Playback Legends
var VStart = "Start";
var VDestination = "Destination";
var VVehicle = "Vehicle";
var VAlarm = "Alarms";
var VInfopanel = "Show Info Panel";
var VMarkers = "Show Markers";
var Caption_Play = "Play";
var Caption_Pause = "Pause";
var Caption_Reset = "Reset";
var Caption_Stop = "Stop";
var Caption_Fast = "Fast";
var Caption_Medium = "Medium";
var Caption_Slow = "Slow";

var platform = new H.service.Platform({
    //'apikey': '0OaPhakkm6zOHUc55oZIxP1mXOVPYk9KQdF7omnlmQo'   //VWYjajXdN_OtsvW2akEG9Ys3uszv8gC1ktVFX7U-eto
    'apikey': 'VWYjajXdN_OtsvW2akEG9Ys3uszv8gC1ktVFX7U-eto'
});
var defaultLayers = platform.createDefaultLayers();

var infoBubble = null;
var infoMarkers = {};

// Set the alert messages from the Resource File
function SetIconLegendText(AllLandmarkAlert, CurrLocationAlert, IgnitionOnAlert, IgnitionOffAlert, MovingAlert, IdlingAlert, AlarmsAlert, VDetailsTab, VOtherinfoTab, VDateTimeAlert, VMessageAlert, VAddressAlert, VLegendAlignAlert, VLandmarkAlert, VDirectionMessage, VSleepMessage, VOtherMessage, VLegendHdrMessage, VLegendToolTipMessage, VShowNames, VShowRouteMessage) {

    VAllLandmark = AllLandmarkAlert;
    VCurrLocation = CurrLocationAlert;
    VIgnitionOn = IgnitionOnAlert;
    VIgnitionOff = IgnitionOffAlert;
    VMoving = MovingAlert;
    VIdling = IdlingAlert;
    VAlarms = AlarmsAlert;
    VDetails = VDetailsTab;
    VOtherinfo = VOtherinfoTab;
    VDateTime = VDateTimeAlert;
    VMessage = VMessageAlert;
    VAddress = VAddressAlert;
    VLegendAlign = VLegendAlignAlert;
    VLandmark = VLandmarkAlert;
    VDirection = VDirectionMessage;
    VSleep = VSleepMessage;
    VOthers = VOtherMessage;
    VLegendHeader = VLegendHdrMessage;
    VLegendToolTip = VLegendToolTipMessage;
    VShowRoute = VShowRouteMessage;

    //try {
    //    document.getElementById("map-legend").innerHTML = iconLegendText();
    //}
    //catch (ex)
    //{ }
}

function SetPlayBackLegends(Startpoint, Destination, Vehicle, Alarm, InfoPanel, ShowMarkers) {
    VStart = Startpoint;
    VDestination = Destination;
    VVehicle = Vehicle;
    VAlarm = Alarm;
    VInfopanel = InfoPanel;
    VMarkers = ShowMarkers;

    //try {
    //    document.getElementById("map-legend").innerHTML = PlaybackLegends();
    //}
    //catch (ex)
    //{ }
}

//Playback Captions.
function SetPlaybackCaptions(Play, Pause, Reset, Stop, Fast, Medium, Slow) {
    Caption_Play = Play;
    Caption_Pause = Pause;
    Caption_Reset = Reset;
    Caption_Stop = Stop;
    Caption_Fast = Fast;
    Caption_Medium = Medium;
    Caption_Slow = Slow;
}

var VLandmarkLocationDetails = "Landmark Location Details";
var VOrgCoordinates = "Original Coordinates";
var VEnterRadious = "Enter a number for radius";

function SetLandMarkText(VLandmarkLocationDetailsMessage, VOrgCoordinatesMessage, VAddressMessage, VDirectionMessage, VLandmarkAlert, VEnterRadiousAlert) {
    VLandmarkLocationDetails = VLandmarkLocationDetailsMessage;
    VOrgCoordinates = VOrgCoordinatesMessage;
    VAddress = VAddressMessage;
    VDirection = VDirectionMessage;
    VLandmark = VLandmarkAlert;
    VEnterRadious = VEnterRadiousAlert;
}


// Create a default observer for display properties that will just log a message.
var defaultObserver = function (obj, key, newValue, oldValue) {
    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (newValue.uri) {
            case 'normal': mapTypeHolder.value = 'N'; maptype = 'normal.day'; break;
            case 'hybrid': mapTypeHolder.value = 'H'; maptype = 'hybrid.day'; break;
            case 'terrain': mapTypeHolder.value = 'T'; maptype = 'terrain.day'; break;
            default: mapTypeHolder.value = 'N'; maptype = 'normal.day';
        }
    }

    if (document.getElementById("hdnlang") != null) {
        if (document.getElementById("hdnlang").value == "LanguageArNew") {
            //Change the map type to arabic.
            changeTileProvider(maptype, 'Ar');
        }
        else if (document.getElementById("hdnlang").value == "LanguageHindi") {
            changeTileProvider(maptype, 'hin');
        }
    }
};

//load NavTeq Maps
function load() {
    isShowLandmarkPlotter = 0;
    isShowGeozonePlotter = false;
    document.getElementById("map-legend").innerHTML = iconLegendText();
    try {
        try { if (objContainer != null && objContainer.getObjects().length > 0) { objContainer.removeObjects(objContainer.getObjects()); } } catch (ex) { }
        try { if (objMkr_Grp != null && objMkr_Grp.getObjects().length > 0) { objMkr_Grp.removeObjects(objMkr_Grp.getObjects()); } } catch (ex) { } try { if (objMkr_Grp != null && objMkr_Grp.getObjects().length > 0) { objMkr_Grp.removeObjects(objMkr_Grp.getObjects()); } } catch (ex) { }
        try { if (mkr_group_st != null && mkr_group_st.getObjects().length > 0) { mkr_group_st.removeObjects(mkr_group_st.getObjects()); } } catch (ex) { } try { if (objMkr_Grp != null && objMkr_Grp.getObjects().length > 0) { objMkr_Grp.removeObjects(objMkr_Grp.getObjects()); } } catch (ex) { }
        try { if (mkr_group != null && mkr_group.getObjects().length > 0) { mkr_group.removeObjects(mkr_group.getObjects()); } } catch (ex) { }
        try { if (map && map.getObjects().length > 0) { map.removeObjects(map.getObjects()); } } catch (ex) { }
    }
    catch (Error) {
        //alert(Error);
    }
    try {
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = gridViewControl.width; //document.body.clientWidth ;//document.documentElement.clientWidth-35//screen.width - 35;
        }

        if (document.getElementById('chart-dsply') != null) {
            document.getElementById('chart-dsply').style.width = document.body.clientWidth + 'px';
            document.getElementById('chart-dsply').style.height = ((document.body.clientHeight / 2) - 20) + 'px';
            document.getElementById('wcTempChart').style.width = document.body.clientWidth + 'px';
            document.getElementById('wcTempChart').style.height = ((document.body.clientHeight / 2) - 20) + 'px';
            document.getElementById('chartCrtical').value = document.body.clientWidth;
            document.getElementById('chartWidth').value = document.body.clientWidth;
            document.getElementById('chartHeight').value = ((document.body.clientHeight / 2) - 20);
        }
        if (document.getElementById('map-dsply_cpt') != null) {
            document.getElementById('map-dsply_cpt').style.width = document.body.clientWidth;
            //document.getElementById('map-dsply_cpt').style.height = (document.body.clientHeight / 2) + 'px';
        }

        if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1 || location.pathname.indexOf("VehicleSummary.aspx") != -1) {
            document.getElementById('map-dsply').style.height = 600 + 'px';
            document.getElementById('grid-dsply').style.height = 600 + 'px';
        }
        else {
            console.log(document.body.clientHeight);
            if (document.body.clientHeight < 640)
                document.getElementById('map-dsply').style.height = (document.body.clientHeight) + 'px';
            if (document.body.clientHeight < 800)
                document.getElementById('map-dsply').style.height = (document.body.clientHeight / 2) + 'px';
            else
                document.getElementById('map-dsply').style.height = (document.body.clientHeight / 2) + 'px';
        }
        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            //context menu

            map = new H.Map(document.getElementById("map-dsply"),
            defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                //zoom: orgZoomLevel != null ? orgZoomLevel : 4,
                //setMax: 12,
                zoom: 4,
                //engineType: H.map.render.RenderEngine.EngineType.P2D
            });

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

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

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

            ui.addControl('zoomRectangle', new H.ui.ZoomRectangle());
            ui.getControl('zoomRectangle').setAlignment('left-middle');
            //ui.removeControl('mapsettings');
            ui.removeControl('scalebar');
            ui.getControl('mapsettings').setAlignment('top-left');
            //ui.removeControl('zoom');
            ui.getControl('zoom').setAlignment('left-middle');
            //ui.getControl('mapsettings').removeChild(new H.ui.base.Element("div", "H_btn"));
            //var child = ui.getControl('mapsettings').getChildren();
            //ui.getControl('mapsettings').el.childNodes[0].removeNode();
            if (location.pathname.indexOf("VehicleSummary.aspx") != -1) {
                //ui.removeControl('zoomRectangle');
            }
            CreateContextMenuNew(map);

            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value == "LanguageArNew") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'Ar');
                    LoadTime = null;
                }

                else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'hin');
                    LoadTime = null;
                }
            }

            //map.addObserver("baseMapType", defaultObserver);

            //To enable the Mouse wheel Scroll
            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value != "LanguageArNew") {
                    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);
        orgCenter = null;
        orgZoomLevel = null;
        resultContainer = document.getElementById('map-dsply_cpt');
        // Step 7: Handle capture button click event
        capture(resultContainer, map, ui);

        // Create container for the "Capture" button
        var containerNode = document.createElement('div');
        containerNode.setAttribute('style', 'position:absolute;top:0;left:0;background-color:#fff; padding:10px;');
        containerNode.className = 'ControlHide';

        // Create the "Capture" button
        var captureBtn = document.createElement('input');
        captureBtn.value = 'Capture';
        captureBtn.type = 'button';
        captureBtn.id = "captureBtn";
        //captureBtn.className = 'btn btn-sm btn-default';
        captureBtn.className = 'ControlHide';

        // Add both button and container to the DOM
        containerNode.appendChild(captureBtn);
        document.getElementById("map-dsply").appendChild(containerNode);

        // Step 7: Handle capture button click event
        captureBtn.onclick = function () {
            capture(resultContainer, map, ui);

        };

        if (document.getElementById('gvHistory') != null) {
            map.addEventListener('mapviewchangeend', function () {
                capture(resultContainer, map, ui);
            });
        }
        //setInteractive(map);
        //addShapesToMap(map);
        return true;
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }


}

/***********************************************************/

function capture(resultContainer, map, ui) {
    // Capturing area of the map is asynchronous, callback function receives HTML5 canvas
    // element with desired map area rendered on it.
    // We also pass an H.ui.UI reference in order to see the ScaleBar in the output.
    // If dimensions are omitted, whole veiw port will be captured
    map.capture(function (canvas) {
        if (resultContainer != null && resultContainer != undefined) {
            if (canvas) {
                resultContainer.innerHTML = '';
                resultContainer.appendChild(canvas);
                //doCanvas(canvas);
                downloadCanvas(this, canvas, 'test.svg');
            } else {
                // For example when map is in Panorama mode
                resultContainer.innerHTML = 'Capturing is not supported';
            }
        }
    }, [ui], 0, 0, 1250, 900);
}

function clickCanvas() {
    //capture(resultContainer, map, ui);
    document.getElementById('captureBtn').click();
}

/**
 * Demonstrates how to download a canvas an image with a single
 * direct click on a link.
 */
function doCanvas(canvas) {
    //var canvas = document.getElementById('canvas'),
    var ctx = canvas.getContext('2d');
    /* draw something */
    ctx.fillStyle = '#f90';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#fff';
    ctx.font = '60px sans-serif';
    ctx.fillText('Code Project', 10, canvas.height / 2 - 15);
    ctx.font = '26px sans-serif';
    ctx.fillText('Click link below to save this as image', 15, canvas.height / 2 + 35);
}

/**
 * This is the function that will take care of image extracting and
 * setting proper filename for the download.
 * IMPORTANT: Call it from within a onclick event.
*/
function downloadCanvas(link, canvas, filename) {
    document.getElementById('hdnCapImage').value = canvas.toDataURL();
}

function captureChartImage() {
    if (document.getElementById('wcTempChart_IMG') != null) {
        document.getElementById('hdnChartImageVal').value = document.getElementById('wcTempChart_IMG').src.toString();
    }
}
/***********************************************************/

function iconLegendText() {
    var height = '';

    if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1 || location.pathname.indexOf("VehicleSummary.aspx") != -1) {
        var landmarkIconText = "";
        var landmarkIconTextForFullscreen = "";
        var downIconText = "";
    }
    else {
        var landmarkIconText = '';
        var landmarkIconTextForFullscreen = '';
        var downIconText = (document.getElementById('gvHistory') != null) ? landmarkIconTextForFullscreen : (document.getElementById('gvData') != null) ? landmarkIconText : (document.getElementById('hdnLandmarkEntries') != null && document.getElementById('hdnLandmarkEntries').value.length != 0) ? landmarkIconTextForFullscreen : "";

        //downIconText += (location.pathname.indexOf("HistoryPage.aspx") != -1) ? "<h3 class='foot'><table><tr>" +
        //                "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value, this.checked);clusterDataPoints(clusterPoint, this.checked);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
        //                "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllLandmark + "</b></span></td>" +
        //                "</tr><tr>" +
        //                "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkGeozone' style='height:15px;width:15px;' name='chkGeozone' onclick='PlotGeozone(this.checked,\"M\");'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
        //                "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllGeozone + "</b></span></td>" +
        //                "</tr><tr>" +
        //                //"  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLine' style='height:15px;width:15px;' name='chkLine' onclick='Addcontainer(this);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
        //                //"  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VMarkers + "</b></span></td>" +
        //                //"</tr><tr>" +
        //                "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLine' style='height:15px;width:15px;' name='chkLine' checked='checked' onclick='hideLine(this.checked,\"M\");'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
        //                "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>Show Line</b></span></td>" +
        //                "</tr><tr>" +
        //                "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkTravelPath' style='height:15px;width:15px;' name='chkTravelPath' onclick='ShowPopUp();drawRoute(this.checked,\"r\")'><span style='vertical-align:top;background-color:white;color:Blue'></td>" + //DrawRoute(this);
        //                  "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>Show Path</b></span></td>" +
        //                "</tr><tr>" +
        //                "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkRoute' style='height:15px;width:15px;' name='chkRoute' onclick='DrawRoute(this)'><span style='vertical-align:top;background-color:white;color:Blue'></td>" + //DrawRoute(this);
        //                  "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VShowRoute + "</b></span></td>" +
        //                "</tr></table></h3>" :
        //                ((location.pathname.indexOf("MapPage.aspx") != -1) ?
        //                "<h3 class='foot'><table><tr>" +
        //                "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value, this.checked);clusterDataPoints(clusterPoint, this.checked);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
        //                "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllLandmark + "</b></span></td>" +
        //                "</tr><tr>" +
        //                "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkGeozone' style='height:15px;width:15px;' name='chkGeozone' onclick='PlotGeozone(this.checked,\"M\");'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
        //                "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllGeozone + "</b></span></td>" +
        //                "</tr></table></h3>" : "");
    }

    var CurrentPosistion = (document.getElementById('gvHistory') != null) ? "<tr>" +
                       "  <td style='padding-left:2px'><img src='../images/down.svg' alt='current location' style='height:15px;width:15px'/></td>" +
                       "  <td align=" + VLegendAlign + "><span class='txt' id='spLocation' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VCurrLocation + "</span></td>" +
                       "</tr>" : '';

    var legendText = "<div class='panel' align='center' id='lnkLegend'> <h2><b>" + VLegendHeader + "</b></h2><div class='panelcontent'><table id='tblLegend' align='right'" + height + " style='direction:" + VDirection + ";'>" +
                "<tr><td align='right' style='padding: 6px 0px 6px 6px;'>" +
                 "<table cellpadding='2' cellspacing='2' align='right' width='112px' " +
                 ((location.pathname.indexOf("FullscreenMap.aspx") != -1 && location.search.indexOf("?pMy9nEs9WLFPu5OGp76JWA==") != -1) ?
                 "height='20px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.svg' alt='Alarms' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
                 "</tr>" + CurrentPosistion + "</table></td></tr></table>"
                 :
                 "height='114px'>" +
                 ((location.pathname.indexOf("HistoryPage.aspx") != -1 && location.pathname.indexOf("AdvancedHistoryPage.aspx") == -1) ?
                 "<tr>" +
                 "  <td style='padding-left:2px' align='center'><img src='../images/Start_point_legend.svg' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VStart + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px' align='center'><img src='../images/End_point_legend.svg' alt='Ignition Off' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VDestination + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/car1_Mod.svg' alt='Animate' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;Playback Icon</span></td>" +
                 "</tr>" : "") +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Device_Offline.png' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + "Offline" + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Device_Online.png' alt='Ignition Off' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + "Information" + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Device_Running.png' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + "Running" + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Device_Warning.png' alt='Idling' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt'  id='spIdling' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + "Warning" + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Device_ElectricalTrip.png' alt='moving' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + "Electrical Trip" + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Device_Shutdown.png' alt='sleep' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spSleep' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + "Shutdown" + "</span></td>" +
                 "</tr>" +
                 //"<tr>" +
                 //"  <td style='padding-left:2px'><img src='../images/fuellow-1_.svg' alt='Alarms' style='height:15px;width:15px' /></td>" +
                 //"  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
                 //"</tr>" + CurrentPosistion +
                 "</table></td></tr></table>") +
                 "</div><b>" + downIconText + "</b></div>";
    return legendText;
}

//Legends for Playback Feature
function PlaybackLegends() {
    var height = '';

    var InfoBubble = "<h3 class='foot'><table><tr>" +
                          "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkInfoBubble' style='height:15px;width:15px;' name='chkInfoBubble' onclick='document.getElementById(\"chkInfoBubble\").checked = this.checked;'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                          "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VInfopanel + "</b></span></td>" +
    "</tr></table></h3>";

    var ShowMarkers = "<h3 class='foot'><table><tr>" +
                          "  <td align='right'><input type='checkbox' id='chkShowMarker' style='height:15px;width:15px;margin-right:8px;' name='chkShowMarker' onclick='Addcontainer(this);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                          "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VMarkers + "</b></span></td>" +
                        "</tr></table></h3>";

    var CurrentPosistion = (document.getElementById('gvHistory') != null) ? "<tr>" +
                       "  <td style='padding-left:2px'><img src='../images/down.svg' alt='current location' style='height:15px;width:15px'/></td>" +
                       "  <td align=" + VLegendAlign + "><span class='txt' id='spLocation' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VCurrLocation + "</span></td>" +
                       "</tr>" : '';

    var ShowLine = "<h3 class='foot'><table><tr>" +
                    "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLine' style='height:15px;width:15px;' name='chkLine' checked='checked' onclick='hideLine(this.checked,\"M\");'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                    "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>Show Line</b></span></td>" +
                    "</tr><tr>" +
                    "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkTravelPath' style='height:15px;width:15px;' name='chkTravelPath' onclick='ShowPopUp();drawRoute(this.checked,\"r\")'><span style='vertical-align:top;background-color:white;color:Blue'></td>" + //DrawRoute(this);
                    "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>Show Path</b></span></td>" +
                    "</tr>" +
                    "</table></h3>";

    var legendText = "<div class='panel' align='center' id='lnkLegend'> <h2><b>" + VLegendHeader + "</b></h2><div class='panelcontent'><table id='tblLegend' align='right'" + height + " style='direction:" + VDirection + ";'>" +
                "<tr><td align='right' style='padding: 6px 0px 6px 6px;'>" +
                 "<table cellpadding='2' cellspacing='2' align='right' width='112px' height='114px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px' align='center'><img src='../images/Start_point_legend.svg' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VStart + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px' align='center'><img src='../images/End_point_legend.svg' alt='Ignition Off' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VDestination + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/ignition-on_play.svg' alt='Ignition On' style='height:20px;width:35px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOn + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/ignition-off_play.svg' alt='Ignition Off' style='height:20px;width:35px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOff + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/car1_Mod.svg' alt='Ignition On' style='height:20px;width:35px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VMoving + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Idling.svg' alt='Idling' style='height:20px;width:35px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt'  id='spIdling' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIdling + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/SleepMode.svg' alt='sleep' style='height:20px;width:35px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spSleep' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VSleep + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px' align='center'><img src='../images/carmarker_Alarm.svg' alt='Idling' style='height:20px;width:16px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt'  id='spIdling' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px' align='center'><img src='../images/N.svg' alt='moving' style='height:30px;width:20px' /></td>" +
                 "  <td align='" + VLegendAlign + "' style='vertical-align:middle;'><span class='txt' id='spMoving' runat='server' style='font:11px arial;color:#333333;'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VOthers + "</span></td>" +
                 "</tr>" +
                 "</table></td></tr></table></div>" + InfoBubble + ShowMarkers + "</div>"; //ShowLine +

    //legendText = "<div class='panel' align='center' id='lnkLegend'> <h2><b>" + VLegendHeader + "</b></h2><div class='panelcontent'><table id='tblLegend' align='right'" + height + " style='direction:" + VDirection + ";'>" +
    //            "<tr><td align='right' style='padding: 6px 0px 6px 6px;'>" +
    //             "<table cellpadding='2' cellspacing='2' align='right' width='112px' " +
    //             ((location.pathname.indexOf("FullscreenMap.aspx") != -1 && location.search.indexOf("?pMy9nEs9WLFPu5OGp76JWA==") != -1) ?
    //             "height='20px'>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/fuellow-1_.svg' alt='Alarms' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
    //             "</tr>" + CurrentPosistion + "</table></td></tr></table>"
    //             :
    //             "height='114px'>" +
    //              "<tr>" +
    //             "  <td style='padding-left:2px' align='center'><img src='../images/Start_point_legend.svg' alt='Ignition On' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VStart + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px' align='center'><img src='../images/End_point_legend.svg' alt='Ignition Off' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VDestination + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/purple-1_.svg' alt='Ignition On' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOn + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/orange-1_.svg' alt='Ignition Off' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOff + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/1_.svg' alt='Ignition On' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VMoving + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/pink-1_.svg' alt='Idling' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt'  id='spIdling' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIdling + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/3.svg' alt='moving' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VOthers + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/mapit-9_.svg' alt='sleep' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spSleep' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VSleep + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/fuellow-1_.svg' alt='Alarms' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
    //             "</tr>" +
    //             "<tr>" +
    //             "  <td style='padding-left:2px'><img src='../images/fuelnormal-1_.svg' alt='Animate' style='height:15px;width:15px' /></td>" +
    //             "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;Playback Icon</span></td>" +
    //             "</tr>" +
    //             "</table></td></tr></table>") +
    //             "</div>" + ShowMarkers + ShowLine + "</div>";

    return legendText;
}

//TO load Map in Full screen mode
function loadFullscreen() {

    isShowLandmarkPlotter = 0;
    isShowGeozonePlotter = false;
    //document.getElementById("map-legend").innerHTML = document.getElementById("hdnAlarmIDs") == null ? PlaybackLegends() : iconLegendText();
    try {

    }
    catch (Error) {
    }
    try {
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = document.body.clientWidth; //document.documentElement.clientWidth-35//screen.width - 35;
        }
        document.getElementById('map-dsply').style.height = document.body.clientHeight + 'px';

        if (document.getElementById('chart-dsply') != null) {
            document.getElementById('chart-dsply').style.width = document.body.clientWidth + 'px';
            document.getElementById('chart-dsply').style.height = document.body.clientHeight + 'px';
            document.getElementById('wcTempChart').style.width = document.body.clientWidth + 'px';
            document.getElementById('wcTempChart').style.height = document.body.clientHeight + 'px';
            document.getElementById('chartWidth').value = document.body.clientWidth;
            document.getElementById('chartHeight').value = document.body.clientHeight;
        }
        if (document.getElementById('map-dsply_cpt') != null) {
            document.getElementById('map-dsply_cpt').style.width = document.body.clientWidth;
            document.getElementById('map-dsply_cpt').style.height = document.body.clientHeight + 'px';
        }

        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            //context menu

            map = new H.Map(document.getElementById("map-dsply"),
            defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : new H.geo.Point(20.00, 78.00),
                zoom: 4, //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');

            CreateContextMenuNew(map);

            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value == "LanguageArNew") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'Ar');
                    LoadTime = null;
                }
                else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'hin');
                    LoadTime = null;
                }
            }
            //Get the map view(Center and Zoom level)            
            //map.addObserver("baseMapType", defaultObserver);

            //Set map Type
            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value != "LanguageArNew") {
                    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);
            orgCenter = null;
            orgZoomLevel = null;
        }
        return true;
    }
    catch (Error) {
        alert(Error);
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}
function loadFullscreenAdv() {
    isShowLandmarkPlotter = 0;
    try {
        if (map1) map1.removeObjects(map1.getObjects());
        if (map2) map2.removeObjects(map2.getObjects());
        if (map3) map3.removeObjects(map3.getObjects());
        if (map4) map4.removeObjects(map4.getObjects());
        if (map5) map5.removeObjects(map5.getObjects());
        if (map6) map6.removeObjects(map6.getObjects());
        if (map7) map7.removeObjects(map7.getObjects());
        if (map8) map8.removeObjects(map8.getObjects());

    }
    catch (Error) {
    }
    //document.getElementById("map-legend").innerHTML = iconLegendText();
    try {

        if (document.getElementById('map-dsply1').innerHTML == "" || document.getElementById('map-dsply1').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            //context menu

            map1 = new H.Map(document.getElementById("map-dsply1"), defaultLayers.raster.normal.map, getConfig());
            map2 = new H.Map(document.getElementById("map-dsply2"), defaultLayers.raster.normal.map, getConfig());
            map3 = new H.Map(document.getElementById("map-dsply3"), defaultLayers.raster.normal.map, getConfig());
            map4 = new H.Map(document.getElementById("map-dsply4"), defaultLayers.raster.normal.map, getConfig());
            map5 = new H.Map(document.getElementById("map-dsply5"), defaultLayers.raster.normal.map, getConfig());
            map6 = new H.Map(document.getElementById("map-dsply6"), defaultLayers.raster.normal.map, getConfig());
            map7 = new H.Map(document.getElementById("map-dsply7"), defaultLayers.raster.normal.map, getConfig());
            map8 = new H.Map(document.getElementById("map-dsply8"), defaultLayers.raster.normal.map, getConfig());
            map9 = new H.Map(document.getElementById("map-dsply9"), defaultLayers.raster.normal.map, getConfig());

            orgCenter = null;
            orgZoomLevel = null;

            //Behaviour
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map1));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map2));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map3));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map4));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map5));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map6));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map7));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map8));
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map9));

        }
        return true;
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}
var getConfig = function () {
    return {
        // initial center and zoom level of the map
        center: new H.geo.Point(23.22162, 87.58029), zoom: 5,
        engineType: H.map.render.RenderEngine.EngineType.P2D
    };
};
function mapTypeChanged() {
    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (map.getCurrentMapType()) {
            case G_NORMAL_MAP: mapTypeHolder.value = 'N'; break;
            case G_SATELLITE_MAP: mapTypeHolder.value = 'S'; break;
            case G_HYBRID_MAP: mapTypeHolder.value = 'H'; break;
        }
    }
}

var flag = false;
//To toggle from Fullscreen Mode - Not used now, but kept for future reference
function changeSize() {
    if (flag == false) {
        document.getElementById('top-content').style.display = 'none';
        document.getElementById('updGrid').style.display = 'none';
        document.getElementById('map-dsply').style.width = document.body.clientWidth - 10;
        document.getElementById('map-dsply').style.height = document.body.clientHeight - 10;
    }
    else {
        document.getElementById('top-content').style.display = 'block';
        document.getElementById('updGrid').style.display = 'block';
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = gridViewControl.width;
        }
        document.getElementById('map-dsply').style.height = (document.body.clientHeight / 2) + 'px';
    }
    // Always change value of flag
    // from true to false or vice versa
    flag = !flag;
    // Always call checkResize()
}

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

};

var acMarker = new Array();
function DisplayLocationForAMS(latlng, pageName, mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible, datetimeCaption,
    isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible, speedCaption,
    addLandmarkCaption, isVehicleVisbile, vehicleCaption, isPolylineVisible, isCurrentPositionVisible, LatLong) {

    try {
        if (document.getElementById("hdnlang") != null) {
            if (document.getElementById("hdnlang").value != "LanguageArNew") {
                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;
                    }
                }
            }
        }
        lt = new Array();
        lntlngs = new Array();
        history_latlng = latlng;
        googleResults = new Array();
        lntlngs = new Array();
        markersContainer = new nokia.maps.map.Container();

        if (latlng.indexOf('~&~*') > 0) {
            var currentpos = latlng.split('~&~*');
            lt = currentpos[0].split('~&~');
            positioncurrent = currentpos[1];
        }
        else {
            lt = latlng.split('~&~*');
            positioncurrent = lt[1];

            if (positioncurrent != null) {
                var curpos = positioncurrent.split("~#~");

                var point = H.geo.Point(parseFloat(curpos[0]), parseFloat(curpos[1])); //new GLatLng(curpos[0], curpos[1]);
                map.addObject(createMarker(point, curpos[5], curpos[3], curpos[4], 'current', i, curpos[2],
                     curpos[6], curpos[7], curpos[8], curpos[9], mainCaption, isMessageVisbile, msgCaption,
                     isDateTimeVisible, datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible,
                     landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption));
                canClearCircle = false;
                return;
            }
        }

        for (var i = 0; i < lt.length; i++) {
            var lng = new Array();
            lng = lt[i].split("~#~");

            var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            lntlngs.push(point);
            map.addObject((createMarker(point, lng[5], lng[3], lng[4], i.toString(), i, lng[2],
                     lng[6], lng[7], lng[8], lng[9], mainCaption, isMessageVisbile, msgCaption,
                     isDateTimeVisible, datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible,
                     landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption)));
        }

        if (isPolylineVisible) {
            polyline = new H.map.Polyline(
                        lntlngs,
                        {
                            pen: { strokeColor: "#980900", lineWidth: 2 },
                            brush: { color: "#980900" }
                        }
                    );
            map.addObject(polyline);
            map.setViewBounds(polyline.getBounds());
            if (map.zoom == map.maxZoom)
                map.setZoom(map.zoom - 3);
        }
        acMarker = new Array();
        var ltn = new Array();
        if (LatLong != null && LatLong.length > 0) {
            ltn = LatLong.split(',');
            var lcPoint = new H.geo.Point(parseFloat(ltn[0]), parseFloat(ltn[1]));
            var marker = new H.map.Marker(lcPoint,
            { icon: new H.map.Icon('../images/icon-road-accident.svg', { anchor: new H.math.Point(9, 12) }) });
            ui.removeBubble(infoBubble);
            acMarker.push(marker);
            map.addObject(marker);
            infoBubble = new H.ui.InfoBubble(lcPoint, { content: '<span>Accident Zone</span>' });
            ui.addBubble(infoBubble);
        }
    }
    catch (Error) {
        TrinetraCustomAlerts(Error);
    }
}

function invalidDataAMS(LatLong) {
    acMarker = new Array();
    var ltn = new Array();
    if (LatLong != null && LatLong.length > 0) {
        ltn = LatLong.split(',');
        var lcPoint = new H.geo.Point(parseFloat(ltn[0]), parseFloat(ltn[1]));
        var marker = new H.map.Marker(lcPoint,
            { icon: new H.map.Icon('../images/icon-road-accident.svg', { anchor: new H.math.Point(9, 12) }) });
        ui.removeBubble(infoBubble);
        acMarker.push(marker);
        map.addObject(marker);
        infoBubble = new H.ui.InfoBubble(lcPoint, { content: '<span>Accident Zone</span>' });
        ui.addBubble(infoBubble);
    }
}

function loadMapForChoosingLocation() {
    document.getElementById('map-dsply').style.width = document.body.clientWidth; //'635px';
    document.getElementById('map-dsply').style.height = document.body.clientHeight - 50 + 'px'; //'532px';
    try {
        if (map) {
            map.removeObjects(map.getObjects());
            map.setCenter(orgCenter != null ? orgCenter : centerCoordinate);
            map.setZoom(orgZoomLevel != null ? orgZoomLevel : 4);
        }

        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {

            map = new H.Map(document.getElementById("map-dsply"),
            defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: 4, //orgZoomLevel != null ? orgZoomLevel : 4
                engineType: H.map.render.RenderEngine.EngineType.P2D
            });

            //Behaviour
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
            // Create the default UI components
            ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");

            map.addEventListener("tap", function (evt) {
                for (var ac = 0; ac < acMarker.length; ac++) {
                    map.removeObject(acMarker[ac]);
                }
                acMarker = new Array();
                var cord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                if (cord != null) {
                    if (document.getElementById('hdnLatLong') != null) {
                        var aslatitude = Math.round(cord.lat * 1000000) / 1000000;
                        var aslongitude = Math.round(cord.lng * 1000000) / 1000000;
                        document.getElementById('hdnLatLong').value = aslatitude + ',' + aslongitude;
                    }
                    var lcPoint = new H.geo.Point(parseFloat(cord.lat), parseFloat(cord.lng));
                    var marker = new H.map.Marker(lcPoint,
                     { icon: new H.map.Icon('../images/icon-road-accident.svg', { anchor: new H.math.Point(9, 12) }) });
                    ui.removeBubble(infoBubble);
                    acMarker.push(marker);
                    map.addObject(marker);
                    infoBubble = new H.ui.InfoBubble(lcPoint, { content: '<span>Accident Zone</span>' });
                    ui.addBubble(infoBubble);
                }
            });
        }
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}

function loadMapForChoosingLocationPickupAndDrop() {
    document.getElementById('map-dsply').style.width = document.body.clientWidth; //'635px';
    document.getElementById('map-dsply').style.height = document.body.clientHeight - 50 + 'px'; //'532px';
    try {
        if (map) {
            map.removeObjects(map.getObjects());
            map.setCenter(orgCenter != null ? orgCenter : centerCoordinate);
            map.setZoom(orgZoomLevel != null ? orgZoomLevel : 4);
        }

        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {

            map = new H.Map(document.getElementById("map-dsply"),
            defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4,
                engineType: H.map.render.RenderEngine.EngineType.P2D
            });

            //Behaviour
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
            // Create the default UI components
            ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");

            map.addEventListener("tap", function (evt) {
                for (var ac = 0; ac < acMarker.length; ac++) {
                    map.removeObject(acMarker[ac]);
                }
                acMarker = new Array();
                var cord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                if (cord != null) {
                    if (document.getElementById('hdnLatLong') != null) {
                        var aslatitude = Math.round(cord.lat * 1000000) / 1000000;
                        var aslongitude = Math.round(cord.lng * 1000000) / 1000000;
                        document.getElementById('hdnLatLong').value = aslatitude + ',' + aslongitude;
                    }
                    var lcPoint = new H.geo.Point(parseFloat(cord.lat), parseFloat(cord.lng));
                    var marker = new H.map.Marker(lcPoint,
                     { icon: new H.map.Icon('../images/icon-road-accident.svg', { anchor: new H.math.Point(9, 12) }) });
                    ui.removeBubble(infoBubble);
                    acMarker.push(marker);
                    map.addObject(marker);

                    var reverseGeocodingParameters = {
                        prox: cord.lat + "," + cord.lng + ",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);
                    });
                }
            });
        }
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}

function LocateMapCoordinatesForMap(lat, lng) {
    var image = "../images/flag_2.svg";
    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.svg") {
        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());

    //zoom out if too close
    map.setZoom(20);
    LandMarkImage = '';
}


function loadMapForEmployeeLocation() {
    document.getElementById('map-dsply').style.width = document.body.clientWidth; //'635px';
    document.getElementById('map-dsply').style.height = document.body.clientHeight - 50 + 'px'; //'532px';
    try {
        if (map) {
            map.removeObjects(map.getObjects());
            map.setCenter(orgCenter != null ? orgCenter : centerCoordinate);
            map.setZoom(orgZoomLevel != null ? orgZoomLevel : 4);
        }

        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {

            map = new H.Map(document.getElementById("map-dsply"),
            defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4,
                engineType: H.map.render.RenderEngine.EngineType.P2D
            });

            //Behaviour
            behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
            // Create the default UI components
            ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");

            map.addEventListener("tap", function (evt) {
                for (var ac = 0; ac < acMarker.length; ac++) {
                    map.removeObject(acMarker[ac]);
                }
                acMarker = new Array();
                var cord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                if (cord != null) {
                    if (document.getElementById('hdnLatLong') != null) {
                        var aslatitude = Math.round(cord.lat * 1000000) / 1000000;
                        var aslongitude = Math.round(cord.lng * 1000000) / 1000000;
                        document.getElementById('hdnLatLong').value = aslatitude + ',' + aslongitude;
                    }
                    var lcPoint = new H.geo.Point(parseFloat(cord.lat), parseFloat(cord.lng));
                    var marker = new H.map.Marker(lcPoint);
                    ui.removeBubble(infoBubble);
                    acMarker.push(marker);
                    map.addObject(marker);
                    //infoBubble = new H.ui.InfoBubble(lcPoint, { content: '<span>Accident Zone</span>' });
                    //ui.addBubble(infoBubble);
                }
            });
        }
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}

var marker = null;
var lndMark_grp = new H.map.Group();
function loadForLandMark() {
    try {
        document.getElementById("pnlAddressLocating").style.display = "none";
    }
    catch (Error) {
    }
    try {
        var isIE = CheckBrowser();
        var hdnCanAddLandmarksControl = document.getElementById('hdnCanAddLandmarks');
        var gridViewControl = document.getElementById('gvData');
        if (hdnCanAddLandmarksControl.value == 'false') {
            document.getElementById('search-area').setAttribute(isIE ? 'className' : 'class', 'ControlHide');
            if (gridViewControl != null) {
                document.getElementById('map-dsply').style.width = gridViewControl.clientWidth + 'px';
            }
        }
        else {
            document.getElementById('search-area').setAttribute(isIE ? 'className' : 'class', "ControlShow");
            document.getElementById('map-dsply').style.width = '100%';
            //(gridViewControl.clientWidth - 5 - (document.getElementById('search-box').clientWidth)) + 'px';   Jayaram changes for Bootstrap.
        }

        // Setting the height of the map        
        if (document.body.clientHeight < 875) {
            document.getElementById('map-dsply').style.height = ((875 / 2) - 18) + 'px';
            document.getElementById('search-box').style.height = document.getElementById('map-dsply').style.height;
        }
        else {
            document.getElementById('map-dsply').style.height = ((document.body.clientHeight / 2) - 18) + 'px';
            document.getElementById('search-box').style.height = document.getElementById('map-dsply').style.height;
        }

        if (map) {
            if (map.getObjects().length > 0) {

                if (lndMark_grp.getObjects().length > 0) {
                    lndMark_grp.removeObjects(lndMark_grp.getObjects());
                }

                if (landMarkCircles.getObjects().length > 0) {
                    landMarkCircles.removeObjects(landMarkCircles.getObjects());
                }
                map.removeObjects(map.getObjects());
            }
            map.setCenter(orgCenter != null ? orgCenter : centerCoordinate);
            map.setZoom(orgZoomLevel != null ? orgZoomLevel : 4);
        }

        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {

            map = new H.Map(document.getElementById("map-dsply"),
            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);

            //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('zoom').setAlignment('left-middle');
            ui.getControl('mapsettings').setAlignment('top-left');
            ui.addControl('zoomRectangle', new H.ui.ZoomRectangle());
            ui.getControl('zoomRectangle').setAlignment('bottom-right');
            //createContextMenu(map);

            map.addEventListener("tap", function (evt) {
                for (var b = 0; b < ui.getBubbles().length; b++) {
                    ui.removeBubble(ui.getBubbles()[b]);
                }
                var cord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                var Restriction = document.getElementById('hdnRestriction').value;

                showControls(1);
                if (cord != null) {
                    document.getElementById('txtlat').value = Math.round(cord.lat * 1000000) / 1000000;
                    document.getElementById('txtlong').value = Math.round(cord.lng * 1000000) / 1000000;
                    if (document.getElementById('hdnLatLong') != null) {
                        document.getElementById('hdnLatLong').value = cord.lat + ',' + cord.lng;
                    }
                    chkValue = 0;
                    document.getElementById('hdnIsLocateMe').value = 'N';
                }

                //  if (Restriction == '0') {
                //      if (document.getElementById("hdnlang").value == "LanguageArNew") {
                //          TrinetraCustomAlerts('بلغ الحد الأقصى لعدد معالم! . لا يمكن إنشاء أكثر معالم.');
                //      }
                //     else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                //          TrinetraCustomAlerts('स्थलों की अधिकतम संख्या तक पहुंच! . अधिक मील का पत्थर नहीं बना सकता है.');
                //     } else {
                //         TrinetraCustomAlerts('Maximum number of Landmarks reached. Cannot create more Landmarks.');
                //    }
                // }

            });
            CreateContextMenuNewLandmark(map);

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

        if (document.getElementById('hdnMapZoomLevelLatLong').value != "") {
            var zoomLevelLatLong = document.getElementById('hdnMapZoomLevelLatLong').value.split(',');
        }
    }
    catch (Error) {
        //alert(Error);
        TrinetraCustomAlerts('Please check your Internet Connection. Map cannot be loaded');
    }
}
//------End------Added by Ramya on 03 Oct 09 (To change the width of the map displaying div----------//
var lt;
var count = '';
//To get the array of LatLong values
var collectdata = null;

var lntlngs = new Array();
var polyStrip = new H.geo.LineString();
var geocoder;
var address = new Array();
var disArray = new Array();
var googleResults;
var lastvalue = null;
var positioncurrent = null;
var landmarkInfo = null;
var canClearCircle = true;
var historyLandmarks = ''
var markerTrips = new Array();

function DisplayLocation(latlng, pageName, mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible, datetimeCaption,
    isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible, speedCaption,
    addLandmarkCaption, isVehicleVisbile, vehicleCaption, isPolylineVisible, isCurrentPositionVisible) {

    try {
        try {
            var mapItValueList = document.getElementById("hdnAlarmIDs") == null ? new Array() : document.getElementById("hdnAlarmIDs").value.split(',');
        }
        catch (ex) {
        }

        if (document.getElementById("hdnlang") != null) {
            if (document.getElementById("hdnlang").value != "LanguageArNew") {
                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;
                    }
                }
            }
        }

        //if (document.getElementById("playbackControls") != null) {
        //document.getElementById("playbackControls").setAttribute("class", "ControlHide");
        //}

        lt = new Array();
        history_latlng = latlng;
        googleResults = new Array();
        lntlngs = new Array();
        polyStrip = new H.geo.LineString();
        polyStripAdv1 = new H.geo.LineString();
        polyStripAdv2 = new H.geo.LineString();
        polyStripAdv3 = new H.geo.LineString();
        polyStripAdv = new H.geo.LineString();
        lntlngTrip1 = new Array();
        lntlngTrip2 = new Array();
        lntlngTrip3 = new Array();
        lntlngTrip = new Array();
        var waypoints = new Array();
        var Tripcount = 1;
        //markersContainer = new nokia.maps.map.Container();


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

        mkr_group = new H.map.Group();


        if (latlng.indexOf('~&~*') > 0) {
            var currentpos = latlng.split('~&~*');
            lt = currentpos[0].split('~&~');
            positioncurrent = currentpos[1];
        }
        else {
            lt = latlng.split('~&~*');
            positioncurrent = lt[1];

            if (positioncurrent != null) {
                var curpos = positioncurrent.split("~#~");
                var point = H.geo.Point(parseFloat(curpos[0]), parseFloat(curpos[1])); //new GLatLng(curpos[0], curpos[1]);
                markerTrips.push(createMarker(point, curpos[5], curpos[3], curpos[4], 'current', i, curpos[2],
                     curpos[6], curpos[7], curpos[8], curpos[9], mainCaption, isMessageVisbile, msgCaption,
                     isDateTimeVisible, datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible,
                     landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption));
                //map.addObject(
                canClearCircle = false;
                //map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
                return;
            }
        }

        for (var i = 0; i < lt.length; i++) {
            var lng = new Array();
            lng = lt[i].split("~#~");
            if (i == lt.length - 1) {
                lastvalue = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            }
            if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1) {
                if (lng[7] != 0) {
                    polyStripAdv.pushPoint(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));
                }
                else if (lng[7] == 0) {

                    polyStripAdv.pushPoint(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));

                    if (polyStripAdv.getPointCount() != 0) {
                        if (Tripcount == 1)
                            polyStripAdv1 = polyStripAdv;
                        else if (Tripcount == 2)
                            polyStripAdv2 = polyStripAdv;
                        else
                            polyStripAdv3 = polyStripAdv;
                        Tripcount++;
                        polyStripAdv = new H.geo.LineString();
                    }
                }
            }
            lntlngs.push(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));
            polyStrip.pushPoint(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));
            PlayBackZoom.push(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));
            //var coords = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            //playBackArray.push(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));//parseFloat(lng[0])); playBackArray.push(parseFloat(lng[1]));
            //waypoints.push({ position: coords });
        }

        //create our new class
        var work = new threadedLoop(lntlngs);
        var mapMarker;


        work.action = function (item, index, total) {
            var lng = new Array();
            if (index <= total) {
                lng = lt[index - 1].split("~#~");
                mapMarker =
                    createMarker(lntlngs[index - 1], lng[5], lng[3], lng[4],
                    Array.contains(mapItValueList, "'" + lng[10].toString().toUpperCase() + "'") ?
                     'MapIt' : i.toString(), i, lng[2], lng[6], lng[7], lng[8], lng[9],
                     mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible, datetimeCaption,
                     isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                     isSpeedVisible, speedCaption, addLandmarkCaption);
                markerTrips.push(mapMarker);
                mkr_group.addObject(mapMarker);
                //markersContainer.objects.add(mapMarker);
            }
        };
        work.finish = function (thread) {
            if (positioncurrent != null && isCurrentPositionVisible == 'true') {
                var curpos = positioncurrent.split("~#~");
                var point = new H.geo.Point(parseFloat(curpos[0]), parseFloat(curpos[1])); //GLatLng(curpos[0], curpos[1]);
                if (document.getElementById("hdnAlarmIDs") != null) {
                    mapMarker = createMarker(point, curpos[5], curpos[3], curpos[4], 'current', i, curpos[2],
                 curpos[6], curpos[7], curpos[8], curpos[9], mainCaption, isMessageVisbile, msgCaption,
                 isDateTimeVisible, datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible,
                 landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption)
                    markerTrips.push(mapMarker);
                    mkr_group.addObject(mapMarker);
                    canClearCircle = false;
                }
            }

            if (document.getElementById("hdnAlarmIDs") == null) {
                playBack(lntlngs, polyStrip);
                map.addObject(mkr_group);
                //map.setViewBounds(mkr_group.getBounds());
                map.getViewModel().setLookAtData({
                    bounds: mkr_group.getBoundingBox()
                });
            }
            else {
                map.addObject(mkr_group);
                //map.setViewBounds(mkr_group.getBounds());
                map.getViewModel().setLookAtData({
                    bounds: mkr_group.getBoundingBox()
                });
            }

            work = null;
            HidePopUp();
        };
        work.start();
        z = 0;
        if (isPolylineVisible) {
            if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1) {
                if (polyStripAdv1.getPointCount() > 0) {
                    polyline = null;
                    polyline = new H.map.Polyline(
                        polyStripAdv1,
                        {
                            style: { strokeColor: "#0B2161", lineWidth: 2, color: "#0B2161" }
                        }
                    );
                    map.addObject(polyline);
                    z++;
                }
                if (document.getElementById('lblTrip1') != undefined) {
                    document.getElementById('lblTrip1').style.backgroundColor = "#0B2161";
                    document.getElementById('lblTrip1').style.color = "#FBEFEF";
                }
                if (polyStripAdv2.getPointCount() > 0) {
                    polyline = null;
                    polyline = new H.map.Polyline(
                        polyStripAdv2,
                        {
                            style: { strokeColor: "#FF0000", lineWidth: 2, color: "#FF0000" }
                        }
                    );
                    map.addObject(polyline);
                    z++;
                }
                if (document.getElementById('lblTrip2') != undefined) {
                    document.getElementById('lblTrip2').style.backgroundColor = "#FF0000";
                    document.getElementById('lblTrip2').style.color = "#FBEFEF";
                }
                if (polyStripAdv3.getPointCount() != 0) {
                    polyline = null;
                    polyline = new H.map.Polyline(
                        polyStripAdv3,
                        {
                            style: { strokeColor: "#2ECCFA", lineWidth: 2, color: "#2ECCFA" }
                        }
                    );
                    map.addObject(polyline);
                    z++;
                }
                if (document.getElementById('lblTrip3') != undefined) {
                    document.getElementById('lblTrip3').style.backgroundColor = "#2ECCFA";
                    document.getElementById('lblTrip3').style.color = "#0A0A2A";
                }
            }
            else {
                if (polyStrip.getPointCount() > 1) {
                    polyline = new H.map.Polyline(
                            polyStrip,
                            {
                                style: { strokeColor: '#980900', lineWidth: 2, color: '#980900' }
                            }
                        );
                    map.addObject(polyline);
                }
            }
        }
        if (location.pathname.indexOf("HistoryPage.aspx") != -1) {
            capture(resultContainer, map, ui);
        }

        //callroute(waypoints);
        //applyFleetLayer_NV(map, platform);
    }
    catch (Error) {
        TrinetraCustomAlerts(Error);
    }
}

function continueOperations(isPolylineVisible, polyline, collectdata) {
    if (isPolylineVisible) {
        polyline = new H.map.Polyline(lntlngs, {
            style: { strokeColor: "#980900", lineWidth: 2 }
        });
        map.addObject(polyline);
    }
    map.setViewBounds(polyline.getBounds());
}

// Creates a marker at the given point with the given number label
function Draw(polystyle) {
    try {
        var ctrl = document.getElementById(polystyle);

        if (ctrl.id == 'dot') {
            var solid = document.getElementById('solid');
            var dash = document.getElementById('dash');
            ctrl.src = '../images/btn-' + polystyle + '-over.jpg';
            solid.src = '../images/btn-solid.jpg';
            dash.src = '../images/btn-dash.jpg';
        }
            //Dash
        else if (ctrl.id == 'dash') {
            var solid = document.getElementById('solid');
            var dot = document.getElementById('dot');
            ctrl.src = '../images/btn-' + polystyle + '-over.jpg';
            solid.src = '../images/btn-solid.jpg';
            dot.src = '../images/btn-dot.jpg';
        }
            //Solid
        else if (ctrl.id == 'solid') {
            var dash = document.getElementById('dash');
            var dot = document.getElementById('dot');
            ctrl.src = '../images/btn-' + polystyle + '-over.jpg';
            dot.src = '../images/btn-dot.jpg';
            dash.src = '../images/btn-dash.jpg';
        }

        if (lntlngs.length > 0) {
            map.removeObject(polyline);
            polyline = new H.map.Polyline(
                        lntlngs,
                        {
                            style: { strokeColor: "#980900", lineWidth: 2, color: "#980900" }
                        }
                    );
            map.addObject(polyline);
        }
    }
    catch (Error) {
        //    return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}
var timeoutMarker;
function createMarker(point, heading, speed, time, id, i_No, addr, dist, ignstatus, landmark, msgdetails,
    mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible, datetimeCaption, isAddressVisible,
    addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption) {
    debugger
    var mapIcon = null;
    var marker;
    try {
        if (heading == -1 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-1_.svg';
                playbackIcon = '../images/vechile_New.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-1_.svg';
                playbackIcon = '../images/ignition-on_play.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-1_.svg';
                playbackIcon = '../images/carmarker_Alarm.svg';
            }
            else if (ignstatus == '3' || ignstatus == '8' || ignstatus == '9') /*Idling start & end 06-Dec-2011 - Sakthi*/ {
                mapIcon = '../images/pink-1_.svg';
                playbackIcon = '../images/Idling.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-1_.svg';;
                playbackIcon = mapIcon;
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-1_.svg';
                playbackIcon = mapIcon;
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/1_.svg';
                playbackIcon = '../images/car1_Mod.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-1_.svg';
                playbackIcon = '../images/ignition-off_play.svg';
            }
            else if (ignstatus == '10') { /*Sleep mode 20-Dec-2011 Sakthi*/
                mapIcon = '../images/mapit-9_.svg';
                playbackIcon = '../images/SleepMode.svg';
            }
        }
        else if (heading >= 0 && heading <= 30 && id != 'current') {
            if (id == 'MapIt') {
                if (heading == '0' && ignstatus == '7') {
                    mapIcon = '../images/mapit-1_.svg';
                    playbackIcon = '../images/vechile_New.svg';
                }
                else {
                    mapIcon = '../images/mapit-3_20.svg';
                    playbackIcon = '../images/N.svg';
                }

            }
            else if (heading == '0' && ignstatus == '7') {
                mapIcon = '../images/fuellow-1_.svg';
                playbackIcon = '../images/vechile_New.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
        }
        else if (heading > 30 && heading <= 70 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-7_20.svg';
                playbackIcon = '../images/NE.svg';
            }
        }
        else if (heading > 70 && heading <= 100 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-1_20.svg';
                playbackIcon = '../images/E.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-1_20.svg';
                playbackIcon = '../images/E.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-1_20.svg';
                playbackIcon = '../images/E.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-1_20.svg';
                playbackIcon = '../images/E.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-1_20.svg';
                playbackIcon = '../images/E.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/1_20.svg';
                playbackIcon = '../images/E.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-1_20.svg';
                playbackIcon = '../images/E.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-1_20.svg';
                playbackIcon = '../images/E.svg';
            }
        }
        else if (heading > 100 && heading <= 150 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-5_20.svg';
                playbackIcon = '../images/SE.svg';
            }
        }
        else if (heading > 150 && heading <= 200 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-4_20.svg';
                playbackIcon = '../images/S.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-4_20.svg';
                playbackIcon = '../images/S.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-4_20.svg';
                playbackIcon = '../images/S.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-4_20.svg';
                playbackIcon = '../images/S.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-4_20.svg';
                playbackIcon = '../images/S.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/4_20.svg';
                playbackIcon = '../images/S.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-4_20.svg';
                playbackIcon = '../images/S.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-4_20.svg';
                playbackIcon = '../images/S.svg';
            }
        }
        else if (heading > 200 && heading <= 240 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-8_20.svg';
                playbackIcon = '../images/SW.svg';
            }
        }
        else if (heading > 240 && heading <= 280 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-2_20.svg';
                playbackIcon = '../images/W.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-2_20.svg';
                playbackIcon = '../images/W.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-2_20.svg';
                playbackIcon = '../images/W.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-2_20.svg';
                playbackIcon = '../images/W.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-2_20.svg';
                playbackIcon = '../images/W.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/2_20.svg';
                playbackIcon = '../images/W.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-2_20.svg';
                playbackIcon = '../images/W.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-2_20.svg';
                playbackIcon = '../images/W.svg';
            }
        }
        else if (heading > 280 && heading <= 330 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-6_20.svg';
                playbackIcon = '../images/NW.svg';
            }
        }
        else if (heading > 330 && heading <= 360 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-3_20.svg';
                playbackIcon = '../images/N.svg';
            }
        }
        else if (heading > 370 && id != 'current') {
            mapIcon = '../images/greendot_16.gif';
            playbackIcon = '../images/greendot_16.gif';
        }
        else {
            mapIcon = '../images/1.svg';
            playbackIcon = '../images/1.svg';
        }

        if (id == 'current') {
            mapIcon = '../images/down.svg';
            playbackIcon = '../images/down.svg';
        }

        if (mapIcon == null || mapIcon == '') {
            mapIcon = '../images/1.svg';
            playbackIcon = '../images/1.svg';
        }

        addr = addr.replace("'", "");

        var temp1 = "'" + point + "'";
        var temp = temp1.substring(2, temp1.length - 2);
        temp = "'" + point.lat + "," + point.lng + "'";
        var infoBubbleMessage = (!isSpeedVisible ? FrameMessage(mainCaption, isMessageVisbile, msgCaption, msgdetails,
        isDateTimeVisible, datetimeCaption, time, isAddressVisible, addressCaption, addr.replace("'", ""), isLandmarkVisible,
        landmarkCaption, landmark, isSpeedVisible, speedCaption, speed, addLandmarkCaption,
        (document.getElementById('hdnAddLandmark').value == "No" || landmark != "-") ? false : true, temp) : '');

        var tabs = (isSpeedVisible ? CreateTabs(mainCaption, isMessageVisbile, msgCaption, msgdetails,
        isDateTimeVisible, datetimeCaption, time, isAddressVisible, addressCaption, addr.replace("'", ""), isLandmarkVisible,
        landmarkCaption, landmark, isSpeedVisible, speedCaption, speed, addLandmarkCaption,
        (document.getElementById('hdnAddLandmark').value == "No" || landmark != "-") ? false : true, temp) : null);

        //Open Bubble function.
        var OpenBubble = function (evt) {
            var coordinate = evt.target.getGeometry();
            ui.removeBubble(infoBubble);
            //Set Info Bubble styles(Rounded like Cornors etc.) 
            //infoBubbleStyle();
            if (isSpeedVisible) {
                infoBubble = new H.ui.InfoBubble(coordinate, { content: tabs });
                bubbles = ui.addBubble(infoBubble);
            }
            else {
                infoBubble = new H.ui.InfoBubble(coordinate, { content: infoBubbleMessage });
                bubbles = ui.addBubble(infoBubble);
            }
        }

        var playBackInfo = isSpeedVisible == true ? tabs : infoBubbleMessage;

        if (ignstatus == '6' || ignstatus == '7') {
            PlayBack[point.lat + ',' + point.lng] = { Info: playBackInfo, Alarm: true, icon: playbackIcon };
        }
        else {
            PlayBack[point.lat + ',' + point.lng] = { Info: playBackInfo, Alarm: false, icon: playbackIcon };
        }

        //Event to close bubble template
        var CloseBubble = function (evt) {
            ui.removeBubble(infoBubble);
        }

        //Event Listener which are added to the bubble.
        map.addEventListener("tap", CloseBubble);
        var myListener = {
            "pointermove": [OpenBubble, true, null],
            "tap": [OpenBubble, true, null]
        };

        var dspX;
        var dspY;
        if (id == 'MapIt' || id == 'current') {
            if (id == 'current') {
                var dspX = 10;
                var dspY = 40;
            }
            else {
                var dspX = 9;
                var dspY = 12;
            }

            // TO set Z-index for Marker
            if (mapIcon != null || mapIcon != '') {
                marker = new H.map.Marker(
                point, {
                    visibility: true,
                    icon: new H.map.Icon(mapIcon, { anchor: new H.math.Point(dspX, dspY) }),
                    zIndex: 1 // function (m) { return 28800001; }
                });
            }
        }
        else {
            if (mapIcon != null || mapIcon != '') {
                marker = new H.map.Marker(
                point, {
                    visibility: true,
                    icon: new H.map.Icon(mapIcon, { anchor: new H.math.Point(11, 23) }),
                    zIndex: 1
                });
            }
        }
        marker.addEventListener("pointermove", OpenBubble);
        marker.addEventListener("tap", OpenBubble);
    }
    catch (Error) {
        //alert(Error);
    }
    return marker;
}


function CreateTabs(mainCaption, isMessageVisbile, msgCaption, msgdetails, isDateTimeVisible, datetimeCaption,
time, isAddressVisible, addressCaption, address, isLandmarkVisible, landmarkCaption, landmarkName, isSpeedVisible,
 speedCaption, speed, addLandmarkCaption, canAddLandmark, temp) {
    var tabs = [];
    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }
    var tabMessage = '<div style="text-align:' + tableAlign + ';"><table style="direction:' + VDirection + ';" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>'; //<tr><td colspan="2"><u><b>' + mainCaption
    //+ '</b></u></td></tr>';
    if (isMessageVisbile) {
        tabMessage += '<tr><td width="45px">' + '<b>' + msgCaption + '</b></td><td>' + msgdetails
            + '</td></tr>';
    }
    if (isDateTimeVisible) {
        tabMessage += '<tr><td width="60px" ><b>' + datetimeCaption + '</b></td><td class="DateStyle">' + time + '</td></tr>';
    }
    if (isAddressVisible) {
        tabMessage += '<tr><td><b>' + addressCaption + '</b></td><td>' + address + '</td></tr>';
    }


    if (isSpeedVisible) {
        tabMessage += '<tr><td><b>' + speedCaption + '</b></td><td>' + speed + '</td></tr>';
    }
    if (isLandmarkVisible) {
        tabMessage += '<tr><td width="40px"><b>' + landmarkCaption + '</b></td><td>' + landmarkName + '</td></tr>';
    }
    if (canAddLandmark) {
        tabMessage += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + address + '\');' +
        'document.getElementById(\'txtLocationName\').focus();" style="color:white">' + addLandmarkCaption + '<\/a></td></tr></table><div>';
    }
    tabMessage += '</table></div>';

    tabs = tabMessage;
    return tabs;
}
function BreakTime(marker) {
    //alert();
    marker.openInfoWindowHtml('infoBubbleMessage');
}

function FrameMessage(mainCaption, isMessageVisbile, msgCaption, msgdetails, isDateTimeVisible, datetimeCaption,
time, isAddressVisible, addressCaption, address, isLandmarkVisible, landmarkCaption, landmarkName, isSpeedVisible,
 speedCaption, speed, addLandmarkCaption, canAddLandmark, temp) {
    var bubbleMessage = '<table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'><tr><td colspan="2"><u><b>' + mainCaption
        + '</b></u></td></tr>';
    if (isMessageVisbile) {
        bubbleMessage += '<tr><td width="25px">' + '<b>' + msgCaption + '</b></td><td>' + msgdetails
    + '</td></tr>';
    }
    if (isDateTimeVisible) {
        bubbleMessage += '<tr><td><b>' + datetimeCaption + '</b></td><td>' + time + '</td></tr>';
    }
    if (isAddressVisible) {
        bubbleMessage += '<tr><td><b>' + addressCaption + '</b></td><td>' + address + '</td></tr>';
    }
    if (isLandmarkVisible) {
        bubbleMessage += '<tr><td width="40px"><b>' + landmarkCaption + '</b></td><td>' + landmarkName + '</td></tr>';
    }
    if (isSpeedVisible) {
        bubbleMessage += '<tr><td><b>' + speedCaption + '</b></td><td>' + speed + '</td></tr>';
    }
    if (canAddLandmark) {
        bubbleMessage += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + address + '\');' +
        'document.getElementById(\'txtLocationName\').focus();" style="color:white">' + addLandmarkCaption + '<\/a></td></tr>';
    }
    bubbleMessage += '</table>';
    return bubbleMessage
}

function MapIT_Marker(point, heading, Status, VehName, id, i_No, addr, dist, msgDetails, mainHeading, isVehicleVisbile, vehCaption, isMessageVisbile, msgCaption, isAddressVisbile, addrCaption, isSpeedVisbile, speedCaption,
                        isLandmarkVisible, landmarkCaption, landmarkName, canAddLandmark, isDriverNameVisible, driverNameCaption, driverName, driverPhoto, driverPhno, PhnoCaption, PassNmbCaption, Passnumber) {

    var temp1 = "'" + point + "'";
    var temp = temp1.substring(2, temp1.length - 2);
    temp = "'" + point.lat + "," + point.lng + "'";

    var icon = null;

    if (Status == 'Offline') {
        icon = '../images/Device_Offline.png';
    }
    else if (Status == 'Online') {
        icon = '../images/Device_Online.png';
    }
    else if (Status == 'Information') {
        icon = '../images/Device_Online.png';
    }
    else if (Status == 'Running') {
        icon = '../images/Device_Running.png';
        // icon = '../images/Device_Warning.png';
    }
    else if (Status == 'Shutdown') {
        icon = '../images/Device_Shutdown.png';
    }
    else {
        icon = '../images/Device_Warning.png';
    }
    //else {
    //        var hd = heading.split('-');
    //    if (hd != null) {
    //        if (hd[0] == 'A') {
    //            icon = '../images/fuellow-1_.svg';   //+ hd[1] + '-alert.gif';
    //        }
    //    }
    //}



    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }
    var bubbleMessage = '<div style="text-align:' + tableAlign + ';"><table style="direction:' + VDirection + '" cellspacing=5 class=\'InfoBubble\'>';
    var monitorTabs = [];

    if (isVehicleVisbile) {
        bubbleMessage += '<tr><td><b>' + ((vehCaption == null || vehCaption == '') ? 'Vehicle' : vehCaption) + '</b></td><td>' + VehName + '</td>';
        if (isDriverNameVisible) {
            bubbleMessage += '<td rowspan="3" align="left"><br><img src=" ' + ((driverPhoto == null || driverPhoto == '') ? '../images/default-user.svg' : driverPhoto) + '" width="60px" height="60px" alt="Driver" /></td>';
        }
        bubbleMessage += '</tr>';
    }
    if (isDriverNameVisible) {
        bubbleMessage += '<tr><td><b>' + ((driverNameCaption == null || driverNameCaption == '') ? 'Driver' : driverNameCaption) + '</b></td><td>' + ((driverName == null || driverName == '') ? '-' : driverName) + '</td></tr>';
        bubbleMessage += '<tr><td><b>' + ((PhnoCaption == null || PhnoCaption == '') ? 'Phno' : PhnoCaption) + '</b></td><td>' + driverPhno + '</td></tr>';
        bubbleMessage += '<tr><td><b>' + ((PassNmbCaption == null || PassNmbCaption == '') ? 'Pass Number' : PassNmbCaption) + '</b></td><td>' + Passnumber + '</td></tr>';
    }
    //if (hd != null && hd[0] != undefined && hd[0] == 'A' && isVehicleVisbile == true) {
    //    bubbleMessage += '<tr><td class="DateStyle"><b>' + VDateTime + '</b></td><td>' + hd[1] + '</td></tr>';
    //}
    if (isMessageVisbile) {
        bubbleMessage += '<tr><td><b>' + ((msgCaption == null || msgCaption == '') ? VMessage : msgCaption) + '</b></td><td>' + msgDetails + '</td></tr>';
    }
    if (isAddressVisbile) {
        bubbleMessage += '<tr><td><b>' + ((addrCaption == null || addrCaption == '') ? VAddress : addrCaption) + '</b></td><td>' + addr + '</td></tr>';
    }

    if (isSpeedVisbile) {
        bubbleMessage += '<tr><td><b>' + 'Status' + '</b></td><td>' + Status + '</td></tr>';
    }
    //if (landmarkName != '-') {
    //    bubbleMessage += '<tr><td width="40px"><b>' + landmarkCaption + '</b></td><td>' + landmarkName + '</td></tr>';
    //}
    //else {
    //    bubbleMessage += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + addr + '\');' +
    //    'document.getElementById(\'txtLocationName\').focus();" style="color:white">' + canAddLandmark + '<\/a></td></tr>';
    //}
    bubbleMessage += '</table><div>';

    //Event to open bubble template
    var coordinate;
    if (bubble) infoBubble.close();

    var OpenBubble = function (evt) {
        coordinate = evt.target.getGeometry(); //evt.target.getPosition();
        ui.removeBubble(infoBubble);
        infoBubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        bubble = ui.addBubble(infoBubble);
    }
    //Event to close bubble template
    var CloseBubble = function (evt) {
        ui.removeBubble(infoBubble);
    }

    map.addEventListener("tap", CloseBubble);
    var myListener = {
        "pointermove": [OpenBubble, true, null],
        "tap": [OpenBubble, true, null]
    };
    var marker = new H.map.Marker(
            point, {
                visibility: true,
                icon: new H.map.Icon(icon, { anchor: new H.math.Point(9, 12) }),
            });
    marker.addEventListener("pointermove", OpenBubble);
    marker.addEventListener("tap", OpenBubble);
    return marker;
}
function MapIT_MarkerAdv(point, heading, speed, VehName, id, i_No, addr, dist, msgDetails, mainHeading, isVehicleVisbile, vehCaption, isMessageVisbile, msgCaption, isAddressVisbile, addrCaption, isSpeedVisbile, speedCaption,
                        isLandmarkVisible, landmarkCaption, landmarkName, canAddLandmark, isDriverNameVisible, driverNameCaption, driverName, driverPhoto, driverPhno, PhnoCaption, MapName) {


    var temp1 = "'" + point + "'";
    var temp = temp1.substring(2, temp1.length - 2);
    temp = "'" + point.lat + "," + point.lng + "'";

    var icon = null;

    if (heading == -1) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-1_.svg';
        }
        else if (id == '0') {
            icon = '../images/orange-1_.svg';
        }
        else if (id == '1') {
            icon = '../images/purple-1_.svg';
        }
        else if (id == '3' || id == '8' || id == '9') /*Idling start & end 06-Dec-2011 - Sakthi*/ {
            icon = '../images/pink-1_.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-1_.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-1_.svg';
        }
        else if (id == '10') {
            icon = '../images/mapit-9_.svg'; /*Sleep mode - 20-Dec-2011 Sakthi*/
        }
        else {
            icon = '../images/1_.svg';
        }
    }
    else if (heading >= 0 && heading <= 30) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-3_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-3_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-3_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-3_20.svg';
        }
        else {
            icon = '../images/3_20.svg';
        }
    }
    else if (heading > 30 && heading <= 70) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-7_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-7_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-7_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-7_20.svg';
        }
        else {
            icon = '../images/7_20.svg';
        }
    }
    else if (heading > 70 && heading <= 100) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-1_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-1_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-1_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-1_20.svg';
        }
        else {
            icon = '../images/1_20.svg';
        }
    }
    else if (heading > 100 && heading <= 150) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-5_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-5_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-5_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-5_20.svg';
        }
        else {
            icon = '../images/5_20.svg';
        }
    }
    else if (heading > 150 && heading <= 200) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-4_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-4_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-4_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-4_20.svg';
        }
        else {
            icon = '../images/4_20.svg';
        }
    }
    else if (heading > 200 && heading <= 240) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-8_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-8_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-8_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-8_20.svg';
        }
        else {
            icon = '../images/8_20.svg';
        }
    }
    else if (heading > 240 && heading <= 280) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-2_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-2_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-2_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-2_20.svg';
        }
        else {
            icon = '../images/2_20.svg';
        }
    }
    else if (heading > 280 && heading <= 330) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-6_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-6_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-6_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-6_20.svg';
        }
        else {
            icon = '../images/6_20.svg';
        }
    }
    else if (heading > 330 && heading <= 360) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-3_20.svg';
        }
        else if (id == '3') {
            icon = '../images/pink-3_20.svg';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-3_20.svg';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-3_20.svg';
        }
        else {
            icon = '../images/3_20.svg';
        }
    }
    else {
        var hd = heading.split('-');
        if (hd != null) {
            if (hd[0] == 'A') {
                icon = '../images/fuellow-1_.svg';
            }
        }
    }

    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }
    var marker = new H.map.Marker(
            point, {
                visibility: true,
                icon: new H.map.Icon(icon, { anchor: new H.math.Point(9, 12) })
            });
    clusterMarkersT = new Array();

    clusterMarkersT.push(marker);
    mkr_group = new H.map.Group();
    mkr_group.addObjects(clusterMarkersT);

    switch (MapName) {
        case 0:
            map1.addObject(mkr_group);
            //map1.setViewBounds(mkr_group.getBounds());
            map1.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map1_Vehicle').innerHTML = vehCaption + ": " + VehName;
            document.getElementById('Map1_Address').innerHTML = addrCaption + ": " + addr;
            document.getElementById('Map1_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 1:
            map2.addObject(mkr_group);
            //map2.setViewBounds(mkr_group.getBounds());
            map2.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map2_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map2_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map2_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 2:
            map3.addObject(mkr_group);
            //map3.setViewBounds(mkr_group.getBounds());
            map3.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map3_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map3_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map3_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 3:
            map4.addObject(mkr_group);
            //map4.setViewBounds(mkr_group.getBounds());
            map4.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map4_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map4_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map4_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 4:
            map5.addObject(mkr_group);
            //map5.setViewBounds(mkr_group.getBounds());
            map5.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map5_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map5_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map5_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 5:
            map6.addObject(mkr_group);
            //map6.setViewBounds(mkr_group.getBounds());
            map6.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map6_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map6_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map6_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 6:
            map7.addObject(mkr_group);
            //map7.setViewBounds(mkr_group.getBounds());
            map7.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map7_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map7_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map7_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 7:
            map8.addObject(mkr_group);
            //map8.setViewBounds(mkr_group.getBounds());
            map8.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map8_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map8_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map8_Speed').innerHTML = speedCaption + ": " + speed;
            break;
        case 8:
            map9.addObject(mkr_group);
            //map9.setViewBounds(mkr_group.getBounds());
            map9.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            document.getElementById('Map9_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
            document.getElementById('Map9_Address').innerHTML = "  Address: " + addr;
            document.getElementById('Map9_Speed').innerHTML = speedCaption + ": " + speed;
            break;
    }
    return marker;
}
var ltMapIT = new Array();
var mapPoints = null;
var clusterMarkers = new Array();
var clusterMarkerArray = new Array();
var markerPlotV3 = new Array();
var mkr_group = null;
var mkr_group_st = null;
var group = null;
//To plot the Map for MapIT
function DisplayMapIt(latlng, pageName, mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
    datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible,
    speedCaption, addLandmarkCaption, isVehicleVisbile, vehicleCaption, isPolylineVisible, driverNameCaption, PassNumberCaption, isDriverNameVisible) {
    Array.clear(clusterMarkers);
    //ClearMap();
    try {
        if (mapItMarkers == null) {
            mapItMarkers = new Array();
        }
        else {
            //for (var j = 0; j < mapItMarkers.length; j++) {
            //    map.removeObject(mapItMarkers[j]);
            //}
            mapItMarkers = new Array();
        }

        if (document.getElementById("hdnlang") != null) {
            if (document.getElementById("hdnlang").value != "LanguageArNew") {
                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;
                    }
                }
            }
        }

        if (pageName == 'H') {
            PerformScrollSetting();
            CheckMapItBoxes();
            SetDivPosition();
        }

        var bounds = null; // new GLatLngBounds();
        ltMapIT = latlng.split('~&~');
        if (pageName == 'M' || pageName == 'MF') {
            if (mkr_group != null && mkr_group.getObjects().length > 0) {
                mkr_group.removeObjects(mkr_group.getObjects());
            }
            if (group != null && group.getObjects().length > 0) {
                group.removeObjects(group.getObjects());
            }
        }
        clusterPoint_Monitor.length = 0;
        clusterMarkerArray = new Array();
        markerPlotV3 = new Array();
        for (var i = 0; i <= ltMapIT.length - 1; i++) {
            if (ltMapIT[i] == "") {
            }
            else {
                var lng = new Array();
                lng = ltMapIT[i].split("~#~");
                markerPlotV3.push(parseFloat(lng[0]));
                markerPlotV3.push(parseFloat(lng[1]));
                var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
                lntlngs.push(point);
                clusterPoint_Monitor.push(new H.clustering.DataPoint(parseFloat(lng[0]), parseFloat(lng[1]), 1, { id: lng[5] }));
                if (pageName == 'M' || pageName == 'MF') {
                    var mapMarker = MapIT_Marker(point, lng[3], lng[4], lng[5], lng[6], i, lng[2], lng[2],
                                      lng[6], mainCaption, isVehicleVisbile, vehicleCaption, isMessageVisbile, msgCaption, isAddressVisible, addressCaption, isSpeedVisible, speedCaption,
                                      isLandmarkVisible, landmarkCaption, lng[8], addLandmarkCaption, isDriverNameVisible, driverNameCaption, lng[9], lng[10], lng[11], lng[12], PassNumberCaption, lng[13]);
                    mapMarker.setData(lng[5]);
                    var zoom = new Array();
                    clusterMarkerArray.push(mapMarker);
                    clusterMarkers.push(mapMarker.getGeometry());
                }
                else if (pageName == 'H') {
                    var mapMarker = createMarker(point, lng[5], lng[3], lng[4], 'MapIt', i, lng[2], lng[6],
                        lng[7], lng[8], lng[9], mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
                        datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                         isSpeedVisible, speedCaption, addLandmarkCaption);
                    Array.add(mapItMarkers, mapMarker);
                    map.addObject(mapMarker);
                    clusterMarkers.push(mapMarker.getGeometry());
                }
                else if (pageName == 'HF') {
                    var mapMarker = createMarker(point, lng[5], lng[3], lng[4], '1', i, lng[2], lng[6],
                        lng[7], lng[8], lng[9], mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
                        datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                         isSpeedVisible, speedCaption, addLandmarkCaption);
                    Array.add(mapItMarkers, mapMarker);
                    map.addOverlay(mapMarker);
                    clusterMarkers.push(mapMarker.getGeometry());
                }

            }
        }

        if (pageName == 'H' || pageName == 'HF') {
            mkr_group = new H.map.Group();
            mkr_group.addObjects(((pageName == 'M' || pageName == 'MF') ? clusterMarkerArray : mapItMarkers));
            map.addObject(mkr_group);
            map.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
            // map.setViewBounds(mkr_group.getBounds());
        }

        //Sakthi 15-Dec-2014 For Map Clustering
        if (location.pathname.indexOf("FullscreenMap.aspx") != -1 && location.search.indexOf("?pMy9nEs9WLFPu5OGp76JWA==") != -1) {
            mkr_group = new H.map.Group();
            mkr_group.addObjects(clusterMarkerArray);
            map.addObject(mkr_group);
            map.setViewBounds(mkr_group.getBoundingBox());
            //map.getViewModel().setLookAtData({
            //    bounds: mkr_group.getBoundingBox()
            //});
        }
        else if (pageName == 'M' || pageName == 'MF') {
            //initialiseSVGParser_Monitor();
            mkr_group = new H.map.Group();
            mkr_group.addObjects(clusterMarkerArray);
            //map.addObject(mkr_group);
            //console.log(mkr_group);
            //clusterDataPoints_Monitor(clusterPoint_Monitor, true);     
            OnlineClustering(clusterPoint_Monitor, true);
            // map.addObject(mkr_group);
            //map.setViewBounds(mkr_group.getBounds());
            map.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
        }

        if (pageName == 'M') {
            if (MapView.length > 0) {
                map.setCenter(MapView[0]);
                Array.clear(MapView);
            }
        }
        else if (pageName == 'MF') {
            if (MapViewFullScreen.length > 0) {
                map.setCenter(MapViewFullScreen[0]);
                map.setZoom(MapViewFullScreen[1]);
                Array.clear(MapViewFullScreen);
            }
        }
        HidePopUp();

        //applyFleetLayer_NV(map, platform);
    }
    catch (Error) {
        // alert(Error);
    }
}
function DisplayMapItAdv(latlng, pageName, mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
    datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible,
    speedCaption, addLandmarkCaption, isVehicleVisbile, vehicleCaption, isPolylineVisible, driverNameCaption, isDriverNameVisible) {
    Array.clear(clusterMarkers);
    try {
        if (mapItMarkers == null) {
            mapItMarkers = new Array();
        }
        else {
            for (var j = 0; j < mapItMarkers.length; j++) {
                map1.removeObject(mapItMarkers[j]);
                map2.removeObject(mapItMarkers[j]);
                map3.removeObject(mapItMarkers[j]);
                map4.removeObject(mapItMarkers[j]);
                map5.removeObject(mapItMarkers[j]);
                map6.removeObject(mapItMarkers[j]);
                map7.removeObject(mapItMarkers[j]);
                map8.removeObject(mapItMarkers[j]);
                map9.removeObject(mapItMarkers[j]);
            }
            mapItMarkers = new Array();
        }

        var bounds = null; // new GLatLngBounds();
        ltMapIT = latlng.split('~&~');

        clusterPoint_Monitor.length = 0;
        clusterMarkerArray = new Array();

        for (var i = 0; i <= ltMapIT.length - 1; i++) {

            if (ltMapIT[i] == "") {
                break;
            }
            var lng = new Array();
            lng = ltMapIT[i].split("~#~");
            var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            lntlngs.push(point);
            clusterPoint_Monitor.push(point);
            if (pageName == 'MFAdv') {
                var mapMarker = MapIT_MarkerAdv(point, lng[4], lng[3], lng[5], lng[6], i, lng[2], lng[2],
                                  lng[7], mainCaption, isVehicleVisbile, vehicleCaption, isMessageVisbile, msgCaption, isAddressVisible, addressCaption, isSpeedVisible, speedCaption,
                                  isLandmarkVisible, landmarkCaption, lng[8], addLandmarkCaption, isDriverNameVisible, driverNameCaption, lng[9], lng[10], lng[11], lng[12], i);
                var zoom = new Array();
                clusterMarkerArray.push(mapMarker);
                clusterMarkers.push(mapMarker.getGeometry());
            }

        }
    }
    catch (Error) {
        //alert(Error);
    }
}
//To plot the Map for MapIT
function DisplayUpdPosition(latlng) {
    try {
        lt = latlng.split('&');
        for (var i = 0; i < lt.length; i++) {
            var lng = new Array();
            lng = lt[i].split("~#~");

            var Coord = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            var point = new H.map.Marker(Coord);
            map.setCenter(Coord);
            map.addObject(MapIT_Marker(point, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''));
        }
        map.setCenter(point);
    }
    catch (Error) {
    }
}

function getlngs(query, lndaddress) {
    try {
        var isIE = CheckBrowser();
        var lnd_Latlong = query.split(',');
        document.getElementById('txtlat').value = lnd_Latlong[0];
        document.getElementById('txtlong').value = lnd_Latlong[1];
        document.getElementById('txtstreet').value = lndaddress;
        document.getElementById('txtstreet').disabled = true;
        document.getElementById('pnlLandmark').style.display = "block";
    } catch (Error) {
    }
}

function getlngs_geozone(query, lndaddress) {
    try {
        var isIE = CheckBrowser();
        var lnd_Latlong = query.split(',');
        document.getElementById('txtlat').value = lnd_Latlong[0];
        document.getElementById('txtlong').value = lnd_Latlong[1];
        document.getElementById('txtstreet').value = lndaddress;
        document.getElementById('txtstreet').disabled = true;
        document.getElementById('pnlGeozone').style.display = "block";
    } catch (Error) {
    }
}

/* Functions related to Landmark Page */
var geo;
var reasons = [];
var getAddress = null;
var geocoder; var address;
var bubble = null;
var bubbleTemplate;

var isIE = CheckBrowser();

function CheckBrowser() {
    var isIE = false;
    if (navigator.appName == "Microsoft Internet Explorer") {
        isIE = true;
    }
    else {
        isIE = false;
    }
    return isIE;
}
// ====== 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));

        //Add info bubble Template.
        bubbleTemplate = '<br /><table style="direction:' + VDirection + '" class=\'InfoBubble\'cellpadding=\'5\' cellspacing=\'5\'><tr><td><b>Address</b></td><td>:</td><td>' + search + '</td></tr></table>';

        //Event to open bubble template
        var OpenBubble = function (evt) {
            var coordinate = evt.target.getGeometry();
            ui.removeBubble(bubble);
            bubble = new H.ui.InfoBubble(coordinate, { content: bubbleTemplate });
            ui.addBubble(bubble);
        }
        //Event to close bubble template
        var CloseBubble = function (evt) {
            ui.removeBubble(bubble);
        }
        //Event Listener
        var myListener = {
            "pointermove": [OpenBubble, true, null],
            "pointerout": [CloseBubble, true, null]
        };

        var offsetX = null;
        var offsetY = null;
        if (icon == "../images/flag_2.svg") {
            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) })
        });

        marker.addEventListener('pointermove', OpenBubble);
        marker.addEventListener('pointerout', CloseBubble);

        //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 = "";
        document.getElementById("pnlAddressLocating").style.display = "none";
        drawCircle();
        map.setViewBounds(circle.getBounds());
        LandMarkImage = '';
    } catch (Error) {
    }
}


function Findplace(lat, lng, lndMark, addr, radius, isView, image) {
    try {
        getAddress = null;
        if (image == null || image == '') {
            image = '../images/flag_2.svg';
        }
        else {
            LandMarkImage = image;
        }
        if (LandMarkImage == null || LandMarkImage == '')
            LandMarkImage = image;
        var icon = LandMarkImage;
        //map.objects.clear();
        var point = new H.geo.Point(parseFloat(lat), parseFloat(lng));

        //Event to open bubble template
        var OpenBubble = function (evt) {
            var coordinate = evt.target.getGeometry();
            ui.removeBubble(bubble);
            bubble = new H.ui.InfoBubble(coordinate, { content: bubbleTemplate });
            ui.addBubble(bubble);
        }

        //Event to close bubble template
        var CloseBubble = function (evt) {
            ui.removeBubble(bubble);
        }

        //Event Listener
        var myListener = {
            "pointermove": [OpenBubble, true, null],
            "pointerout": [CloseBubble, true, null]
        };


        var offsetX = null;
        var offsetY = null;
        if (icon == "../images/flag_2.svg") {
            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) })
        });
        marker.addEventListener('pointermove', OpenBubble, false);
        marker.addEventListener('pointerout', CloseBubble, false);
        try {
            lndMark_grp.addObject(marker);
            map.addObject(lndMark_grp);
            //map.addObject(marker);
        }
        catch (ex) {
        }
        if (map.getZoom() > 13) map.setZoom(13); //Zoom Out if too close.

        if (lndMark == '') {
            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;

            //info Bubble Template frame.
            var tableAlign;
            if (VDirection == 'rtl') {
                tableAlign = 'right';
            }
            else {
                tableAlign = 'left';
            }
            bubbleTemplate = '<br /> <div style="text-align:' + tableAlign + ';"><table cellpadding=\'5\' class=\'InfoBubble\'cellspacing=\'5\'><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + search + '</td></tr></table></div>';
        }
        else {

            bubbleTemplate = '<br/><div style="text-align:' + tableAlign + ';"><table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'><tr style="direction:' + VDirection + '"><td><b>' + VLandmark + '</b></td><td>:</td><td>'
                 + lndMark + '</td></tr><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + addr + '</td></tr></table></div>';
        }

        centerPoint = new H.geo.Point(parseFloat(lat), parseFloat(lng));
        document.getElementById("message").innerHTML = "";

        drawCircle_Landmark();
        // map.setViewBounds(circle.getBounds());
        map.getViewModel().setLookAtData({
            bounds: circle.getBoundingBox()
        });
    }
    catch (Error) {
    }
}

//Sakthi for Landmark View
function drawCircle_LandmarkPage(landmarkEntries, isLandmarkEnable) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        if (landMarkCircles != null) {
            landMarkCircles.removeObjects(landMarkCircles.getObjects());
            map.removeObject(landMarkCircles);
        }
    }
    for (var iterator = 0; iterator < lanmarkInformation.length; iterator++) {
        if (lanmarkInformation[iterator] == "") {
            break;
        }
        else {
            var landmarkinfo = lanmarkInformation[iterator].split("~#~");
            console.log(landmarkinfo);
            centerPoint = new H.geo.Point(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new H.map.Marker(centerPoint);
            map.setZoom(6);
            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);
                ui.removeBubble(ui.getBubbles());
                lndMark_grp.addObject(lndMarks);
                map.addObject(lndMark_grp);
                //map.addObject(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) {
                doDrawCircle(); map.getViewModel().setLookAtData({
                    bounds: circle.getBoundingBox()
                });
            }
        }
    }
}
function flagMarker_LandmarkPage(point, lndName, lndAddr, time, id, i_No, content) {
    var icon = null;
    icon = '../images/flag_2.svg';
    //if (document.getElementById('hdnLandmarkImage') != null && document.getElementById('hdnLandmarkImage').value != "") {
    //    lndImage = String(document.getElementById('hdnLandmarkImage').value);
    //}
    icon = document.getElementById('hdnLandmarkImage').value != "" ? String(document.getElementById('hdnLandmarkImage').value) : '../images/flag_2.svg';

    var bubble = null;

    var OpenBubble = function (evt) {
        bubbleMessage = content;
        var coordinate = evt.target.getGeometry();
        ui.removeBubble(bubble);
        bubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        ui.addBubble(bubble);
    }
    var CloseBubble = function (evt) {
        ui.removeBubble(bubble);
    }


    var myListener = {
        "tap": [OpenBubble, true, null],
        "pointermove": [OpenBubble, true, null],
        "pointerout": [CloseBubble, true, null]
    };

    var marker = new H.map.Marker(
    point, {
        icon: new H.map.Icon(icon, { anchor: new H.math.Point(2, 22) })
    });
    marker.addEventListener('tap', OpenBubble, false);
    marker.addEventListener('pointermove', OpenBubble, false);
    marker.addEventListener('pointerout', CloseBubble, false);
    return marker;
}
//End of Landmark View


var search = '';
var chkValue = 0;
var LandMarkImage = '';

var searchManager = platform.getGeocodingService();
var revGeocodeTerm;
var searchTerm;
// ====== Geocoding ======
function showAddress(IsNew, image, addr) {

    try {
        loadForLandMark();
        if (image == null || image == '') {
            if (document.getElementById('hdnLandmarkImage') != null) {

                image = document.getElementById('hdnLandmarkImage').value != "" ? String(document.getElementById('hdnLandmarkImage').value) : '../images/flag_2.svg';
            }
            else {
                image = '../images/flag_2.svg'; //poi_viewer_house.gif';
            }
        }
        LandMarkImage = image;

        getAddress = null;
        chkValue = 1;
        document.getElementById('hdnIsLocateMe').value = 'Y';

        if (document.getElementById('ddlType').value == 'addr') {
            search = FrameAddress();

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

            //======= GeCode Callback function ======
            geo.geocode({ 'searchText': search, language: 'en' },
            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>";

                        }
                        document.getElementById("pnlAddressLocating").style.display = "block";
                        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;
                        }
                        var radius = document.getElementById('txtRadius').value;
                        if (radius.length == 0) {
                            radius = 200;
                        }
                        //Findplace(p.Longitude, p.Longitude, '', document.getElementById('txtRadius').value, 0);
                        Findplace(p.Latitude, p.Longitude, '', radius, 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 {

            //To Get the Address for the LatLng Values given by user
            var latlong = document.getElementById('txtlat').value + ',' + document.getElementById('txtlong').value;

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

            centerPoint = new H.geo.Point(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value));
            map.setCenter(centerPoint);

            //Search Process for Reverse geoCode.
            var bubble = null;
            var bubbleTemplate;
            var OpenBubble = function (evt) {
                var coordinate = evt.target.getGeometry();
                ui.removeBubble(bubble);
                bubble = new H.ui.InfoBubble(coordinate, { content: bubbleTemplate });
                ui.addBubble(bubble);
            }
            var CloseBubble = function (evt) {
                ui.removeBubble(bubble);
            }

            var DragEnd = function (evt) {
                behavior.enable();
                var coord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                document.getElementById('txtlat').value = coord.lat;
                document.getElementById('txtlong').value = coord.lng;
                point = coord;
                marker.setPosition(coord);
                if (!map.getViewBounds().containsPoint(coord)) {
                    map.setCenter(coord, true);
                }
            }

            var myListener = {
                "pointermove": [OpenBubble, true, null],
                "pointerout": [CloseBubble, true, null],
                "dragend": [DragEnd, true, null],
                "dragstart": [CloseBubble, true, null]
            };

            //Search Callback function.
            searchManager.search({
                'searchText': document.getElementById('txtlat').value + ',' + document.getElementById('txtlong').value, language: 'en'
            },
            function (serviceResponse) {
                var locations = serviceResponse.Response.View[0].Result;
                // Add a marker for each location found
                for (i = 0; i < locations.length; i++) {
                    coord =
		    {
		        lat: document.getElementById('txtlat').value, //locations[i].Location.DisplayPosition.Latitude,
		        lng: document.getElementById('txtlong').value  //locations[i].Location.DisplayPosition.Longitude
		    };
                    if (locations.length > 0) {
                        var strAddress = addr != '' ? addr : BubbleAddress(locations[1].Location.Address.Street) + BubbleAddress(locations[1].Location.Address.City) + BubbleAddress(locations[1].Location.Address.State) + locations[1].Location.Address.Country;
                        var tableAlign;
                        if (VDirection == 'rtl') {
                            tableAlign = 'right';
                        }
                        else {
                            tableAlign = 'left';
                        }

                        bubbleTemplate = '<div style="text-align:' + tableAlign + ';"><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>'
                                    + coord.lat + " , " + coord.lng + '</td></tr><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + strAddress + '</td></tr></table></div>';

                        if (lndMark_grp != null && lndMark_grp.getObjects().length > 0) {
                            //alert(lndMark_grp.getObjects().length);
                            lndMark_grp.removeObjects(lndMark_grp.getObjects());
                        }
                        //if (marker) map.removeObject(marker);

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

                        marker = new H.map.Marker(coord, {
                            icon: new H.map.Icon(image, { anchor: new H.math.Point(offsetX, offsetY) })
                        });

                        marker.draggable = true;
                        marker.addEventListener('pointermove', OpenBubble, false);
                        marker.addEventListener('pointerout', CloseBubble, false);
                        marker.addEventListener('dragend', DragEnd, false);
                        marker.addEventListener("drag", DragEnd, false);
                        marker.addEventListener("dragstart", function (evt) { behavior.disable(); }, false);
                        lndMark_grp.addObject(marker);
                        map.addObject(lndMark_grp);

                        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 + '#' + centerPoint.lat + '#' + centerPoint.lng + '#' + LocDesc + '#' + strAddress + '#' + Radius + '#' + /*document.getElementById('txtEmail').value + '#' + document.getElementById('txtSMS').value + '#' + document.getElementById('ddlSeverity').value */(document.getElementById('chkNotify').checked ? 1 : 0) + '#0';  /* + document.getElementById('ddlTimezone').value; */
                        document.getElementById('txtstreet').value = strAddress;

                        //Set the center point value.
                        centerPoint = new H.geo.Point(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value))

                        //Draw circle around the Landmark.
                        drawCircle_Landmark();

                        //map.setViewBounds(circle.getbox());
                        map.getViewModel().setLookAtData({
                            bounds: circle.getBoundingBox()
                        });

                        //zoom out if too close
                        // map.setZoom(15);
                        LandMarkImage = '';
                    }
                }
                //handle response
            }, function () {
                //TrinetraCustomAlerts("Address Cannot be found. Please check the LatLong Values ");
                var strAddress = '';
                var tableAlign;
                if (VDirection == 'rtl') {
                    tableAlign = 'right';
                }
                else {
                    tableAlign = 'left';
                }
                bubbleTemplate = '<div style="text-align:' + tableAlign + ';"><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>'
                                    + coord.lat + " , " + coord.lng + '</td></tr></table></div>';

                //if (marker) map.removeObject(marker);
                if (lndMark_grp != null && lndMark_grp.getObjects().length > 0) {
                    //alert('Welcome ' + lndMark_grp.getObjects().length);
                    lndMark_grp.removeObjects(lndMark_grp.getObjects());
                }

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

                marker = new H.map.Marker(coord, {
                    icon: new H.map.Icon(image, { anchor: new H.math.Point(offsetX, offsetY) })
                });

                marker.draggable = true;
                marker.addEventListener('pointermove', OpenBubble, false);
                marker.addEventListener('pointerout', CloseBubble, false);
                marker.addEventListener('dragend', DragEnd, false);
                marker.addEventListener("drag", DragEnd, false);
                marker.addEventListener("dragstart", function (evt) { behavior.disable(); }, false);
                lndMark_grp.addObject(marker);
                map.addObject(lndMark_grp);

                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 + '#' + centerPoint.lat + '#' + centerPoint.lng + '#' + LocDesc + '#' + strAddress + '#' + Radius + '#' + /*document.getElementById('txtEmail').value + '#' + document.getElementById('txtSMS').value + '#' + document.getElementById('ddlSeverity').value */(document.getElementById('chkNotify').checked ? 1 : 0) + '#0';  /* + document.getElementById('ddlTimezone').value; */
                document.getElementById('txtstreet').value = strAddress;

                //Set the center point value.
                centerPoint = new H.geo.Point(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value))

                //Draw circle around the Landmark.
                drawCircle();

                //map.setViewBounds(circle.getBounds());
                map.getViewModel().setLookAtData({
                    bounds: circle.getBoundingBox()
                });

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

            landmarkLatitude = document.getElementById('txtlat').value;
            landmarkLongitude = document.getElementById('txtlong').value;
            var coord = new H.geo.Point(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value))

            //Set attributes for the search term.
            revGeocodeTerm = {//reverse geocode
                spatialFilter: {
                    center: coord,
                    radius: 8000
                },
                representationOptions: {
                    language: [document.getElementById("hdnMapLng").value], //["en-US"],
                    maxResults: 1,
                    pageInformation: 2,
                    searchResponseAttributes: ["la", "dm", "mq", "mt"],
                    locationAttributes: ["ar", "mr", "mv", "ad", "al"],
                    addressAttributes: ["ctr", "sta", "cty", "cit", "dis", "str", "hnr", "pst", "sui", "flr", "add", "alt"]
                },
                reverseGeocodeSettings: {
                    mode: "retrieveAddresses"
                },
                metaInfo: {
                    requestId: "qwertzuiop",
                    verboseMode: 2
                }
            };
            searchManager.clear();
            searchManager.reverseGeocode(revGeocodeTerm);
            showControls(1);
        }
    }
    catch (Error) {

    }
}
function searchaddress(Name) {
    loadForLandMark();
    try {
        search = Name;
        geo = platform.getGeocodingService();
        geo.geocode({ 'searchText': search, language: 'en' },
            function (serviceResponse) {
                var locations = serviceResponse.Response.View[0].Result;
                if (locations != null && locations.length > 0) {
                    if (locations.length > 0) {
                        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;
                            //alert(p.Latitude)
                            document.getElementById("message").innerHTML += "<br>" + (i + 1) + ": <a href='#' onclick='Findlocations(" + p.Latitude + "," + p.Longitude + "); return false;'>" + FormAddressList(locations[i].Location) + "<\/a>";

                        }
                        document.getElementById("pnlAddressLocating").style.display = "block";
                        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;
                        }
                        Findlocations(p.Latitude, p.Longitude, '', '', 200, 0);
                        LandMarkImage = '';
                    }
                }
                else {
                    if (document.getElementById("hdnlang") != null) {
                        if (document.getElementById("hdnlang").value == "LanguageArNew") {

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

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

                        else {
                            alert('नहीं मिल सका "' + search + '" ');
                        }
                    }
                    loadForLandMark();
                }
            }, function () {
                if (document.getElementById("hdnlang") != null) {
                    if (document.getElementById("hdnlang").value == "LanguageArNew") {

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

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

                    else {
                        alert('नहीं मिल सका "' + search + '" ');
                    }
                }
                loadForLandMark();
            }
            );
        return Countries;
    } catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }

}



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

// 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(","));
}


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

function AddToDB() {
    try {

        var isError = false;
        var alertMessage = '';
        var txtLocationName = document.getElementById('txtLocationName');
        var controlToBeFocussed;
        var txtRadius = document.getElementById('txtRadius');
        var hdnLandmark = document.getElementById('hdnLand');
        if (txtLocationName.value == "Location Name" || txtLocationName.value == 'اسم الموقع(الإنجليزية)' || RemoveSpaces(txtLocationName).length == 0) {
            alertMessage = locationNameAlert;
            isError = true;
            controlToBeFocussed = txtLocationName;
            txtLocationName.style.backgroundColor = 'lightyellow';
        }
        else {
            txtLocationName.style.backgroundColor = 'white';
        }
        if (txtRadius.value == "Radius" || RemoveSpaces(txtRadius).length == 0 || isNaN(txtRadius.value)) {
            alertMessage += (isError ? '</br>' : '') + radiusAlert;
            txtRadius.style.backgroundColor = 'lightyellow';
            controlToBeFocussed = isError ? controlToBeFocussed : txtRadius;
            isError = true;
        }
        else {
            if (eval(txtRadius.value) == 0) {
                alertMessage += (isError ? '</br>' : '') + radiusAlert;
                txtRadius.style.backgroundColor = 'lightyellow';
                controlToBeFocussed = isError ? controlToBeFocussed : txtRadius;
                isError = true;
            }
            else {
                txtRadius.style.backgroundColor = 'white';
            }
        }
        if (!isError) {
            if (chkValue == 0) {
                alertMessage += (isError ? '</br>' : '') + locateMeError;
                controlToBeFocussed = isError ? controlToBeFocussed : document.getElementById('btnAddress');
                isError = true;
            }
        }
        if (!isError) {
            if (getAddress != null) {
                document.getElementById('hdnLand').value = getAddress;
            }
            else {
                alertMessage += (isError ? '</br>' : '') + locationAlert;
                isError = true;
            }
        }
    }
    catch (Error) {
        isError = true;
    }
    if (isError) { TrinetraCustomAlerts(alertMessage); if (controlToBeFocussed != null) { controlToBeFocussed.focus(); } }
    return !isError;
}

function ReceiveServerData(arg, context) {
}

/* End of Function Context Menu */
function showControls(typeid) {
    try {
        if (typeid == '0') {

            document.getElementById('spLatlng').style.display = 'none';
            document.getElementById('spAddr').style.display = (CheckBrowser() ? "block" : "table-row");
            document.getElementById('txtlat').value = '';
            document.getElementById('txtlong').value = '';
        }
        else {
            document.getElementById('ddlType').value = 'ltlng';
            document.getElementById('spLatlng').style.display = (CheckBrowser() ? "block" : "table-row");
            document.getElementById('spAddr').style.display = 'none';
        }
    }
    catch (Error) {
    }
}

var landmarkLatitude = '';
var landmarkLongitude = '';
var landmarkMarkers = new Array();
var landMarkCircles = new H.map.Group();
function drawCircleForLandmark(landmarkEntries, isLandmarkEnable) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        if (landMarkCircles != null) {
            landMarkCircles.removeObjects(landMarkCircles.getObjects());
            //map.removeObject(landMarkCircles);

        }
    }

    if (group != null) {
        group.removeObjects(group.getObjects());
    }
    clusterPoint.length = 0;
    landmarkMarkers = new Array();
    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]));
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new H.map.Marker(centerPoint, {});
            if (isLandmarkEnable) {
                clusterPoint.push(new H.clustering.DataPoint(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]), 1,
                    {
                        id: landmarkinfo[3]
                    }));
                var lndMarks = flagMarker(centerPoint, landmarkinfo[3], landmarkinfo[4], landmarkinfo[0], 'green', 1, landmarkinfo[5])
                landmarkMarkers.push(lndMarks);

                //map.addObject(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) { doDrawCircle(); }
        }
    }
    setTimeout(clickCanvas, 3000);
}
function flagMarker(point, lndName, lndAddr, time, id, i_No, LandMarkIcon) {
    var icon = null;
    if (LandMarkIcon != null && LandMarkIcon != '') {
        icon = LandMarkIcon.replace("~", "..");
    }
    else {
        icon = '../images/flag_2.svg';
    }

    var bubble;
    var OpenBubble = function (evt) {
        ui.removeBubble(infoBubble);
        bubbleMessage = '<br><table style="direction:' + VDirection + '" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>' + VLandmark + '</b></td><td><b>:</b></td></td><td>' + lndName + '</td></tr><td>'
             + '<b>' + VAddress + '</b></td><td><b>:</b></td><td>' + lndAddr + '</td></tr></table>';
        var coordinate = evt.target.getGeometry();
        infoBubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        ui.addBubble(infoBubble);
    }
    var CloseBubble = function (evt) {
        ui.removeBubble(infoBubble);
    }

    map.addEventListener("tap", CloseBubble);
    var myListener = {
        "click": [OpenBubble, true, null],
        "mouseover": [OpenBubble, true, null],
        "mouseout": [CloseBubble, true, null]
    };

    var marker = new H.map.Marker(point, { icon: new H.map.Icon(icon, { anchor: new H.math.Point(2, 22) }) });
    marker.addEventListener('tap', OpenBubble, false);
    marker.addEventListener('pointermove', OpenBubble, false);
    marker.addEventListener('pointerout', CloseBubble, false);
    return marker;
}

var circle;
var centerMarker;
var circleUnits;
var circleRadius;
var centerPoint;

//-------------- Function Using for Circle Resize -------------//
function drawCircle_Landmark() {
    try {
        var oRadius = document.getElementById('txtRadius');
        oRadius.value = ((oRadius.value != '' && oRadius.value != "Radius" && oRadius.value != 'الإشعاع') && oRadius.value != "0") ? oRadius.value : 500;
        if (oRadius.value.match(/[^\d.]/)) {
            TrinetraCustomAlerts(VEnterRadious);
            return;
        }
        if (oRadius.value > 9999) {
        }
        circleRadius = oRadius.value;
        doDrawCircle_Landmark();
    }
    catch (Error) {
    }
}

function doDrawCircle_Landmark() {
    try {
        if (circle != null && landMarkCircles != null) {
            landMarkCircles.removeObjects(landMarkCircles.getObjects());
            //map.removeObject(landMarkCircles);
        }
        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: "#5270B2", lineWidth: 4, fillColor: "rgba(198,155,204,0.5)" } // "#C69ACC" }
                            }
                        );
            }
            else {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: canClearCircle ? '#000000' : "rgba(198,155,204,0.5)" } //'#C69ACC' }
                            }
                        );
            }
            circle.draggable = true;
            landMarkCircles.addObject(circle);
            map.addObject(landMarkCircles);

            //----------------Circle Resize  code --------------------------------//
            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);
    }
}
//--------------------------------------------------End of Landmark Circle Resize -------------------------------------------//


function drawCircle() {
    try {
        var oRadius = document.getElementById('txtRadius');
        oRadius.value = ((oRadius.value != '' && oRadius.value != "Radius" && oRadius.value != 'الإشعاع') && oRadius.value != "0") ? oRadius.value : 500;
        if (oRadius.value.match(/[^\d.]/)) {
            TrinetraCustomAlerts(VEnterRadious);
            return;
        }
        if (oRadius.value > 9999) {
        }
        circleRadius = oRadius.value;
        doDrawCircle();
    }
    catch (Error) {
    }
}

function doDrawCircle() {
    try {
        if (circle != null && landMarkCircles != null && canClearCircle) {
            landMarkCircles.removeObjects(landMarkCircles.getObjects());
            //map.removeObject(landMarkCircles);
        }
        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: "#5270B2", lineWidth: 4, fillColor: "rgba(198,155,204,0.5)" } // "#C69ACC" }
                            }
                        );
            }
            else {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: canClearCircle ? '#000000' : "rgba(198,155,204,0.5)" } //'#C69ACC' }
                            }
                        );
            }
            circle.draggable = true;
            landMarkCircles.addObject(circle);
            map.addObject(landMarkCircles);
        }
    }
    catch (Error) {
        //alert(Error);
    }
}

function plotLandMark(latlong) {
    try {
        //To Get the Address for the LatLng Values given by user
        var latlong = latlong;
        var ltlng = latlong.split(',');

        //Set attributes for the search term.
        revGeocodeTerm = {//reverse geocode
            spatialFilter: {
                center: coord,
                radius: 8000
            },
            representationOptions: {
                language: [document.getElementById("hdnMapLng").value], //["en-US"],
                maxResults: 5,
                pageInformation: 2,
                searchResponseAttributes: ["la", "dm", "mq", "mt"],
                locationAttributes: ["ar", "mr", "mv", "ad", "al"],
                addressAttributes: ["ctr", "sta", "cty", "cit", "dis", "str", "hnr", "pst", "sui", "flr", "add", "alt"]
            },
            reverseGeocodeSettings: {
                mode: "retrieveAddresses"
            },
            metaInfo: {
                requestId: "qwertzuiop",
                verboseMode: 2
            }
        };
        searchManager.clear();
        //make a rev geocode request
        searchManager.reverseGeocode(revGeocodeTerm);
    }
    catch (Error) {
    }
}

/* End of Landmark page */

function DoCancel() {
    try {
        $find("mpAddEditLandmarkCategory").hide();
    }
    catch (Error) {
    }
}

/*********** Functions for Map It************************/
function SetMapItValue(mapItValue, isChecked, checkBoxName) {
    var mapValue = document.getElementById('hdnMapItValue').value;
    var mapItValueList = mapValue.split('~&~');
    if (isChecked) {
        if (!Array.contains(mapItValueList, mapItValue.toString().replace('~&~', ''))) {
            mapValue += mapItValue.replace("'", "\\'");
        }
    }
    else {
        if (Array.contains(mapItValueList, mapItValue.toString().replace('~&~', '').replace("'", "\\'"))) {
            Array.remove(mapItValueList, mapItValue.toString().replace('~&~', '').replace("'", "\\'"));
            mapValue = mapItValueList.join('~&~');
        }
    }
    document.getElementById('hdnMapItValue').value = mapValue;
}
function MapIt(errorMessage, pageName) {
    if (document.getElementById('hdnMapItValue').value.length > 0 && !document.getElementById('hdnMapItValue').value.includes("N/A")) {
        ShowPopUp();

        eval("DisplayMapIt('" + document.getElementById('hdnMapItValue').value + "\',\'" + pageName + "\',"
        + document.getElementById('hdnInfoBubbleProcessing').value + ")");
    }
    else if (document.getElementById('hdnMapItValue').value.includes("N/A")) {
        TrinetraCustomAlerts("Unable to plot invalid location(s).");
    }
    else {
        TrinetraCustomAlerts(errorMessage);
    }
    return false;
}

function SelectGridRow(keyValue, isChecked) {
    gvData.SelectRowsByKey(keyValue, isChecked);
}

//Jquery Collapse Panel form Legend
function CollapseLegend(MemberName, tab) {
    //$("#" + MemberName).slideToggle("slow");

};
function GetMapView() {
    Array.clear(MapView);
    MapView.push(new H.geo.Point(map.getCenter().lat, map.getCenter().lng));
    MapView.push(map.getZoom());
}

function GetMapViewFullScreen() {
    Array.clear(MapViewFullScreen);
    MapViewFullScreen.push(new H.geo.Point(map.getCenter().lat, map.getCenter().lng));
    MapViewFullScreen.push(map.getZoom());
}

function MapViewEvent() {
    GetMapView();
}

function SetMapView() {
    if (MapView.length > 0) {
        var coord = new H.geo.Point(parseFloat(String(MapView[0].lat)), parseFloat(String(MapView[0].lng)));
        var marker = new H.map.Marker(coord)
        map.setCenter(coord);
        map.setZoom(MapView[1]);
    }
}

//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];
}

//To clear the all the overlays in the maps container.
function ClearOverlays() {
    if (bubble) ui.removeBubble(infoBubble);
    if (bubbles) ui.removeBubble(infoBubble);

    if (mkr_group != null && mkr_group.getObjects().length > 0) {
        mkr_group.removeObjects(mkr_group.getObjects());
    }
    if (group != null && group.getObjects().length > 0) {
        group.removeObjects(group.getObjects());
    }
    if (objectLayer_monitor != null) {
        map.removeLayer(objectLayer_monitor);
    }
    //if (clusterMarkerArray.length > 0) {
    //    for (var k = 0; k < clusterMarkerArray.length; k++) {
    //        map.removeObjects(clusterMarkerArray);
    //    }
    //}
}
//To clear the all the overlays in the maps container.
function ClearMap() {
    if (bubble) ui.removeBubble(infoBubble);
    if (bubbles) ui.removeBubble(infoBubble);
    if (map) map.removeObjects(map.getObjects());
}

var IsMSIE9 = null;
//Set Center to dubai 
function SetCenter() {
    if (map) {
        map.setCenter(centerCoordinate);
        map.setZoom(4);
    }
}

//Set the Custome center based on fleet
function SetDynamicCenter(Center) {
    if (Center != '') {
        var Coor = Center.split('$');
        if (Coor[0] != '0.000000,0.000000') {
            var latlng = Coor[0].split(',');
            centerCoordinate = new H.geo.Point(parseFloat(latlng[0]), parseFloat(latlng[1]));
            DefaultZoomLevel = Coor[1];
        }
        else {
            centerCoordinate = new H.geo.Point(20.00, 78.00);
            DefaultZoomLevel = Coor[1];
        }
        if (map) {
            map.setCenter(centerCoordinate);
            map.setZoom(DefaultZoomLevel);
        }
    }
}

//Set the info Bubble Style
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 CheckBrowserForChrome() {
    var isIE = true;

    if (navigator.appName == "Microsoft Internet Explorer" || navigator.appVersion.length <= 13) {
        isIE = false;
    }
    else {
        isIE = true;
    }
    return isIE;
}


/********************Route in History***************/
//Draw route form the particular vehicle in History.
function DrawRoute(Id) {
    ShowPopUp();
    if (Id == true) {
        //Id.checked = true;
        document.getElementById("hdnRoute").value = 1;
        __doPostBack('btn', '');
    }
    else {
        //Id.checked = false;
        document.getElementById("hdnRoute").value = 0;
        clearRoute();
    }
}

/********************Colapse panel JQuery foe Legends***************/

var PANEL_NORMAL_CLASS = "panel";
var PANEL_COLLAPSED_CLASS = "panelcollapsed";
var PANEL_HEADING_TAG = "h2";
var PANEL_CONTENT_CLASS = "panelcontent";
var PANEL_COOKIE_NAME = "panels";
var PANEL_ANIMATION_DELAY = 15; /*ms*/
var PANEL_ANIMATION_STEPS = 10;

function setUpPanels() {
    loadSettings();

    // get all headings
    var headingTags = document.getElementsByTagName(PANEL_HEADING_TAG);

    // go through all tags
    for (var i = 0; i < headingTags.length; i++) {
        var el = headingTags[i];

        // make sure it's the heading inside a panel
        if (el.parentNode.className != PANEL_NORMAL_CLASS && el.parentNode.className != PANEL_COLLAPSED_CLASS)
            continue;

        // get the text value of the tag
        var name = el.firstChild.nodeValue;

        // look for the name in loaded settings, apply the normal/collapsed class
        if (panelsStatus[name] == "false")
            el.parentNode.className = PANEL_COLLAPSED_CLASS;
        else
            if (panelsStatus[name] == "true")
                el.parentNode.className = PANEL_NORMAL_CLASS;
            else {
                // if no saved setting, see the initial setting
                panelsStatus[name] = (el.parentNode.className == PANEL_NORMAL_CLASS) ? "true" : "false";
            }

        // add the click behavor to headings
        el.onclick = function () {
            var target = this.parentNode;
            var name = this.firstChild.nodeValue;
            var collapsed = (target.className == PANEL_COLLAPSED_CLASS);
            saveSettings(name, collapsed ? "true" : "false");
            animateTogglePanel(target, collapsed);
        };
    }
}

function animateTogglePanel(panel, expanding) {
    // find the .panelcontent div
    var elements = panel.getElementsByTagName("div");
    var panelContent = null;
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].className == PANEL_CONTENT_CLASS) {
            panelContent = elements[i];
            break;
        }
    }

    // make sure the content is visible before getting its height
    panelContent.style.display = "block";

    // get the height of the content
    var contentHeight = panelContent.offsetHeight;

    // if panel is collapsed and expanding, we must start with 0 height
    if (expanding)
        panelContent.style.height = "0px";

    var stepHeight = contentHeight / PANEL_ANIMATION_STEPS;
    var direction = (!expanding ? -1 : 1);

    setTimeout(function () { animateStep(panelContent, 1, stepHeight, direction) }, PANEL_ANIMATION_DELAY);
}


function animateStep(panelContent, iteration, stepHeight, direction) {
    if (iteration < PANEL_ANIMATION_STEPS) {
        panelContent.style.height = Math.round(((direction > 0) ? iteration : 10 - iteration) * stepHeight) + "px";
        iteration++;
        setTimeout(function () { animateStep(panelContent, iteration, stepHeight, direction) }, PANEL_ANIMATION_DELAY);
    }
    else {
        // set class for the panel
        panelContent.parentNode.className = (direction < 0) ? PANEL_COLLAPSED_CLASS : PANEL_NORMAL_CLASS;
        // clear inline styles
        panelContent.style.display = panelContent.style.height = "";
    }
}

function loadSettings() {
    // prepare the object that will keep the panel statuses
    panelsStatus = {};

    // find the cookie name
    var start = document.cookie.indexOf(PANEL_COOKIE_NAME + "=");
    if (start == -1) return;

    // starting point of the value
    start += PANEL_COOKIE_NAME.length + 1;

    // find end point of the value
    var end = document.cookie.indexOf(";", start);
    if (end == -1) end = document.cookie.length;

    // get the value, split into key:value pairs
    var cookieValue = unescape(document.cookie.substring(start, end));
    var panelsData = cookieValue.split("|");

    // split each key:value pair and put in object
    for (var i = 0; i < panelsData.length; i++) {
        var pair = panelsData[i].split(":");
        panelsStatus[pair[0]] = pair[1];
    }
}

function expandAll() {
    for (var key in panelsStatus)
        saveSettings(key, "true");

    setUpPanels();
}

function collapseAll() {
    for (var key in panelsStatus)
        saveSettings(key, "false");

    setUpPanels();
}

function saveSettings(key, value) {
    // put the new value in the object
    panelsStatus[key] = value;

    // create an array that will keep the key:value pairs
    var panelsData = [];
    for (var key in panelsStatus)
        panelsData.push(key + ":" + panelsStatus[key]);

    // set the cookie expiration date 1 year from now
    var today = new Date();
    var expirationDate = new Date(today.getTime() + 365 * 1000 * 60 * 60 * 24);
    // write the cookie
    document.cookie = PANEL_COOKIE_NAME + "=" + escape(panelsData.join("|")) + ";expires=" + expirationDate.toGMTString();
}

// Register setUpPanels to be executed on load
if (window.addEventListener) {
    // the "proper" way
    window.addEventListener("load", setUpPanels, false);
}
else
    if (window.attachEvent) {
        // the IE way
        window.attachEvent("onload", setUpPanels);
    }
//To set the Collapsable legends alive.
if (location.pathname.indexOf("Map.aspx") == -1) {
    Sys.Application.add_load(setUpPanels);
}
/********************End of Colapse panel JQuery foe Legends***************/


/***********************************Maps in Arabic******************************************/
function changeTileProvider(MapType, PasLang) {

    if (PasLang == "Ar") {
        Plang = 'ARA';
    }
    else if (PasLang == "hin") { Plang = 'hin'; }
    else {
        Plang = 'En';
    }
    defaultLayers = platform.createDefaultLayers(256, 72, Plang);

    switch (MapType) {
        case 'N':
            mapType = 'N';
            map.setBaseLayer(defaultLayers.raster.normal.map);
            break;
        case 'S':
            mapType = 'S';
            map.setBaseLayer(defaultLayers.raster.satellite.map);
            break;
        case 'T':
            mapType = 'T';
            map.setBaseLayer(defaultLayers.raster.terrain.map);
            break;
        default:
            mapType = 'N';
            map.setBaseLayer(defaultLayers.raster.normal.map);
            break;
    }
}
/***********************************End of Maps in Arabic******************************************/

function Deselect() {
    if (document.getElementById('chkLandmark')) {
        document.getElementById('chkLandmark').checked = false;
    }
}

/***********************************History Play Back******************************************/
var route;
var coordPlayBack = null;
var iconPlayback = null;
var fastSpeed = 150;// 1000;
var mediumSpeed = 500; // 1500;
var slowSpeed = 2000;

function playBack(arr, playPolyStrip) {

    var doc = document,
    // Alias function for getElementById
    $ = function (id) {
        return doc.getElementById(id);
    },
    btn = $("btn"),
    animate = $("animate"),
    resetPlay = $("resetPlay"),
    stopPlayBack = $("stopPlayBack"),
    fast = $("fast"),
    medium = $("medium"),
    slow = $("slow");

    animate.title = Caption_Play;
    resetPlay.title = Caption_Reset;
    stopPlayBack.title = Caption_Stop;
    fast.title = Caption_Fast;
    medium.title = Caption_Medium;
    slow.title = Caption_Slow;

    // We create a polygon route, marker and a circle
    route = new H.map.Polyline(
    playPolyStrip, {
        color: "#00F6", width: 5
    });

    Start = new H.map.Marker(arr[0], {
        icon: new H.map.Icon("../images/Start_point.svg", { anchor: new H.math.Point(4, 28) }),
        $id: "marker",
        zIndex: function (m) {
            return 28800001;
        }
    });

    End = new H.map.Marker(arr[arr.length - 1], {
        icon: new H.map.Icon("../images/End_point.svg", { anchor: new H.math.Point(4, 28) }),
        $id: "marker",
        zIndex: function (m) {
            return 28800001;
        }
    });
    coordPlayBack = arr[0];
    iconPlayback = PlayBack[coordPlayBack.lat + "," + coordPlayBack.lng].icon;
    //if (iconPlayback != null) {
    //    busMarker = new H.map.Marker(arr[0], {
    //        icon: new H.map.Icon('../images/fuelnormal-1_.svg', { anchor: new H.math.Point(9, 12) }),
    //        $id: "marker",
    //        zIndex: function (m) {
    //            return 28800001;
    //        }
    //    });
    //}
    //else {
    //    busMarker = new H.map.Marker(arr[0], {
    //        icon: //new H.map.Icon(svgMarkup),
    //            new H.map.Icon('../images/fuelnormal-1_.svg', { anchor: new H.math.Point(9, 12) }),
    //        $id: "marker",
    //        zIndex: function (m) {
    //            return 28800001;
    //        }
    //    });
    //}

    busMarker = new H.map.Marker(arr[0], {
        icon: new H.map.Icon(iconPlayback, { anchor: new H.math.Point(9, 12) }),
        $id: "marker",
        zIndex: function (m) {
            return 28800001;
        }
    });

    // We add above created three object to the map and we change the zoomLevel
    // in such a way that the route is fully visible with the browser's window.
    mkr_group_st = new H.map.Group();
    mkr_group_st.addObjects([Start, End, busMarker]);
    map.addObject(mkr_group_st);
    //map.setViewBounds(route.getBounds());
    map.getViewModel().setLookAtData({
        bounds: route.getBoundingBox()
    });

    var time = 1500;
    var count = 0;
    var startCount = 0;
    var CanZoom = false;

    Walker = function (marker, path) {
        this.path = path;
        this.marker = marker;
        this.idx = 0;
        this.dir = -1;
        this.isWalking = false;
        var that = this;
        this.walk = function () {
            // Get the next coordinate from the route and set the marker to this coordinate
            var coord = path.extractPoint(that.idx);
            marker.setGeometry(coord);
            var Info = PlayBack[coord.lat + "," + coord.lng];       //findNearestMarker(coord); 
            if (Info == null || Info == 'f') {
                //PlayBack[coord.lat + "," + coord.lng] = { Info: '', Alarm: false, icon: '../images/fuelnormal-1_.svg' };
                Info = PlayBack[coord.lat + "," + coord.lng];
            }
            //else { Info.icon = '../images/fuelnormal-1_.svg'; }
            if (document.getElementById('chkInfoBubble') != null && document.getElementById('chkInfoBubble').checked) {
                if (!CheckBrowserForBubble() || IsMSIE9 == true) {
                    ui.removeBubble(infoBubble);
                    infoBubble = new H.ui.InfoBubble(coord, { content: Info.Info });
                    bubbles = ui.addBubble(infoBubble);
                }
                else {
                    setTimeout(function () {
                        ui.removeBubble(infoBubble);
                        infoBubble = new H.ui.InfoBubble(coord, { content: Info.Info });
                        bubbles = ui.addBubble(infoBubble);
                    }, 500);
                }
            }

            if (Info.Alarm) {
                //if (marker.getIcon() != null) {
                //    marker.getIcon().setAnchor(new H.math.Point(15, 31));
                //}
                //var markerAlarm = plotPlaynBackAlarm(Info.Info, coord);
                //map.addObject(markerAlarm);
                //playAlarm.push(markerAlarm);
            }
            else {

                if (Info.icon == '../images/NW.svg' || Info.icon == '../images/NE.svg' || Info.icon == '../images/SW.svg' || Info.icon == '../images/SE.svg') {
                    marker.setIcon(new H.map.Icon(Info.icon, { anchor: new H.math.Point(22, 22) }));
                }
                else if (Info.icon == '../images/W.svg' || Info.icon == '../images/E.svg') {
                    marker.setIcon(new H.map.Icon(Info.icon, { anchor: new H.math.Point(9, 12) }));
                }
                else {
                    marker.setIcon(new H.map.Icon(Info.icon, { anchor: new H.math.Point(12, 12) }));
                }
            }

            /*******************Zoom the map according to the vehicle movement*******************************/
            if (that.idx % 10 == 0) {
                count += 1;
                CanZoom = true;
                if (that.idx != 0) {
                    startCount += 10;
                }
                else {
                    walker.clearAlarms();
                }
            }
            else {
                CanZoom = false;
            }

            if (that.idx != path.getPointCount() - 1) {
                if (CanZoom) {
                    var RouteMovement = PlayBackZoom.slice(startCount, 10 * count)
                    var routeStrip = new H.geo.LineString();
                    for (var r = 0; r < RouteMovement.length; r++) {
                        routeStrip.pushPoint(RouteMovement[r]);
                    }
                    //map.setViewBounds((new H.map.Polyline(routeStrip, {})).getBounds());
                    map.getViewModel().setLookAtData({
                        bounds: new H.map.Polyline(routeStrip, {}).getBoundingBox()
                    });
                    if (map.getZoom() > 17) map.setZoom(map.getZoom() - 1);
                }
            }
            else {
                //map.setViewBounds(route.getBounds());
                map.getViewModel().setLookAtData({
                    bounds: route.getBoundingBox()
                });
            }
            /*********************************************************************************************/

            /****Play Event****/
            // If we get to the end of the route reverse direction
            if (!that.idx || that.idx === path.getPointCount() - 1) {
                that.dir *= -1;
                if (that.idx === path.getPointCount() - 1) {
                    walker.pause();
                    that.dir = -1;
                    that.idx = 0;
                    animate.title = Caption_Play;
                    animate.src = "../images/play.png";
                    ui.removeBubble(infoBubble);
                    walker.ClearSettings();
                    return;
                }
            }
            that.idx += that.dir;

            // Recursively call this function with time that depends on the distance to the next point
            // which makes the marker move in similar random fashion
            //that.timeout = setTimeout(that.walk, Math.round(coord.distance(path.get(that.idx)) * 2.5));
            that.timeout = setTimeout(that.walk, time == null ? mediumSpeed : time);
            that.isWalking = true;
        }

        /****Pause Event****/
        this.pause = function () {
            clearTimeout(that.timeout);
            this.isWalking = false;
        }
        /****Reset Event****/
        this.reset = function () {
            clearTimeout(that.timeout);
            that.idx = 0;
            that.dir = -1;
            this.isWalking = true;
            walker.ClearSettings();
            walker.clearAlarms();
            walker.walk();
        }
        /****stop Event****/
        this.stopplay = function () {
            clearTimeout(that.timeout);
            that.idx = 0;
            that.dir = -1;
            var coord = path.extractPoint(that.idx);
            marker.setPosition(coord);
            marker.setIcon(new H.map.Icon(iconPlayback, {}));
            //marker.setIcon(new H.map.Icon('../images/fuelnormal-1_.svg', {}));
            this.isWalking = false;
            ui.removeBubble(infoBubble);
            walker.ClearSettings();
            walker.clearAlarms();
            //map.setViewBounds(route.getBounds());
            map.getViewModel().setLookAtData({
                bounds: route.getBoundingBox()
            });
        }
        /****Speed Event****/
        this.Speed = function (playSpeed) {
            time = playSpeed;
        }

        this.ClearSettings = function () {
            count = 0;
            startCount = 0;
            CanZoom = false;
            fast.src = "../images/fast.png";
            medium.src = "../images/medium.png";
            slow.src = "../images/slow.png";
            walker.Speed(slowSpeed);
        }

        this.clearAlarms = function () {
            if (playAlarm.length > 0) {
                for (var k = 0; k < playAlarm.length; k++) {
                    map.removeObject(playAlarm[k]);
                }
            }
            Array.clear(playAlarm);
        }
    };

    // Constructs Walk object which makes given marker walk along provided path
    walker = new Walker(busMarker, playPolyStrip);
    if (animate != null && resetPlay != null && stopPlayBack != null) {
        animate.onclick = function () {
            if (walker.isWalking) {
                animate.title = Caption_Play;
                animate.src = "../images/play.png";
                walker.pause();
            } else {
                animate.title = Caption_Pause;
                animate.src = "../images/pause_click.png";
                walker.walk();
            }
        };

        resetPlay.onclick = function () {
            animate.title = Caption_Pause;
            animate.src = "../images/pause_click.png";
            fast.src = "../images/fast.png";
            medium.src = "../images/medium.png";
            slow.src = "../images/slow.png";
            walker.reset();
        };

        stopPlayBack.onclick = function () {
            animate.title = Caption_Play;
            animate.src = "../images/play.png";
            fast.src = "../images/fast.png";
            medium.src = "../images/medium.png";
            slow.src = "../images/slow.png";
            walker.stopplay();
        };

        fast.onclick = function () {
            walker.Speed(fastSpeed);
            fast.src = "../images/fast_click.png";
            medium.src = "../images/medium.png";
            slow.src = "../images/slow.png";
        };
        medium.onclick = function () {
            walker.Speed(mediumSpeed);
            fast.src = "../images/fast.png";
            medium.src = "../images/medium_click.png";
            slow.src = "../images/slow.png";
        };
        slow.onclick = function () {
            walker.Speed(slowSpeed);
            fast.src = "../images/fast.png";
            medium.src = "../images/medium.png";
            slow.src = "../images/slow_click.png";
        };
    }
}

//Plot alarm marker for palyback.
function plotPlaynBackAlarm(bubbleMessage, coord) {
    var OpenBubble = function (evt) {
        ui.removeBubble(infoBubble);
        coordinate = evt.currentTarget.coordinate;
        infoBubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        bubble = ui.addBubble(infoBubble);
    }
    //Event to close bubble template
    var CloseBubble = function (evt) {

        setTimeout(function () {
            ui.removeBubble(infoBubble);
        }, 3000);
    }

    //Remove the info bubble on map click.
    map.addEventListener("tap", function (evt) {
        ui.removeBubble(infoBubble);
    });

    var myListener = {
        "mouseover": [OpenBubble, true, null],
        "mouseout": [CloseBubble, true, null]
    };

    var alarmMarker = new H.map.Marker(coord, {
        icon: new H.map.Icon("../images/carmarker_Alarm.svg", { anchor: new H.math.Point(15, 31) }),
        zIndex: function (m) {
            return 28800001;
        }
    });
    alarmMarker.addEventListener('pointermove', OpenBubble, false);
    alarmMarker.addEventListener('pointerout', CloseBubble, false);
    return alarmMarker;
}

//Show hide marker in playback.
function Addcontainer(id) {
    if (id.checked) {
        if (mkr_group) map.addObject(mkr_group);
    }
    else {
        map.removeObject(mkr_group);
    }
}

function hideLine(checksts, pageName) {
    if (!checksts) {
        if (polyline != null) {
            try {
                map.removeObject(polyline);
            }
            catch (exc) { }
        }
    }
    else {
        if (polyline != null) {
            try {
                map.addObject(polyline);
            }
            catch (exc) { }
        }
    }
    setTimeout(clickCanvas, 3000);
}

function PlotGeozone(checksts, pageName) {

    if (!checksts) {
        clearPoly_Hstry();
        isShowGeozonePlotter = false;
    }
    else {
        var GeozoneDetails = document.getElementById('hdnGeozoneValue').value;
        var Geozones = GeozoneDetails.split('&');
        var details = "";
        var latlng = "";
        if (GeozoneDetails != "" && GeozoneDetails != null) {
            poly_group = new H.map.Group();
            for (var i = 0; i < Geozones.length; i++) {
                details = Geozones[i].split('|');
                latlng = details[0].replace(/~/gi, "&");
                if (latlng != null && latlng != "")
                    ShowGeozone_Hstry(latlng, '1', details[1], details[2], details[4], details[3], pageName);
            }
            isShowGeozonePlotter = true;
        }
        else {
            if (pageName == "G") {
                TrinetraCustomAlerts('There is no Geozones available.');
            }
            else {
                TrinetraCustomAlerts('There is no Geozones available in this trip(s).');
            }
            isShowGeozonePlotter = false;
        }
    }
    setTimeout(clickCanvas, 3000);
}
/***********************************************************************************************/
/***********************************Show Geozones in the history page******************************************/
var r1 = null;
var r2 = null;
var myrectangle;
var dragRectangle;

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

function loadMap_Hstry() {
    try {
        if (map) {
            if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            }
        }
    }
    catch (Error) {

    }
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    var holderControl = document.getElementById("content");

    try {
        var mapContainer = document.getElementById('map-dsply').innerHTML;
        if (document.getElementById('map-dsply').innerHTML == "" || mapContainer.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            map = new H.Map(document.getElementById("map-dsply"),
            defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4,
                engineType: H.map.render.RenderEngine.EngineType.P2D
            });
            IsDblClick = false;
        }
        else {
        }
    }
    catch (Error) {
    }

    if (Geozonetype == 'PL') {
        circleUnits = 'PL';
        geoType = 2;
    }
    else if (Geozonetype == 'CR') {
        circleUnits = 'CR';
        dragRectangle = false;
        geoType = 3;
    }
    else {
        circleUnits = 'RC';
        dragRectangle = false;
        geoType = 1;
    }

    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (mapTypeHolder.value) {
            case 'N': map.setBaseLayer(defaultLayers.raster.normal.map); break;
            case 'S': map.setBaseLayer(defaultLayers.raster.satellite.map); break;
            case 'H': map.setBaseLayer(defaultLayers.raster.terrain.map); break;
        }
    }
}
var rect_group = null;
function draw_rectangle(a, b, isRestricted, pageName) {
    var icon = "../images/flag_8.svg"
    if (myrectangle != null) {
        map.removeObject(myrectangle);
    }
    if (a != null && b != null) {

        var rFilClr = "rgba(144,238,144, 0.5)";
        var rLneClr = "rgba(0,128,0,0)";

        if (isRestricted == 'true' || isRestricted == '1') {
            rFilClr = "rgba(255,0,0,0.5)";
            rLneClr = "rgba(0,0,0,1)";
        }
        else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
            rFilClr = "rgba(144,238,144, 0.5)";
            rLneClr = "rgba(5,45,0,1)";
        }
        else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
            rFilClr = "rgba(65,105,225, 0.5)";
            rLneClr = "rgba(0,0,128,1)";
        }

        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)), {
                    style: { strokeColor: rLneClr, lineWidth: 1, fillColor: rFilClr }
                });
            }
            else {
                myrectangle = new H.map.Rect(new H.geo.Rect(parseFloat(a.lat), parseFloat(b.lng), parseFloat(b.lat), parseFloat(a.lng)), {
                    style: { strokeColor: rLneClr, lineWidth: 1, fillColor: rFilClr }
                });
            }
        }

        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.getData()),
                  { content: 'Geozone Name : ' + e.target.getData() });
              ui.addBubble(infoBubble);
          }
        );
        poly_group.addObject(myrectangle);
        polyShapeArray.push(poly_group);
        polyShapeArray.push(myrectangle);
        map.addObject(poly_group);
    }
}
function mapClickRectangle(overlay, point, isRestricted, pageName) {

    if (point == null) { return; }

    if (!r1) {   // First click
        r1 = point;
        myrectangle = null;
        dragRectangle = false;
    }
    else {   // Second click

        dragRectangle = false;
        draw_rectangle(r1, point, isRestricted, pageName);
        r2 = point;

        //Rec_bounds = new H.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 = ''
        if (location.pathname.indexOf("HistoryPage.aspx") == -1)
            //map.setViewBounds(myrectangle.getBounds());
            map.getViewModel().setLookAtData({
                bounds: myrectangle.getBoundingBox()
            });
    }
}

var polyShapeArray = new Array();
var polyStrip = new H.geo.LineString();
var poly_group = null;
function drawPoly_hstry(point, isRestricted, pageName) {
    var icon = "../images/flag_8.svg"

    document.getElementById('hdnCoordinates').value = polyArray;

    var pFilClr = "rgba(144,238,144, 0.5)";  //"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
    var pLneClr = "rgba(0,128,0,0)"; //#3355ff - Normal Geozone #FF0000 - Restricted Geozone #2E8B57 - UnRestricted Geozone

    if (isRestricted == 'true' || isRestricted == '1') {
        pFilClr = "rgba(255,0,0,0.5)";
        pLneClr = "rgba(0,0,0,1)";
    }
    else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
        pFilClr = "rgba(144,238,144, 0.5)";
        pLneClr = "rgba(5,45,0,1)";
    }
    else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
        pFilClr = "rgba(65,105,225, 0.5)";
        pLneClr = "rgba(0,0,128,1)";
    }
    polyShape = new H.map.Polygon(polyStrip, {
        style: { strokeColor: pLneClr, lineWidth: 1, fillColor: pFilClr }
    });
    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);
              }
            );
    //polyShape = new H.map.Polygon(polyPoints, {
    //    $name: sGeoName,
    //    pen: { strokeColor: pLneClr, lineWidth: .3 },
    //    brush: { color: pFilClr }
    //}); //2387
    //polyShape.addEventListener(
    //          'tap',
    //          function (e) {
    //              infoBubble = new H.ui.InfoBubble(getCentroid(e.target.path), { content: 'Geozone Name : ' + sGeoName });
    //              ui.addBubble(infoBubble);
    //              nokia.maps.dom.EventTarget(bubble.node).addListener('click', function (e) {
    //                  infoBubble.closeAll();
    //              });
    //          });

    poly_group = new H.map.Group();
    poly_group.addObject(polyShape);
    polyShapeArray.push(poly_group);
    map.addObject(poly_group);
}

function clearPoly_Hstry() {

    // Remove polygon and reset arrayse
    //if (map) map.objects.clear();    
    polyPoints.length = 0;
    polyArray.length = 0;
    markers.length = 0;
    //Clear Rectangle Geozone
    r1 = null;

    if (polyShapeArray != undefined && polyShapeArray != null) {
        //for (var i = 0; i < polyShapeArray.length; i++) {
        //    if (polyShapeArray[i] != null) {
        //        map.removeObject(polyShapeArray[i]);
        //    }
        //}
        for (var i = 0; i < polyShapeArray.length; i++) {
            if (polyShapeArray[i] != null) {
                polyShapeArray[i].removeObjects(polyShapeArray[i].getObjects());
            }

        }
        polyShapeArray = new Array();
    }
    loadMap_Hstry();
}

function doDrawCircle_gz(centerPoint, lat, long, isRestricted, circleRadius, pageName) {
    try {

        var center = map.getCenter();
        var circlePoints = Array();

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

            var lat1 = (PI / 180) * (lat); // radians
            var lng1 = (PI / 180) * (long); // 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);
            }

            var cFilClr = "rgba(144,238,144, 0.5)";  //"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
            var cLneClr = "rgba(0,128,0,0)"; //#3355ff - Normal Geozone #FF0000 - Restricted Geozone #2E8B57 - UnRestricted Geozone

            if (isRestricted == 'true' || isRestricted == '1') {
                cFilClr = "rgba(255,0,0,0.5)";
                cLneClr = "rgb(0,0,0,1)";
            }
            else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
                cFilClr = "rgba(144,238,144, 0.5)";
                cLneClr = "rgba(5,45,0,1)";
            }
            else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
                cFilClr = "rgba(65,105,225, 0.5)";
                cLneClr = "rgba(0,0,128,1)";
            }

            if (d < 1.5678565720686044) {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {//Stroke Color:#5270B2
                                style: { strokeColor: cLneClr, lineWidth: 1, fillColor: cFilClr }// "rgba(198,155,204,0.5)" } // "#C69ACC" }
                            }
                        );
            }
            else {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                style: { strokeColor: cLneClr, lineWidth: 1, fillColor: cFilClr } //'#C69ACC' }
                            }
                        );
            }

            circle.setData(sGeoName);
            circle.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.getData()),
                      { content: 'Geozone Name : ' + e.target.getData() });
                  ui.addBubble(infoBubble);
              }
            );

            poly_group.addObject(circle);
            polyShapeArray.push(poly_group);
            map.addObject(poly_group);
            //polyShapeArray.push(circle);
            //map.addObject(circle);
        }
    }
    catch (Error) {
        //alert(Error);
    }
}

function ShowGeozone_Hstry(latlng, isView, geoName, geoType, isRestricted, cRadius, pageName) {
    if (geoType == 1) {
        var isIE = CheckBrowser();
        isview = isView;
        sGeoName = geoName;
        Geozonetype = 'RC';
        loadMap_Hstry();
        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_new('', point, isRestricted, pageName);
        }
    }
    else if (geoType == 2) {
        var isIE = CheckBrowser();
        isview = isView;
        sGeoName = geoName;
        Geozonetype = 'PL';
        IsDblClick = false; //To reassign the Double click event to the map.
        loadMap_Hstry();
        var collectdata = new Array();
        var lt = latlng.split('&');
        polyStrip = new H.geo.LineString();
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            polyStrip.pushPoint(point);
        }
        drawPoly_hstry(point, isRestricted, pageName);
    }
    else if (geoType == 3) {
        var isIE = CheckBrowser();
        isview = isView;
        sGeoName = geoName;
        Geozonetype = 'CR';
        IsDblClick = false; //To reassign the Double click event to the map.
        loadMap_Hstry();
        var collectdata = new Array();
        var lt = latlng.split('&');
        polyStrip = new H.geo.LineString();
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            polyStrip.pushPoint(point);
            doDrawCircle_gz(point, parseFloat(lng[0]), parseFloat(lng[1]), isRestricted, cRadius, pageName);
        }
    }
}
/***********************************End of Maps Geozones in the history page******************************************/
/*********************************Context Menu Start***********************************************/
function createContextMenu(map) {

    try {
        if (!map.getComponentById("ContextMenu")) {
            ctxtMenu = new nokia.maps.map.component.ContextMenu();
            /* Add Custom Context Menu Items */
            //This adds three items with a menu separator
            trnMenuItems = function (contextMenuEvent, group) {
                group.addEntry("Show All Landmarks",
      function (activationEvent) {
          if (isShowLandmarkPlotter == 0) {
              if (document.getElementById("hdnLandmarkEntries").value.length == 0) {
                  TrinetraCustomAlerts('No landmarks available to be plotted.');
              }
              else {
                  drawCircleForLandmark(document.getElementById("hdnLandmarkEntries").value, true);
                  //sakthi 09-Apr-2014
                  initialiseSVGParser();
                  clusterDataPoints(clusterPoint, landmarkMarkers, true);
                  isShowLandmarkPlotter = 1;
              }
              var lng = new Array();
              lng = ltMapIT[i].split("~#~");
              markerPlotV3.push(parseFloat(lng[0]));
              markerPlotV3.push(parseFloat(lng[1]));
              HidePopUp();
          }
          else { TrinetraCustomAlerts('Already \"Show All Landmarks\" option is in enable mode'); }
      });
                group.addEntry("Disable All Landmarks",
      function (activationEvent) {
          if (isShowLandmarkPlotter == 1) {

              drawCircleForLandmark(document.getElementById("hdnLandmarkEntries").value, false);
              initialiseSVGParser();
              clusterDataPoints(clusterPoint, landmarkMarkers, false);
              isShowLandmarkPlotter = 0;
              HidePopUp();
          }
          else { TrinetraCustomAlerts('Already \"Show All Landmarks\" option is in disable mode'); }
      });

                group.addEntry("Show All Geozones",
      function (activationEvent) {
          if (isShowGeozonePlotter == false) {
              PlotGeozone(true, 'M');
          }
          else { TrinetraCustomAlerts('Already \"Show All Geozone\" option is in enable mode'); }
      });
                group.addEntry("Hide All Geozones",
      function (activationEvent) {
          if (isShowGeozonePlotter == true) {
              PlotGeozone(false, 'M');
          }
          else { TrinetraCustomAlerts('Already \"Show All Geozone\" option is in disable mode'); }
      });
                group.addEntry("Test Leh Locations", function (activationEvent) { plotLehMarkers(); });
            };

            // Remove Zoom
            //contextMenu.removeHandler(nokia.maps.map.component.ContextMenu.zoomHandler);
            // Remove  Routing
            if (nokia.maps.routing.component !== undefined) {
                ctxtMenu.removeHandler(nokia.maps.routing.component.ContextMenuHandler);
            }
            ctxtMenu.addHandler(trnMenuItems);
            map.components.add(ctxtMenu);
        }
    }
    catch (ex) { }
}

//Here v3.0 Context menu
// Get an instance of the geocoding service:
var geocoder = platform.getGeocodingService();
var notReverseGeocoded = true;
var address = ''
var isShowLine = true;
var isShowPath = false;
var isShowRoute = false;

function reverseGeocode(platform, param) {
    var geocoder = platform.getGeocodingService(),
      reverseGeocodingParameters = {
          prox: param,
          mode: 'retrieveAddresses',
          maxresults: '1',
          jsonattributes: 1
      };

    geocoder.reverseGeocode(reverseGeocodingParameters, onSuccess, onError);
}

function CreateContextMenuNew(map) {
    // add context menu listner  
    map.addEventListener('contextmenu', function (e) {
        // reverse geocode at the point of click if not already
        debugger;
        if (notReverseGeocoded) {
            clickCoords = map.screenToGeo(e.viewportX, e.viewportY);
            var reverseGeocodingParameters = {
                prox: clickCoords.lat + "," + clickCoords.lng + ",200",
                mode: 'retrieveAddresses',
                maxresults: 1,
                language: 'en'
            };
            geocoder.reverseGeocode(reverseGeocodingParameters, function (result) {
                try {
                    address = result.Response.View[0].Result[0].Location.Address.Label;
                    notReverseGeocoded = false;
                    // disptach to the context menu event again to add results to the 
                    // context menu
                    map.dispatchEvent(e);
                }
                catch (e) {
                    console.log(e);
                }
            }, function (e) {
                console.log(e);
            });
        }
        else {
            // add address to context menu
            e.items.push(new H.util.ContextItem({
                label: address,
            }));

            //e.items.push(new H.util.ContextItem({ label: '--------------------------------------------------------------------------------' }));

            // add menus
            //e.items.push(new H.util.ContextItem({
            //    label: '> Show / Hide Landmark(s)',
            //    callback: function () {
            //        if (isShowLandmarkPlotter == 0) {
            //            if (document.getElementById("hdnLandmarkEntries").value.length == 0) {
            //                TrinetraCustomAlerts('No landmarks available to be plotted.');
            //            }
            //            else {
            //                drawCircleForLandmark(document.getElementById("hdnLandmarkEntries").value, true);
            //                clusterDataPoints(clusterPoint, true);
            //                isShowLandmarkPlotter = 1;
            //            }
            //            HidePopUp();
            //        }
            //        else if (isShowLandmarkPlotter == 1) {
            //            drawCircleForLandmark(document.getElementById("hdnLandmarkEntries").value, false);
            //            clusterDataPoints(clusterPoint, false);
            //            isShowLandmarkPlotter = 0;
            //            HidePopUp();
            //        }
            //        //else { TrinetraCustomAlerts('Already \"Show All Landmarks\" option is in disable mode'); }
            //    }
            //}));

            //e.items.push(new H.util.ContextItem({
            //    label: '> Show / Hide Geozone(s)',
            //    callback: function () {
            //        if (isShowGeozonePlotter == false) {
            //            PlotGeozone(true, 'M');
            //            isShowGeozonePlotter = true;
            //        }
            //        else {
            //            PlotGeozone(false, 'M');
            //            isShowGeozonePlotter = false;
            //        }
            //    }
            //}));

            if (location.pathname.indexOf("HistoryPage.aspx") != -1) {
                //e.items.push(new H.util.ContextItem({
                //    label: '> Show / Hide Line',
                //    callback: function () {
                //        if (isShowLine == false) {
                //            hideLine(true, 'M');
                //            isShowLine = true;
                //        }
                //        else {
                //            hideLine(false, 'M');
                //            isShowLine = false;
                //        }
                //    }
                //}));

                //e.items.push(new H.util.ContextItem({
                //    label: '> Show / Hide Path',
                //    callback: function () {
                //        if (isShowPath == false) {
                //            ShowPopUp();
                //            drawRoute(true, 'r');
                //            isShowPath = true;
                //        }
                //        else {
                //            ShowPopUp();
                //            drawRoute(false, 'r');
                //            isShowPath = false;
                //        }
                //    }
                //}));

                e.items.push(new H.util.ContextItem({
                    label: '> Show / Hide Route',
                    callback: function () {
                        if (isShowRoute == false) {
                            ShowPopUp();
                            DrawRoute(true);
                            isShowRoute = true;
                        }
                        else {
                            ShowPopUp();
                            DrawRoute(false);
                            isShowRoute = false;
                        }
                    }
                }));
            }

            //e.items.push(new H.util.ContextItem({
            //    label: '> Zoom Out',
            //    callback: function (e) {
            //        map.setCenter(orgCenter != null ? orgCenter : centerCoordinate);
            //        map.setZoom(6);
            //    }
            //}));

            notReverseGeocoded = true;
        }
    });
}
/*********************************Context Menu End***********************************************/
/********************************* Jayaram include context menu for landmark *********************/
function CreateContextMenuNewLandmark(map) {
    // add context menu listner  
    map.addEventListener('contextmenu', function (e) {
        // reverse geocode at the point of click if not already
        if (notReverseGeocoded) {
            clickCoords = map.screenToGeo(e.viewportX, e.viewportY);
            var reverseGeocodingParameters = {
                prox: clickCoords.lat + "," + clickCoords.lng + ",200",
                mode: 'retrieveAddresses',
                maxresults: 1,
                language: 'en'
            };
            geocoder.reverseGeocode(reverseGeocodingParameters, function (result) {
                try {
                    address = result.Response.View[0].Result[0].Location.Address.Label;
                    notReverseGeocoded = false;
                    // disptach to the context menu event again to add results to the 
                    // context menu
                    map.dispatchEvent(e);
                }
                catch (e) {
                    console.log(e);
                }
            }, function (e) {
                console.log(e);
            });
        }
        else {
            // add address to context menu
            e.items.push(new H.util.ContextItem({
                label: address,
            }));

            e.items.push(new H.util.ContextItem({ label: '--------------------------------------------------------------------------------' }));

            // add menus
            e.items.push(new H.util.ContextItem({
                label: '> Show / Hide Landmark(s)',
                callback: function () {
                    if (isShowLandmarkPlotter == 0) {

                        if (document.getElementById("hdnLandmarkEntries").value.length == 0) {
                            TrinetraCustomAlerts('No landmarks available to be plotted.');
                        }
                        else {

                            drawCircleForLandmark(document.getElementById("hdnLandmarkEntries").value, true);
                            clusterDataPoints(clusterPoint, true);
                            isShowLandmarkPlotter = 1;
                        }
                        HidePopUp();
                    }
                    else if (isShowLandmarkPlotter == 1) {
                        drawCircleForLandmark(document.getElementById("hdnLandmarkEntries").value, false);
                        clusterDataPoints(clusterPoint, false);
                        isShowLandmarkPlotter = 0;
                        HidePopUp();
                    }
                    //else { TrinetraCustomAlerts('Already \"Show All Landmarks\" option is in disable mode'); }
                }
            }));




            //e.items.push(new H.util.ContextItem({
            //    label: '> Zoom Out',
            //    callback: function (e) {
            //        map.setCenter(orgCenter != null ? orgCenter : centerCoordinate);
            //        map.setZoom(6);
            //    }
            //}));

            notReverseGeocoded = true;
        }
    });
}

/*********************************Clustering Start***********************************************/
function initialiseSVGParser() {
    var color,
    iconSVG =
      ['<svg width=\'51\' height=\'51\' xmlns=\'https://www.w3.org/2000/svg\'>' +
          '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'25\' cy=\'25\' r=\'25\' stroke-width=\'2\'/>' +
          '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'25\' cy=\'25\' r=\'21\' stroke-width=\'2\'/>' +
          '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'25\' cy=\'25\' r=\'17\' stroke-width=\'2\'/>' +
          '<text x=\'25\' y=\'29\' font-size=\'10pt\' font-family=\'arial\' font-weight=\'bold\' text-anchor=\'middle\' fill=\'#FFF\' textContent=\'__TEXTCONTENT__\'>__TEXT__</text>' +
          '</svg>',
        '<svg width=\'47\' height=\'47\' xmlns=\'https://www.w3.org/2000/svg\'>' +
         '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'23\' cy=\'23\' r=\'23\' stroke-width=\'2\'/>' +
         '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'23\' cy=\'23\' r=\'19\' stroke-width=\'2\'/>' +
         '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'23\' cy=\'23\' r=\'15\' stroke-width=\'2\'/>' +
         '<text x=\'23\' y=\'27\' font-size=\'10pt\' font-family=\'arial\' font-weight=\'bold\' text-anchor=\'middle\' fill=\'#FFF\' textContent=\'__TEXTCONTENT__\'>__TEXT__</text>' +
         '</svg>',
        '<svg width=\'43\' height=\'43\' xmlns=\'https://www.w3.org/2000/svg\'>' +
         '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'21\' cy=\'21\' r=\'21\' stroke-width=\'2\'/>' +
         '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'21\' cy=\'21\' r=\'17\' stroke-width=\'2\'/>' +
         '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'21\' cy=\'21\' r=\'13\' stroke-width=\'2\'/>' +
         '<text x=\'21\' y=\'25\' font-size=\'10pt\' font-family=\'arial\' font-weight=\'bold\' text-anchor=\'middle\' fill=\'#FFF\' textContent=\'__TEXTCONTENT__\'>__TEXT__</text>' +
         '</svg>',
        '<svg width=\'39\' height=\'39\' xmlns=\'https://www.w3.org/2000/svg\'>' +
          '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'19\' cy=\'19\' r=\'19\' stroke-width=\'2\'/>' +
          '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'19\' cy=\'19\' r=\'15\' stroke-width=\'2\'/>' +
          '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'19\' cy=\'19\' r=\'11\' stroke-width=\'2\'/>' +
          '<text x=\'19\' y=\'23\' font-size=\'10pt\' font-family=\'arial\' font-weight=\'bold\' text-anchor=\'middle\' fill=\'#FFF\' textContent=\'__TEXTCONTENT__\'>__TEXT__</text>' +
          '</svg>'],
    stops = {
        '0': '#8A8A8A',    //Grey for 0-10
        '10': '#CACA00', //Yellow for 11-50
        '50': '#00CC00',  //Green for 51-100
        '100': '#0000CC', //Blue for 101-200
        '200': '#CC00CC',  //Purple for 201-500
        '500': '#FF0000'   //Red for over 500
    },
    svgParser = new nokia.maps.gfx.SvgParser();
    createIcon = function (count) {
        var digit = Math.min(3, 4 - Math.floor(Math.log(count) / Math.log(10))),
      svg,
      i;

        for (var i in stops) {
            if (count > i) {
                color = stops[i];
            }
        }
        svg = iconSVG[digit]
        .replace(/__TEXTCONTENT__/g, count)
        .replace(/__TEXT__/g, count)
        .replace(/__MAINCOLOR__/g, color);
        return new nokia.maps.gfx.GraphicsImage(svgParser.parseSvg(svg));
    }
}

function clusterDataPoints(data, val, isEnable) {
    var svgTheme = {
        // Add a SVG Marker for Clusters.
        getClusterPresentation: function (dataPoints) {
            if (dataPoints.getSize() > 0) {
                var markerIcon = createIcon(dataPoints.getSize());
                return new H.map.Marker(dataPoints.getBounds().getCenter(),
                          {
                              icon: new H.map.Icon(markerIcon, { anchor: new H.math.Point(25, 25) })
                          }
                 );
            }
        },
        // Add a Standard Marker for Noise Points.
        getNoisePresentation: function (dataPoint) {
            var i = 0;
            for (j = 0; j < data.length; j++) {
                if (data[j] == dataPoint) {
                    i = j;
                }
            }
            return landmarkMarkers[i];
            //new nokia.maps.map.StandardMarker([dataPoint.latitude, dataPoint.longitude]);
        }
    },
    clusterProvider = new mapsjs.clustering.ClusterProvider(map, {
        eps: 16,
        minPts: 1,
        dataPoints: data,
        theme: svgTheme
    });
    //clusterBackup = new Array();
    clusterBackup.push(clusterProvider);

    if (isEnable) {
        clusterProvider.cluster();
    }
    else {
        for (var l = 0; l < clusterBackup.length; l++) {
            clusterBackup[l].clean();
            clusterBackup[l].cluster();
        }
    }

}

/***********************************************************************************************************************************************/

function clusterDataPoints(data, isEnable) {

    if (!isEnable) {
        if (objectLayer != null) {
            map.removeLayer(objectLayer);
        }
        return;
    }


    var dataPoints = data;

    var noiseSvg =
        '<svg xmlns="http://www.w3.org/2000/svg" height="50px" width="50px">' +
        '<circle cx="20px" cy="20px" r="20" fill="red" />' +
        '<text x="20" y="35" font-size="30pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white" textContent="!">!</text></svg>';

    var noiseIcon = new H.map.Icon(noiseSvg, {
        size: { w: 22, h: 22 },
        anchor: { x: 11, y: 11 }
    });


    var clusterSvgTemplate =
        '<svg xmlns="http://www.w3.org/2000/svg" height="50px" width="50px"><circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="20" fill="#835C3B" stroke-opacity="0.5" />' +
        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="16" fill="#835C3B" stroke-opacity="0.5" />' +
        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="12" fill="#835C3B" stroke-opacity="0.5" />' +
        '<text x="24" y="29" font-size="10pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white">{text}</text>' +
        '</svg>';


    var clusteringProvider = new H.clustering.Provider(dataPoints, {
        //min: 5,
        //max: 20,
        clusteringOptions: {
            minWeight: 1,
            eps: 32
        },
        theme: {
            getClusterPresentation: function (markerCluster) {

                // Use cluster weight to change icon size:
                var svgString = clusterSvgTemplate.replace('{radius}', markerCluster.getWeight() * 5);
                svgString = svgString.replace('{text}', +markerCluster.getWeight());

                var w, h;
                var weigth = markerCluster.getWeight();

                //Set cluster size depending on the weight
                if (weigth <= 6) {
                    w = 35;
                    h = 35;
                }
                else if (weigth <= 12) {
                    w = 50;
                    h = 50;
                }
                else {
                    w = 75;
                    h = 75;
                }

                var clusterIcon = new H.map.Icon(svgString, {
                    size: { w: w, h: h },
                    anchor: { x: (w / 2), y: (h / 2) }
                });

                // Create a marker for clusters:
                var clusterMarker = new H.map.Marker(markerCluster.getPosition(), {
                    icon: clusterIcon,
                    // Set min/max zoom with values from the cluster, otherwise
                    // clusters will be shown at all zoom levels:
                    min: markerCluster.getMinZoom(),
                    max: markerCluster.getMaxZoom()
                });

                // Bind cluster data to the marker:
                clusterMarker.setData(markerCluster);

                return clusterMarker;
            },
            getNoisePresentation: function (noisePoint) {
                var i = 0;
                group = new H.map.Group({ min: noisePoint.getMinZoom() });
                for (j = 0; j < dataPoints.length; j++) {

                    if (dataPoints[j].data.id == noisePoint.getData().id) {
                        i = j;

                    }
                }
                group.addObject(landmarkMarkers[i]);
                return group;
            }
        }

    });

    objectLayer = new H.map.layer.ObjectLayer(clusteringProvider);
    map.addLayer(objectLayer);

    //clusteringProvider.addEventListener('tap', function (event) {
    //    // Log data bound to the marker that has been tapped:
    //    alert(event.target.getData());
    //});
}

function clusterDataPoints_Monitor(data, isEnable) {

    if (objectLayer_monitor != null) {
        map.removeLayer(objectLayer_monitor);
    }

    var dataPoints = data;

    var noiseSvg =
        '<svg xmlns="http://www.w3.org/2000/svg" height="50px" width="50px">' +
        '<circle cx="20px" cy="20px" r="20" fill="red" />' +
        '<text x="20" y="35" font-size="30pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white" textContent="!">!</text></svg>';

    var noiseIcon = new H.map.Icon(noiseSvg, {
        size: { w: 22, h: 22 },
        anchor: { x: 11, y: 11 }
    });


    var clusterSvgTemplate =
        '<svg xmlns="http://www.w3.org/2000/svg" height="50px" width="50px"><circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="20" fill="#7E354D" stroke-opacity="0.5" />' +
        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="16" fill="#7E354D" stroke-opacity="0.5" />' +
        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="12" fill="#7E354D" stroke-opacity="0.5" />' +
        '<text x="24" y="29" font-size="10pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white">{text}</text>' +
        '</svg>';


    var clusteringProvider = new H.clustering.Provider(dataPoints, {
        //min: 5,
        //max: 20,
        clusteringOptions: {
            minWeight: 1,
            eps: 32
        },
        theme: {
            getClusterPresentation: function (markerCluster) {

                // Use cluster weight to change icon size:
                var svgString = clusterSvgTemplate.replace('{radius}', markerCluster.getWeight() * 5);
                svgString = svgString.replace('{text}', +markerCluster.getWeight());

                var w, h;
                var weigth = markerCluster.getWeight();

                //Set cluster size depending on the weight
                if (weigth <= 6) {
                    w = 35;
                    h = 35;
                }
                else if (weigth <= 12) {
                    w = 50;
                    h = 50;
                }
                else {
                    w = 75;
                    h = 75;
                }

                var clusterIcon = new H.map.Icon(svgString, {
                    size: { w: w, h: h },
                    anchor: { x: (w / 2), y: (h / 2) }
                });

                // Create a marker for clusters:
                var clusterMarker = new H.map.Marker(markerCluster.getPosition(), {
                    icon: clusterIcon,
                    // Set min/max zoom with values from the cluster, otherwise
                    // clusters will be shown at all zoom levels:
                    min: markerCluster.getMinZoom(),
                    max: markerCluster.getMaxZoom()
                });

                // Bind cluster data to the marker:
                clusterMarker.setData(markerCluster);

                clusterMarker.addEventListener("pointerenter", function (event) {
                    var isMapIt1 = 'LanguageEng'; //document.getElementById('hdnUserlan').value = null ? 'LanguageEng' : document.getElementById('hdnUserlan').value;

                    var point = event.target.getGeometry(),
                        screenPosition = map.geoToScreen(point),
                        t = event.target,
                        data = t.getData();

                    var tooltipContent

                    if (isMapIt1 == "LanguageArNew") {
                        tooltipContent = '<div style="padding-bottom:10px"><b><u>قائمة السيارات / ذيول أدناه أدناه. ،</u></b></div><div style="text-align:left;<#htwt#>"><table style="direction:ltr" cellspacing=5 class=\'InfoBubble\'>';
                        tooltipContent += '<td style="width:5%"><b>سنو</b></td><td style="width:40%"><b>مركبة</b></td></tr>';
                    }
                    else {
                        tooltipContent = '<div style="padding-bottom:10px"><b><u>Following list of vehicles / tails are under here.,</u></b></div><div style="text-align:left;<#htwt#>"><table style="direction:ltr" cellspacing=5 class=\'InfoBubble\'>';
                        tooltipContent += '<td style="width:5%"><b>Sno</b></td><td style="width:40%"><b>Vehicle</b></td></tr>';
                    }

                    //tooltipContent = '<div style="padding-bottom:10px"><b><u>Following list of vehicles / tails are under here.,</u></b></div><div style="text-align:left;<#htwt#>"><table style="direction:ltr" cellspacing=5 class=\'InfoBubble\'>';
                    ////tooltipContent += '<td colspan="3"><b>Total no. of vehicles : </b><#noOfVeh#></td></tr>';
                    ////tooltipContent += '<td style="width:5%"><b>Sno</b></td><td style="width:40%"><b>Vehicle</b></td><td style="width:100%"><b>Address</b></td></tr>';
                    //tooltipContent += '<td style="width:5%"><b>Sno</b></td><td style="width:40%"><b>Vehicle</b></td></tr>';
                    var count = 0;
                    data.forEachDataPoint(
                        function (o) {
                            var sno = count++;
                            //tooltipContent += o.getPosition().lat + " " + o.getPosition().lng + "," + o.getData().id + "</br>";
                            //tooltipContent += '<td style="width:2%;text-align:center">' + (sno + 1).toString() + '</td><td style="width:28%"> ' + o.getData().id + ' </td><td style="width:70%">' + o.getData().address + '</td></tr>';
                            tooltipContent += '<td style="width:2%;text-align:center">' + (sno + 1).toString() + '</td><td style="width:28%"> ' + o.getData().id + ' </td></tr>';
                        }
                    );
                    tooltipContent += '</table></div>';
                    if (count > 3) {
                        tooltipContent = tooltipContent.replace("<#htwt#>", "height:150px;width:0px;overflow-y: scroll;")
                    }
                    tooltipContent = tooltipContent.replace("<#noOfVeh#>", count.toString());
                    infoBubble = new H.ui.InfoBubble(map.screenToGeo(screenPosition.x, screenPosition.y), { content: tooltipContent });
                    ui.addBubble(infoBubble);
                });

                clusterMarker.addEventListener("pointerleave", function (event) {
                    if (infoBubble) {
                        ui.removeBubble(infoBubble);
                        infoBubble = null;
                    }
                });


                return clusterMarker;
            },
            getNoisePresentation: function (noisePoint) {
                var i = 0;
                group = new H.map.Group({ min: noisePoint.getMinZoom() });
                for (j = 0; j < dataPoints.length; j++) {

                    if (dataPoints[j].data.id == noisePoint.getData().id) {
                        i = j;

                    }
                }
                group.addObject(clusterMarkerArray[i]);
                return group;
            }
        }

    });

    objectLayer_monitor = new H.map.layer.ObjectLayer(clusteringProvider);
    map.addLayer(objectLayer_monitor);
}


//function clusterDataPoints(data, isEnable) {

//    if (!isEnable) {
//        if (objectLayer != null) {
//            map.removeLayer(objectLayer);
//        }
//        return;
//    }


//    var dataPoints = data;

//    var noiseSvg =
//        '<svg xmlns="https://www.w3.org/2000/svg" height="50px" width="50px">' +
//        '<circle cx="20px" cy="20px" r="20" fill="red" />' +
//        '<text x="20" y="35" font-size="30pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white" textContent="!">!</text></svg>';

//    var noiseIcon = new H.map.Icon(noiseSvg, {
//        size: { w: 22, h: 22 },
//        anchor: { x: 11, y: 11 }
//    });


//    var clusterSvgTemplate =
//        '<svg xmlns="https://www.w3.org/2000/svg" height="50px" width="50px"><circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="20" fill="#835C3B" stroke-opacity="0.5" />' +
//        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="16" fill="#835C3B" stroke-opacity="0.5" />' +
//        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="12" fill="#835C3B" stroke-opacity="0.5" />' +
//        '<text x="24" y="29" font-size="10pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white">{text}</text>' +
//        '</svg>';


//    var clusteringProvider = new mapsjs.clustering.Provider(dataPoints, {
//        //min: 5,
//        //max: 20,
//        clusteringOptions: {
//            minWeight: 1,
//            eps: 32
//        },
//        theme: {
//            getClusterPresentation: function (markerCluster) {

//                // Use cluster weight to change icon size:
//                var svgString = clusterSvgTemplate.replace('{radius}', markerCluster.getWeight() * 5);
//                svgString = svgString.replace('{text}', +markerCluster.getWeight());

//                var w, h;
//                var weigth = markerCluster.getWeight();

//                //Set cluster size depending on the weight
//                if (weigth <= 6) {
//                    w = 35;
//                    h = 35;
//                }
//                else if (weigth <= 12) {
//                    w = 50;
//                    h = 50;
//                }
//                else {
//                    w = 75;
//                    h = 75;
//                }

//                var clusterIcon = new H.map.Icon(svgString, {
//                    size: { w: w, h: h },
//                    anchor: { x: (w / 2), y: (h / 2) }
//                });

//                // Create a marker for clusters:
//                var clusterMarker = new H.map.Marker(markerCluster.getPosition(), {
//                    icon: clusterIcon,
//                    // Set min/max zoom with values from the cluster, otherwise
//                    // clusters will be shown at all zoom levels:
//                    min: markerCluster.getMinZoom(),
//                    max: markerCluster.getMaxZoom()
//                });

//                // Bind cluster data to the marker:
//                clusterMarker.setData(markerCluster);

//                return clusterMarker;
//            },
//            getNoisePresentation: function (noisePoint) {
//                var i = 0;
//                group = new H.map.Group({ min: noisePoint.getMinZoom() });
//                for (j = 0; j < dataPoints.length; j++) {

//                    if (dataPoints[j].data.id == noisePoint.getData().id) {
//                        i = j;

//                    }
//                }
//                group.addObject(landmarkMarkers[i]);
//                return group;
//            }
//        }

//    });

//    objectLayer = new mapsjs.map.layer.ObjectLayer(clusteringProvider);
//    map.addLayer(objectLayer);

//    //clusteringProvider.addEventListener('tap', function (event) {
//    //    // Log data bound to the marker that has been tapped:
//    //    alert(event.target.getData());
//    //});
//}

//function clusterDataPoints_Monitor(data, isEnable) {

//    if (objectLayer_monitor != null) {
//        map.removeLayer(objectLayer_monitor);
//    }

//    var dataPoints = data;

//    var noiseSvg =
//        '<svg xmlns="https://www.w3.org/2000/svg" height="50px" width="50px">' +
//        '<circle cx="20px" cy="20px" r="20" fill="red" />' +
//        '<text x="20" y="35" font-size="30pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white" textContent="!">!</text></svg>';

//    var noiseIcon = new H.map.Icon(noiseSvg, {
//        size: { w: 22, h: 22 },
//        anchor: { x: 11, y: 11 }
//    });


//    var clusterSvgTemplate =
//        '<svg xmlns="https://www.w3.org/2000/svg" height="50px" width="50px"><circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="20" fill="#7E354D" stroke-opacity="0.5" />' +
//        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="16" fill="#7E354D" stroke-opacity="0.5" />' +
//        '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="12" fill="#7E354D" stroke-opacity="0.5" />' +
//        '<text x="24" y="29" font-size="10pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white">{text}</text>' +
//        '</svg>';


//    var clusteringProvider = new mapsjs.clustering.Provider(dataPoints, {
//        //min: 5,
//        //max: 20,
//        clusteringOptions: {
//            minWeight: 1,
//            eps: 32
//        },
//        theme: {
//            getClusterPresentation: function (markerCluster) {

//                // Use cluster weight to change icon size:
//                var svgString = clusterSvgTemplate.replace('{radius}', markerCluster.getWeight() * 5);
//                svgString = svgString.replace('{text}', +markerCluster.getWeight());

//                var w, h;
//                var weigth = markerCluster.getWeight();

//                //Set cluster size depending on the weight
//                if (weigth <= 6) {
//                    w = 35;
//                    h = 35;
//                }
//                else if (weigth <= 12) {
//                    w = 50;
//                    h = 50;
//                }
//                else {
//                    w = 75;
//                    h = 75;
//                }

//                var clusterIcon = new H.map.Icon(svgString, {
//                    size: { w: w, h: h },
//                    anchor: { x: (w / 2), y: (h / 2) }
//                });

//                // Create a marker for clusters:
//                var clusterMarker = new H.map.Marker(markerCluster.getPosition(), {
//                    icon: clusterIcon,
//                    // Set min/max zoom with values from the cluster, otherwise
//                    // clusters will be shown at all zoom levels:
//                    min: markerCluster.getMinZoom(),
//                    max: markerCluster.getMaxZoom()
//                });

//                // Bind cluster data to the marker:
//                clusterMarker.setData(markerCluster);

//                return clusterMarker;
//            },
//            getNoisePresentation: function (noisePoint) {
//                var i = 0;
//                group = new H.map.Group({ min: noisePoint.getMinZoom() });
//                for (j = 0; j < dataPoints.length; j++) {

//                    if (dataPoints[j].data.id == noisePoint.getData().id) {
//                        i = j;

//                    }
//                }
//                group.addObject(clusterMarkerArray[i]);
//                return group;
//            }
//        }

//    });

//    objectLayer_monitor = new mapsjs.map.layer.ObjectLayer(clusteringProvider);
//    map.addLayer(objectLayer_monitor);
//}
/********************End of Colapse panel JQuery foe Legends***************/
function mapTypeChoosen() {
    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (mapTypeHolder.value) {
            case 'N': maptype = 'normal.day'; break;
            case 'H': maptype = 'hybrid.day'; break;
            case 'T': maptype = 'terrain.day'; break;
            default: maptype = 'normal.day';
        }
    }
}
/********************************************Start Nearest Marker******************************************/
function findNearestMarker(coords, minDist) {
    var landmarkinfo = coords.split("~#~");
    var centerPoint = new H.geo.Point(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
    var vehiclePosition = null;
    var nearest_text = '-',
      markerDist,
      // get all objects added to the map
      objects = clusterMarkerArray,//map.getObjects(),
    len = clusterMarkerArray.length,//map.getObjects().length,
      i;

    // iterate over objects and calculate distance between them
    for (i = 0; i < len; i += 1) {
        markerDist = objects[i].getPosition().distance(centerPoint);
        if (markerDist < minDist) {
            minDist = markerDist;
            vehiclePosition = objects[i];
            nearest_text = objects[i].getData();
        }
    }
    if (nearest_text != '-' && vehiclePosition != null) {
        TrinetraCustomAlerts('Nearest vehicle "' + nearest_text + '" found inside the selected region of' + minDist.toString() + ' meters');
        map.setCenter(vehiclePosition.getPosition());
        if (map.getZoom() < 18) {
            map.setZoom(18);
        }
    }
}
function findNearestMarker(coords) {
    var minDist = 7,
      nearest_text = 'f',
      markerDist,
      // get all objects added to the map
      objects = clusterMarkerArray,
      len = clusterMarkerArray.length,
      i;

    // iterate over objects and calculate distance between them
    for (i = 0; i < len; i += 1) {
        markerDist = objects[i].getPosition().distance(coords);
        if (markerDist < minDist) {
            minDist = markerDist;
            var coords = objects[i].getPosition();
            nearest_text = PlayBack[coords.lat + "," + coords.lng];
        }
    }
    return nearest_text;
}
/********************************************End Nearest Marker******************************************/
/********************************************Start For Demo******************************************/
function plotLehMarkers() {
    var lehLocations = new Array("Leh", "Base Camp 2", "Bimbat", "Bimbat TAC", "Budhkharbu", "Changla", "Chumathang", "Chushul", "Dungti", "Fukche-2/Fukche", "Hanle", "Hanuthang", "K TOP/Khardungla", "Kargil", "Karu", "Lamayuru", "Leh1(Sig Cen)", "Leh ICN", "Lukung", "North Pullu", "Nimmoo", "Nurla", "Pandras", "Partapur", "Pather Sahib", "Phobrang A/ Phobrang", "Tyaksi", "Batalik");
    var lehLatitude = new Array("34.152294", "35.207401", "34.399932", "34.443718", "34.336708", "34.062561", "33.360544", "33.603325", "33.197570", "32.948025", "32.790801", "34.561261", "34.278978", "34.555344", "33.920242", "34.283607", "34.157607", "34.147062", "33.996381", "34.335167", "34.202288", "34.322687", "34.500326", "34.659994", "34.217192", "34.069505", "34.911078", "34.701113");
    var lehLongitude = new Array("77.577288", "77.204699", "75.840172", "75.838873", "76.571472", "77.929990", "78.341231", "78.656402", "78.952308", "79.211467", "79.001924", "76.593450", "77.604741", "76.134528", "77.739140", "76.773153", "77.580303", "77.556880", "78.412793", "77.642595", "77.337597", "76.977742", "75.616213", "77.448531", "77.375927", "78.440038", "76.804089", "76.353049");
    var lehHeader = new Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    var lehPoint = null;
    for (var l = 0; l < lehLocations.length; l++) {
        lehPoint = new nokia.maps.geo.Coordinate(parseFloat(lehLatitude[l]), parseFloat(lehLongitude[l]));
        map.objects.add(LehLocationMarker(lehHeader[l], lehLocations[l], lehPoint));
    }
}
function LehLocationMarker(lehHeader, locationName, point) {
    var lehMarker;
    var lehIcon = null;
    if (lehHeader == 1) { lehIcon = '../images/lehHeader.svg'; }
    else { lehIcon = '../images/lehLocation.svg'; }
    var lehBubbleMessage = '';
    lehBubbleMessage = '<div style="text-align:left;"><table style="direction:left" cellspacing=5 class=\'InfoBubble\'>';
    lehBubbleMessage += '<tr><td><b>Location Name :</b></td><td>' + locationName + '</td>';
    lehBubbleMessage += '</tr></table><div>';

    var bubble = null;
    if (bubble) { infoBubble.closeAll(); }

    var coordinate;
    var OpenBubble = function (evt) {
        if (bubble) infoBubble.closeAll();
        //Set Info Bubble styles(Rounded like Cornors etc.) 
        infoBubbleStyle();
        coordinate = evt.currentTarget.coordinate;
        bubble = infoBubble.openBubble(lehBubbleMessage, coordinate);
    }
    //Event to close bubble template
    var CloseBubble = function (evt) {
        infoBubble.closeAll();
    }

    var myLehListener = {
        "mouseover": [OpenBubble, true, null],
        "click": [OpenBubble, true, null]
    };
    map.addListener("click", function (evt) {
        if (bubbles) infoBubble.closeAll();
    });
    lehMarker = new nokia.maps.map.Marker(
            point, {
                visibility: true,
                icon: new H.map.Icon(lehIcon, { anchor: new H.math.Point(9, 12) }),
                eventListener: myLehListener
            });


    return lehMarker;
}

/********************************************End For Demo******************************************/

/*************** To Display Vehicle current position in Ticket module *******Ranjith 07-June-2016*********************/
function loadTicketVehicle() {
    isShowLandmarkPlotter = 0;
    isShowGeozonePlotter = false;
    //document.getElementById("map-legend").innerHTML = iconLegendTextTicketVehicle();
    try {
        if (map) map.removeObjects(map.getObjects());
    }
    catch (Error) {
    }
    try {
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = gridViewControl.width; //document.body.clientWidth ;//document.documentElement.clientWidth-35//screen.width - 35;
        }


        if (document.getElementById('chart-dsply') != null) {
            //document.getElementById('chart-dsply').style.width = document.body.clientWidth + 'px';
            document.getElementById('chart-dsply').style.height = ((document.body.clientHeight / 2) - 20) + 'px';
            document.getElementById('wcTempChart').style.width = document.body.clientWidth + 'px';
            document.getElementById('wcTempChart').style.height = ((document.body.clientHeight / 2) - 20) + 'px';
            document.getElementById('chartWidth').value = document.body.clientWidth;
            document.getElementById('chartHeight').value = ((document.body.clientHeight / 2) - 20);
        }
        if (document.getElementById('map-dsply_cpt') != null) {
            document.getElementById('map-dsply_cpt').style.width = document.body.clientWidth;
            //document.getElementById('map-dsply_cpt').style.height = (document.body.clientHeight / 2) + 'px';
        }

        if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1 || location.pathname.indexOf("VehicleSummary.aspx") != -1) {
            document.getElementById('map-dsply').style.height = 500 + 'px';
            document.getElementById('grid-dsply').style.height = 500 + 'px';
        }
        else {
            document.getElementById('map-dsply').style.height = (document.body.clientHeight) + 'px';
        }

        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            //context menu

            map = new H.Map(document.getElementById("map-dsply"),
            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 mapsjs.mapevents.MapEvents(map);

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

            mapEvents = new H.mapevents.MapEvents(map); //mapsjs.mapevents.MapEvents(map);

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

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

            ui.addControl('zoomRectangle', new H.ui.ZoomRectangle());
            ui.getControl('zoomRectangle').setAlignment('bottom-right');

            //ui.removeControl('mapsettings');
            ui.removeControl('scalebar');
            ui.getControl('mapsettings').setAlignment('top-left');
            ui.getControl('zoom').setAlignment('left-middle');
            //ui.getControl('mapsettings').removeChild(new H.ui.base.Element("div", "H_btn"));
            //var child = ui.getControl('mapsettings').getChildren();
            //ui.getControl('mapsettings').el.childNodes[0].removeNode();
            if (location.pathname.indexOf("VehicleSummary.aspx") != -1) {
                //ui.removeControl('zoomRectangle');
            }

            //createContextMenu(map);

            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value == "LanguageArNew") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'Ar');
                    LoadTime = null;
                }

                else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'hin');
                    LoadTime = null;
                }
            }

            //map.addObserver("baseMapType", defaultObserver);

            //To enable the Mouse wheel Scroll
            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value != "LanguageArNew") {
                    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;
                        }
                    }
                }
            }
        }
        orgCenter = null;
        orgZoomLevel = null;
        __doPostBack('btnView', '');

        return true;
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }


}

function iconLegendTextTicketVehicle() {
    var height = '';

    if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1 || location.pathname.indexOf("VehicleSummary.aspx") != -1) {
        var landmarkIconText = "";
        var landmarkIconTextForFullscreen = "";
        var downIconText = "";
    }
    else {
        var landmarkIconText = '';
        var landmarkIconTextForFullscreen = '';
        var downIconText = (document.getElementById('gvHistory') != null) ? landmarkIconTextForFullscreen : (document.getElementById('gvData') != null) ? landmarkIconText : (document.getElementById('hdnLandmarkEntries') != null && document.getElementById('hdnLandmarkEntries').value.length != 0) ? landmarkIconTextForFullscreen : "";

        downIconText += (document.getElementById('gvHistory') != null) ? "<h3 class='foot'><table><tr>" +
                        "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value, this.checked);clusterDataPoints(clusterPoint, this.checked);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                        "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllLandmark + "</b></span></td>" +
                        "</tr><tr>" +
                        "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkGeozone' style='height:15px;width:15px;' name='chkGeozone' onclick='PlotGeozone(this.checked,\"M\");'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                        "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllGeozone + "</b></span></td>" +
                        "</tr><tr>" +
                          "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkRoute' style='height:15px;width:15px;' name='chkRoute' onclick='DrawRoute(this);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                          "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VShowRoute + "</b></span></td>" +
                        "</tr></table></h3>" :
                        ((document.getElementById('gvData') != null) ?
                        "<h3 class='foot'><table><tr>" +
                        "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value, this.checked);clusterDataPoints(clusterPoint, this.checked);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                        "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllLandmark + "</b></span></td>" +
                        "</tr><tr>" +
                        "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkGeozone' style='height:15px;width:15px;' name='chkGeozone' onclick='PlotGeozone(this.checked,\"M\");'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                        "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='" + VLegendAlign + "'><b>" + VAllGeozone + "</b></span></td>" +
                        "</tr></table></h3>" : "");
    }

    var CurrentPosistion = (document.getElementById('gvHistory') != null) ? "<tr>" +
                       "  <td style='padding-left:2px'><img src='../images/down.svg' alt='current location' style='height:15px;width:15px'/></td>" +
                       "  <td align=" + VLegendAlign + "><span class='txt' id='spLocation' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VCurrLocation + "</span></td>" +
                       "</tr>" : '';

    var legendText = "<div class='panel' align='center' id='lnkLegend'> <h2><b>" + VLegendHeader + "</b></h2><div class='panelcontent'><table id='tblLegend' align='right'" + height + " style='direction:" + VDirection + ";'>" +
                "<tr><td align='right' style='padding: 6px 0px 6px 6px;'>" +
                 "<table cellpadding='2' cellspacing='2' align='right' width='112px' " +
                 ((location.pathname.indexOf("FullscreenMap.aspx") != -1 && location.search.indexOf("?pMy9nEs9WLFPu5OGp76JWA==") != -1) ?
                 "height='20px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.svg' alt='Alarms' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
                 "</tr>" + CurrentPosistion + "</table></td></tr></table>"
                 :
                 "height='114px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/Device_Offline.png' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + "Offline" + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOn + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/orange-1_.svg' alt='Ignition Off' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOff + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/1_.svg' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VMoving + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/pink-1_.svg' alt='Idling' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt'  id='spIdling' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIdling + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/3.svg' alt='moving' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VOthers + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/mapit-9_.svg' alt='sleep' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spSleep' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VSleep + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.svg' alt='Alarms' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
                 "</tr>" + CurrentPosistion + "</table></td></tr></table>") +
                 "</div><b>" + downIconText + "</b></div>";
    return legendText;
}
/********************************End of Current vehicle location for Lease Management*********************************************/

/*************** To Display Vehicle current position in Guest module *******Ranjith 07-June-2016*********************/
function loadGuestVehicle() {
    isShowLandmarkPlotter = 0;
    isShowGeozonePlotter = false;
    try {
        if (map) map.removeObjects(map.getObjects());
    }
    catch (Error) {
    }
    try {
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = gridViewControl.width; //document.body.clientWidth ;//document.documentElement.clientWidth-35//screen.width - 35;
        }

        if (document.getElementById('map-dsply_cpt') != null) {
            document.getElementById('map-dsply_cpt').style.width = document.body.clientWidth;
            //document.getElementById('map-dsply_cpt').style.height = (document.body.clientHeight / 2) + 'px';
        }
        document.getElementById('map-dsply').style.height = (document.body.clientHeight) / 2.5 + 'px';


        if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            //context menu

            map = new H.Map(document.getElementById("map-dsply"),
            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 mapsjs.mapevents.MapEvents(map);

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

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

            //ui.addControl('zoomRectangle', new H.ui.ZoomRectangle());
            //ui.getControl('zoomRectangle').setAlignment('bottom-right');

            //ui.removeControl('mapsettings');
            ui.removeControl('scalebar');
            //ui.getControl('mapsettings').setAlignment('top-left');
            //ui.getControl('zoom').setAlignment('left-middle');
            //ui.getControl('mapsettings').removeChild(new H.ui.base.Element("div", "H_btn"));
            //var child = ui.getControl('mapsettings').getChildren();
            //ui.getControl('mapsettings').el.childNodes[0].removeNode();
            //createContextMenu(map);

            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value == "LanguageArNew") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'Ar');
                    LoadTime = null;
                }

                else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                    maptype = 'normal.day';
                    changeTileProvider(maptype, 'hin');
                    LoadTime = null;
                }
            }

            //map.addObserver("baseMapType", defaultObserver);

            //To enable the Mouse wheel Scroll
            if (document.getElementById("hdnlang") != null) {
                if (document.getElementById("hdnlang").value != "LanguageArNew") {
                    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;
                        }
                    }
                }
            }
        }
        orgCenter = null;
        orgZoomLevel = null;
        __doPostBack('btnView', '');

        return true;
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }


}
function DisplayMapItguest(latlng, pageName, mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
    datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible,
    speedCaption, addLandmarkCaption, isVehicleVisbile, vehicleCaption, isPolylineVisible, driverNameCaption, isDriverNameVisible) {
    Array.clear(clusterMarkers);

    try {
        if (mapItMarkers == null) {
            mapItMarkers = new Array();
        }
        else {
            //for (var j = 0; j < mapItMarkers.length; j++) {
            //    map.removeObject(mapItMarkers[j]);
            //}
            mapItMarkers = new Array();
        }

        if (document.getElementById("hdnlang") != null) {
            if (document.getElementById("hdnlang").value != "LanguageArNew") {
                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;
                    }
                }
            }
        }



        if (pageName == 'H') {

            PerformScrollSetting();
            CheckMapItBoxes();
            SetDivPosition();
        }

        var bounds = null; // new GLatLngBounds();
        ltMapIT = latlng.split('~&~');
        if (pageName == 'M' || pageName == 'MF') {
            if (mkr_group != null && mkr_group.getObjects().length > 0) {
                mkr_group.removeObjects(mkr_group.getObjects());
            }
            if (group != null && group.getObjects().length > 0) {
                group.removeObjects(group.getObjects());
            }
        }

        clusterPoint_Monitor.length = 0;
        clusterMarkerArray = new Array();
        markerPlotV3 = new Array();
        for (var i = 0; i <= ltMapIT.length - 1; i++) {
            if (ltMapIT[i] == "") {
            }
            else {
                var lng = new Array();
                lng = ltMapIT[i].split("~#~");
                markerPlotV3.push(parseFloat(lng[0]));
                markerPlotV3.push(parseFloat(lng[1]));
                var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
                lntlngs.push(point);
                clusterPoint_Monitor.push(new H.clustering.DataPoint(parseFloat(lng[0]), parseFloat(lng[1]), 1, { id: lng[5] }));
                if (pageName == 'M' || pageName == 'MF') {
                    var mapMarker = MapIT_MarkerGuest(point, lng[4], lng[3], lng[5], lng[6], i, lng[2], lng[2],
                                      lng[7], mainCaption, isVehicleVisbile, vehicleCaption, isMessageVisbile, msgCaption, isAddressVisible, addressCaption, isSpeedVisible, speedCaption,
                                      isLandmarkVisible, landmarkCaption, lng[8], addLandmarkCaption, isDriverNameVisible, driverNameCaption, lng[9], lng[10], lng[11], lng[12]);
                    mapMarker.setData(lng[5]);
                    var zoom = new Array();
                    clusterMarkerArray.push(mapMarker);
                    clusterMarkers.push(mapMarker.getGeometry());
                }
                else if (pageName == 'H') {
                    var mapMarker = createMarker(point, lng[5], lng[3], lng[4], 'MapIt', i, lng[2], lng[6],
                        lng[7], lng[8], lng[9], mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
                        datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                         isSpeedVisible, speedCaption, addLandmarkCaption);
                    Array.add(mapItMarkers, mapMarker);
                    map.addObject(mapMarker);
                    clusterMarkers.push(mapMarker.getGeometry());
                }
                else if (pageName == 'HF') {
                    var mapMarker = createMarker(point, lng[5], lng[3], lng[4], '1', i, lng[2], lng[6],
                        lng[7], lng[8], lng[9], mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
                        datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                         isSpeedVisible, speedCaption, addLandmarkCaption);
                    Array.add(mapItMarkers, mapMarker);
                    map.addOverlay(mapMarker);
                    clusterMarkers.push(mapMarker.getGeometry());
                }
            }
        }

        if (pageName == 'H' || pageName == 'HF') {
            mkr_group = new H.map.Group();
            mkr_group.addObjects(((pageName == 'M' || pageName == 'MF') ? clusterMarkerArray : mapItMarkers));
            map.addObject(mkr_group);
            map.setViewBounds(mkr_group.getBounds());
        }

        //Sakthi 15-Dec-2014 For Map Clustering
        if (location.pathname.indexOf("FullscreenMap.aspx") != -1 && location.search.indexOf("?pMy9nEs9WLFPu5OGp76JWA==") != -1) {
            mkr_group = new H.map.Group();
            mkr_group.addObjects(clusterMarkerArray);
            map.addObject(mkr_group);
            map.setViewBounds(mkr_group.getBounds());
        }
        else if (pageName == 'M' || pageName == 'MF') {
            //initialiseSVGParser_Monitor();
            mkr_group = new H.map.Group();
            mkr_group.addObjects(clusterMarkerArray);
            map.addObject(mkr_group);
            clusterDataPoints_Monitor(clusterPoint_Monitor, true);
            //map.setViewBounds(mkr_group.getBounds());
            map.getViewModel().setLookAtData({
                bounds: mkr_group.getBoundingBox()
            });
        }

        if (pageName == 'M') {
            if (MapView.length > 0) {
                map.setCenter(MapView[0]);
                Array.clear(MapView);
            }
        }
        else if (pageName == 'MF') {
            if (MapViewFullScreen.length > 0) {
                map.setCenter(MapViewFullScreen[0]);
                map.setZoom(MapViewFullScreen[1]);
                Array.clear(MapViewFullScreen);
            }
        }
        HidePopUp();
    }
    catch (Error) {
        // alert(Error);
    }
}

function MapIT_MarkerGuest(point, heading, speed, VehName, id, i_No, addr, dist, msgDetails, mainHeading, isVehicleVisbile, vehCaption, isMessageVisbile, msgCaption, isAddressVisbile, addrCaption, isSpeedVisbile, speedCaption,
                        isLandmarkVisible, landmarkCaption, landmarkName, canAddLandmark, isDriverNameVisible, driverNameCaption, driverName, driverPhoto, driverPhno, PhnoCaption) {

    var temp1 = "'" + point + "'";
    var temp = temp1.substring(2, temp1.length - 2);
    temp = "'" + point.lat + "," + point.lng + "'";

    var icon = null;
    icon = '../images/W.svg';

    var marker = new H.map.Marker
        (
            point, {
                visibility: true,
                icon: new H.map.Icon(icon, { anchor: new H.math.Point(9, 12) })
            });
    return marker;
}



/********************************End of Current vehicle location for Guest Module*********************************************/
/*Geozone Code for monitor screen*/
var r1 = null;
var r2 = null;
var myrectangle;
var dragRectangle;
var first = '';
var second = '';
var clandmark = new H.map.Group();
var cGeozone = new H.map.Group();
var maxMarkers = 5, maxGeozoneMarkers = 'Geozones are restricted to have only <#maxMarkers#> points !';
var gMarkers = new Array();
var gMarker;
var polyArray = new Array();
var polyStrip = new H.geo.LineString();
var polyShape;
var mapClick = true;
var IsDragStart = false;
var PrevCoordinates = null;
var CurrCoordinates = null;
var welcome = null;

function fnSetRadiusView() {
    var dRadiusView = document.getElementById('dGeozoneRadiusDiv');
    if (dRadiusView != null && circleUnits == 'CR') {
        dRadiusView.setAttribute('class', 'form-group');
    }
    else { dRadiusView.setAttribute('class', 'ControlHide'); }
}


function fnSetGeoTypes(id) {
    var gCircleView = document.getElementById('typCircular');
    var gRectView = document.getElementById('typRectangle');
    var gPolyView = document.getElementById('typPolygon');
    var muGeozoneDetails = document.getElementById('muGeozoneDetails');
    var dRadiusView = document.getElementById('dGeozoneRadiusDiv');
    if (muGeozoneDetails != null) {
        muGeozoneDetails.setAttribute('class', 'H_btn H_disabled');
    }

    if (document.getElementById("hdnGeozoneType") != null) {
        document.getElementById("hdnGeozoneType").value = id;
    }

    switch (id) {
        case 1:
            if (gCircleView != null) {
                gCircleView.setAttribute('class', 'H_btn');
            }
            if (gRectView != null) {
                gRectView.setAttribute('class', 'H_btn H_active');
                fnSetGeozones(2);
            }
            if (gPolyView != null) {
                gPolyView.setAttribute('class', 'H_btn');
            }
            if (dRadiusView != null) {
                dRadiusView.setAttribute('class', 'ControlHide');
            }
            break;
        case 2:
            if (gCircleView != null) {
                gCircleView.setAttribute('class', 'H_btn');
            }
            if (gRectView != null) {
                gRectView.setAttribute('class', 'H_btn');
            }
            if (gPolyView != null) {
                gPolyView.setAttribute('class', 'H_btn H_active');
                fnSetGeozones(3);
            }
            if (dRadiusView != null) {
                dRadiusView.setAttribute('class', 'ControlHide');
            }
            break;
        case 3:
            if (gCircleView != null) {
                gCircleView.setAttribute('class', 'H_btn H_active');
                fnSetGeozones(1);
            }
            if (dRadiusView != null) {
                dRadiusView.setAttribute('class', 'form-group');
            }
            if (gRectView != null) {
                gRectView.setAttribute('class', 'H_btn');
            }
            if (gPolyView != null) {
                gPolyView.setAttribute('class', 'H_btn');
            }
            break;
    }
}
function fnEnableGeozones() {
    var geoButton = document.getElementById('geozoneButton');
    var geoView = document.getElementById('geozoneView');
    var landmarkButton = document.getElementById('landmarkButton');
    var typRectangle = document.getElementById('typRectangle');
    var typPolygon = document.getElementById('typPolygon');
    var typCircular = document.getElementById('typCircular');
    var muGeozoneDetails = document.getElementById('muGeozoneDetails');
    if (isCreateGeozone == false) {
        isCreateGeozone = true;
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn H_active');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_open H_top H_left');
        }
        if (landmarkButton != null) {
            landmarkButton.setAttribute('class', 'H_btn');
            isCreateLandmark = false;
        }
        if (typRectangle != null) {
            typRectangle.setAttribute('class', 'H_btn');
        }
        if (typPolygon != null) {
            typPolygon.setAttribute('class', 'H_btn');
        }
        if (typCircular != null) {
            typCircular.setAttribute('class', 'H_btn');
        }
        if (muGeozoneDetails != null) {
            muGeozoneDetails.setAttribute('class', 'H_btn H_disabled');
        }
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        try {
            map.removeEventListener("tap", welcome);
        }
        catch (ex) { }
    }
    else {
        isCreateGeozone = false;
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_top H_left');
        }
        map.removeEventListener("tap", getCoordinate, false);
        map.removeEventListener("pointermove", mapDragRectangle, false);
        map.removeEventListener("tap", Getlatlng);
        map.removeEventListener("tap", leftClick);
        map.removeEventListener("mousemove", mapDragRectangle);
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
    }
}
function fnEnableTooltip() {
    var geoButton = document.getElementById('Tooltip');
    var geoView = document.getElementById('Tooltipmenu');
    //var landmarkButton = document.getElementById('landmarkButton');
    //var typRectangle = document.getElementById('typRectangle');
    //var typPolygon = document.getElementById('typPolygon');
    //var typCircular = document.getElementById('typCircular');
    //var muGeozoneDetails = document.getElementById('muGeozoneDetails');
    if (isCreateGeozone == false) {
        isCreateGeozone = true;
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn H_active');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_open H_top H_right');
        }
        //if (landmarkButton != null) {
        //    landmarkButton.setAttribute('class', 'H_btn');
        //    isCreateLandmark = false;
        //}
        //if (typRectangle != null) {
        //    typRectangle.setAttribute('class', 'H_btn');
        //}
        //if (typPolygon != null) {
        //    typPolygon.setAttribute('class', 'H_btn');
        //}
        //if (typCircular != null) {
        //    typCircular.setAttribute('class', 'H_btn');
        //}
        //if (muGeozoneDetails != null) {
        //    muGeozoneDetails.setAttribute('class', 'H_btn H_disabled');
        //}
        //if (clandmark != null && clandmark.getObjects().length > 0) {
        //    clandmark.removeObjects(clandmark.getObjects());
        //}
        //if (cGeozone != null && cGeozone.getObjects().length > 0) {
        //    cGeozone.removeObjects(cGeozone.getObjects());
        //}
        try {
            map.removeEventListener("tap", welcome);
        }
        catch (ex) { }
    }
    else {
        isCreateGeozone = false;
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_top H_left');
        }
        map.removeEventListener("tap", getCoordinate, false);
        map.removeEventListener("pointermove", mapDragRectangle, false);
        map.removeEventListener("tap", Getlatlng);
        map.removeEventListener("tap", leftClick);
        map.removeEventListener("mousemove", mapDragRectangle);
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
    }
}


var fnSetGeozones = function (type) {
    if (clandmark != null && clandmark.getObjects().length > 0) {
        clandmark.removeObjects(clandmark.getObjects());
    }
    if (cGeozone != null && cGeozone.getObjects().length > 0) {
        cGeozone.removeObjects(cGeozone.getObjects());
    }

    if (document.getElementById('hdnRestriction_G') != null && document.getElementById('hdnRestriction_G').value == '0') {
        if (document.getElementById("hdnlang").value == "LanguageArNew") {
            TrinetraCustomAlerts('بلغ الحد الأقصى لعدد Geozone! . لا يمكن إنشاء أكثر Geozone.');
        }
        else if (document.getElementById("hdnlang").value == "LanguageHindi") {
            TrinetraCustomAlerts('Geozone की अधिकतम संख्या तक पहुंच! . अधिक Geozone नहीं बना सकता है.');
        } else {
            TrinetraCustomAlerts('Maximum number of Geozones reached. Cannot create more Geozone.');
        }
        return;
    }

    if (type == 3) {
        circleUnits = 'PL';
        gMarkers.length = 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 if (type == 2) {
        circleUnits = 'RC';
        gMarkers.length = 0;
        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);
        dragRectangle = false;
    }
    else {
        circleUnits = 'CR';
        myrectangle = null;
        gMarkers.length = 0;
        map.removeEventListener("tap", getCoordinate);
        map.removeEventListener("mousemove", mapDragRectangle);
        map.removeEventListener("tap", leftClick);
        map.removeEventListener("tap", Getlatlng);
        eventOnclick = map.addEventListener("tap", Getlatlng);
    }
};
function Getlatlng(overlay, point) {
    //  var cord = map.pixelToGeo(evt.displayX, evt.displayY);
    if (!point || point == '') {
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
        var centerPoint = new H.geo.Point(parseFloat(point.lat), parseFloat(point.lng));
        var center = map.getCenter();
        with (Math) {
            var d = 200 / 6378.8;
            d = d / 1000;

            var lat1 = (PI / 180) * (center.lat); // radians
            var lng1 = (PI / 180) * (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 czPoint = new H.geo.Point(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
            }

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

            if (document.getElementById('hdnGeoCoordinates') != null) {
                document.getElementById('hdnGeoCoordinates').value = point.lat + ',' + point.lng;
            }

            var icon = null;
            icon = '../images/flag_8.svg';
            var bubble = null;

            var OpenBubble = function (evt) {
                var coordinate = evt.target.getGeometry();
                var landmarkAddress = '';
                var rvrGeocodingParameters = {
                    prox: coordinate.lat + "," + coordinate.lng + ",200",
                    mode: 'retrieveAddresses',
                    maxresults: 1,
                    language: 'en'
                };
                geocoder.reverseGeocode(rvrGeocodingParameters, function (result) {
                    try {
                        landmarkAddress = result.Response.View[0].Result[0].Location.Address.Label;
                        var ltlng = result.Response.View[0].Result[0].Location.Latitude + ',' + result.Response.View[0].Result[0].Location.Longitude;

                        getlngs_geozone(ltlng, landmarkAddress);
                    }
                    catch (e) {
                        console.log(e);
                        landmarkAddress = 'exception';
                    }
                }, function (e) {
                    console.log(e);
                    landmarkAddress = 'failure';
                });
            }

            var marker = new H.map.Marker(centerPoint, {});
            //{
            //    icon: new H.map.Icon(icon, { anchor: new H.math.Point(2, 22) })
            //});
            //marker.addEventListener('tap', OpenBubble, false);
            clandmark.addObject(marker);
            map.addObject(clandmark);
            //map.setViewBounds(clandmark.getBounds());
            map.getViewModel().setLookAtData({
                bounds: clandmark.getBoundingBox()
            });

            var muGeozoneDetails = document.getElementById('muGeozoneDetails');
            if (muGeozoneDetails != null) {
                muGeozoneDetails.setAttribute('class', 'H_btn');
            }
        }
    }
}
function getCoordinate(overlay, point) {
    if (!point || point == '') {
        point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
    }

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

        var marker1 = r1;
        var marker2 = 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('hdnGeoCoordinates') != null) {
            document.getElementById('hdnGeoCoordinates').value = polyArray;
        }

        r1 = ''
        r2 = ''


        try {
            //map.setViewBounds(myrectangle.getBounds());
            map.getViewModel().setLookAtData({
                bounds: myrectangle.getBoundingBox()
            });
            var muGeozoneDetails = document.getElementById('muGeozoneDetails');
            if (muGeozoneDetails != null) {
                muGeozoneDetails.setAttribute('class', 'H_btn');
            }
        }
        catch (er) {
            TrinetraCustomAlerts(er);
        }
        r1 = first = '';
        r2 = second = '';
    }
}
function mapClickRectangle(overlay, point) {
    if (point == null) { return; }

    if (!r1) {   // First click
        r1 = point;
        myrectangle = null;
        dragRectangle = true;
    }
    else {   // Second click
        dragRectangle = false;
        draw_rectangle(r1, point);
        r2 = point;
        r1 = r2 = '';
        if (cGeozone != null)
            map.setViewBounds(cGeozone.getBounds());
        else if (clandmark != null)
            map.setViewBounds(clandmark.getBounds());
    }
}
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 (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)), {
                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)), {
                style: { strokeColor: "rgba(0,0,128,1)", lineWidth: 1, fillColor: "rgba(65, 105, 225, 0.5)" } //stroke color : "#fd942d" fill color : "#859CB3"
            });
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        var OpenBubble = function (evt) {
            getlngs_geozone('', '');
        }
        //myrectangle.addEventListener('tap', OpenBubble, false);
        cGeozone.addObject(myrectangle);
        map.addObject(cGeozone);
        map.addObject(clandmark);
    }
}
function leftClick(overlay, point) {
    if (true) {
        if (!point || point == '') {
            point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
            //map.pixelToGeo(overlay.displayX, overlay.displayY);
        }
        if (point) {
            maxMarkers = 5;

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

                if ((gMarkers.length + 1) > maxMarkers) {
                    TrinetraCustomAlerts(maxGeozoneMarkers.replace("<#maxMarkers#>", maxMarkers));
                    return false;
                }
            }

            // Make markers draggable
            if (isview == 0) {
                gMarker = new H.map.Marker(point, {});
                gMarker.draggable = true;
            }
            else {
                gMarker = new H.map.Marker(point, {});
                gMarker.draggable = true;
            }

            gMarkers.push(gMarker);
            clandmark.addObject(gMarker);
            map.addObject(clandmark);
            if (isview == 0) {
                gMarker.addEventListener("dragstart", function (evt) { behavior.disable(); }, false);
                gMarker.addEventListener("drag", function (evt) {
                    CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                    PrevCoordinates = evt.target.getGeometry();
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                });

                gMarker.addEventListener("dragend", function (evt) {
                    behavior.enable();
                    CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                    PrevCoordinates = evt.target.getGeometry();
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                });

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

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

        polyPoints.length = 0;
        polyArray.length = 0;
        polyStrip = new H.geo.LineString();
        for (i = 0; i < gMarkers.length; i++) {
            if (IsDragStart) {
                gMarkers[i].setPosition(gMarkers[i].getPosition() == PrevCoordinates ? CurrCoordinates : gMarkers[i].getPosition());
            }

            polyPoints.push(gMarkers[i].getPosition());
            polyStrip.pushPoint(gMarkers[i].getPosition());
            var appendvalues = gMarkers[i].getPosition().lat + ',' + gMarkers[i].getPosition().lng + '#';
            polyArray.push(appendvalues);
        }

        if (document.getElementById('hdnGeoCoordinates') != null) {
            document.getElementById('hdnGeoCoordinates').value = polyArray;
        }

        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: .3, fillColor: filClr }
        });

        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        var OpenBubble = function (evt) {
            getlngs_geozone('', '');
        }
        //polyShape.addEventListener('tap', OpenBubble, false);
        cGeozone.addObject(polyShape);
        map.addObject(cGeozone);
        var muGeozoneDetails = document.getElementById('muGeozoneDetails');
        if (muGeozoneDetails != null) {
            muGeozoneDetails.setAttribute('class', 'H_btn');
        }
    }
    catch (e) {
        //alert(e);
    }
}
function ValidateGeozonePanelEntries() {

    var geozoneNameField = document.getElementById('txtGeozoneName');
    var directionField = document.getElementById('ddlGeozoneDirection')
    var severityField = document.getElementById('ddlGeozoneSeverity');
    var categoryField = document.getElementById('ddlGeozoneCategory');
    var txtRadius = document.getElementById('txtGeozoneRadius');
    s = geozoneNameField.value.replace(/(^\s*)|(\s*$)/gi, "");
    s = s.replace(/[ ]{2,}/gi, " ");
    s = s.replace(/\n /, "\n");

    var isError = false;
    var alertMessage = '';

    if (s.length == 0 || s == 'Geozone Name' || s == 'اسم المنطقة الجغرافية') {
        alertMessage = Alert_EnterGeozone;
        isError = true;
        geozoneNameField.focus();
        geozoneNameField.style.backgroundColor = 'lightyellow';
    }
    else {
        geozoneNameField.style.backgroundColor = 'white';
    }

    if (severityField.value == '- Select Severity -') {
        alertMessage += (alertMessage.length == 0 ? '' : '</br>') + Alert_SelectSeverity;
        if (!isError) {
            severityField.focus();
            isError = true;
        }
        severityField.style.backgroundColor = 'lightyellow';
    }
    else {
        severityField.style.backgroundColor = 'white';
    }

    if (directionField.value == '- Select Direction -') {
        alertMessage += (alertMessage.length == 0 ? '' : '</br>') + Alert_SelectDirection;
        if (!isError) {
            directionField.focus();
            isError = true;
        }
        directionField.style.backgroundColor = 'lightyellow';
    }
    else {
        directionField.style.backgroundColor = 'white';
    }

    if (categoryField.value == '- Select Category -') {
        alertMessage += (alertMessage.length == 0 ? '' : '</br>') + Alert_SelectCategory;
        if (!isError) {
            categoryField.focus();
            isError = true;
        }
        categoryField.style.backgroundColor = 'lightyellow';
    }
    else {
        categoryField.style.backgroundColor = 'white';
    }

    if (circleUnits == 'CR') {
        if (RemoveSpaces(txtRadius).length == 0) {
            alertMessage = (isError ? alertMessage + '</br>' : '') + Alert_EnterRadius;
            if (!isError) {
                txtRadius.focus();
            }
            isError = true;
            txtRadius.style.backgroundColor = 'lightyellow';
        }
        else if (txtRadius.value < 10) {
            alertMessage = (isError ? alertMessage + '</br>' : '') + Alert_EnterRadius;
            if (!isError) {
                txtRadius.focus();
            }
            isError = true;
            txtRadius.style.backgroundColor = 'lightyellow';
        }
        else {
            txtRadius.style.backgroundColor = 'white';
        }
    }
    if (isError) {
        TrinetraCustomAlerts(alertMessage);
        return false;
    }
    else {
        return true;
    }
}
/*end geozone*/

/*landmark code for monitor screen*/
function fnEnableLandmarks() {
    var landmarkButton = document.getElementById('landmarkButton');
    var geoButton = document.getElementById('geozoneButton');
    var geoView = document.getElementById('geozoneView');
    if (isCreateLandmark == false) {
        if (landmarkButton != null) {
            landmarkButton.setAttribute('class', 'H_btn H_active');
        }
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_top H_left');
            isCreateGeozone = false;
        }
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }

        try {
            map.removeEventListener("tap", getCoordinate, false);
            map.removeEventListener("pointermove", mapDragRectangle, false);
            map.removeEventListener("tap", Getlatlng);
            map.removeEventListener("tap", leftClick);
            map.removeEventListener("mousemove", mapDragRectangle);
        }
        catch (ex) { }

        welcome = function (evt) {

            if (document.getElementById('hdnRestriction_L') != null && document.getElementById('hdnRestriction_L').value == '0') {
                if (document.getElementById("hdnlang").value == "LanguageArNew") {
                    TrinetraCustomAlerts('بلغ الحد الأقصى لعدد معالم! . لا يمكن إنشاء أكثر معالم.');
                }
                else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                    TrinetraCustomAlerts('स्थलों की अधिकतम संख्या तक पहुंच! . अधिक मील का पत्थर नहीं बना सकता है.');
                } else {
                    TrinetraCustomAlerts('Maximum number of Landmarks reached. Cannot create more Landmarks.');
                }
                return;
            }

            if (clandmark != null && clandmark.getObjects().length > 0) {
                clandmark.removeObjects(clandmark.getObjects());
            }
            var cord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY)
            var centerPoint = new H.geo.Point(parseFloat(cord.lat), parseFloat(cord.lng));
            var center = map.getCenter();
            with (Math) {
                var d = 200 / 6378.8;
                d = d / 1000;

                var lat1 = (PI / 180) * (center.lat); // radians
                var lng1 = (PI / 180) * (center.lng); // radians
                var centerPoint;
                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)));
                }

                if (d < 1.5678565720686044) {
                    circle = new H.map.Circle(
                                centerPoint,
                                200,
                                {
                                    style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: "rgba(198,155,204,0.5)" } // "#C69ACC" }
                                }
                            );
                }
                else {
                    circle = new H.map.Circle(
                                centerPoint,
                                200,
                                {
                                    style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: canClearCircle ? '#000000' : "rgba(198,155,204,0.5)" } //'#C69ACC' }
                                }
                            );
                }
                clandmark.addObject(circle);


                var icon = null;
                icon = '../images/flag_8.svg';
                var bubble = null;

                var OpenBubble = function (evt) {
                    var coordinate = evt.target.getGeometry();
                    var landmarkAddress = '';
                    var rvrGeocodingParameters = {
                        prox: coordinate.lat + "," + coordinate.lng + ",200",
                        mode: 'retrieveAddresses',
                        maxresults: 1,
                        language: 'en'
                    };
                    geocoder.reverseGeocode(rvrGeocodingParameters, function (result) {
                        try {
                            landmarkAddress = result.Response.View[0].Result[0].Location.Address.Label;
                            var ltlng = result.Response.View[0].Result[0].Location.DisplayPosition.Latitude + ',' + result.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
                            getlngs(ltlng, landmarkAddress);
                        }
                        catch (e) {
                            console.log(e);
                            landmarkAddress = 'exception';
                        }
                    }, function (e) {
                        console.log(e);
                        landmarkAddress = 'failure';
                    });
                }

                var marker = new H.map.Marker(
                centerPoint, {
                    icon: new H.map.Icon(icon, { anchor: new H.math.Point(2, 22) })
                });
                marker.addEventListener('tap', OpenBubble, false);
                clandmark.addObject(marker);
                map.addObject(clandmark);
                //map.setViewBounds(clandmark.getBounds()); 
                map.getViewModel().setLookAtData({
                    bounds: clandmark.getBoundingBox()
                });
            }
        };

        map.addEventListener("tap", welcome);
        isCreateLandmark = true;
    }
    else {
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (landmarkButton != null) {
            landmarkButton.setAttribute('class', 'H_btn');
        }
        map.removeEventListener("tap", welcome);
        isCreateLandmark = false;
    }
}

/*end landmark*//********************************End of Current vehicle location for Lease Management*********************************************/

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

function PlotAddress() {

    //    if (document.getElementById("txtLocationName").value == "" || document.getElementById("txtLocationName").value == "Name") {
    //        alert(enterLocationName);
    //        document.getElementById("txtLocationName").focus();
    //        return false;
    //    }

    var plotType = document.getElementById('popup_ddlType');
    var street = document.getElementById('popup_txtStreet1');
    //var latitude = document.getElementById('popup_txtLat1');
    //var longitude = document.getElementById('popup_txtLong1');

    //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();
    return true;
}

function ShowAddress() {
    try {
        loadForLandMark();
        var image = "../images/flag_2.svg";         //"../images/End_point_legend.svg";   //
        LandMarkImage = image;
        if (document.getElementById('popup_ddlType').value == 'addr') {
            if (map) {
                map.removeObjects(map.getObjects());

                search = FrameStreetAddress();

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

                //======= GeoCode Callback function ======
                geo.geocode({ 'searchText': search, language: 'en' },
                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>";
                            }
                            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);
                            Findplace(p.Latitude, p.Longitude, '', '', 200, 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 + '" ');
                        }
                    }
                });
            }
        }
    }
    catch (error) {
        alert(error);
        TrinetraCustomAlerts('Could not find "' + search + '" ');
        HidePopUp();
    }
}

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

    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.svg") {
        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());

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

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

        if (document.getElementById('popup_txtStreet1').value != '') {
            if (address1 != '') {
                address1 = address1 + ' ' + document.getElementById('popup_txtStreet1').value;
            }
            else {
                address1 = document.getElementById('popup_txtStreet1').value;
            }
        }
        if (document.getElementById('popup_txtcity').value != '' && document.getElementById('popup_txtcity').value != "City" && document.getElementById('popup_txtcity').value != "المدينة") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('popup_txtcity').value;
            }
            else {
                address1 = document.getElementById('popup_txtcity').value;
            }
        }
        if (document.getElementById('popup_txtstate').value != '' && document.getElementById('popup_txtstate').value != "State" && document.getElementById('popup_txtstate').value != "الدولة") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('popup_txtstate').value;
            }
            else {
                address1 = document.getElementById('popup_txtstate').value;
            }
        }
        if (document.getElementById('popup_txtCountry').value != '' && document.getElementById('popup_txtCountry').value != "Country" && document.getElementById('popup_txtCountry').value != "الدولة") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('popup_txtCountry').value;
            }
            else {
                address1 = document.getElementById('popup_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 = "../images/flag_2.svg";
        var point = new H.geo.Point(parseFloat(lat), parseFloat(lng));

        var offsetX = null;
        var offsetY = null;
        if (icon == "../images/flag_2.svg") {
            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(10);

        //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('popup_txtLat1').value = lat;
        //document.getElementById('popup_txtLong1').value = lng;
        //centerPoint = new H.geo.Point(parseFloat(lat), parseFloat(lng));
        //document.getElementById("popup_hdnCoords").value = lat + ',' + lng;
        //document.getElementById("message").innerHTML = "";
        //AddressSuggestionPanelVisibility(false);
        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 = "";
        document.getElementById("pnlAddressLocating").style.display = "none";
        drawCircle_Landmark();
        map.setViewBounds(circle.getBounds());
        LandMarkImage = '';
    }
    catch (Error) {
    }
}

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

function plotDestination(lat, lng) {
    try {

        var icon = "../images/End_point.svg";
        var point = new H.geo.Point(parseFloat(lat), parseFloat(lng));

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

        //Check and clear previous destination point markers.
        clearMapObjects();

        //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.
        objContainer.addObject(marker);

        //Zoom out if to close.
        if (map.getZoom() > 15) map.setZoom(10);

        //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; */

        var routestartendpoints = [];
        routestartendpoints.push({ position: centerPoint });

        //document.getElementById('popup_txtLat1').value = lat;
        //document.getElementById('popup_txtLong1').value = lng;
        centerPoint = new H.geo.Point(parseFloat(lat), parseFloat(lng));
        routestartendpoints.push({ position: centerPoint });

        drawCircle();
        LandMarkImage = '';
        RouteToDestination(routestartendpoints);
    }
    catch (Error) {
    }
}

var routingRequest, routeColor, routeTrafficMode, polylineRoute;
var objContainer = new H.map.Group();
var router = platform.getRoutingService();

function RouteToDestination(waypoints) {
    routeRequestParams = {
        mode: 'fastest;car',
        representation: 'display',
        routeattributes: 'waypoints,summary,shape,legs',
        maneuverattributes: 'direction,action',
        //waypoint0: '11.0123,76.3610',
        //waypoint1: '11.1082,77.3418'  
    };

    for (var i = 0; i < waypoints.length; i++) {
        routeRequestParams["waypoint" + i] = waypoints[i].position.lat + ',' + waypoints[i].position.lng;
    }

    //make a calculateRoute request
    router.calculateRoute(routeRequestParams, onSuccess, onError);
}

function onSuccess(result) {
    var route = result.response.route[0];
    addRouteShapeToMap(route);
    //addManueversToMap(route);
    //addWaypointsToPanel(route.waypoint);
    //addManueversToPanel(route);
    //addSummaryToPanel(route.summary);
    // ... etc.
}

function onError(error) {
    HidePopUp();
    TrinetraCustomAlerts("The routing request failed.");
}

function addRouteShapeToMap(route) {
    clearMapObjects();

    //Event to open bubble template
    var coordinate, summary;
    summary = route.summary;

    var bubbleMessage = '<div style="text-align:left;"><table style="direction:vertical" cellspacing=5 class=\'InfoBubble\'>';
    bubbleMessage += '<tr><td><b>Distance from destination</b>:</td><td>' + (summary.distance / 1000).toFixed(1) + ' km(s).</td></tr>';
    bubbleMessage += '<tr><td><b>Time to reach</b>:</td><td> ' + summary.travelTime.toMMSS() + '</tr></table></div>';    //(in current traffic)';

    if (bubble) infoBubble.close();

    var OpenBubble = function (e) {
        coordinate = map.screenToGeo(e.pointers[0].viewportX, e.pointers[0].viewportY);     //evt.target.getPosition();
        ui.removeBubble(infoBubble);
        infoBubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        bubble = ui.addBubble(infoBubble);
    }
    //Event to close bubble template
    var CloseBubble = function (evt) {
        ui.removeBubble(infoBubble);
    }

    var myListener = {
        "pointermove": [OpenBubble, true, null],
        "tap": [OpenBubble, true, null]
    };

    routeTrafficMode = route.mode.trafficMode;
    var strip = new H.geo.LineString(), routeShape = route.shape, polyline;
    routeShape.forEach(function (point) {
        var parts = point.split(',');
        strip.pushLatLngAlt(parts[0], parts[1]);
    });
    polyline = new H.map.Polyline(strip, {
        style: {
            lineWidth: 8,
            strokeColor: 'rgba(3, 116, 48, 0.7)'
        },
        arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 }
    });
    polylineRoute = polyline;
    polylineRoute.addEventListener("pointermove", OpenBubble);
    polylineRoute.addEventListener("tap", OpenBubble);
    polylineRoute.addEventListener("pointerleave", CloseBubble);
    polylineRoute.addEventListener("tap", CloseBubble);

    objContainer.addObject(polylineRoute);
    // Add the polyline to the map
    map.addObject(objContainer);
    // And zoom to its bounding rectangle
    map.setViewBounds(polyline.getBounds(), true);
}

Number.prototype.toMMSS = function () {
    return Math.floor(this / 60) + ' minute(s) ' + (this % 60) + ' second(s).';
}

function addSummaryToPanel(summary) {
    var summaryDiv = document.createElement('div'),
     content = '';
    content += '<b>Total distance</b>: ' + summary.distance + 'm. <br/>';
    content += '<b>Travel Time</b>: ' + summary.travelTime.toMMSS() + ' (in current traffic)';

    summaryDiv.style.fontSize = 'small';
    summaryDiv.style.marginLeft = '5%';
    summaryDiv.style.marginRight = '5%';
    summaryDiv.innerHTML = content;
    routeInstructionsContainer.appendChild(summaryDiv);
}

function clearMapObjects() {
    try {
        if (polylineRoute != null && objContainer != null)
            objContainer.removeObject(polylineRoute);
        if (objContainer != null && objContainer.getObjects().length > 0)
            objContainer.removeObjects(objContainer.getObjects());
    }
    catch (er) {
    }
    HidePopUp();
}

/*********************************End of Locate Me Functionality******************************************/
/********************************End of Current vehicle location for Lease Management*********************************************/

/*Geozone Code for monitor screen*/
var r1 = null;
var r2 = null;
var myrectangle;
var dragRectangle;
var first = '';
var second = '';
var clandmark = new H.map.Group();
var cGeozone = new H.map.Group();
var maxMarkers = 5, maxGeozoneMarkers = 'Geozones are restricted to have only <#maxMarkers#> points !';
var gMarkers = new Array();
var gMarker;
var polyArray = new Array();
var polyStrip = new H.geo.LineString();
var polyShape;
var mapClick = true;
var IsDragStart = false;
var PrevCoordinates = null;
var CurrCoordinates = null;
var welcome = null;

function fnSetRadiusView() {
    var dRadiusView = document.getElementById('dGeozoneRadiusDiv');
    if (dRadiusView != null && circleUnits == 'CR') {
        dRadiusView.setAttribute('class', 'form-group');
    }
    else { dRadiusView.setAttribute('class', 'ControlHide'); }
}


function fnSetGeoTypes(id) {
    var gCircleView = document.getElementById('typCircular');
    var gRectView = document.getElementById('typRectangle');
    var gPolyView = document.getElementById('typPolygon');
    var muGeozoneDetails = document.getElementById('muGeozoneDetails');
    var dRadiusView = document.getElementById('dGeozoneRadiusDiv');
    if (muGeozoneDetails != null) {
        muGeozoneDetails.setAttribute('class', 'H_btn H_disabled');
    }

    if (document.getElementById("hdnGeozoneType") != null) {
        document.getElementById("hdnGeozoneType").value = id;
    }

    switch (id) {
        case 1:
            if (gCircleView != null) {
                gCircleView.setAttribute('class', 'H_btn');
            }
            if (gRectView != null) {
                gRectView.setAttribute('class', 'H_btn H_active');
                fnSetGeozones(2);
            }
            if (gPolyView != null) {
                gPolyView.setAttribute('class', 'H_btn');
            }
            if (dRadiusView != null) {
                dRadiusView.setAttribute('class', 'ControlHide');
            }
            break;
        case 2:
            if (gCircleView != null) {
                gCircleView.setAttribute('class', 'H_btn');
            }
            if (gRectView != null) {
                gRectView.setAttribute('class', 'H_btn');
            }
            if (gPolyView != null) {
                gPolyView.setAttribute('class', 'H_btn H_active');
                fnSetGeozones(3);
            }
            if (dRadiusView != null) {
                dRadiusView.setAttribute('class', 'ControlHide');
            }
            break;
        case 3:
            if (gCircleView != null) {
                gCircleView.setAttribute('class', 'H_btn H_active');
                fnSetGeozones(1);
            }
            if (dRadiusView != null) {
                dRadiusView.setAttribute('class', 'form-group');
            }
            if (gRectView != null) {
                gRectView.setAttribute('class', 'H_btn');
            }
            if (gPolyView != null) {
                gPolyView.setAttribute('class', 'H_btn');
            }
            break;
    }
}
function fnEnableGeozones() {
    var geoButton = document.getElementById('geozoneButton');
    var geoView = document.getElementById('geozoneView');
    var landmarkButton = document.getElementById('landmarkButton');
    var typRectangle = document.getElementById('typRectangle');
    var typPolygon = document.getElementById('typPolygon');
    var typCircular = document.getElementById('typCircular');
    var muGeozoneDetails = document.getElementById('muGeozoneDetails');
    if (isCreateGeozone == false) {
        isCreateGeozone = true;
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn H_active');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_open H_top H_left');
        }
        if (landmarkButton != null) {
            landmarkButton.setAttribute('class', 'H_btn');
            isCreateLandmark = false;
        }
        if (typRectangle != null) {
            typRectangle.setAttribute('class', 'H_btn');
        }
        if (typPolygon != null) {
            typPolygon.setAttribute('class', 'H_btn');
        }
        if (typCircular != null) {
            typCircular.setAttribute('class', 'H_btn');
        }
        if (muGeozoneDetails != null) {
            muGeozoneDetails.setAttribute('class', 'H_btn H_disabled');
            muGeozoneDetails.setAttribute('disabled', true);
        }
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        try {
            map.removeEventListener("tap", welcome);
        }
        catch (ex) { }
    }
    else {
        isCreateGeozone = false;
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_top H_left');
        }
        map.removeEventListener("tap", getCoordinate, false);
        map.removeEventListener("pointermove", mapDragRectangle, false);
        map.removeEventListener("tap", Getlatlng);
        map.removeEventListener("tap", leftClick);
        map.removeEventListener("mousemove", mapDragRectangle);
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
    }
}
var fnSetGeozones = function (type) {
    if (clandmark != null && clandmark.getObjects().length > 0) {
        clandmark.removeObjects(clandmark.getObjects());
    }
    if (cGeozone != null && cGeozone.getObjects().length > 0) {
        cGeozone.removeObjects(cGeozone.getObjects());
    }

    if (document.getElementById('hdnRestriction_G') != null && document.getElementById('hdnRestriction_G').value == '0') {
        if (document.getElementById("hdnlang").value == "LanguageArNew") {
            TrinetraCustomAlerts('بلغ الحد الأقصى لعدد Geozone! . لا يمكن إنشاء أكثر Geozone.');
        }
        else if (document.getElementById("hdnlang").value == "LanguageHindi") {
            TrinetraCustomAlerts('Geozone की अधिकतम संख्या तक पहुंच! . अधिक Geozone नहीं बना सकता है.');
        } else {
            TrinetraCustomAlerts('Maximum number of Geozones reached. Cannot create more Geozone.');
        }
        return;
    }

    if (type == 3) {
        circleUnits = 'PL';
        gMarkers.length = 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 if (type == 2) {
        circleUnits = 'RC';
        gMarkers.length = 0;
        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);
        dragRectangle = false;
    }
    else {
        circleUnits = 'CR';
        myrectangle = null;
        gMarkers.length = 0;
        map.removeEventListener("tap", getCoordinate);
        map.removeEventListener("mousemove", mapDragRectangle);
        map.removeEventListener("tap", leftClick);
        map.removeEventListener("tap", Getlatlng);
        eventOnclick = map.addEventListener("tap", Getlatlng);
    }
};
function Getlatlng(overlay, point) {
    //  var cord = map.pixelToGeo(evt.displayX, evt.displayY);
    if (!point || point == '') {
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
        var centerPoint = new H.geo.Point(parseFloat(point.lat), parseFloat(point.lng));
        var center = map.getCenter();
        with (Math) {
            var d = 200 / 6378.8;
            d = d / 1000;

            var lat1 = (PI / 180) * (center.lat); // radians
            var lng1 = (PI / 180) * (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 czPoint = new H.geo.Point(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
            }

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

            if (document.getElementById('hdnGeoCoordinates') != null) {
                document.getElementById('hdnGeoCoordinates').value = point.lat + ',' + point.lng;
            }

            var icon = null;
            icon = '../images/flag_8.svg';
            var bubble = null;

            var OpenBubble = function (evt) {
                var coordinate = evt.target.getGeometry();
                var landmarkAddress = '';
                var rvrGeocodingParameters = {
                    prox: coordinate.lat + "," + coordinate.lng + ",200",
                    mode: 'retrieveAddresses',
                    maxresults: 1,
                    language: 'en'
                };
                geocoder.reverseGeocode(rvrGeocodingParameters, function (result) {
                    try {
                        landmarkAddress = result.Response.View[0].Result[0].Location.Address.Label;
                        var ltlng = result.Response.View[0].Result[0].Location.Latitude + ',' + result.Response.View[0].Result[0].Location.Longitude;

                        getlngs_geozone(ltlng, landmarkAddress);
                    }
                    catch (e) {
                        console.log(e);
                        landmarkAddress = 'exception';
                    }
                }, function (e) {
                    console.log(e);
                    landmarkAddress = 'failure';
                });
            }

            var marker = new H.map.Marker(centerPoint, {});
            //{
            //    icon: new H.map.Icon(icon, { anchor: new H.math.Point(2, 22) })
            //});
            //marker.addEventListener('tap', OpenBubble, false);
            clandmark.addObject(marker);
            map.addObject(clandmark);
            //map.setViewBounds(clandmark.getBounds());
            map.getViewModel().setLookAtData({
                bounds: clandmark.getBoundingBox()
            });
            var muGeozoneDetails = document.getElementById('muGeozoneDetails');
            if (muGeozoneDetails != null) {
                muGeozoneDetails.setAttribute('class', 'H_btn');
            }
        }
    }
}
function getCoordinate(overlay, point) {
    if (!point || point == '') {
        point = map.screenToGeo(overlay.currentPointer.viewportX, overlay.currentPointer.viewportY);
    }

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

        var marker1 = r1;
        var marker2 = 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('hdnGeoCoordinates') != null) {
            document.getElementById('hdnGeoCoordinates').value = polyArray;
        }

        r1 = ''
        r2 = ''


        try {
            //map.setViewBounds(myrectangle.getBounds());
            map.getViewModel().setLookAtData({
                bounds: myrectangle.getBoundingBox()
            });
            var muGeozoneDetails = document.getElementById('muGeozoneDetails');
            if (muGeozoneDetails != null) {
                muGeozoneDetails.setAttribute('class', 'H_btn');
            }
        }
        catch (er) {
            TrinetraCustomAlerts(er);
        }
        r1 = first = '';
        r2 = second = '';
    }
}
function mapClickRectangle(overlay, point) {
    if (point == null) { return; }

    if (!r1) {   // First click
        r1 = point;
        myrectangle = null;
        dragRectangle = true;
    }
    else {   // Second click
        dragRectangle = false;
        draw_rectangle(r1, point);
        r2 = point;
        r1 = r2 = '';
        if (cGeozone != null)
            map.setViewBounds(cGeozone.getBounds());
        else if (clandmark != null)
            map.setViewBounds(clandmark.getBounds());
    }
}

var rect_group = null;
function draw_rectangle_h(a, b, isRestricted, pageName) {
    var icon = "../images/flag_8.svg"
    if (myrectangle != null) {
        map.removeObject(myrectangle);
    }
    if (a != null && b != null) {

        var rFilClr = "rgba(144,238,144, 0.5)";
        var rLneClr = "rgba(0,128,0,0)";

        if (isRestricted == 'true' || isRestricted == '1') {
            rFilClr = "rgba(255,0,0,0.5)";
            rLneClr = "rgba(0,0,0,1)";
        }
        else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
            rFilClr = "rgba(144,238,144, 0.5)";
            rLneClr = "rgba(5,45,0,1)";
        }
        else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
            rFilClr = "rgba(65,105,225, 0.5)";
            rLneClr = "rgba(0,0,128,1)";
        }

        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)), {
                    style: { strokeColor: rLneClr, lineWidth: 1, fillColor: rFilClr }
                });
            }
            else {
                myrectangle = new H.map.Rect(new H.geo.Rect(parseFloat(a.lat), parseFloat(b.lng), parseFloat(b.lat), parseFloat(a.lng)), {
                    style: { strokeColor: rLneClr, lineWidth: 1, fillColor: rFilClr }
                });
            }
        }

        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.getData()),
                    { content: 'Geozone Name : ' + e.target.getData() });
                ui.addBubble(infoBubble);
            }
        );
        //poly_group = new H.map.Group();
        poly_group.addObject(myrectangle);
        polyShapeArray.push(poly_group);
        //polyShapeArray.push(myrectangle);
        map.addObject(poly_group);
    }
}
function mapClickRectangle_new(overlay, point, isRestricted, pageName) {

    if (point == null) { return; }

    if (!r1) {   // First click
        r1 = point;
        myrectangle = null;
        dragRectangle = false;
    }
    else {   // Second click

        dragRectangle = false;
        draw_rectangle_h(r1, point, isRestricted, pageName);
        r2 = point;

        //Rec_bounds = new H.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 = ''
        if (location.pathname.indexOf("HistoryPage.aspx") == -1)
            //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 (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)), {
                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)), {
                style: { strokeColor: "rgba(0,0,128,1)", lineWidth: 1, fillColor: "rgba(65, 105, 225, 0.5)" } //stroke color : "#fd942d" fill color : "#859CB3"
            });
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        var OpenBubble = function (evt) {
            getlngs_geozone('', '');
        }
        //myrectangle.addEventListener('tap', OpenBubble, false);
        cGeozone.addObject(myrectangle);
        map.addObject(cGeozone);
        map.addObject(clandmark);

    }
}


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

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

                if ((gMarkers.length + 1) > maxMarkers) {
                    TrinetraCustomAlerts(maxGeozoneMarkers.replace("<#maxMarkers#>", maxMarkers));
                    return false;
                }
            }

            // Make markers draggable
            if (isview == 0) {
                gMarker = new H.map.Marker(point, {});
                gMarker.draggable = true;
            }
            else {
                gMarker = new H.map.Marker(point, {});
                gMarker.draggable = true;
            }

            gMarkers.push(gMarker);
            clandmark.addObject(gMarker);
            map.addObject(clandmark);
            if (isview == 0) {
                gMarker.addEventListener("dragstart", function (evt) { behavior.disable(); }, false);
                gMarker.addEventListener("drag", function (evt) {
                    CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                    PrevCoordinates = evt.target.getGeometry();
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                });

                gMarker.addEventListener("dragend", function (evt) {
                    behavior.enable();
                    CurrCoordinates = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);
                    PrevCoordinates = evt.target.getGeometry();
                    IsDragStart = true;
                    drawPoly(0);
                    IsDragStart = false;
                });

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

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

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

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

        if (document.getElementById('hdnGeoCoordinates') != null) {
            document.getElementById('hdnGeoCoordinates').value = polyArray;
        }

        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: .3, fillColor: filClr }
        });

        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }
        var OpenBubble = function (evt) {
            getlngs_geozone('', '');
        }
        //polyShape.addEventListener('tap', OpenBubble, false);
        cGeozone.addObject(polyShape);
        map.addObject(cGeozone);
        var muGeozoneDetails = document.getElementById('muGeozoneDetails');
        if (muGeozoneDetails != null) {
            muGeozoneDetails.setAttribute('class', 'H_btn');
        }
    }
    catch (e) {
        //alert(e);
    }
}
function ValidateGeozonePanelEntries() {

    var geozoneNameField = document.getElementById('txtGeozoneName');
    var directionField = document.getElementById('ddlGeozoneDirection')
    var severityField = document.getElementById('ddlGeozoneSeverity');
    var categoryField = document.getElementById('ddlGeozoneCategory');
    var txtRadius = document.getElementById('txtGeozoneRadius');
    s = geozoneNameField.value.replace(/(^\s*)|(\s*$)/gi, "");
    s = s.replace(/[ ]{2,}/gi, " ");
    s = s.replace(/\n /, "\n");

    var isError = false;
    var alertMessage = '';

    if (s.length == 0 || s == 'Geozone Name' || s == 'اسم المنطقة الجغرافية') {
        alertMessage = Alert_EnterGeozone;
        isError = true;
        geozoneNameField.focus();
        geozoneNameField.style.backgroundColor = 'lightyellow';
    }
    else {
        geozoneNameField.style.backgroundColor = 'white';
    }

    if (severityField.value == '- Select Severity -') {
        alertMessage += (alertMessage.length == 0 ? '' : '</br>') + Alert_SelectSeverity;
        if (!isError) {
            severityField.focus();
            isError = true;
        }
        severityField.style.backgroundColor = 'lightyellow';
    }
    else {
        severityField.style.backgroundColor = 'white';
    }

    if (directionField.value == '- Select Direction -') {
        alertMessage += (alertMessage.length == 0 ? '' : '</br>') + Alert_SelectDirection;
        if (!isError) {
            directionField.focus();
            isError = true;
        }
        directionField.style.backgroundColor = 'lightyellow';
    }
    else {
        directionField.style.backgroundColor = 'white';
    }

    if (categoryField.value == '- Select Category -') {
        alertMessage += (alertMessage.length == 0 ? '' : '</br>') + Alert_SelectCategory;
        if (!isError) {
            categoryField.focus();
            isError = true;
        }
        categoryField.style.backgroundColor = 'lightyellow';
    }
    else {
        categoryField.style.backgroundColor = 'white';
    }

    if (circleUnits == 'CR') {
        if (RemoveSpaces(txtRadius).length == 0) {
            alertMessage = (isError ? alertMessage + '</br>' : '') + Alert_EnterRadius;
            if (!isError) {
                txtRadius.focus();
            }
            isError = true;
            txtRadius.style.backgroundColor = 'lightyellow';
        }
        else if (txtRadius.value < 10) {
            alertMessage = (isError ? alertMessage + '</br>' : '') + Alert_EnterRadius;
            if (!isError) {
                txtRadius.focus();
            }
            isError = true;
            txtRadius.style.backgroundColor = 'lightyellow';
        }
        else {
            txtRadius.style.backgroundColor = 'white';
        }
    }
    if (isError) {
        TrinetraCustomAlerts(alertMessage);
        return false;
    }
    else {
        return true;
    }
}
/*end geozone*/

/*landmark code for monitor screen*/
function fnEnableLandmarks() {
    var landmarkButton = document.getElementById('landmarkButton');
    var geoButton = document.getElementById('geozoneButton');
    var geoView = document.getElementById('geozoneView');
    if (isCreateLandmark == false) {
        if (landmarkButton != null) {
            landmarkButton.setAttribute('class', 'H_btn H_active');
        }
        if (geoButton != null) {
            geoButton.setAttribute('class', 'H_btn');
        }
        if (geoView != null) {
            geoView.setAttribute('class', 'H_overlay H_top H_left');
            isCreateGeozone = false;
        }
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (cGeozone != null && cGeozone.getObjects().length > 0) {
            cGeozone.removeObjects(cGeozone.getObjects());
        }

        try {
            map.removeEventListener("tap", getCoordinate, false);
            map.removeEventListener("pointermove", mapDragRectangle, false);
            map.removeEventListener("tap", Getlatlng);
            map.removeEventListener("tap", leftClick);
            map.removeEventListener("mousemove", mapDragRectangle);
        }
        catch (ex) { }

        welcome = function (evt) {

            if (document.getElementById('hdnRestriction_L') != null && document.getElementById('hdnRestriction_L').value == '0') {
                if (document.getElementById("hdnlang").value == "LanguageArNew") {
                    TrinetraCustomAlerts('بلغ الحد الأقصى لعدد معالم! . لا يمكن إنشاء أكثر معالم.');
                }
                else if (document.getElementById("hdnlang").value == "LanguageHindi") {
                    TrinetraCustomAlerts('स्थलों की अधिकतम संख्या तक पहुंच! . अधिक मील का पत्थर नहीं बना सकता है.');
                } else {
                    TrinetraCustomAlerts('Maximum number of Landmarks reached. Cannot create more Landmarks.');
                }
                return;
            }

            if (clandmark != null && clandmark.getObjects().length > 0) {
                clandmark.removeObjects(clandmark.getObjects());
            }
            var cord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY)
            var centerPoint = new H.geo.Point(parseFloat(cord.lat), parseFloat(cord.lng));
            var center = map.getCenter();
            with (Math) {
                var d = 200 / 6378.8;
                d = d / 1000;

                var lat1 = (PI / 180) * (center.lat); // radians
                var lng1 = (PI / 180) * (center.lng); // radians
                var centerPoint;
                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)));
                }

                if (d < 1.5678565720686044) {
                    circle = new H.map.Circle(
                                centerPoint,
                                200,
                                {
                                    style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: "rgba(198,155,204,0.5)" } // "#C69ACC" }
                                }
                            );
                }
                else {
                    circle = new H.map.Circle(
                                centerPoint,
                                200,
                                {
                                    style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: canClearCircle ? '#000000' : "rgba(198,155,204,0.5)" } //'#C69ACC' }
                                }
                            );
                }
                clandmark.addObject(circle);


                var icon = null;
                icon = '../images/flag_8.svg';
                var bubble = null;

                var OpenBubble = function (evt) {
                    var coordinate = evt.target.getGeometry();
                    var landmarkAddress = '';
                    var rvrGeocodingParameters = {
                        prox: coordinate.lat + "," + coordinate.lng + ",200",
                        mode: 'retrieveAddresses',
                        maxresults: 1,
                        language: 'en'
                    };
                    geocoder.reverseGeocode(rvrGeocodingParameters, function (result) {
                        try {
                            landmarkAddress = result.Response.View[0].Result[0].Location.Address.Label;
                            var ltlng = result.Response.View[0].Result[0].Location.DisplayPosition.Latitude + ',' + result.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
                            getlngs(ltlng, landmarkAddress);
                        }
                        catch (e) {
                            console.log(e);
                            landmarkAddress = 'exception';
                        }
                    }, function (e) {
                        console.log(e);
                        landmarkAddress = 'failure';
                    });
                }

                var marker = new H.map.Marker(
                centerPoint, {
                    icon: new H.map.Icon(icon, { anchor: new H.math.Point(2, 22) })
                });
                marker.addEventListener('tap', OpenBubble, false);
                clandmark.addObject(marker);
                map.addObject(clandmark);
                //map.setViewBounds(clandmark.getBounds());
                map.getViewModel().setLookAtData({
                    bounds: clandmark.getBoundingBox()
                });
            }
        };

        map.addEventListener("tap", welcome);
        isCreateLandmark = true;
    }
    else {
        if (clandmark != null && clandmark.getObjects().length > 0) {
            clandmark.removeObjects(clandmark.getObjects());
        }
        if (landmarkButton != null) {
            landmarkButton.setAttribute('class', 'H_btn');
        }
        map.removeEventListener("tap", welcome);
        isCreateLandmark = false;
    }
}

/*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 landmark*//********************************End of Current vehicle location for Lease Management*********************************************/
function mapclicks(types) {
    try {
        var divMap = document.getElementById('map-dsply');
        var FSVImg = document.getElementById('imgFS');
        var NVImg = document.getElementById('imgNV');
        var divfsbtn = document.getElementById('mapFscreen');
        if (types == 1) {
            divMap.setAttribute("class", "mapFullscreenView");
            FSVImg.setAttribute("class", "ControlHide");
            NVImg.setAttribute("class", "ControlShow");
            divfsbtn.setAttribute("class", "mapFSControlShow");
            map.getViewPort().resize();
        }
        else {
            divMap.setAttribute("class", "mapNormalView");
            FSVImg.setAttribute("class", "ControlShow");
            NVImg.setAttribute("class", "ControlHide");
        }
        return false;

    } catch (e) {

    }
}

var objonline = null;

function OnlineClustering(data, isEnable) {
    // First we need to create an array of DataPoint objects,
    // for the ClusterProvider
    //var dataPoints1 = [];
    ////dataPoints1.push(new H.clustering.DataPoint('22.996715', '53.186252', 1, { id: 'red' }));
    //dataPoints1.push(new H.clustering.DataPoint('23.101089', '54.755897', 1, { id: 'green' }));
    //dataPoints1.push(new H.clustering.DataPoint('23.105278', '54.775989', 1, { id: 'blue' }));
    if (objonline != null) {
        map.removeLayer(objonline);
    }

    if (objonline != null) {
        map.removeLayer(objonline);
    }

    var dataPoints = data;
    var Estatus = status;

    var noiseSvg =
        '<svg xmlns="http://www.w3.org/2000/svg" height="50px" width="50px">' +
        '<circle cx="20px" cy="20px" r="20" fill="red" />' +
        '<text x="20" y="35" font-size="30pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white" textContent="!">!</text></svg>';

    var noiseIcon = new H.map.Icon(noiseSvg, {
        size: { w: 22, h: 22 },
        anchor: { x: 11, y: 11 }
    });


    //var clusterSvgTemplate =
    //    '<svg xmlns="http://www.w3.org/2000/svg" height="50px" width="50px"><circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="20" fill="#7E354D" stroke-opacity="0.5" />' +
    //    '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="16" fill="#7E354D" stroke-opacity="0.5" />' +
    //    '<circle stroke="#FFF" stroke-width="2" cx="25px" cy="25px" r="12" fill="#7E354D" stroke-opacity="0.5" />' +
    //    '<text x="24" y="29" font-size="10pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white">{text}</text>' +
    //    '</svg>';

    var clusterSvgTemplate =
    '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-100 -100 200 200" height="80px" width="80px">' +
    '<defs>' +
        '<g id="a" transform="rotate(45)">' +
            '<path d="M0 47A47 47 0 0 0 47 0L62 0A62 62 0 0 1 0 62Z" fill-opacity="0.7"/>' +
            '<path d="M0 67A67 67 0 0 0 67 0L81 0A81 81 0 0 1 0 81Z" fill-opacity="0.5"/>' +
            '<path d="M0 86A86 86 0 0 0 86 0L100 0A100 100 0 0 1 0 100Z" fill-opacity="0.3"/>' +
        '</g>' +
    '</defs>' +
    '<g fill="#008cff">' +
        '<circle r="42"/>' +
        '<g>' +
            '<use xlink:href="#a"/>' +
        '</g>' +
        '<g transform="rotate(120)">' +
            '<use xlink:href="#a"/>' +
        '</g>' +
        '<g transform="rotate(240)">' +
            '<use xlink:href="#a"/>' +
        '</g>' +
    '</g>' +
    '<text x="5" y="25" font-size="50pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="white">{text}</text>' +
'</svg>';
    var clusteringProvider = new H.clustering.Provider(dataPoints, {
        //min: 5,
        //max: 20,
        clusteringOptions: {
            minWeight: 1,
            eps: 32
        },
        theme: {
            getClusterPresentation: function (markerCluster) {
                var svgString = clusterSvgTemplate.replace('{radius}', markerCluster.getWeight() * 5);
                svgString = svgString.replace('{text}', +markerCluster.getWeight());
                var w, h;
                var weigth = markerCluster.getWeight();
                //Set cluster size depending on the weight
                if (weigth <= 6) {
                    w = 35;
                    h = 35;
                }
                else if (weigth <= 12) {
                    w = 50;
                    h = 50;
                }
                else {
                    w = 75;
                    h = 75;
                }

                var clusterIcon = new H.map.Icon(svgString, {
                    size: { w: w, h: h },
                    anchor: { x: (w / 2), y: (h / 2) }
                });

                // Create a marker for clusters:
                var clusterMarker = new H.map.Marker(markerCluster.getPosition(), {
                    icon: clusterIcon,
                    // Set min/max zoom with values from the cluster, otherwise
                    // clusters will be shown at all zoom levels:
                    min: markerCluster.getMinZoom(),
                    max: markerCluster.getMaxZoom()
                });

                // Bind cluster data to the marker:
                clusterMarker.setData(markerCluster);

                clusterMarker.addEventListener("pointerenter", function (event) {
                    var isMapIt1 = 'LanguageEng'; //document.getElementById('hdnUserlan').value = null ? 'LanguageEng' : document.getElementById('hdnUserlan').value;

                    var point = event.target.getGeometry(),
                        screenPosition = map.geoToScreen(point),
                        t = event.target,
                        data = t.getData();

                    var tooltipContent

                    if (isMapIt1 == "LanguageArNew") {
                        tooltipContent = '<div style="padding-bottom:10px"><b><u>قائمة السيارات / ذيول أدناه أدناه. ،</u></b></div><div style="text-align:left;<#htwt#>"><table style="direction:ltr" cellspacing=5 class=\'InfoBubble\'>';
                        tooltipContent += '<td style="width:5%"><b>سنو</b></td><td style="width:40%"><b>مركبة</b></td></tr>';
                    }
                    else {
                        tooltipContent = '<div style="padding-bottom:10px"><b><u>Following list of Device are under here.,</u></b></div><div style="text-align:left;<#htwt#>"><table style="direction:ltr" cellspacing=5 class=\'InfoBubble\'>';
                        tooltipContent += '<td style="width:5%"><b>Sno</b></td><td style="width:40%"><b>Device(s)</b></td></tr>';
                    }

                    //tooltipContent = '<div style="padding-bottom:10px"><b><u>Following list of vehicles / tails are under here.,</u></b></div><div style="text-align:left;<#htwt#>"><table style="direction:ltr" cellspacing=5 class=\'InfoBubble\'>';
                    ////tooltipContent += '<td colspan="3"><b>Total no. of vehicles : </b><#noOfVeh#></td></tr>';
                    ////tooltipContent += '<td style="width:5%"><b>Sno</b></td><td style="width:40%"><b>Vehicle</b></td><td style="width:100%"><b>Address</b></td></tr>';
                    //tooltipContent += '<td style="width:5%"><b>Sno</b></td><td style="width:40%"><b>Vehicle</b></td></tr>';
                    var count = 0;
                    data.forEachDataPoint(
                        function (o) {
                            var sno = count++;
                            //tooltipContent += o.getPosition().lat + " " + o.getPosition().lng + "," + o.getData().id + "</br>";
                            //tooltipContent += '<td style="width:2%;text-align:center">' + (sno + 1).toString() + '</td><td style="width:28%"> ' + o.getData().id + ' </td><td style="width:70%">' + o.getData().address + '</td></tr>';
                            tooltipContent += '<td style="width:2%;text-align:center">' + (sno + 1).toString() + '</td><td style="width:28%"> ' + o.getData().id + ' </td></tr>';
                        }
                    );
                    tooltipContent += '</table></div>';
                    if (count > 3) {
                        tooltipContent = tooltipContent.replace("<#htwt#>", "height:100px;overflow-y: scroll;")
                    }
                    tooltipContent = tooltipContent.replace("<#noOfVeh#>", count.toString());
                    infoBubble = new H.ui.InfoBubble(map.screenToGeo(screenPosition.x, screenPosition.y), { content: tooltipContent });
                    ui.addBubble(infoBubble);
                });

                clusterMarker.addEventListener("pointerleave", function (event) {
                    if (infoBubble) {
                        ui.removeBubble(infoBubble);
                        infoBubble = null;
                    }
                });


                return clusterMarker;

                //return clusterMarker;
            },
            getNoisePresentation: function (noisePoint) {
                var i = 0;
                var group = new H.map.Group({ min: noisePoint.getMinZoom() });
                for (j = 0; j < dataPoints.length; j++) {

                    if (dataPoints[j].data.id == noisePoint.getData().id) {
                        i = j;

                    }
                }
                group.addObject(clusterMarkerArray[i]);
                return group;
            }
        }

    });

    objonline = new H.map.layer.ObjectLayer(clusteringProvider);
    map.addLayer(objonline);
}
