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

// 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({
    app_id: 'UdwAigBKPRhu01vbIGkI',
    app_code: 'PzCfyYAsV98qvfU8gusqRg',
    useCIT: true,
    useHTTPS: true
});
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 {
        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.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4
            });

            // 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();
            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.normal.map); break;
                            case 'H': map.setBaseLayer(defaultLayers.satellite.map); break;
                            case 'T': map.setBaseLayer(defaultLayers.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 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 (canvas) {
            resultContainer.innerHTML = '';
            resultContainer.appendChild(canvas);
            //doCanvas(canvas);
            downloadCanvas(this, canvas, 'test.png');
        }
        else {
            // For example when map is in Panorama mode
            resultContainer.innerHTML = 'Capturing is not supported';
        }
    }, [ui], 0, 0, 1250, 900);
}

function clickCanvas() {
    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 += (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.png' 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("?q=A") != -1) ?
                 "height='20px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.png' 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/purple-1_.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;" + VIgnitionOn + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/orange-1_.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;" + VIgnitionOff + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/1_.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;" + VMoving + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/pink-1_.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;" + VIdling + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/3.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;" + VOthers + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/mapit-9_.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;" + VSleep + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.png' 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 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.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;" + VStart + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px' align='center'><img src='../images/End_point_legend.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;" + VDestination + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/ignition-on_play.png' 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.png' 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.png' 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.png' 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.png' 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.png' 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.png' 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>";
    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.normal.map,
            {
                center: orgCenter != null ? orgCenter : new H.geo.Point(20.00, 78.00),
                zoom: orgZoomLevel != null ? orgZoomLevel : 4
            });

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

            //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;
                }
            }
            //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.normal.map); break;
                            case 'H': map.setBaseLayer(defaultLayers.satellite.map); break;
                            case 'T': map.setBaseLayer(defaultLayers.terrain.map); break;
                        }
                    }
                }
            }
            orgCenter = null;
            orgZoomLevel = null;
        }
        return true;
    }
    catch (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.normal.map, getConfig());
            map2 = new H.Map(document.getElementById("map-dsply2"), defaultLayers.normal.map, getConfig());
            map3 = new H.Map(document.getElementById("map-dsply3"), defaultLayers.normal.map, getConfig());
            map4 = new H.Map(document.getElementById("map-dsply4"), defaultLayers.normal.map, getConfig());
            map5 = new H.Map(document.getElementById("map-dsply5"), defaultLayers.normal.map, getConfig());
            map6 = new H.Map(document.getElementById("map-dsply6"), defaultLayers.normal.map, getConfig());
            map7 = new H.Map(document.getElementById("map-dsply7"), defaultLayers.normal.map, getConfig());
            map8 = new H.Map(document.getElementById("map-dsply8"), defaultLayers.normal.map, getConfig());
            map9 = new H.Map(document.getElementById("map-dsply9"), defaultLayers.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
    };
};
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.normal.map); break;
                        case 'H': map.setBaseLayer(defaultLayers.satellite.map); break;
                        case 'T': map.setBaseLayer(defaultLayers.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.png', { 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.png', { 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 = '635px';
    document.getElementById('map-dsply').style.height = '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.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4
            });

            //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.png', { 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.');
    }
}

