/********************************************************************
The functions listed below are related to Vehicle tracking Feature in Navteq 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 mapBckup = null;
var polyline = null;
var history_latlng = null;
var centerCoordinate = new nokia.maps.geo.Coordinate(20.00, 78.00);  //ew GLatLng(23.805450, 78.486328);
var markersContainer = new nokia.maps.map.Container();
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 = "#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 = nokia.maps.clustering.ClusterProvider;
var clusterBackup = new Array();
var clusterBackup_Monitor = new Array();
var isShowLandmarkPlotter = 0;
var isShowGeozonePlotter = false;
var kmlGenerator;
// Legend Icons
var VAllLandmark = "All 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";


//nokia.maps.util.ApplicationContext.set("authenticationToken", "4b25c0fb0d9f746bbe44a74f549b49208f1833336bb01f04");
//nokia.maps.util.ApplicationContext.set("appId", "<AppId>");

//nokia.maps.util.ApplicationContext.set("authenticationToken", "PzCfyYAsV98qvfU8gusqRg");
//nokia.maps.util.ApplicationContext.set("appId", "UdwAigBKPRhu01vbIGkI");
nokia.Settings.set("authenticationToken", "PzCfyYAsV98qvfU8gusqRg");
nokia.Settings.set("appId", "UdwAigBKPRhu01vbIGkI");
//nokia.Settings.set("secureConnection", "force");
(document.location.protocol == "https:") && nokia.Settings.set("secureConnection", "force");
var infoBubble = new nokia.maps.map.component.InfoBubbles(), infoMarkers = {};

///infoBubble.Bubble.prototype.defaultWidth = 300;

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

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

// 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.objects.clear();
    }
    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 (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 / 2) + 'px';

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

            map = new nokia.maps.map.Display(document.getElementById("map-dsply"), {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoomLevel: orgZoomLevel != null ? orgZoomLevel : 4,
                components: [infoBubble, new nokia.maps.map.component.ZoomBar(),
                //new nokia.maps.map.component.TypeSelector(),
                new nokia.maps.map.component.TypeSelector(),
                //new nokia.maps.map.component.zoom.DoubleClick(),
                new nokia.maps.map.component.Behavior(),
                new nokia.maps.map.component.ViewControl(), //]
                //, new nokia.maps.map.component.ContextMenu()]
                new nokia.maps.map.component.Traffic(),
                new nokia.maps.map.component.PublicTransport(),
                new nokia.maps.map.component.ZoomRectangle()]
                //new nokia.maps.map.component.OverlaysSelector(["trafficflow", "trafficincidents"])]
            });
            //                                new nokia.maps.map.component.TypeSelector(),
            //                                new nokia.maps.map.component.Traffic(),
            //                                new nokia.maps.map.component.PublicTransport()


            //            map.addComponent(new nokia.maps.map.component.panning.Drag());
            //            map.addComponent(new nokia.maps.map.component.panning.Kinetic());

            //Get the map view(Center and Zoom level)

            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.set("baseMapType", map.NORMAL); break;
                            case 'H': map.set("baseMapType", map.SATELLITE); break;
                            case 'T': map.set("baseMapType", map.TERRAIN); 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 iconLegendText() {
    var height = '';
    //if (navigator.appName == 'IE') {
    //    if (document.getElementById('gvHistory') != null) { height = "height='190px'"; } else { height = "height='162px'"; }
    //}
    //else {
    //}
    if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1 || location.pathname.indexOf("VehicleSummary.aspx") != -1) {
        var landmarkIconText = "";
        var landmarkIconTextForFullscreen = "";
        var downIconText = "";
    }
    else {
        var landmarkIconText = '';
        //"<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='ShowPopUp();document.getElementById(\"chkShowLandmarks\").checked = this.checked;drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value,this.checked);saveMapObjects(map);HidePopUp();'><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></table></h3>";



        var landmarkIconTextForFullscreen = '';
        //"<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='ShowPopUp();" + ((document.getElementById('gvHistory') != null) ? "drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value,this.checked);HidePopUp();'" : "drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value,this.checked);HidePopUp();'") +
        //        //"                 <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='ShowPopUp();" + ((document.getElementById('gvHistory') != null) ? "Drawlandmark(this);'" : "drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value,this.checked);HidePopUp();'") +
        //                          "><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></table></h3>" +



        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='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>"
        //<h3 class='foot'><table><tr>" +
        //   "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkGeozone' style='height:15px;width:15px;' name='chkGeozone' onclick='ShowPopUp();" + ((document.getElementById('gvHistory') != null) ? "PlotGeozone(this.checked);HidePopUp();'" : "PlotGeozone(this.checked);HidePopUp();'") +
        //"                 <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='ShowPopUp();" + ((document.getElementById('gvHistory') != null) ? "Drawlandmark(this);'" : "drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value,this.checked);HidePopUp();'") +
        //   "><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>"
                 :
                 "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('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
            //context menu

            map = new nokia.maps.map.Display(document.getElementById("map-dsply"), {
                center: orgCenter != null ? orgCenter : new nokia.maps.geo.Coordinate(20.00, 78.00),
                zoomLevel: orgZoomLevel != null ? orgZoomLevel : 4,
                components: [infoBubble, new nokia.maps.map.component.ZoomBar(),
            new nokia.maps.map.component.TypeSelector(),
            new nokia.maps.map.component.zoom.DoubleClick(),
            new nokia.maps.map.component.Behavior(),
            new nokia.maps.map.component.ViewControl(),
            new nokia.maps.map.component.Traffic(),
             new nokia.maps.map.component.ZoomRectangle(),
            new nokia.maps.map.component.PublicTransport()]//, ctxtMenu
                //             new nokia.maps.map.component.Traffic(),
                //                new nokia.maps.map.component.PublicTransport()]
                //new nokia.maps.map.component.OverlaysSelector(["trafficflow", "trafficincidents"])]
            });

            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.set("baseMapType", map.NORMAL); break;
                            case 'H': map.set("baseMapType", map.SATELLITE); break;
                            case 'T': map.set("baseMapType", map.TERRAIN); 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.objects.clear();
        if (map2) map2.objects.clear();
        if (map3) map3.objects.clear();
        if (map4) map4.objects.clear();
        if (map5) map5.objects.clear();
        if (map6) map6.objects.clear();
        if (map7) map7.objects.clear();
        if (map8) map8.objects.clear();

    }
    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 nokia.maps.map.Display(document.getElementById("map-dsply1"), getConfig());
            map2 = new nokia.maps.map.Display(document.getElementById("map-dsply2"), getConfig());
            map3 = new nokia.maps.map.Display(document.getElementById("map-dsply3"), getConfig());
            map4 = new nokia.maps.map.Display(document.getElementById("map-dsply4"), getConfig());
            map5 = new nokia.maps.map.Display(document.getElementById("map-dsply5"), getConfig());
            map6 = new nokia.maps.map.Display(document.getElementById("map-dsply6"), getConfig());
            map7 = new nokia.maps.map.Display(document.getElementById("map-dsply7"), getConfig());
            map8 = new nokia.maps.map.Display(document.getElementById("map-dsply8"), getConfig());
            map9 = new nokia.maps.map.Display(document.getElementById("map-dsply9"), getConfig());

            //            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);
            //map1.addObserver("baseMapType", defaultObserver);
            //            map2.addObserver("baseMapType", defaultObserver);


            orgCenter = null;
            orgZoomLevel = null;

        }
        return true;
    }
    catch (Error) {
        //alert(Error);
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}
var getConfig = function () {
    return {
        // initial center and zoom level of the map
        center: [23.22162, 87.58029],
        zoomLevel: 5,
        //mapLogo: false,   
        components: [
        // ZoomBar provides a UI to zoom the map in & out
        //new nokia.maps.map.component.ZoomBar(),
        // We add the behavior component to allow panning / zooming of the map
						new nokia.maps.map.component.Behavior()//,
        // Creates UI to easily switch between street map satellite and terrain mapview modes
        //				new nokia.maps.map.component.TypeSelector(),
        // Creates a toggle button to show/hide traffic information on the map
        //				new nokia.maps.map.component.Traffic(),
        // Creates a toggle button to show/hide public transport lines on the map
        //				new nokia.maps.map.component.PublicTransport()//,
        // Creates a toggle button to enable the distance measurement tool
        //new nokia.maps.map.component.DistanceMeasurement(),
        // Shows a min-map in the bottom right corner of the map
        //new nokia.maps.map.component.Overview(),
        /* Shows a scale bar in the bottom right corner of the map depicting
        * ratio of a distance on the map to the corresponding distance in the real world
        * in either kilometers or miles
        */
        //new nokia.maps.map.component.ScaleBar()//,
        /* Positioning will show a set "map to my GPS position" UI button
        * Note: this component will only be visible if W3C geolocation API
        * is supported by the browser and if you agree to share your location.
        * If you location can not be found the positioning button will reset
        * itself to its initial state
        */
        //new nokia.maps.positioning.component.Positioning(),
        // Add ContextMenu component so we get context menu on right mouse click / long press tap
        //new nokia.maps.map.component.ContextMenu()
        ]
    };
};
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.body.clientWidth ;//document.documentElement.clientWidth-35//screen.width - 35;
        }
        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.checkResize();
    //map.setCenter();
}

//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.set("baseMapType", map.NORMAL); break;
                        case 'H': map.set("baseMapType", map.SATELLITE); break;
                        case 'T': map.set("baseMapType", map.TERRAIN); 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 = nokia.maps.geo.Coordinate(parseFloat(curpos[0]), parseFloat(curpos[1])); //new GLatLng(curpos[0], curpos[1]);
                map.objects.add(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 nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
            lntlngs.push(point);
            map.objects.add((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 nokia.maps.map.Polyline(
                        lntlngs,
                        {
                            pen: { strokeColor: "#980900", lineWidth: 2 },
                            brush: { color: "#980900" }
                        }
                    );
            map.objects.add(polyline);
            map.zoomTo(polyline.getBoundingBox(), false, "default");
            if (map.zoomLevel == map.maxZoomLevel)
                map.setZoomLevel(map.zoomLevel - 3);
        }
        acMarker = new Array();
        var ltn = new Array();
        if (LatLong != null && LatLong.length > 0) {
            ltn = LatLong.split(',');
            var lcPoint = new nokia.maps.geo.Coordinate(parseFloat(ltn[0]), parseFloat(ltn[1]));
            var marker = new nokia.maps.map.Marker(lcPoint,
            { icon: '../images/icon-road-accident.png' });
            acMarker.push(marker);
            map.objects.add(marker);
            infoBubble.openBubble('<span>Accident Zone</span>', lcPoint);
        }
    }
    //}
    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 nokia.maps.geo.Coordinate(parseFloat(ltn[0]), parseFloat(ltn[1]));
        var marker = new nokia.maps.map.Marker(lcPoint,
            { icon: '../images/icon-road-accident.png' });
        acMarker.push(marker);
        map.objects.add(marker);
        infoBubble.openBubble('<span>Accident Zone</span>', lcPoint);
    }
}

function loadMapForChoosingLocation() {
    document.getElementById('map-dsply').style.width = '635px';
    document.getElementById('map-dsply').style.height = '532px';
    try {
        if (map) {
            map.objects.clear();
            map.set("center", orgCenter != null ? orgCenter : centerCoordinate);
            map.setZoomLevel(orgZoomLevel != null ? orgZoomLevel : 4, "default");
        }

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

            map = new nokia.maps.map.Display(document.getElementById("map-dsply"), {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoomLevel: orgZoomLevel != null ? orgZoomLevel : 4,
                components: [infoBubble,
                new nokia.maps.map.component.ZoomBar(),
                new nokia.maps.map.component.TypeSelector(),
                new nokia.maps.map.component.zoom.DoubleClick(),
                new nokia.maps.map.component.Behavior(),
                new nokia.maps.map.component.ViewControl(),
                new nokia.maps.map.component.Traffic(),
                 new nokia.maps.map.component.ZoomRectangle(),
                new nokia.maps.map.component.PublicTransport()]
            });

            map.addListener("click", function (evt) {
                for (var ac = 0; ac < acMarker.length; ac++) {
                    map.objects.remove(acMarker[ac]);
                }
                acMarker = new Array();
                var cord = map.pixelToGeo(evt.displayX, evt.displayY);
                if (cord != null) {
                    if (document.getElementById('hdnLatLong') != null) {
                        var aslatitude = Math.round(cord.latitude * 1000000) / 1000000;
                        var aslongitude = Math.round(cord.longitude * 1000000) / 1000000;
                        document.getElementById('hdnLatLong').value = aslatitude + ',' + aslongitude;
                    }
                    var lcPoint = new nokia.maps.geo.Coordinate(parseFloat(cord.latitude), parseFloat(cord.longitude));
                    var marker = new nokia.maps.map.Marker(lcPoint,
                     { icon: '../images/icon-road-accident.png' });
                    acMarker.push(marker);
                    map.objects.add(marker);
                    infoBubble.openBubble('<span>Accident Zone</span>', lcPoint);
                }
            });
        }
    }
    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.setCenter(new nokia.maps.geo.Coordinate(23.805450, 78.486328), "default");
            map.objects.clear();
            map.set("center", orgCenter != null ? orgCenter : centerCoordinate);
            map.setZoomLevel(orgZoomLevel != null ? orgZoomLevel : 4, "default");
        }

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

            map = new nokia.maps.map.Display(document.getElementById("map-dsply"), {
                //                center: centerCoordinate, //new nokia.maps.geo.Coordinate(23.805450, 78.486328),
                //                zoomLevel: 4,
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoomLevel: orgZoomLevel != null ? orgZoomLevel : 4,
                components: [infoBubble,
                new nokia.maps.map.component.ZoomBar(),
                new nokia.maps.map.component.TypeSelector(),
                new nokia.maps.map.component.zoom.DoubleClick(),
                new nokia.maps.map.component.Behavior(),
                new nokia.maps.map.component.ViewControl(),
                new nokia.maps.map.component.Traffic(),
                 new nokia.maps.map.component.ZoomRectangle(),
                new nokia.maps.map.component.PublicTransport()]
            });

            createContextMenu(map);

            map.addListener("click", function (evt) {

                var cord = map.pixelToGeo(evt.displayX, evt.displayY);
                var Restriction = document.getElementById('hdnRestriction').value;

                //var v = document.getElementById('<%= hdnRestriction.ClientID %>').value;

                showControls(1);
                if (cord != null) {
                    document.getElementById('txtlat').value = Math.round(cord.latitude * 1000000) / 1000000;
                    document.getElementById('txtlong').value = Math.round(cord.longitude * 1000000) / 1000000;
                    if (document.getElementById('hdnLatLong') != null) {
                        document.getElementById('hdnLatLong').value = cord.latitude + ',' + cord.longitude;
                    }
                    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(',');
            //centerCoordinate = new nokia.maps.geo.Coordinate(parseFloat(zoomLevelLatLong[0]), parseFloat(zoomLevelLatLong[1]));
        }

    }
    catch (Error) {
        TrinetraCustomAlerts('Please check your Internet Connection. Map cannot be loaded');
    }

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

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

    try {
        //        ShowPopUp();
        //        load();
        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.set("baseMapType", map.NORMAL); break;
                        case 'H': map.set("baseMapType", map.SATELLITE); break;
                        case 'T': map.set("baseMapType", map.TERRAIN); break;
                    }
                }
            }
        }
        lt = new Array();
        history_latlng = latlng;
        googleResults = new Array();
        lntlngs = new Array();
        lntlngTrip1 = new Array();
        lntlngTrip2 = new Array();
        lntlngTrip3 = new Array();
        lntlngTrip = new Array();
        var Tripcount = 1;
        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 = nokia.maps.geo.Coordinate(parseFloat(curpos[0]), parseFloat(curpos[1])); //new GLatLng(curpos[0], curpos[1]);
                map.objects.add(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;
                //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 nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
            }
            if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1) {
                if (lng[7] != 0) {
                    lntlngTrip.push(new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1])));
                }
                else if (lng[7] == 0) {

                    lntlngTrip.push(new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1])));

                    if (lntlngTrip.length != 0) {
                        if (Tripcount == 1)
                            lntlngTrip1 = lntlngTrip;
                        else if (Tripcount == 2)
                            lntlngTrip2 = lntlngTrip;
                        else
                            lntlngTrip3 = lntlngTrip;
                        Tripcount++;
                        lntlngTrip = new Array();
                    }
                }
            }
            lntlngs.push(new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1])));
            PlayBackZoom.push(new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1])));
            playBackArray.push(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);
                //if (document.getElementById("hdnAlarmIDs") != null) {
                //map.objects.add(mapMarker);
                markersContainer.objects.add(mapMarker);
                //}

                //map.zoomTo(mapMarker.getBoundingBox(), false);
                //if (map.zoomLevel > 12) map.set("zoomLevel", 12); //zoom out if too close                
            }
        };
        work.finish = function (thread) {
            if (positioncurrent != null && isCurrentPositionVisible == 'true') {
                var curpos = positioncurrent.split("~#~");
                var point = new nokia.maps.geo.Coordinate(parseFloat(curpos[0]), parseFloat(curpos[1])); //GLatLng(curpos[0], curpos[1]);
                if (document.getElementById("hdnAlarmIDs") != null) {
                    map.objects.add(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;
                    //map.zoomTo(lntlngs.getBoundingBox(), false);
                    //map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
                }
            }

            if (document.getElementById("hdnAlarmIDs") == null) {
                playBack(playBackArray);
            }
            else {
                map.objects.add(markersContainer);
            }
            work = null;
            HidePopUp();
        };
        work.start();
        z = 0;
        if (isPolylineVisible) {
            if (location.pathname.indexOf("AdvancedHistoryPage.aspx") != -1) {
                if (lntlngTrip1.length > 0) {
                    polyline = null;
                    polyline = new nokia.maps.map.Polyline(
                        lntlngTrip1,
                        {
                            pen: { strokeColor: "#0B2161", lineWidth: 2 },
                            brush: { color: "#0B2161" }
                        }
                    );
                    map.objects.add(polyline);
                    z++;
                }
                if (document.getElementById('lblTrip1') != undefined) {
                    document.getElementById('lblTrip1').style.backgroundColor = "#0B2161";
                    document.getElementById('lblTrip1').style.color = "#FBEFEF";
                }
                if (lntlngTrip2.length > 0) {
                    polyline = null;
                    polyline = new nokia.maps.map.Polyline(
                        lntlngTrip2,
                        {
                            pen: { strokeColor: "#FF0000", lineWidth: 2 },
                            brush: { color: "#FF0000" }
                        }
                    );
                    map.objects.add(polyline);
                    z++;
                }
                if (document.getElementById('lblTrip2') != undefined) {
                    document.getElementById('lblTrip2').style.backgroundColor = "#FF0000";
                    document.getElementById('lblTrip2').style.color = "#FBEFEF";
                }
                if (lntlngTrip3.length != 0) {
                    polyline = null;
                    polyline = new nokia.maps.map.Polyline(
                        lntlngTrip3,
                        {
                            pen: { strokeColor: "#2ECCFA", lineWidth: 2 },
                            brush: { color: "#2ECCFA" }
                        }
                    );
                    map.objects.add(polyline);
                    z++;
                }
                if (document.getElementById('lblTrip3') != undefined) {
                    document.getElementById('lblTrip3').style.backgroundColor = "#2ECCFA";
                    document.getElementById('lblTrip3').style.color = "#0A0A2A";
                }
                map.zoomTo(polyline.getBoundingBox(), false, "default");
                if (z > 1)
                    map.setZoomLevel(10, "default");
                if (map.zoomLevel == map.maxZoomLevel)
                    map.setZoomLevel(map.zoomLevel - 3);
            }
            else {
                polyline = new nokia.maps.map.Polyline(
                        lntlngs,
                        {
                            pen: { strokeColor: "#980900", lineWidth: 2 },
                            brush: { color: "#980900" }
                        }
                    );
                map.objects.add(polyline);
                map.zoomTo(polyline.getBoundingBox(), false, "default");
                //map.setZoomLevel(8, "default");
                if (map.zoomLevel == map.maxZoomLevel)
                    map.setZoomLevel(map.zoomLevel - 3);
            }


            //map.setZoomLevel(14, "default");
        }
    }
    //}
    catch (Error) {
        TrinetraCustomAlerts(Error);
    }
}

function continueOperations(isPolylineVisible, polyline, collectdata) {
    if (isPolylineVisible) {
        polyline = new nokia.maps.map.Polyline(lntlngs, {
            pen: { strokeColor: "#980900", lineWidth: 2 }
        });
        map.objects.add(polyline);
    }
    map.zoomTo(polyline.getBoundingBox(), false, "default");
}