var marker = null;
function loadForLandMark() {
    try {
        document.getElementById("pnlInfoWindow").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 = (gridViewControl.clientWidth - 5 -
             (document.getElementById('search-box').clientWidth)) + 'px';
        }

        // 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) {
            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.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4
            });

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

            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) {
        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.Strip();
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.normal.map); break;
                        case 'H': map.setBaseLayer(defaultLayers.satellite.map); break;
                        case 'T': map.setBaseLayer(defaultLayers.terrain.map); break;
                    }
                }
            }
        }
        lt = new Array();
        history_latlng = latlng;
        googleResults = new Array();
        lntlngs = new Array();
        polyStrip = new H.geo.Strip();
        polyStripAdv1 = new H.geo.Strip();
        polyStripAdv2 = new H.geo.Strip();
        polyStripAdv3 = new H.geo.Strip();
        polyStripAdv = new H.geo.Strip();
        lntlngTrip1 = new Array();
        lntlngTrip2 = new Array();
        lntlngTrip3 = new Array();
        lntlngTrip = new Array();
        var Tripcount = 1;
        //markersContainer = new nokia.maps.map.Container();
        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.Strip();
                    }
                }
            }
            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])));
            //playBackArray.push(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));//parseFloat(lng[0])); playBackArray.push(parseFloat(lng[1]));
        }

        //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);
            }
            else {
                map.addObject(mkr_group);
                map.setViewBounds(mkr_group.getBounds());
            }
            work = null;

        };
        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 {
                polyline = new H.map.Polyline(
                        polyStrip,
                        {
                            style: { strokeColor: '#980900', lineWidth: 2, color: '#980900' }
                        }
                    );
                map.addObject(polyline);
                if (location.pathname.indexOf("HistoryPage.aspx") != -1) {
                    setTimeout(function () { clickCanvas(); }, 2000);

                }
            }
        }
    }
    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) {
    var mapIcon = null;
    var marker;
    try {
        if (heading == -1 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-1_.png';
                playbackIcon = '../images/vechile_New.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-1_.png';
                playbackIcon = '../images/ignition-on_play.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-1_.png';
                playbackIcon = '../images/carmarker_Alarm.png';
            }
            else if (ignstatus == '3' || ignstatus == '8' || ignstatus == '9') /*Idling start & end 06-Dec-2011 - Sakthi*/ {
                mapIcon = '../images/pink-1_.png';
                playbackIcon = '../images/Idling.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-1_.png';
                playbackIcon = mapIcon;
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-1_.png';
                playbackIcon = mapIcon;
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/1_.png';
                playbackIcon = '../images/car1_Mod.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-1_.png';
                playbackIcon = '../images/ignition-off_play.png';
            }
            else if (ignstatus == '10') { /*Sleep mode 20-Dec-2011 Sakthi*/
                mapIcon = '../images/mapit-9_.png';
                playbackIcon = '../images/SleepMode.png';
            }
        }
        else if (heading >= 0 && heading <= 30 && id != 'current') {
            if (id == 'MapIt') {
                if (heading == '0' && ignstatus == '7') {
                    mapIcon = '../images/mapit-1_.png';
                    playbackIcon = '../images/vechile_New.png';
                }
                else {
                    mapIcon = '../images/mapit-3_20.png';
                    playbackIcon = '../images/N.png';
                }

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

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

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

        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.getPosition();
            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 = 15;
                var dspY = 31;
            }
            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(9, 12) }),
                    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, 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;

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

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

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

    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());
            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());
            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());
            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());
            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());
            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());
            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());
            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());
            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());
            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 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, 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.normal.map); break;
                        case 'H': map.setBaseLayer(defaultLayers.satellite.map); break;
                        case 'T': map.setBaseLayer(defaultLayers.terrain.map); break;
                    }
                }
            }
        }      

        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[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.getPosition());
                }               
            }
        }       

        //Sakthi 15-Dec-2014 For Map Clustering
        if (pageName == 'M' || pageName == 'MF') {
            //initialiseSVGParser_Monitor();
            //clusterDataPoints_Monitor(clusterPoint_Monitor, true);
            mkr_group = new H.map.Group();
            mkr_group.addObjects(clusterMarkerArray);
            map.addObject(mkr_group);
            map.setViewBounds(mkr_group.getBounds());
        }

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

    }
    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.getPosition());
            }

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