// 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.objects.remove(polyline);
            polyline = new nokia.maps.map.Polyline(
                        lntlngs,
                        {
                            pen: { strokeColor: "#980900", lineWidth: 2 },
                            brush: { color: "#980900" }
                        }
                    );
            map.objects.add(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 = null;
    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.latitude + "," + point.longitude + "'";
        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.
        if (bubbles) infoBubble.closeAll();
        var OpenBubble = function (evt) {
            if (bubbles) infoBubble.closeAll();
            var coordinate = evt.currentTarget.coordinate;
            //Set Info Bubble styles(Rounded like Cornors etc.) 
            infoBubbleStyle();
            if (isSpeedVisible) {
                bubbles = infoBubble.openBubble(tabs, coordinate);
            }
            else {
                bubbles = infoBubble.openBubble(infoBubbleMessage, coordinate);
            }
        }

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

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

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

        //Event Listener which are added to the bubble.
        var myListener = {
            "mouseover": [OpenBubble, true, null],
            //"mouseout": [CloseBubble, true, null],
            "click": [OpenBubble, true, null]
        };
        map.addListener("click", function (evt) {
            if (bubbles) infoBubble.closeAll();
        });
        // Add tabs to the InfowWindow

        //        map.addListener("mouseover", OpenBubble);
        //        map.addListener("mouseout", CloseBubble);

        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 nokia.maps.map.Marker(
                point, {
                    draggable: false,
                    eventListener: myListener,
                    icon: mapIcon,
                    //offset the top left icon corner so that it's centered above the coordinate
                    anchor: new nokia.maps.util.Point(dspX, dspY),
                    zIndexProcess: function (m) {
                        return 28800001;
                    }
                });
            }
        }
        else {
            if (mapIcon != null || mapIcon != '') {
                marker = new nokia.maps.map.Marker(
                point, {
                    draggable: false,
                    eventListener: myListener,
                    //offset the top left icon corner so that it's centered above the coordinate
                    anchor: new nokia.maps.util.Point(9, 12),
                    icon: mapIcon,
                    zIndexProcess: 1
                });
            }
        }
    }
    catch (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();">' + addLandmarkCaption + '<\/a></td></tr></table><div>';
    }
    tabMessage += '</table></div>';

    //tabs.push(new GInfoWindowTab(VDetails, tabMessage));

    //    tabMessage += '<div style="text-align:' + tableAlign + ';"><table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>';
    //    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();">' + addLandmarkCaption + '<\/a></td></tr></table><div>';
    //    }
    //tabs.push(new GInfoWindowTab(VOtherinfo, tabMessage));
    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();">' + 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.latitude + "," + point.longitude + "'";

    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';
            }
        }
    }
    //    icon.shadowSize = new GSize(1, 1);
    //    icon.iconAnchor = new GPoint(12, 12);
    //    icon.infoWindowAnchor = new GPoint(12, 5);

    //var marker = new GMarker(point, { draggable: false, icon: icon });
    // TO set Z-index for Marker
    //    var marker = new google.maps.Marker(point, { draggable: false, icon: icon,
    //        zIndexProcess: function(m) {
    //            return 28800001;
    //        }
    //    });
    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }
    //<div style="text-align:' + tableAlign + ';">
    var bubbleMessage = '<div style="text-align:' + tableAlign + ';"><table style="direction:' + VDirection + '" cellspacing=5 class=\'InfoBubble\'>';
    //<tr><td colspan="2"><u><b>' + ((mainHeading == null || mainHeading == '') ? 'Vehicle Statistics' : mainHeading) + '</b></u></td></tr>';
    //var validlocationImage = addr == 'N/A' ? '<img src="../Images/icn-address-notvalid.gif" />' : '<img src="../Images/icn-address-valid.gif" />';
    var monitorTabs = [];

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

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

    //monitorTabs.push(new GInfoWindowTab(VDetails, bubbleMessage));
    //    var isSpeedVisbile = true;
    //    var isLandmarkVisible = true;
    //    var canAddLandmark = true;
    //    
    //    var tabMessage = '<table cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>';
    //    if (isSpeedVisbile) {
    //        tabMessage += '<tr><td><b>' + speedCaption + '</b></td><td>' + speed + '</td></tr>';
    //        }

    //    var tabMessage = '<table style="direction:' + VDirection + '; cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>';
    //    if (isSpeedVisbile) {
    //        tabMessage += '<tr><td><b>' + ((speedCaption == null || speedCaption == '') ? 'Speed' : speedCaption) + '</b></td><td>' + speed + '</td></tr>';
    //    }
    //    if (landmarkName != '-') {
    //        tabMessage += '<tr><td width="40px"><b>' + landmarkCaption + '</b></td><td>' + landmarkName + '</td></tr>';
    //    }
    //    else {
    //        tabMessage += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + addr + '\');' +
    //        'document.getElementById(\'txtLocationName\').focus();">' + canAddLandmark + '<\/a></td></tr></table><div>';
    //    }

    //monitorTabs.push(new GInfoWindowTab(VOtherinfo, tabMessage));
    //    var clicks = function(evt) {
    //        var coordinate = evt.currentTarget.coordinate;
    //        //var element =
    //        infoBubble.addBubble(bubbleMessage + tabMessage, coordinate);
    //        //map.objects.add(infoMarkers[element.id] = marker);
    //    }

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

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

    //Remove the info bubble on map click.
    map.addListener("click", function (evt) {
        if (bubble) infoBubble.closeAll();
    });

    var myListener = {
        "mouseover": [OpenBubble, true, null],
        //"mouseout": [CloseBubble, true, null],
        "click": [OpenBubble, true, null]
    };
    var marker = new nokia.maps.map.Marker(
            point, {
                visibility: true,
                icon: icon,
                eventListener: myListener,
                anchor: new nokia.maps.util.Point(9, 12)
                //offset the top left icon corner so that it's centered above the coordinate
                ///anchor: new nokia.maps.util.Point(35, 17)
            });

    map.objects.add(marker);

    //map.addListener("click", clicks, true);

    //Handle closing of the bubble(s)
    //    infoBubble.openBubbleHandles.addObserver(function(list, method, element, idx) {
    //        map.objects.remove(infoMarkers[element.id]);
    //    });

    // tabs.push(new GInfoWindowTab('Other Info', tabMessage));

    //    GEvent.addListener(marker, "mouseover", function() {
    //        timerInterval = setTimeout(function() { marker.openInfoWindowTabsHtml(monitorTabs); }, 1000)
    //    });
    //    GEvent.addListener(marker, "mouseout", function() { clearInterval(timerInterval) });
    //    if (isSpeedVisible) {
    //        GEvent.addListener(marker, "mouseover", function() { timerInterval = setTimeout(function() { marker.openInfoWindowTabsHtml(tabs); }, 1000) });
    //        GEvent.addListener(marker, "mouseout", function() { clearInterval(timerInterval) });
    //    }
    //    else {
    //        GEvent.addListener(marker, "mouseover", function() { timerInterval = setTimeout(function() { marker.openInfoWindowHtml(infoBubbleMessage); }, 1000) });
    //        GEvent.addListener(marker, "mouseout", function() { clearInterval(timerInterval) });
    //    }
    //GEvent.addListener(marker, "mouseout", function() {marker.closeInfoWindow(marker);});

    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.latitude + "," + point.longitude + "'";

    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';
            }
        }
    }
    //    icon.shadowSize = new GSize(1, 1);
    //    icon.iconAnchor = new GPoint(12, 12);
    //    icon.infoWindowAnchor = new GPoint(12, 5);

    //var marker = new GMarker(point, { draggable: false, icon: icon });
    // TO set Z-index for Marker
    //    var marker = new google.maps.Marker(point, { draggable: false, icon: icon,
    //        zIndexProcess: function(m) {
    //            return 28800001;
    //        }
    //    });
    var tableAlign;
    if (VDirection == 'rtl') {
        tableAlign = 'right';
    }
    else {
        tableAlign = 'left';
    }
    var marker = new nokia.maps.map.Marker(
            point, {
                visibility: true,
                icon: icon,
                eventListener: myListener,
                anchor: new nokia.maps.util.Point(9, 12)
                //offset the top left icon corner so that it's centered above the coordinate
                ///anchor: new nokia.maps.util.Point(35, 17)
            });
    clusterMarkersT = new Array();

    if (MapName == '0') {
        map1.objects.clear();
        map1.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map1.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map1.zoomTo(pol.getBoundingBox(), false, "default");
        map1.setZoomLevel(17);
        document.getElementById('Map1_Vehicle').innerHTML = vehCaption + ": " + VehName;
        document.getElementById('Map1_Address').innerHTML = addrCaption + ": " + addr;
        document.getElementById('Map1_Speed').innerHTML = speedCaption + ": " + speed;
        if (map1.zoomLevel == map1.maxZoomLevel) map1.setZoomLevel(map1.zoomLevel - 3);

    }
    else if (MapName == '1') {
        map2.objects.clear();
        map2.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map2.setCenter(pol.getBoundingBox().getCenter(), "default");
        // map2.zoomTo(pol.getBoundingBox(), false, "default");
        map2.setZoomLevel(17);
        document.getElementById('Map2_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map2_Address').innerHTML = "  Address: " + addr;
        document.getElementById('Map2_Speed').innerHTML = speedCaption + ": " + speed;
        if (map2.zoomLevel == map2.maxZoomLevel) map2.setZoomLevel(map2.zoomLevel - 3);
    }

    else if (MapName == '2') {
        map3.objects.clear();
        map3.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map3.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map3.zoomTo(pol.getBoundingBox(), false, "default");
        map3.setZoomLevel(17);
        document.getElementById('Map3_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map3_Address').innerHTML = "  Address: " + addr;
        document.getElementById('Map3_Speed').innerHTML = speedCaption + ": " + speed;
        if (map3.zoomLevel == map3.maxZoomLevel) map3.setZoomLevel(map3.zoomLevel - 3);
    }

    else if (MapName == '3') {
        map4.objects.clear();
        map4.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map4.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map4.zoomTo(pol.getBoundingBox(), false, "default");
        map4.setZoomLevel(17);
        document.getElementById('Map4_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map4_Address').innerHTML = "  Address: " + addr;
        document.getElementById('Map4_Speed').innerHTML = speedCaption + ": " + speed;
        if (map4.zoomLevel == map4.maxZoomLevel) map4.setZoomLevel(map4.zoomLevel - 3);
    }

    else if (MapName == '4') {
        map5.objects.clear();
        map5.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map5.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map5.zoomTo(pol.getBoundingBox(), false, "default");
        map5.setZoomLevel(17);
        document.getElementById('Map5_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map5_Address').innerHTML = "  Address: " + addr;
        document.getElementById('Map5_Speed').innerHTML = speedCaption + ": " + speed;
        if (map5.zoomLevel == map5.maxZoomLevel) map5.setZoomLevel(map5.zoomLevel - 3);
    }
    else if (MapName == '5') {
        map6.objects.clear();
        map6.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map6.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map6.zoomTo(pol.getBoundingBox(), false, "default");
        map6.setZoomLevel(17);
        document.getElementById('Map6_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map6_Address').innerHTML = "  Address: " + addr;
        document.getElementById('Map6_Speed').innerHTML = speedCaption + ": " + speed;
        if (map6.zoomLevel == map6.maxZoomLevel) map6.setZoomLevel(map6.zoomLevel - 3);
    }
    else if (MapName == '6') {
        map7.objects.clear();
        map7.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map7.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map7.zoomTo(pol.getBoundingBox(), false, "default");
        map7.setZoomLevel(17);
        document.getElementById('Map7_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map7_Address').innerHTML = "  Address: " + addr;
        document.getElementById('Map7_Speed').innerHTML = speedCaption + ": " + speed;
        if (map7.zoomLevel == map7.maxZoomLevel) map7.setZoomLevel(map7.zoomLevel - 3);
    }
    else if (MapName == '7') {
        map8.objects.clear();
        map8.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map8.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map8.zoomTo(pol.getBoundingBox(), false, "default");
        map8.setZoomLevel(17);
        document.getElementById('Map8_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map8_Address').innerHTML = "  Address: " + addr;
        document.getElementById('Map8_Speed').innerHTML = speedCaption + ": " + speed;
        if (map8.zoomLevel == map8.maxZoomLevel) map8.setZoomLevel(map8.zoomLevel - 3);
    }
    else if (MapName == '8') {
        map9.objects.clear();
        map9.objects.add(marker);
        clusterMarkersT.push(marker.coordinate);
        var pol = new nokia.maps.map.Polyline(clusterMarkersT);
        map9.setCenter(pol.getBoundingBox().getCenter(), "default");
        //map9.zoomTo(pol.getBoundingBox(), false, "default");
        map9.setZoomLevel(17);
        document.getElementById('Map9_Vehicle').innerHTML = "  Vehicle Name: " + VehName;
        document.getElementById('Map9_Address').innerHTML = "  Address: " + addr;
        if (map9.zoomLevel == map9.maxZoomLevel) map9.setZoomLevel(map9.zoomLevel - 3);
    }

    return marker;
}
var ltMapIT = new Array();
var mapPoints = null;
var clusterMarkers = new Array();
var clusterMarkerArray = new Array();
//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.objects.remove(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.set("baseMapType", map.NORMAL); break;
                        case 'H': map.set("baseMapType", map.SATELLITE); break;
                        case 'T': map.set("baseMapType", map.TERRAIN); break;
                    }
                }
            }
        }
       
        var bounds = null; // new GLatLngBounds();
        ltMapIT = latlng.split('~&~');
        if (pageName == 'M' || pageName == 'MF') {
            for (var k = 0; k < clusterMarkerArray.length; k++) {
                map.objects.remove(clusterMarkerArray[k]);
                //map.objects.clear();
            }
        }
        clusterPoint_Monitor.length = 0;
        clusterMarkerArray = new Array();

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

            }
            else {
                var lng = new Array();
                lng = ltMapIT[i].split("~#~");
                var point = new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
                lntlngs.push(point);
                clusterPoint_Monitor.push(point);
                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]);
                    var zoom = new Array();
                    clusterMarkerArray.push(mapMarker);
                    clusterMarkers.push(mapMarker.coordinate);
                }               
            }

            //Sakthi 15-Dec-2014 For Map Clustering

            if (location.pathname.indexOf("FullscreenMap.aspx") != -1 && location.search.indexOf("?q=A") != -1) { }
            else if (pageName == 'M' || pageName == 'MF') {
                initialiseSVGParser_Monitor();
                //clusterDataPoints_Monitor(clusterPoint_Monitor, clusterMarkerArray, true);
            }

            if (pageName == 'M' || pageName == 'H' || pageName == 'HF' || pageName == 'MF') {
                var pol = new nokia.maps.map.Polyline(clusterMarkers);
                //map.setCenter(pol.getBoundingBox().getCenter(), "default");
                map.zoomTo(pol.getBoundingBox(), false, "default");
                if (map.zoomLevel == map.maxZoomLevel) map.setZoomLevel(map.zoomLevel - 3);
            }

            if (pageName == 'M') {
                if (MapView.length > 0) {
                    map.set("center", MapView[0]);
                    //map.setZoomLevel(MapView[1]);
                    Array.clear(MapView);
                }
            }
            else if (pageName == 'MF') {
                if (MapViewFullScreen.length > 0) {
                    map.set("center", MapViewFullScreen[0]);
                    map.setZoomLevel(MapViewFullScreen[1]);
                    Array.clear(MapViewFullScreen);
                }
            }
        }      

        // zoom[0] = map.center.latitude;
        // zoom[1] = map.center.longitude;
        // var point = new nokia.maps.geo.Coordinate(parseFloat(zoom[0]), parseFloat(zoom[1]));
        // map.setCenter(point, "default");

    }
    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.objects.remove(mapItMarkers[j]);
                map2.objects.remove(mapItMarkers[j]);
                map3.objects.remove(mapItMarkers[j]);
                map4.objects.remove(mapItMarkers[j]);
                map5.objects.remove(mapItMarkers[j]);
                map6.objects.remove(mapItMarkers[j]);
                map7.objects.remove(mapItMarkers[j]);
                map8.objects.remove(mapItMarkers[j]);
                map9.objects.remove(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 nokia.maps.geo.Coordinate(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.coordinate);
            }

        }


        // zoom[0] = map.center.latitude;
        // zoom[1] = map.center.longitude;
        // var point = new nokia.maps.geo.Coordinate(parseFloat(zoom[0]), parseFloat(zoom[1]));
        // map.setCenter(point, "default");

    }
    catch (Error) {
        //alert(Error);
    }
}
//To plot the Map for MapIT
function DisplayUpdPosition(latlng) {
    try {
        //if (GBrowserIsCompatible()) {
        //collectdata = new GLatLngBounds();
        lt = latlng.split('&');

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

            var Coord = new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
            //var marker = new GMarker(new GLatLng(lng[0], lng[1]));
            var point = new nokia.maps.map.StandardMarker(Coord); //new GLatLng(lng[0], lng[1]);
            map.setCenter(point, "default");
            map.objectgs.add(MapIT_Marker(point, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''));
            //map.addOverlay(MapIT_Marker(point, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''));
            //collectdata.extend(new GLatLng(lng[0], lng[1]));
        }
        map.setCenter(point, "default");
        //map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
        //}
    }
    catch (Error) {
    }
}

function getlngs(query, lndaddress) {

    try {
        var isIE = CheckBrowser();
        //document.getElementById('hdnInput').value = query;
        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; //new GIcon(G_DEFAULT_ICON);
        //        icon = new GIcon(icon, LandMarkImage);
        //        icon.iconSize = new GSize(32, 32);
        var point = new nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        map.setCenter = point;

        //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
        if (bubble) infoBubble.closeAll();
        var OpenBubble = function (evt) {
            var coordinate = evt.currentTarget.coordinate;
            //Set Info Bubble styles(Rounded like Cornors etc.) 
            infoBubbleStyle();
            bubble = infoBubble.openBubble(bubbleTemplate, coordinate);
            //map.setCenter(coordinate, "default");
        }
        //Event to close bubble template
        var CloseBubble = function (evt) {
            infoBubble.closeAll();
        }
        //Event Listener
        var myListener = {
            "mouseover": [OpenBubble, true, null],
            "mouseout": [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 nokia.maps.map.Marker(point, {
            draggable: false,  //the marker is marked to be draggable
            icon: icon,
            eventListener: myListener,
            anchor: new nokia.maps.util.Point(offsetX, offsetY)
        });

        //        if (icon != "../images/flag_2.png") {
        //            marker.icon.width = "32";
        //            marker.icon.height = "32";
        //        }

        //Add marker to the map.
        map.objects.add(marker);
        //Zoom to the result.
        map.zoomTo(marker.getBoundingBox());
        //Zoom out if to close.
        if (map.zoomLevel > 15) map.set("zoomLevel", 15);

        //        GEvent.addListener(marker, "mouseover", function() {
        //            marker.openInfoWindowHtml('<br /><table style="direction:' + VDirection + '" class=\'InfoBubble\'cellpadding=\'5\' cellspacing=\'5\'><tr><td><b>Address</b></td><td>:</td><td>' + search + '</td></tr></table>');
        //        });

        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; */
        //        map.enableScrollWheelZoom();
        //        map.enableContinuousZoom();
        document.getElementById('txtlat').value = lat;
        document.getElementById('txtlong').value = lng;
        centerPoint = new nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        document.getElementById("message").innerHTML = "";
        document.getElementById("pnlInfoWindow").style.display = "none";
        //        $find('ModalPopupExtender1').hide();
        drawCircle();
        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; //new GIcon(G_DEFAULT_ICON);        
        //map = new GMap(document.getElementById("map-dsply"));
        map.objects.clear();
        //icon = new GIcon(icon, LandMarkImage);
        //icon.iconSize = new GSize(32, 32);
        var point = new nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        //map.setCenter(point, "default");


        //Event to open bubble template
        if (bubble) infoBubble.closeAll();
        var OpenBubble = function (evt) {
            var coordinate = evt.currentTarget.coordinate;;
            //Set Info Bubble styles(Rounded like Cornors etc.) 
            infoBubbleStyle();
            bubble = infoBubble.openBubble(bubbleTemplate, coordinate);
            //map.setCenter(coordinate, "default");
        }

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

        //Event Listener
        var myListener = {
            "mouseover": [OpenBubble, true, null],
            "mouseout": [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 nokia.maps.map.Marker(point, {
            draggable: false,  //the marker is marked to be draggable
            icon: icon,
            eventListener: myListener,
            anchor: new nokia.maps.util.Point(offsetX, offsetY)
        });

        //        if (icon != "../images/flag_2.png") {
        //            marker.icon.width = "32";
        //            marker.icon.height = "32";
        //        }

        //var marker = new GMarker(point, { draggable: false, icon: icon });
        try {
            map.objects.add(marker);
            map.zoomTo(marker.getBoundingBox());
        }
        catch (ex) {
        }
        if (map.zoomLevel > 13) map.set("zoomLevel", 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>';

            //            GEvent.addListener(marker, "mouseover", function() {
            //                marker.openInfoWindowHtml('<br /><table cellpadding=\'5\' class=\'InfoBubble\'cellspacing=\'5\'><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + search + '</td></tr></table>');
            //            });

            //            GEvent.addListener(marker, "mouseout", function() { marker.closeInfoWindow(marker); });
        }
        else {
            //document.getElementById('txtlat').value = '';
            //document.getElementById('txtlong').value = '';

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

            //            GEvent.addListener(marker, "mouseover", function() {
            //                //marker.openInfoWindowHtml();
            //            });

            //GEvent.addListener(marker, "mouseout", function() { marker.closeInfoWindow(marker); });
        }

        centerPoint = new nokia.maps.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        document.getElementById("message").innerHTML = "";
        //$find('ModalPopupExtender1').hide();

        //        if (isView == 1) {
        //            document.getElementById('txtRadius').value = radius;
        //        }
        drawCircle();
        map.zoomTo(circle.getBoundingBox(), false, "default");

        //        if (isView == 1)
        //        { document.getElementById('txtRadius').value = ''; }
    }
    catch (Error) {
    }
    //    map.enableScrollWheelZoom();
    //    map.enableContinuousZoom();
}

//Sakthi for Landmark View
function drawCircle_LandmarkPage(landmarkEntries, isLandmarkEnable) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        for (var n = 0; n < landmarkMarkers.length; n++) {
            map.objects.remove(landmarkMarkers[n]);
        }
        landmarkMarkers.splice(n, 1);
        for (var c = 0; c < landMarkCircles.length; c++) {
            map.objects.remove(landMarkCircles[c]);
            //map.removeOverlay(landMarkCircles[c]);
        }
        landMarkCircles.splice(c, 1);
        //landmarkMarkers = null;
    }
    for (var iterator = 0; iterator < lanmarkInformation.length; iterator++) {
        if (lanmarkInformation[iterator] == "") {
            break;
        }
        else {
            var landmarkinfo = lanmarkInformation[iterator].split("~#~");
            centerPoint = new nokia.maps.geo.Coordinate(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
            //centerPoint = new GLatLng(landmarkinfo[0], landmarkinfo[1]);
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new nokia.maps.map.Marker(centerPoint);
            map.setZoomLevel(6);
            //DrawCircle = marker;
            //var marker = new GMarker(new GLatLng(landmarkinfo[0], landmarkinfo[1]));
            var lndTemplate =
            '<div style="text-align:left;"><table style="direction:' + VDirection + '" class=\'InfoBubble\' cellpadding=\'5\' cellspacing=\'2\'><tr><td colspan=3><b><u>' + VLandmarkLocationDetails + '</u></b></td><tr><td><b>' + VOrgCoordinates + '</b></td><td>:</td><td>'
                                    + landmarkLatitude + " , " + landmarkLongitude
            + '</td></tr><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + landmarkinfo[4] + '</td></tr></table></div>';
            if (isLandmarkEnable) {
                var lndMarks = flagMarker_LandmarkPage(centerPoint, landmarkinfo[3], landmarkinfo[4], landmarkinfo[0], 'green', 1, lndTemplate)
                landmarkMarkers.push(lndMarks);
                map.objects.add(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) { doDrawCircle(); map.zoomTo(circle.getBoundingBox(), false, "default"); }
        }
    }
    //    lat, lng, radius, lndName, lndAddr

}
function flagMarker_LandmarkPage(point, lndName, lndAddr, time, id, i_No, content) {
    var icon = null; //new GIcon();
    icon = '../images/flag_2.png';
    if (document.getElementById('hdnLandmarkImage') != null && document.getElementById('hdnLandmarkImage').value != "") {

        lndImage = String(document.getElementById('hdnLandmarkImage').value);

    }
    //    }
    //icon.shadowSize = new GSize(1, 1);
    //icon.iconAnchor = new GPoint(12, 12);
    //icon.infoWindowAnchor = new GPoint(0, 0);




    var bubble = null;
    //map.removeListener("click",);    
    var OpenBubble = function (evt) {
        if (bubble) infoBubble.closeAll();
        bubbleMessage = content;
        var coordinate = evt.currentTarget.coordinate;
        //Set Info Bubble styles(Rounded like Cornors etc.) 
        infoBubbleStyle();
        bubble = infoBubble.openBubble(bubbleMessage, coordinate);
        //map.setCenter(coordinate, "default");
    }
    var CloseBubble = function (evt) {
        infoBubble.closeAll();
    }
    var myListener = {
        "click": [OpenBubble, true, null],
        "mouseover": [OpenBubble, true, null],
        "mouseout": [CloseBubble, true, null]
    };

    var marker = new nokia.maps.map.Marker(
    point, {
        draggable: false,
        eventListener: myListener,
        icon: icon,
        anchor: new nokia.maps.util.Point(2, 22)
    });
    return marker;
}
//End of Landmark View


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

var searchManager = new nokia.maps.advsearch.Manager();
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 (GBrowserIsCompatible()) {
        map.objects.clear();  //clearOverlays();
        if (document.getElementById('ddlType').value == 'addr') {
            search = FrameAddress();
            //geo = new GClientGeocoder();

            //Set the Advance Search manager to the variable
            geo = new nokia.maps.advsearch.Manager();


            //======= GeCode Callback function ======
            geo.addObserver("state", function (observedManager, key, value) {
                if (value == "finished") {
                    if (observedManager.locations.length > 0) {
                        // ===== If there was more than one result, "ask did you mean" on them all =====                       
                        if (observedManager.locations.length > 1) {
                            document.getElementById("message").innerHTML = "Did you mean:";
                            // Loop through the results
                            for (var i = 0; i < observedManager.locations.length; i++) {
                                var p = observedManager.getLocations()[i].displayPosition;

                                document.getElementById("message").innerHTML += "<br>" + (i + 1) + ": <a href='#' onclick='place(" + p.latitude + "," + p.longitude + "); return false;'>" + FormAddressList(observedManager.getLocations()[i]) + "<\/a>";

                            }
                            document.getElementById("pnlInfoWindow").style.display = "block";
                            map.set("center", new nokia.maps.geo.Coordinate(-1.757537, 92.460937));
                        }
                        else {

                            document.getElementById("message").innerHTML = "";
                            var p = observedManager.getLocations()[0].displayPosition;

                            if (document.getElementById('hdnLatLong') != null) {
                                document.getElementById('hdnLatLong').value = p.latitude + ',' + p.longitude;
                            }
                            Findplace(p.latitude, p.longitude, '', document.getElementById('txtRadius').value, 0);
                            LandMarkImage = '';
                        }
                    }
                    else {
                        //var reason = "Code " + result.Status.code;     
                        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 if (value == "failed") {
                    //var reason = "Code " + result.Status.code;
                    //if (reasons[result.Status.code]) { reason = reasons[result.Status.code] }
                    //alert('Could not find "' + search + '" ' + reason);
                    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 + '" ');
                        }
                    }

                    //    TrinetraCustomAlerts('Could not find "' + search + '" ');
                    loadForLandMark();
                    //alert("Unable to find the address. Please verify the location");
                }
            });

            // ====== Perform the Geocoding ======
            searchTerm = {//geocode
                searchText: search,
                spatialFilter: {
                    radius: 8000
                },
                representationOptions: {
                    language: [document.getElementById("hdnMapLng").value], //["en-US"],
                    maxResults: 20,
                    pageInformation: 1,
                    //possible SearchResponseAttribute switches: 
                    //"perfomedSearch(ps)", "label(la)", "didYouMeanSuggestion(dm)", "matchQuality(mq)", "matchType(mt)"
                    //request label, didYouMeanSuggestion, matchType and skip matchQuality
                    searchResponseAttributes: ["la", "dm", "mq", "mt"],
                    //possible LocationAttribute switches:
                    //"address(ar)", "mapReference(mr)", "mapView(mv)", "additionalData(ad)", "alternativeLabels(al)"
                    //request address, mapReference, mapView, additionalData and alternativeLabels
                    locationAttributes: ["ar", "mr", "mv", "ad", "al"],
                    //possible AddressAttribute switches:
                    //"country(ctr)", "state(sta)", "county(cty)", "city(cit)", "district(dis)", "street(str)", 
                    //"houseNumber(hnr)", "postalCode(pst)", "suite(sui)", "floor(flr)", "additionalAttributes(add)", "alternativeAttributes(alt)"
                    //request state, city, street, houseNumber, postalCode, suite, floor, and skip county and district
                    addressAttributes: ["sta", "-cty", "cit", "dis", "str", "hnr", "pst", "sui", "flr", "add"]
                },
                metaInfo: {
                    requestId: "qwertzuiop",
                    //Level of verbose information which will be included in the response structure. 
                    //Can be a value between 0 and 5.
                    verboseMode: 2
                }
            };
            geo.clear();
            geo.geocode(search);
        }
        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 nokia.maps.geo.Coordinate(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value));
            //map.setCenter(centerPoint, 16);
            map.setCenter(centerPoint, "default")

            //Search Process for Reverse geoCode.
            var bubble = null;
            var bubbleTemplate;
            if (bubble) infoBubble.closeAll();
            var OpenBubble = function (evt) {
                var coordinate = evt.currentTarget.coordinate;
                //Set Info Bubble styles(Rounded like Cornors etc.) 
                infoBubbleStyle();
                bubble = infoBubble.openBubble(bubbleTemplate, coordinate);
            }
            var CloseBubble = function (evt) {
                infoBubble.closeAll();
            }

            var DragEnd = function (evt) {
                var coord = map.pixelToGeo(evt.displayX, evt.displayY);
                document.getElementById('txtlat').value = coord.latitude;
                document.getElementById('txtlong').value = coord.longitude;
                point = coord;
            }

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

            //Search Callback function.
            searchManager.addObserver("state", function (observedManager, key, value) {
                if (value == "finished") {

                    if (observedManager.locations.length > 0) {

                        //var strAddress = observedManager.getLocations()[0].address.street + ',' + observedManager.getLocations()[0].address.city + ',' + observedManager.getLocations()[0].address.state + ',' + observedManager.getLocations()[0].address.additionalData.CountryName;
                        var strAddress = addr != '' ? addr : BubbleAddress(observedManager.getLocations()[0].address.street) + BubbleAddress(observedManager.getLocations()[0].address.city) + BubbleAddress(observedManager.getLocations()[0].address.state) + observedManager.getLocations()[0].address.additionalData.CountryName;
                        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.latitude + " , " + coord.longitude
            + '</td></tr><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + strAddress + '</td></tr></table></div>';

                        //var te = map.geoToPixel(coord);
                        //var offset = map.getDisplayOffset(coord, te.x, te.y)
                        if (marker) map.objects.remove(marker);

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

                        marker = new nokia.maps.map.Marker(coord, {
                            draggable: true,  //the marker is marked to be draggable
                            icon: image,
                            eventListener: myListener,
                            anchor: new nokia.maps.util.Point(offsetX, offsetY)
                        });

                        //                        if (image != "../images/flag_2.png") {
                        //                            marker.icon.width = "32";
                        //                            marker.icon.height = "32";
                        //                        }

                        //                    var imageMarker = new nokia.maps.map.Marker([52.52, 13.5], {
                        //                        icon: "../images/flag_2.png",
                        //                        anchor: new nokia.maps.util.Point(29, 71)
                        //                    });


                        //map.objects.add(imageMarker);
                        map.objects.add(marker);

                        //map.objects.add(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.latitude + '#' + centerPoint.longitude + '#' + 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 nokia.maps.geo.Coordinate(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value))

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

                        //zoom out if too close
                        if (map.zoomLevel > 15) map.set("zoomLevel", 15);
                        LandMarkImage = '';
                    }
                    //                    else {
                    //                        alert("Address Cannot be found. Please check the LatLong Values ");
                    //                    }
                } else if (value == "failed") {
                    TrinetraCustomAlerts("Address Cannot be found. Please check the LatLong Values ");
                }
            });

            landmarkLatitude = document.getElementById('txtlat').value;
            landmarkLongitude = document.getElementById('txtlong').value;
            var coord = new nokia.maps.geo.Coordinate(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();
            //make a rev geocode request
            searchManager.reverseGeocode(revGeocodeTerm);
            //var geoFinder = new GClientGeocoder();                
            //geoFinder.getLocations(latlong, showAddress_Latlng);
            showControls(1);
        }
        //}
        // display a warning if the browser was not compatible
        //else {
        //    alert("Sorry, the Google Maps API is not compatible with this browser"); 
        //}
    }
    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 (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) {
}

//Get Address by Map Co-ordinates
//function getAddress(overlay, latlng) {
//    if (latlng != null) {
//        address = latlng;

//        geocoder.getLocations(latlng, showAddress_Latlng);
//    }
//}

/* Function for zoom-in ,zoom-out in Context Menu */

//function hideContext() {
//    contextmenu.style.visibility = "hidden";
//}
//// === functions that perform the context menu options ===
//function zoomIn() {
//    // perform the requested operation
//    map.zoomIn();
//    // hide the context menu now that it has been used
//    contextmenu.style.visibility = "hidden";
//}
//function zoomOut() {
//    // perform the requested operation
//    map.zoomOut();
//    // hide the context menu now that it has been used
//    contextmenu.style.visibility = "hidden";
//}



/* 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) {
    }
}
//function showAddress_Latlng(response) {
//    if (document.getElementById('ddlType') != null) {
//        showControls(document.getElementById('ddlType').selectedIndex);
//    }

//    var icon = new GIcon(G_DEFAULT_ICON);
//    //To enable the Mouse wheel Scroll
//    map.enableScrollWheelZoom();
//    map.enableContinuousZoom();
//    icon = new GIcon(icon, LandMarkImage);
//    icon.iconSize = new GSize(32, 32);

//    if (!response || response.Status.code != 200) {
//        alert("Address Cannot be found. Please check the LatLong Values ");
//    } else {
//        if (response != null) {
//            place = response.Placemark[0];
//            marker = new GMarker(centerPoint, { draggable: true, icon: icon });

//            GEvent.addListener(marker, "dragstart", function() {
//                map.closeInfoWindow();
//            });

//            GEvent.addListener(marker, "dragend", function() {
//                document.getElementById('txtlat').value = marker.getPoint().lat();
//                document.getElementById('txtlong').value = marker.getPoint().lng();
//                point = new GLatLng(document.getElementById('txtlat').value, document.getElementById('txtlong').value);
//            });
//            //marker = new GMarker(point, { draggable: true, icon: icon });
//            map.addOverlay(marker);

//            GEvent.addListener(marker, "mouseover", function() {
//                marker.openInfoWindowHtml(
//            '<table style="direction:' + VDirection + '" class=\'InfoBubble\' cellpadding=\'5\' cellspacing=\'2\'><tr><td colspan=3><b><u>Landmark Location Details</u></b></td><tr><td><b>Original Coordinates</b></td><td>:</td><td>'
//            + response.name.split(",")[0] + " , " + response.name.split(",")[1]
//            + '</td></tr><tr><td><b>Address</b></td><td>:</td><td>' + place.address + '</td></tr></table>');
//            });

//            GEvent.addListener(marker, "mouseout", function() { marker.closeInfoWindow(marker); });
//        }
//        var LocDesc = (document.getElementById('txtLocationDesc').value == "Description") ? "" : document.getElementById('txtLocationDesc').value;
//        var Radius = (document.getElementById('txtRadius').value == "Radius") ? 500 : document.getElementById('txtRadius').value;


//        getAddress = document.getElementById('txtLocationName').value + '#' + centerPoint.y + '#' + centerPoint.x + '#' + LocDesc + '#' + place.address + '#' + 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('txtlat').value = place.Point.coordinates[1];
//        //document.getElementById('txtlong').value = place.Point.coordinates[0];
//        document.getElementById('txtstreet').value = place.address;

//        centerPoint = new GLatLng(document.getElementById('txtlat').value, document.getElementById('txtlong').value);
//        drawCircle();

//        //        if (isViewLatLong == 1) {
//        //            document.getElementById('txtlat').value = '';
//        //            document.getElementById('txtlong').value = '';
//        //        }
//    }
//}

var landmarkLatitude = '';
var landmarkLongitude = '';
var landmarkMarkers = new Array();
var landMarkCircles = new Array();
function drawCircleForLandmark(landmarkEntries, isLandmarkEnable) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        for (var n = 0; n < landmarkMarkers.length; n++) {
            map.objects.remove(landmarkMarkers[n]);
        }
        landmarkMarkers.splice(n, 1);
        for (var c = 0; c < landMarkCircles.length; c++) {
            map.objects.remove(landMarkCircles[c]);
            //map.removeOverlay(landMarkCircles[c]);
        }
        landMarkCircles.splice(c, 1);
        //landmarkMarkers = null;
    }
    clusterPoint.length = 0;
    for (var iterator = 0; iterator < lanmarkInformation.length; iterator++) {
        if (lanmarkInformation[iterator] == "") {
            break;
        }
        else {
            var landmarkinfo = lanmarkInformation[iterator].split("~#~");
            centerPoint = new nokia.maps.geo.Coordinate(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
            //centerPoint = new GLatLng(landmarkinfo[0], landmarkinfo[1]);
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new nokia.maps.map.Marker(centerPoint);
            //DrawCircle = marker;
            //var marker = new GMarker(new GLatLng(landmarkinfo[0], landmarkinfo[1]));
            if (isLandmarkEnable) {
                clusterPoint.push(centerPoint);
                var lndMarks = flagMarker(centerPoint, landmarkinfo[3], landmarkinfo[4], landmarkinfo[0], 'green', 1, landmarkinfo[5])
                landmarkMarkers.push(lndMarks);
                //                if (isShowLandmarkPlotter == 0 && document.getElementById('chkShowLandmarks') != null && document.getElementById('chkShowLandmarks').checked == true) {
                //                    if (clusterBackup != null) {
                //                        for (var l = 0; l < clusterBackup.length; l++) {
                //                            clusterBackup[l].destroy();
                //                            clusterBackup[l].cluster();
                //                        } 
                //                    }
                //                    map.objects.add(lndMarks);
                //                }
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) { doDrawCircle(); }
        }
    }
    //    lat, lng, radius, lndName, lndAddr


}
function flagMarker(point, lndName, lndAddr, time, id, i_No, LandMarkIcon) {
    var icon = null; //new GIcon();

    //    if (id == 'green') {
    //icon = new GIcon(icon, '../images/flag_1.png');
    //icon = '../images/flag_2.png';
    //    }
    //icon.shadowSize = new GSize(1, 1);
    //icon.iconAnchor = new GPoint(12, 12);
    //icon.infoWindowAnchor = new GPoint(0, 0);

    if (LandMarkIcon != null && LandMarkIcon != '') {
        icon = LandMarkIcon.replace("~", "..");
    }
    else {
        icon = '../images/flag_2.png';
    }



    var bubble = null;
    //map.removeListener("click",);    
    var OpenBubble = function (evt) {
        if (bubble) infoBubble.closeAll();
        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.currentTarget.coordinate;
        //Set Info Bubble styles(Rounded like Cornors etc.) 
        infoBubbleStyle();
        bubble = infoBubble.openBubble(bubbleMessage, coordinate);
        //map.setCenter(coordinate, "default");
    }
    var CloseBubble = function (evt) {
        infoBubble.closeAll();
    }
    var myListener = {
        "click": [OpenBubble, true, null],
        "mouseover": [OpenBubble, true, null],
        "mouseout": [CloseBubble, true, null]
    };

    var marker = new nokia.maps.map.Marker(
    point, {
        draggable: false,
        eventListener: myListener,
        icon: icon,
        anchor: new nokia.maps.util.Point(2, 22)
    });
    return marker;
}

var circle;
var centerMarker;
var circleUnits;
var circleRadius;
//var zoom = 2;
var centerPoint; // = new GLatLng(40,-100);
//var oRadius;

function drawCircle() {
    try {
        var oRadius = document.getElementById('txtRadius');
        //oRadius.value = ((oRadius.value != '' && oRadius.value != "Radius" && oRadius.value != 'الشُّعاع')) ? oRadius.value : 500;
        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();
        //map.addControl(new GLargeMapControl());
        //map.addControl(new GMapTypeControl());
        //map.addControl(new GOverviewMapControl());
    }
    catch (Error) {
    }
}

function doDrawCircle() {
    try {
        if (circle && canClearCircle) {
            map.objects.remove(circle);
        }

        var center = map.center;

        //var bounds = new GLatLngBounds();


        var circlePoints = Array();

        with (Math) {
            //if (circleUnits == 'KM') {
            var d = circleRadius / 6378.8; // radians
            d = d / 1000;
            //}
            //		else { //miles
            //			var d = circleRadius/3963.189;	// radians
            //		}
            //var d = circleRadius/6378.8;	
            //            var lat1 = (PI / 180) * (!canClearCircle ? landmarkLatitude : center.lat()); // radians
            //            var lng1 = (PI / 180) * (!canClearCircle ? landmarkLongitude : center.lng()); // radians

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

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

                var point = new nokia.maps.geo.Coordinate(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                //var point = new GLatLng(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                circlePoints.push(point);
                //bounds.extend(point);
            }

            if (d < 1.5678565720686044) {


                circle = new nokia.maps.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                pen: { strokeColor: "#5270B2", lineWidth: 2 },
                                brush: { color: "#A4A7" }
                            }
                        );

                //circle = new GPolygon(circlePoints, '#5270B2'/*#000000'*/, 2, 1, '#D8E2FA', 0.25);
            }
            else {
                circle = new nokia.maps.map.Circle(
                            centerPoint,
                //circleRadius,
                            circleRadius,
                            {
                                pen: { strokeColor: "#5270B2", lineWidth: 2 },
                                brush: { color: canClearCircle ? '#000000' : '#A4A7' }
                            }
                        );

                //circle = new GPolygon(circlePoints, canClearCircle ? '#000000' : '#D8E2FA', 2, 1);
            }

            landMarkCircles.push(circle);
            map.objects.add(circle);
            //map.zoomTo(circle.getBoundingBox(), false, "default");
            // Included code to append Landmark & MapIT for best zoom level
            if (mapPoints != null) {
                //bounds.extend(mapPoints);
            }
            else {
                //map.setZoom(map.getBoundsZoomLevel(bounds));
            }
        }

    }
    catch (Error) {
    }
}

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