/* 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.getPosition();
            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.png") {
            offsetX = 2;
            offsetY = 22;
        }
        else {
            offsetX = 0;
            offsetY = 32;
        }

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

        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("pnlInfoWindow").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.png';
        }
        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.getPosition();
            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.png") {
            offsetX = 2;
            offsetY = 22;
        }
        else {
            offsetX = 0;
            offsetY = 32;
        }

        //Set marker to a variable.
        var marker = new H.map.Marker(point, {
            icon: new H.map.Icon(icon, { anchor: new H.math.Point(offsetX, offsetY) })
        });
        marker.addEventListener('pointermove', OpenBubble, false);
        marker.addEventListener('pointerout', CloseBubble, false);
        try {
            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();
        map.setViewBounds(circle.getBounds());
    }
    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("~#~");
            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());
                map.addObject(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) { doDrawCircle(); map.setViewBounds(circle.getBounds()); }
        }
    }
}
function flagMarker_LandmarkPage(point, lndName, lndAddr, time, id, i_No, content) {
    var icon = null;
    icon = '../images/flag_2.png';
    if (document.getElementById('hdnLandmarkImage') != null && document.getElementById('hdnLandmarkImage').value != "") {
        lndImage = String(document.getElementById('hdnLandmarkImage').value);
    }

    var bubble = null;

    var OpenBubble = function (evt) {
        bubbleMessage = content;
        var coordinate = evt.target.getPosition();
        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 {
        if (image == null || image == '') {
            if (document.getElementById('hdnLandmarkImage') != null) {

                image = document.getElementById('hdnLandmarkImage').value != "" ? String(document.getElementById('hdnLandmarkImage').value) : '../images/flag_2.png';
            }
            else {
                image = '../images/flag_2.png'; //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 },
            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("pnlInfoWindow").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.lat + ',' + p.lng;
                        }
                        Findplace(p.latitude, p.longitude, '', document.getElementById('txtRadius').value, 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.getPosition();
                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
            },
            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 (marker) map.removeObject(marker);

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

                        marker = new H.map.Marker(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);
                        map.addObject(marker);

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

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

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

                marker = new H.map.Marker(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);
                map.addObject(marker);

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

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

    }
}

//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);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) { doDrawCircle(); }
        }
    }
}
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.png';
    }

    var bubble = null;
    var OpenBubble = function (evt) {
        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.getPosition();
        ui.removeBubble(bubble);
        bubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        ui.addBubble(bubble);
    }
    var CloseBubble = function (evt) {
        ui.removeBubble(bubble);
    }
    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 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' }
                            }
                        );
            }
            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) {
        ShowPopUp();
        eval("DisplayMapIt('" + document.getElementById('hdnMapItValue').value + "\',\'" + pageName + "\',"
        + document.getElementById('hdnInfoBubbleProcessing').value + ")");
    }
    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]));
    }
    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 (clusterMarkerArray.length > 0) {
        for (var k = 0; k < clusterMarkerArray.length; k++) {
            map.removeObject(clusterMarkerArray[k]);
        }
    }
}
//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.checked) {
        document.getElementById("hdnRoute").value = 1;
        Id.checked = true;
        __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.normal.map);
            break;
        case 'S':
            mapType = 'S';
            map.setBaseLayer(defaultLayers.satellite.map);
            break;
        case 'T':
            mapType = 'T';
            map.setBaseLayer(defaultLayers.terrain.map);
            break;
        default:
            mapType = 'N';
            map.setBaseLayer(defaultLayers.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 = 1000;
var mediumSpeed = 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.png", { 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.png", { anchor: new H.math.Point(4, 28) }),
        $id: "marker",
        zIndex: function (m) {
            return 28800001;
        }
    });
    coordPlayBack = arr[0];
    iconPlayback = PlayBack[coordPlayBack.lat + "," + coordPlayBack.lng].icon;
    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.
    map.addObjects([Start, End, busMarker]);
    map.setViewBounds(route.getBounds());

    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.setPosition(coord);
            var Info = PlayBack[coord.lat + "," + coord.lng];
            if (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) {
                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.png' || Info.icon == '../images/NE.png' || Info.icon == '../images/SW.png' || Info.icon == '../images/SE.png') {
                    marker.setIcon(new H.map.Icon(Info.icon, { anchor: new H.math.Point(22, 22) }));
                }
                else if (Info.icon == '../images/W.png' || Info.icon == '../images/E.png') {
                    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.Strip();
                    for (var r = 0; r < RouteMovement.length; r++) {
                        routeStrip.pushPoint(RouteMovement[r]);
                    }
                    map.setViewBounds((new H.map.Polyline(routeStrip, {})).getBounds());
                    if (map.getZoom() > 17) map.setZoom(map.getZoom() - 1);
                }
            }
            else {
                map.setViewBounds(route.getBounds());
            }
            /*********************************************************************************************/

            /****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, {}));
            this.isWalking = false;
            ui.removeBubble(infoBubble);
            walker.ClearSettings();
            walker.clearAlarms();
            map.setViewBounds(route.getBounds());
        }
        /****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.png", { 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 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) {
            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;
        }
    }
}
/***********************************************************************************************/
/***********************************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.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4
            });
            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.normal.map); break;
            case 'S': map.setBaseLayer(defaultLayers.satellite.map); break;
            case 'H': map.setBaseLayer(defaultLayers.terrain.map); break;
        }
    }
}
var rect_group = null;
function draw_rectangle(a, b, isRestricted, pageName) {
    var icon = "../images/flag_8.png"
    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);
          }
        );

        polyShapeArray.push(myrectangle);
        map.addObject(myrectangle);
    }
}
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());
    }
}

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

    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 (myrectangle != null) {
    //    map.removeObject(myrectangle);
    //    myrectangle = null;
    //}
    if (polyShapeArray != undefined && polyShapeArray != null) {
        for (var i = 0; i < polyShapeArray.length; i++) {
            if (polyShapeArray[i] != null) {
                map.removeObject(polyShapeArray[i]);
            }
        }
        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);
              }
            );

            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('', 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.Strip();
        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.Strip();
        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;
              }

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

          }
          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) { }
}
/*********************************Context Menu End***********************************************/
/*********************************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="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);
        }
    }
}
/********************************************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.png'; }
    else { lehIcon = '../images/lehLocation.png'; }
    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******************************************/