//Window Functions
//window.onload = load;
//window.onunload = GUnload;

//        function silentErrorHandler() { return true; }
//        window.onerror = silentErrorHandler;

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;
    //    alert(document.getElementById('hdnMapItValue').value);
}
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 nokia.maps.geo.Coordinate(map.center.latitude, map.center.longitude));
    MapView.push(map.zoomLevel);
}

function GetMapViewFullScreen() {
    Array.clear(MapViewFullScreen);
    MapViewFullScreen.push(new nokia.maps.geo.Coordinate(map.center.latitude, map.center.longitude));
    MapViewFullScreen.push(map.zoomLevel);
}

function MapViewEvent() {
    GetMapView();
}

function SetMapView() {
    if (MapView.length > 0) {
        var coord = new nokia.maps.geo.Coordinate(parseFloat(String(MapView[0].latitude)), parseFloat(String(MapView[0].longitude)));
        var marker = new nokia.maps.map.Marker(coord)
        //map.set("center", marker.getBoundingBox().getCenter());
        map.set("center", coord);
        //map.zoomTo(marker.getBoundingBox().getCenter(), false);
        map.setZoomLevel(MapView[1]);

    }
}

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

//To clear the all the overlays in the maps container.
function ClearOverlays() {
    if (bubble) infoBubble.closeAll();
    if (bubbles) infoBubble.closeAll();
    //if (map) map.objects.clear();
    if (clusterMarkerArray.length > 0) {
        for (var k = 0; k < clusterMarkerArray.length; k++) {
            map.objects.remove(clusterMarkerArray[k]);
        }
    }
}
//To clear the all the overlays in the maps container.
function ClearMap() {
    if (bubble) infoBubble.closeAll();
    if (bubbles) infoBubble.closeAll();
    if (map) map.objects.clear();
}

var IsMSIE9 = null;
//Set Center to dubai 
function SetCenter() {
    if (map) {
        map.set('center', centerCoordinate);
        map.setZoomLevel(4, "default");
    }
}

//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";
        //infoBubble.node.firstChild.style.cssText = "borderRadius:10px 10px 10px 10px";
        //infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.right = "5px";
        //infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.top = "4px";
        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.style.borderColor = "#959CC8";
        //border-style: solid;border-color: #959CC8;border-width:1px;box-shadow:10px 10px 20px #000;
        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';
    }

    map.addListener("displayready", nokia.maps.map.Display.NORMAL.setTileLanguage(Plang));
    map.addListener("displayready", nokia.maps.map.Display.TRAFFIC.setTileLanguage(Plang));
    map.addListener("displayready", nokia.maps.map.Display.SATELLITE.setTileLanguage(Plang));
    map.addListener("displayready", nokia.maps.map.Display.SATELLITE.setTileLanguage(Plang));
    map.addListener("displayready", nokia.maps.map.Display.SATELLITE_PLAIN.setTileLanguage(Plang));
    map.addListener("displayready", nokia.maps.map.Display.TERRAIN.setTileLanguage(Plang));
    map.addListener("displayready", nokia.maps.map.Display.SMART_PT.setTileLanguage(Plang));

    //OLD CODE for changing the Language 
    //    if (LoadTime == null) {
    //        var server_rr = 0;
    //        var token = "PzCfyYAsV98qvfU8gusqRg";
    //        var appId = "UdwAigBKPRhu01vbIGkI";
    //        var Plang = "Ar";

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

    //                return ["https://",
    //                					server_rr,
    //                					".maps.nlp.nokia.com/maptile/",
    //                					"2.1",
    //                					"/",
    //                					"maptile",
    //                					"/",
    //                					"newest",
    //                					"/",
    //                					MapType,
    //                					"/",
    //                					level,
    //                					"/",
    //                					col,
    //                					"/",
    //                					row,
    //                					"/",
    //                					"256",
    //                					"/",
    //                					"png",
    //                					"?lg=",
    //                					Plang,
    //                					"&token=",
    //                					token,
    //                					"&app_id=",
    //                					appId
    //                					].join("");
    //            }
    //        });

    //       // https: //1.base.maps.cit.api.here.com/maptile/2.1/maptile/newest/normal.day/13/6693/3575/256/png8?lg=CHI&lg2=ENG&app_id=DemoAppId01082013GAL&app_code=AJKnXv84fjrb0KIHawS0Tg
    //        // very evil to overwrite the base provider for minimap provider
    //        // nokia.maps.map.js.nokiaTileProviders.base[0] = baseMapProvider;
    //        LoadTime = 1;
    //        map.set("baseMapType", baseMapProvider);
    //    }
    //    else {
    //        LoadTime = null;
    //    }
}
/***********************************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) {

    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 nokia.maps.map.Polyline(
                        new nokia.maps.geo.Strip(arr, "values lat lng"),
                        {
                            color: "#00F6", width: 5
                        });

    Start = new nokia.maps.map.Marker(route.path.get(0), {
        icon: "../images/Start_point.png",
        $id: "marker",
        //anchor: new nokia.maps.util.Point(dspX, dspY)
        anchor: { x: 4, y: 28 },
        zIndexProcess: function (m) {
            return 28800001;
        }
    });

    End = new nokia.maps.map.Marker(route.path.get(route.path.getLength() - 1), {
        icon: "../images/End_point.png",
        $id: "marker",
        //anchor: new nokia.maps.util.Point(dspX, dspY)
        anchor: { x: 4, y: 28 },
        zIndexProcess: function (m) {
            return 28800001;
        }
    });
    coordPlayBack = route.path.get(0);
    iconPlayback = PlayBack[coordPlayBack.latitude + "," + coordPlayBack.longitude].icon;
    busMarker = new nokia.maps.map.Marker(route.path.get(0), {
        //icon: "../images/vechile_New.png",
        icon: iconPlayback,
        $id: "marker",
        //anchor: new nokia.maps.util.Point(dspX, dspY)
        anchor: { x: 9, y: 12 },
        zIndexProcess: 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.objects.addAll([route, marker]);    
    //map.objects.add(busMarker);
    map.objects.addAll([Start, End, busMarker]);
    map.zoomTo(route.getBoundingBox());
    //display.setZoomLevel(display.zoomLevel - 1);

    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.get(that.idx);
            marker.set("coordinate", coord);
            if (bubbles) infoBubble.closeAll();
            var Info = PlayBack[coord.latitude + "," + coord.longitude];
            if (document.getElementById('chkInfoBubble').checked) {
                if (!CheckBrowserForBubble() || IsMSIE9 == true) {
                    bubbles = infoBubble.openBubble(Info.Info, coord);
                }
                else {
                    setTimeout(function () { bubbles = infoBubble.openBubble(Info.Info, coord) }, 500);
                }
                //bubbles = infoBubble.openBubble(Info.Info, coord);
            }

            if (Info.Alarm) {
                //marker.set("icon", "../images/carmarker_Alarm.png");
                marker.set("anchor", new nokia.maps.util.Point(15, 31))
                var markerAlarm = plotPlaynBackAlarm(Info.Info, coord);
                map.objects.add(markerAlarm);
                playAlarm.push(markerAlarm);
            }
            else {

                marker.set("icon", Info.icon);
                //marker.set("anchor", new nokia.maps.util.Point(9, 12))
                if (Info.icon == '../images/NW.png' || Info.icon == '../images/NE.png' || Info.icon == '../images/SW.png' || Info.icon == '../images/SE.png') {
                    marker.set("anchor", new nokia.maps.util.Point(22, 22))
                }
                else if (Info.icon == '../images/W.png' || Info.icon == '../images/E.png') {
                    marker.set("anchor", new nokia.maps.util.Point(9, 12))
                }
                else {
                    marker.set("anchor", new nokia.maps.util.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.getLength() - 1) {
                if (CanZoom) {
                    var RouteMovement = PlayBackZoom.slice(startCount, 10 * count)
                    map.zoomTo(new nokia.maps.map.Polyline(RouteMovement).getBoundingBox(), false, "constantvelocity");
                    if (map.zoomLevel > 17) map.setZoomLevel(map.zoomLevel - 1);
                }
            }
            else {
                map.zoomTo(route.getBoundingBox(), false, "constantvelocity");
            }
            /*********************************************************************************************/

            // Force immediate re-render of the map
            //map.update(-0, true);


            /****Play Event****/
            // If we get to the end of the route reverse direction
            if (!that.idx || that.idx === path.getLength() - 1) {
                that.dir *= -1;
                if (that.idx === path.getLength() - 1) {
                    walker.pause();
                    that.dir = -1;
                    that.idx = 0;
                    animate.title = Caption_Play;
                    animate.src = "../images/play.png";
                    if (bubbles) infoBubble.closeAll();
                    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.get(that.idx);
            marker.set("coordinate", coord);
            marker.set("icon", iconPlayback)
            this.isWalking = false;
            if (bubbles) infoBubble.closeAll();
            walker.ClearSettings();
            walker.clearAlarms();
            map.zoomTo(route.getBoundingBox());
            //walker.walk();
        }
        /****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.objects.remove(playAlarm[k]);
                }
            }
            Array.clear(playAlarm);
        }
    };

    // Constructs Walk object which makes given marker walk along provided path
    walker = new Walker(busMarker, route.path);
    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) {
        if (bubble) infoBubble.closeAll();
        //Set Info Bubble styles(Rounded like Cornors etc.) 
        infoBubbleStyle();
        coordinate = evt.currentTarget.coordinate;
        bubble = infoBubble.openBubble(bubbleMessage, coordinate);
    }
    //Event to close bubble template
    var CloseBubble = function (evt) {

        setTimeout(function () {
            // Whatever you want to do after the wait
            infoBubble.closeAll();
        }, 3000);
    }

    //Remove the info bubble on map click.
    map.addListener("click", function (evt) {
        if (bubble) infoBubble.closeAll();
    });

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

    var alarmMarker = new nokia.maps.map.Marker(coord, {
        icon: "../images/carmarker_Alarm.png",
        eventListener: myListener,
        anchor: { x: 15, y: 31 },
        zIndexProcess: function (m) {
            return 28800001;
        }
    });
    return alarmMarker;
}

//Show hide marker in playback.
function Addcontainer(id) {
    if (id.checked) {
        if (markersContainer) map.objects.remove(markersContainer);
        map.objects.add(markersContainer);
    }
    else {
        map.objects.remove(markersContainer);
    }
}




function PlotGeozone(checksts, pageName) {

    if (!checksts) {
        clearPoly_Hstry();
        isShowGeozonePlotter = false;
    }
    else {
        // var GeozoneDetails = "11.060738#76.941433~11.058904#76.943263|GNMills|1&10.997356#76.986947~10.997346#76.987018~10.997289#76.987004~10.997293#76.986949|Angler_small&10.997521#76.987005~10.997579#76.987445~10.997300#76.987670~10.997273#76.987096|Angler_Tec&10.999576#77.051669~10.997742#77.053499|Ondipudur|1"; //document.getElementById('hdnGeozoneValue').value;

        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 nokia.maps.geo.Coordinate(x / f, y / f);
};

function loadMap_Hstry() {
    try {
        if (map) {
            //map.objects.clear();
            if (document.getElementById('map-dsply').innerHTML == "" || document.getElementById('map-dsply').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
                if (map.getComponentById("ZoomBar")) map.removeComponent(map.getComponentById("ZoomBar"));
                //if (map.getComponentById("TypeSelector")) map.removeComponent(map.getComponentById("TypeSelector"));
                if (map.getComponentById("Overview")) map.removeComponent(map.getComponentById("Overview"));
                if (map.getComponentById("zoom.DoubleClick")) map.removeComponent(map.getComponentById("zoom.DoubleClick"));
                if (map.getComponentById("Behavior")) map.removeComponent(map.getComponentById("Behavior"));
                if (map.getComponentById("InfoBubbles")) map.removeComponent(map.getComponentById("InfoBubbles"));
                if (map.getComponentById("ViewControl")) map.removeComponent(map.getComponentById("ViewControl"));
            }
        }
    }
    catch (Error) {

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

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

    }

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

    var mapTypeHolder = document.getElementById("hdnMapType");
    if (mapTypeHolder != null) {
        switch (mapTypeHolder.value) {

            case 'N': map.set("baseMapType", map.NORMAL); break;
            case 'S': map.set("baseMapType", map.SATELLITE); break;
            case 'H': map.set("baseMapType", map.HYBRID); break;
        }
    }
}
function draw_rectangle(a, b, isRestricted) {
    var icon = "../images/flag_8.png"
    if (myrectangle != null) {
        map.objects.remove(myrectangle);
    }
    //var infoBubble1 = new nokia.maps.map.component.InfoBubbles();
    if (a != null && b != null) {

        var rFilClr = "#2387";  //"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
        var rLneClr = "#fd942d"; //#3355ff - Normal Geozone #FF0000 - Restricted Geozone #2E8B57 - UnRestricted Geozone

        if (isRestricted == 'true' || isRestricted == '1') {
            rFilClr = "#F145";
            rLneClr = "#FF0000";
        }
        else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
            rFilClr = "#2E45";
            rLneClr = "#2E8B57";
        }
        else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
            rFilClr = "rgba(65,105,225, 0.5)";
            rLneClr = "rgb(0,0,128,0)";
        }

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


        // On mouse click we fire off the default event handler
        //myrectangle.addListener("click", defaultHandler);
        if (isview == 10) {
            //alert(sGeoName);
            myrectangle.addListener(
              'click',
              function (e) {
                  infoBubble.openBubble(
                  'Geozone Name : ' + sGeoName,
                  getCentroid(e.target.path)
                );
                  nokia.maps.dom.EventTarget(bubble.node).addListener('click', function (e) {
                      infoBubble.closeAll();
                  });
              }
            );
        }
        polyShapeArray.push(myrectangle);
        map.objects.add(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 nokia.maps.geo.BoundingBox(r1, r2);
        var marker1 = r1;  //new nokia.maps.geo.Coordinate(r1); //GMarker(r1);
        var marker2 = r2;

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

        polyArray.length = 0;

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

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

        r1 = ''
        r2 = ''
        if (location.pathname.indexOf("HistoryPage.aspx") == -1)
            map.zoomTo(myrectangle.getBoundingBox(), false, "default");

    }
}

//var polyShapeArray = new Array();
function drawPoly_hstry(point, isRestricted, pageName) {
    var icon = "../images/flag_8.png"
    marker = new nokia.maps.map.StandardMarker(
                                    point,
                                    {
                                        draggable: true
                                    }
                                );
    markers.push(marker);
    map.objects.add(marker);
    // map.objects.add(marker);
    for (i = 0; i < markers.length; i++) {
        polyPoints.push(markers[i].coordinate);
        var appendvalues = markers[i].coordinate.latitude + ',' + markers[i].coordinate.longitude + '#';
        polyArray.push(appendvalues);
    }

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

    // Close the shape with the last line or not
    //polyPoints.push(markers[0].getLatLng()) "#fd942d";

    var pFilClr = "#2387";  //"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
    var pLneClr = "#3355ff"; //#3355ff - Normal Geozone #FF0000 - Restricted Geozone #2E8B57 - UnRestricted Geozone

    if (isRestricted == 'true' || isRestricted == '1') {
        pFilClr = "#F145";
        pLneClr = "#FF0000";
    }
    else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
        pFilClr = "#2E45";
        pLneClr = "#2E8B57";
    }
    else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
        pFilClr = "rgba(65,105,225, 0.5)";
        pLneClr = "rgb(0,0,128,0)";
    }

    polyShape = new nokia.maps.map.Polygon(polyPoints, {
        $name: sGeoName,
        pen: { strokeColor: pLneClr, lineWidth: .3 },
        brush: { color: pFilClr }
    }); //2387
    polyShape.addListener(
              'click',
              function (e) {
                  infoBubble.openBubble(
                  'Geozone Name : ' + sGeoName,
                  getCentroid(e.target.path)
                );
                  nokia.maps.dom.EventTarget(bubble.node).addListener('click', function (e) {
                      infoBubble.closeAll();
                  });
              });
    polyShapeArray.push(polyShape);
    map.objects.add(polyShape);

}


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.objects.remove(myrectangle);
        myrectangle = null;
    }
    if (polyShapeArray != undefined && polyShapeArray != null) {
        for (var i = 0; i < polyShapeArray.length; i++) {
            if (polyShapeArray[i] != null) {
                map.objects.remove(polyShapeArray[i]);
            }
        }
        polyShapeArray = new Array();
    } map.objects.clear();
    loadMap_Hstry();
}

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

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

        with (Math) {
            var d = circleRadius / 6378.8; // radians
            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 nokia.maps.geo.Coordinate(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                circlePoints.push(point);
            }

            var cFilClr = "#2387";  //"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
            var cLneClr = "#3355ff"; //#3355ff - Normal Geozone #FF0000 - Restricted Geozone #2E8B57 - UnRestricted Geozone

            if (isRestricted == 'true' || isRestricted == '1') {
                cFilClr = "#F145";
                cLneClr = "#FF0000";
            }
            else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
                cFilClr = "#2E45";
                cLneClr = "#2E8B57";
            }
            else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
                cFilClr = "rgba(65,105,225, 0.5)";
                cLneClr = "rgb(0,0,128,0)";
            }

            if (d < 1.5678565720686044) {


                circle = new nokia.maps.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                pen: { strokeColor: cLneClr, lineWidth: 2 },
                                brush: { color: cFilClr }
                            }
                        );
            }
            else {
                circle = new nokia.maps.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                pen: { strokeColor: cLneClr, lineWidth: 2 },
                                brush: { color: cFilClr }
                            }
                        );
            }

            polyShapeArray.push(circle);
            map.objects.add(circle);
        }
    }
    catch (Error) {
    }
}

function ShowGeozone_Hstry(latlng, isView, geoName, geoType, isRestricted, cRadius, pageName) {
    if (geoType == 1) {
        var isIE = CheckBrowser();
        isview = isView;
        sGeoName = geoName;
        Geozonetype = 'RC';
        //clearPoly_Hstry();
        loadMap_Hstry();
        //polyPoints.length = 0;
        //polyArray.length = 0;
        var collectdata = new Array();
        var lt = latlng.split('&');
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            polyPoints.push(new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1])));
            var point = new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));

            mapClickRectangle('', point, isRestricted, pageName);
        }
        //zoomToPoly();
    }
    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('&');
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            //polyPoints.push(new GLatLng(lng[0],lng[1]));
            var point = new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
            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('&');
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            var point = new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
            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;
              }
              HidePopUp();
          }
          else { TrinetraCustomAlerts('Already \"Show All Landmarks\" option is in enable mode'); }
      });
                group.addEntry("Disable All Landmarks",
      function (activationEvent) {
          if (isShowLandmarkPlotter == 1) {

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

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

            // 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 clusterDataPoints(data) {
//    clusterProvider = new nokia.maps.clustering.ClusterProvider(map, {
//        eps: 16,
//        minPts: 1,
//        dataPoints: data,
//        theme: new ZoomToTheme()
//    });
//    clusterProvider.cluster();

//    //addZoomToListener(map);
//}
function initialiseSVGParser() {
    var color,
    iconSVG =
      ['<svg width=\'51\' height=\'51\' xmlns=\'http://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=\'http://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=\'http://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=\'http://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 nokia.maps.map.Marker(dataPoints.getBounds().getCenter(),
                          {
                              icon: markerIcon,
                              anchor: new nokia.maps.util.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 nokia.maps.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();
        }
    }

}

/// Clustering for Monitor plotting

function initialiseSVGParser_Monitor() {
    var color_m,
    iconSVG_m =
      ['<svg width=\'51\' height=\'51\' xmlns=\'http://www.w3.org/2000/svg\'>' +
    //'<image src=\'http:\\localhost:53046\TRINETRA_Web\images\electric-vehicle.jpg\' x=\'0\' y=\'0\' height=\'51px\' width=\'51px\'/>' +
    //'<rect x=\'50\' y=\'20\' rx=\'20\' ry=\'20" width=\'51\' height=\'51\' style=\'fill:red;stroke:black;stroke-width:5;opacity:0.5\' />' +
    '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'25\' cy=\'25\' r=\'25\' stroke-width=\'4\'/>' +
    //          '<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=\'http://www.w3.org/2000/svg\'>' +
    //'<rect x=\'50\' y=\'20\' rx=\'20\' ry=\'20" width=\'47\' height=\'47\' style=\'fill:red;stroke:black;stroke-width:5;opacity:0.5\' />' +
    //'<image src=\'http:\\localhost:53046\TRINETRA_Web\images\electric-vehicle.jpg\' x=\'0\' y=\'0\' height=\'47px\' width=\'47px\'/>' +
    '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'23\' cy=\'23\' r=\'23\' stroke-width=\'4\'/>' +
    //         '<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=\'http://www.w3.org/2000/svg\'>' +
    //'<rect x=\'50\' y=\'20\' rx=\'20\' ry=\'20" width=\'43\' height=\'43\' style=\'fill:red;stroke:black;stroke-width:5;opacity:0.5\' />' +
    //'<image src=\'http:\\localhost:53046\TRINETRA_Web\images\electric-vehicle.jpg\' x=\'0\' y=\'0\' height=\'43px\' width=\'43px\'/>' +
    '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'21\' cy=\'21\' r=\'21\' stroke-width=\'4\'/>' +
    //         '<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=\'http://www.w3.org/2000/svg\'>' +
    //'<rect x=\'50\' y=\'20\' rx=\'20\' ry=\'20" width=\'39\' height=\'39\' style=\'fill:red;stroke:black;stroke-width:5;opacity:0.5\' />' +
    //'<image src=\'http:\\localhost:53046\TRINETRA_Web\images\electric-vehicle.jpg\' x=\'0\' y=\'0\' height=\'39px\' width=\'39px\'/>' +
          '<circle stroke=\'#FFF\' fill=\'__MAINCOLOR__\' cx=\'19\' cy=\'19\' r=\'19\' stroke-width=\'4\'/>' +
    //          '<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_m = {
        '0': '#ff3366',    //Light Pink for 0-10
        '10': '#a86bf0', //Light Violet for 11-50
        '50': '#9a9a9a',  //Light Grey for 51-100
        '100': '#446d44', //Green for 101-200
        '200': '#ffc3a0',  //Wood for 201-500
        '500': '#FF0000'   //Red for over 500
    },
    svgParser_m = new nokia.maps.gfx.SvgParser();
    createIcon_m = function (count_m) {
        var digit = Math.min(3, 4 - Math.floor(Math.log(count) / Math.log(10))),
      svg_m,
      i_m;

        for (var i_m in stops_m) {
            if (count_m > i_m) {
                color_m = stops_m[i_m];
            }
        }
        svg_m = iconSVG_m[digit]
        .replace(/__TEXTCONTENT__/g, count_m)
        .replace(/__TEXT__/g, count_m)
        .replace(/__MAINCOLOR__/g, color_m);
        return new nokia.maps.gfx.GraphicsImage(svgParser_m.parseSvg(svg_m));
    }
}

function clusterDataPoints_Monitor(data, val, isEnable) {
    var svgTheme_m = {
        // Add a SVG Marker for Clusters.
        getClusterPresentation: function (dataPoints) {
            if (dataPoints.getSize() > 0) {
                var markerIcon_Monitor = createIcon_m(dataPoints.getSize());
                return new nokia.maps.map.Marker(dataPoints.getBounds().getCenter(),
                          {
                              icon: markerIcon_Monitor,
                              anchor: new nokia.maps.util.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 clusterMarkerArray[i];
        }
    },
    clusterProvider_Monitor = new nokia.maps.clustering.ClusterProvider(map, {
        eps: 16,
        minPts: 1,
        dataPoints: data,
        theme: svgTheme_m
    });
    //clusterBackup = new Array();
    for (var l = 0; l < clusterBackup_Monitor.length; l++) {
        clusterBackup_Monitor[l].clean();
    }

    clusterBackup_Monitor.push(clusterProvider_Monitor);

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

}

//function ZoomToTheme() {
//    var that = this,
//    baseTheme = new nokia.maps.clustering.MarkerTheme();
//    that.getClusterPresentation = function(dataPoints) {
//        var cluster = baseTheme.getClusterPresentation(dataPoints);
//        cluster.$boundingBox = dataPoints.getBounds();
//        return cluster;
//    };
//    that.getNoisePresentation = function(dataPoint) {
//        var noisePoint = baseTheme.getNoisePresentation(dataPoint);
//        noisePoint.$text = dataPoint.text;
//        return noisePoint;
//    };
//}

//function addZoomToListener(map) {
//    var TOUCH = nokia.maps.dom.Page.browser.touch,
//    CLICK = TOUCH ? 'tap' : 'click';
//    map.addListener(CLICK, function(evt) {
//        if (evt.target.$boundingBox !== undefined) {
//            evt.display.zoomTo(evt.target.$boundingBox, false);
//            $('#ticker').text('');
//        } else if (evt.target.$text !== undefined) {
//            $('#ticker').text(evt.target.$text + ' noise point was clicked.');
//        }
//    });
//}
/*********************************Clustering End***********************************************/
/*********************************xRay End***********************************************/
//function addXRayControl(map) {
//map.components.add(new XRayControl(200, 200));
//}
/*********************************xRay End***********************************************/

/********************************* KML Start************************************************/
//function addKMLGenerator(map) {
//    kmlGenerator = new KMLGenerator(document.getElementById("kmlData"), {
//        datasource: "$data",
//        address: "address",
//        styleURL: "styleURL",
//        description: "description",
//        name: "name"
//    });
//    map.addComponent(kmlGenerator);
//}

//function createKML() {
//    kmlGenerator.generateKML();
//}

//var kmlOutput = '';
//// Creates a valid KML file from the Map data.
//function saveMapObjects(map) {
//    var markers = new Array();
//    var lines = new Array();
//    for (i = 0; i < map.objects.getLength(); i++) {
//        if (map.objects.get(i) instanceof nokia.maps.map.Marker) {
//            // Retrieve all the Marker data and add it to an array
//            var markerData = new Object();
//            //markerData.id = toUnicode("&amp;#", map.objects.get(i).text);
//            markerData.latitude = map.objects.get(i).coordinate.latitude;
//            markerData.longitude = map.objects.get(i).coordinate.longitude;
//            markerData.description = map.objects.get(i).html;
//            //toUnicode("&#", map.objects.get(i).$data.description);
//            //markerData.name = toUnicode("&amp;#", map.objects.get(i).$data.name);
//            //markerData.address = toUnicode("&amp;#", map.objects.get(i).$data.address);
//            //markerData.href = map.objects.get(i).icon.src;
//            if (markerData.href === undefined) {
//                //markerData.styleURL = map.objects.get(i).$data.styleURL;
//            }
//            markers.push(markerData);

//        } else if (map.objects.get(i) instanceof nokia.maps.map.Polyline) {
//            // Retrieve all the Polyline data and add it to an array
//            var lineData = new Object();
//            var path = map.objects.get(i).path.asArray();
//            var geocoords = new Array();
//            // Ensure we have all the Geo-coordinates longitude and latitude.
//            for (j = 0; j < path.length; j = j + 3) {
//                var geocoord = new Object();
//                geocoord.latitude = path[j];
//                geocoord.longitude = path[j + 1];
//                geocoords.push(geocoord);
//            }
//            lineData.coordinates = geocoords;
//            //lineData.styleURL = map.objects.get(i).$data.styleURL;
//            lines.push(lineData);
//        }
//    }

//    // Now output the KML, start with the header.
//    kmlOutput = "<?xml version='1.0' encoding='UTF-8'?><kml xmlns='http://www.opengis.net/kml/2.2'><Document>\n";

//    // Loop through all the Polylines and add LineString Placemarks
//    for (i = 0; i < lines.length; i++) {

//        kmlOutput = kmlOutput + "<Placemark>\n";
//        kmlOutput = kmlOutput + "   <LineString>\n"
//        kmlOutput = kmlOutput + "       <coordinates>"
//        for (j = 0; j < lines[i].coordinates.length; j++) {
//            kmlOutput = kmlOutput + lines[i].coordinates[j].longitude + "," + lines[i].coordinates[j].latitude + ",0\n";
//        }
//        kmlOutput = kmlOutput + "       <\/coordinates>\n"
//        kmlOutput = kmlOutput + "   <\/LineString>\n";

//        if (lines[i].styleURL === undefined) {
//            // Do Nothing if no StyleURL entered as it is optional
//        } else if (lines[i].styleURL == "") {
//            // Do Nothing if no StyleURL entered as it is optional
//        } else {
//            kmlOutput = kmlOutput + "   <styleUrl>" + lines[i].styleURL + "<\/styleUrl>\n";
//        }
//        kmlOutput = kmlOutput + "<\/Placemark>\n";
//    }

//    // Loop nthrough the markers and add Point Placemarks
//    for (i = 0; i < markers.length; i++) {

//        if (markers[i].id === undefined) {
//            kmlOutput = kmlOutput + "<Placemark>\n";
//        } else if (markers[i].id == "") {
//            kmlOutput = kmlOutput + "<Placemark>\n";
//        } else {
//            kmlOutput = kmlOutput + "<Placemark id=\"" + markers[i].id + "\">\n";
//        }

//        if (markers[i].name === undefined) {
//            // Do Nothing  if no name entered as it is optional
//        } else if (markers[i].name == "") {
//            // Do Nothing if no name entered as it is optional
//        } else {
//            kmlOutput = kmlOutput + "   <name>" + markers[i].name + "<\/name>\n";
//        }

//        if (markers[i].description === undefined) {
//            // Do Nothing if no description entered as it is optional
//        } else if (markers[i].description == "") {
//            kmlOutput = kmlOutput + "   <description/>\n";
//        } else {
//            kmlOutput = kmlOutput + "   <description><![CDATA[" + markers[i].description + "]]><\/description>\n";
//        }

//        if (markers[i].address === undefined) {
//            // Do Nothing if no address entered as it is optional
//        } else if (markers[i].address == "") {
//            // Do Nothing if no address entered as it is optional
//        } else {
//            kmlOutput = kmlOutput + "   <address>" + markers[i].address + "<\/address>\n";
//        }

//        kmlOutput = kmlOutput + "    <Point><coordinates>" + markers[i].longitude + "," + markers[i].latitude + ",0<\/coordinates><\/Point>\n";
//        // If we have an href, the marker must be an icon, otherwise it is a standard marker.
//        if (markers[i].href === undefined) {

//            if (markers[i].styleURL === undefined) {
//                // Do Nothing if no style URL entered as it is optional
//            } else if (markers[i].styleURL == "") {
//                // Do Nothing if no style URL  entered as it is optional
//            } else {
//                kmlOutput = kmlOutput + "    <styleUrl>" + markers[i].styleURL + "<\/styleUrl>\n";
//            }

//        } else {
//            // This is a Map Marker with icon, it can be represented as an inline style.     
//            kmlOutput = kmlOutput + "    <Style>\n";
//            kmlOutput = kmlOutput + "        <IconStyle>\n";
//            kmlOutput = kmlOutput + "            <Icon>\n";
//            kmlOutput = kmlOutput + "                 <href>" + markers[i].href + "<\/href>\n";
//            kmlOutput = kmlOutput + "            <\/Icon>\n";
//            kmlOutput = kmlOutput + "        <\/IconStyle>\n";
//            kmlOutput = kmlOutput + "    <\/Style>\n";
//        }
//        kmlOutput = kmlOutput + "<\/Placemark>\n\n";
//    }

//    // Close the <document> element to ensure the KML is well formed.
//    kmlOutput = kmlOutput + "<\/Document><\/kml>";
//    //document.getElementById('kmlData').innerHTML = kmlOutput;
//    //downloadInnerHtml('mapExport.kml', kmlOutput, 'text/html');
//    nWin(kmlOutput);
//}
/*********************************KML End************************************************/

/********************Colapse panel JQuery for language legends***************/
//var PANEL_NORMAL_CLASS_lng = "panel";
//var PANEL_COLLAPSED_CLASS_lng = "panelcollapsed";
//var PANEL_HEADING_TAG_lng = "h2";
//var PANEL_CONTENT_CLASS_lng = "panelcontent";
//var PANEL_COOKIE_NAME_lng = "panels";
//var PANEL_ANIMATION_DELAY_lng = 15; /*ms*/
//var PANEL_ANIMATION_STEPS_lng = 10;

//function setUpPanels() {
//    loadSettings();

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

//    // 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_lng && el.parentNode.className != PANEL_COLLAPSED_CLASS_lng)
//            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_lng;
//        else
//            if (panelsStatus[name] == "true")
//            el.parentNode.className = PANEL_NORMAL_CLASS_lng;
//        else {
//            // if no saved setting, see the initial setting
//            panelsStatus[name] = (el.parentNode.className == PANEL_NORMAL_CLASS_lng) ? "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_lng);
//            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_lng) {
//            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_lng;
//    var direction = (!expanding ? -1 : 1);

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


//function animateStep(panelContent, iteration, stepHeight, direction) {
//    if (iteration < PANEL_ANIMATION_STEPS_lng) {
//        panelContent.style.height = Math.round(((direction > 0) ? iteration : 10 - iteration) * stepHeight) + "px";
//        iteration++;
//        setTimeout(function() { animateStep(panelContent, iteration, stepHeight, direction) }, PANEL_ANIMATION_DELAY_lng);
//    }
//    else {
//        // set class for the panel
//        panelContent.parentNode.className = (direction < 0) ? PANEL_COLLAPSED_CLASS_lng : PANEL_NORMAL_CLASS_lng;
//        // 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_lng + "=");
//    if (start == -1) return;

//    // starting point of the value
//    start += PANEL_COOKIE_NAME_lng.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_lng + "=" + 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.
//Sys.Application.add_load(setUpPanels);
/********************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) {
    //Nearest vehicle finding is not available in old version like v2.5.4
    return true;
}
/********************************************End Nearest Marker******************************************/
//function downloadInnerHtml(filename, elId, mimeType) {
//    var elHtml = elId;  //document.getElementById(elId).innerHTML;
//    var link = document.createElement('a');
//    mimeType = mimeType || 'text/plain';

//    link.setAttribute('download', filename);
//    link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
//    link.click();
//}
//$('#downloadLink').click(function() {
//    downloadInnerHtml('mapExport.kml', kmlOutput, 'text/html');
//});

//function nWin(content) {
//    var w = window.open('mapExport.aspx', 'Export', 'width=600, height=600');
//    //var html = $("#kmlData").html();
//    //$(w.document.body).html(content);
//    //var s = new XMLSerializer();
//    //var str = s.serializeToString(content);
//    //w.document.open('text/xml');
//    //w.document.write(content);
//    w.document.getElementById('kmlData').innerText = content;
//}
