
//Variable Declaration.
var maptype = "normal.day";
var LoadTime = null;
var map = null, mapEvents = null, behavior = null, ui = null;
var pageName = null;
var bubbles = null;
//var centerCoordinate = null;
var centerCoordinate = new H.geo.Point(20.00, 78.00);
var Address = new Array();
var rPolylineArray = new Array();
var infoBubbleMessage = new Array();
var infoBubble = null;
var infoMarkers = {};
var CountLandmark = null;
var RouteTypeCond = null;
var bubble = null;
var points = new H.geo.Strip();
var pPointsArray = new Array();
var pPolylineArray = new Array();
var objectContainer = new H.map.Group(); //nokia.maps.map.Container();
var objPolyContainer = new H.map.Group();
var objTotalContainer = new H.map.Group();
var objCurrMarkerContainer = new H.map.Group();
var mkr_group = new H.map.Group();
var routingRequest, routes, mapRoute, routeId, routeColor, routeTrafficMode;
var orgCenter = null;
var orgZoomLevel = null;
var objBoxIdColl = new Array();
var objContainerColl = new Array();
var objCurrMarkerContainerColl = new Array();
var objPolyColl = new Array();
var objPolylineColl = new Array();
var bubbleMessage = '';
var isShowLandmarkPlotter = 0;
var isShowGeozonePlotter = 0;
var isCurrentPosition = 0;
var polyPoints = new Array();
var polyArray = new Array();

var platform = new H.service.Platform({
    app_id: 'UdwAigBKPRhu01vbIGkI',
    app_code: 'PzCfyYAsV98qvfU8gusqRg',
    useCIT: true,
    useHTTPS: true
});

var defaultLayers = platform.createDefaultLayers();

// Get an instance of the geocoding service:
var geocoder = platform.getGeocodingService();
var notReverseGeocoded = true;
// Now use the map as required...
//addMarkersToMap(map, '48.8567,2.3508');

//Load Navteq maps.
function LoadMap() {
    //Load NLP nokia.maps NavTeq maps.
    map = new H.Map(document.getElementById("map-dsply"),
        defaultLayers.normal.map,
        {
            center: centerCoordinate,
            zoom: 4
        });
    // Set up events for the map:
    mapEvents = new mapsjs.mapevents.MapEvents(map);
    //Behaviour
    behavior = new H.mapevents.Behavior(mapEvents);
    // Create the default UI components
    ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");
    //centerCoordinate = map.getCenter();

    //startRouting('12.813777,77.686518$12.987567,80.174152', 'eta', 1);
}

function loadFullscreen() {
    isShowLandmarkPlotter = 0;
    isShowGeozonePlotter = 0;
    document.getElementById("map-legend").innerHTML = iconLegendText();
    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 H.Map(document.getElementById("map-dsply"),
            defaultLayers.normal.map,
            {
                center: orgCenter != null ? orgCenter : new H.geo.Point(20.00, 78.00),
                zoom: orgZoomLevel != null ? orgZoomLevel : 4
            });

            // Set up events for the map:
            mapEvents = new H.mapevents.MapEvents(map); //new mapsjs.mapevents.MapEvents(map); 
            //Behaviour
            behavior = new H.mapevents.Behavior(mapEvents);
            // Create the default UI components
            ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");

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

            orgCenter = null;
            orgZoomLevel = null;
        }

        map.addEventListener("tap", function (evt) {
            for (var b = 0; b < ui.getBubbles().length; b++) {
                ui.removeBubble(ui.getBubbles()[b]);
            }
        });

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

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

                    }
                }));
                if (objBoxIdColl != null && objBoxIdColl.length > 0) {
                    e.items.push(new H.util.ContextItem({ label: '> Zoom option for active live tracking vehicle(s)' }));
                    for (var k = 0; k < objBoxIdColl.length; k++) {
                        e.items.push(new H.util.ContextItem({
                            label: '|------> Go to vehicle (' + (k + 1).toString() + ') view',
                            callback: function (e) {
                                var index = e.target.textContent.split(' ')[4].replace('(', '').replace(')', '');
                                if (index != null && objContainerColl[parseInt(index) - 1] != null) {
                                    map.setViewBounds(objContainerColl[parseInt(index) - 1].getBounds());
                                }
                                else { alert('Points are not available now'); }
                            }
                        }));
                    }
                }

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

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

var landmarkLatitude = '';
var landmarkLongitude = '';
var landmarkMarkers = new Array();
var landMarkCircles = new H.map.Group();

function flagMarker(point, lndName, lndAddr, time, id, i_No, LandMarkIcon) {
    var icon = null;
    if (LandMarkIcon != null && LandMarkIcon != '') {
        icon = LandMarkIcon.replace("~", "..");
    }
    else {
        icon = '../images/flag_2.png';
    }

    var bubble = null;
    var OpenBubble = function (evt) {
        bubbleMessage = '<br><table style="direction:ltr" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>Landmark</b></td><td><b>:</b></td></td><td>' + lndName + '</td></tr><td>'
             + '<b>Address</b></td><td><b>:</b></td><td>' + lndAddr + '</td></tr></table>';
        var coordinate = evt.target.getPosition();
        ui.removeBubble(bubble);
        bubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        ui.addBubble(bubble);
    }
    var CloseBubble = function (evt) {
        ui.removeBubble(bubble);
    }
    var myListener = {
        "click": [OpenBubble, true, null],
        "mouseover": [OpenBubble, true, null],
        "mouseout": [CloseBubble, true, null]
    };

    var marker = new H.map.Marker(point, { icon: new H.map.Icon(icon, { anchor: new H.math.Point(2, 22) }) });
    marker.addEventListener('tap', OpenBubble, false);
    marker.addEventListener('pointermove', OpenBubble, false);
    marker.addEventListener('pointerout', CloseBubble, false);
    return marker;
}
var r1 = null;
var r2 = null;
var myrectangle;
var dragRectangle;
var first = '';
var second = '';
var geozoneColls = new H.map.Group();
function PlotGeozone(geozoneEntries, isGeozoneEnable) {
    var Geozones = geozoneEntries.split('&');
    if (!isGeozoneEnable) {
        if (geozoneColls != null && geozoneColls.getObjects().length > 0) {
            geozoneColls.removeObjects(geozoneColls.getObjects());
        }
        //if (map.getObjects().length > 0) {
        //    map.removeObject(objectContainer);
        //    map.removeObjects(map.getObjects());
        //    map.addObject(objectContainer);
        //}
        return;
    }

    var details = "";
    var latlng = "";
    if (geozoneEntries != "" && geozoneEntries != 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], 'G');
        }
        map.addObject(geozoneColls);
    }
}
function ShowGeozone_Hstry(latlng, isView, geoName, geoType, isRestricted, cRadius, pageName) {
    if (geoType == 1) {
        isview = isView;
        sGeoName = geoName;
        Geozonetype = 'RC';
        var collectdata = new Array();
        var lt = latlng.split('&');
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            //polyPoints.push(new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1])));
            var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            mapClickRectangle('', point, isRestricted, pageName);
        }
    }
    else if (geoType == 2) {
        isview = isView;
        sGeoName = geoName;
        Geozonetype = 'PL';
        IsDblClick = false; //To reassign the Double click event to the map.
        var collectdata = new Array();
        var lt = latlng.split('&');
        polyStrip = new H.geo.Strip();
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            polyStrip.pushPoint(point);
        }
        drawPoly_hstry(point, isRestricted, pageName);
    }
    else if (geoType == 3) {
        isview = isView;
        sGeoName = geoName;
        Geozonetype = 'CR';
        IsDblClick = false; //To reassign the Double click event to the map.
        var collectdata = new Array();
        var lt = latlng.split('&');
        polyStrip = new H.geo.Strip();
        for (var i = 0; i < lt.length; i++) {
            var lng;
            lng = lt[i].split('#');
            var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
            polyStrip.pushPoint(point);
            doDrawCircle_gz(point, parseFloat(lng[0]), parseFloat(lng[1]), isRestricted, cRadius, pageName);
        }
    }
}
function mapClickRectangle(overlay, point, isRestricted, pageName) {

    if (point == null) { return; }

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

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

        //Rec_bounds = new H.geo.BoundingBox(r1, r2);
        var marker1 = r1;
        var marker2 = r2;

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

        polyArray.length = 0;

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

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

        r1 = ''
        r2 = ''
    }
}
var rect_group = null;
function draw_rectangle(a, b, isRestricted, pageName) {
    var icon = "../images/flag_8.png"
    if (myrectangle != null) {
        map.removeObject(myrectangle);
    }
    if (a != null && b != null) {

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

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

        if (a != null && b != null) {
            if (b.lng > a.lng) {
                myrectangle = new H.map.Rect(new H.geo.Rect(parseFloat(a.lat), parseFloat(a.lng), parseFloat(b.lat), parseFloat(b.lng)), {
                    style: { strokeColor: rLneClr, lineWidth: 1, fillColor: rFilClr }
                });
            }
            else {
                myrectangle = new H.map.Rect(new H.geo.Rect(parseFloat(a.lat), parseFloat(b.lng), parseFloat(b.lat), parseFloat(a.lng)), {
                    style: { strokeColor: rLneClr, lineWidth: 1, fillColor: rFilClr }
                });
            }
        }

        myrectangle.setData('geozone;' + sGeoName);
        InfoBubbleSet(myrectangle, sGeoName);
        //var bubble = null;
        //var OpenBubble = function (evt) {
        //    bubbleMessage = '<br><table style="direction:ltr" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>Geozone</b></td><td><b>:</b></td></td><td>' + sGeoName + '</td></tr></table>';
        //    var coordinate = map.screenToGeo(evt.pointers[0].viewportX, evt.pointers[0].viewportY);//evt.target.getPosition();
        //    ui.removeBubble(bubble);
        //    bubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        //    ui.addBubble(bubble);
        //}
        //var CloseBubble = function (evt) {
        //    for (var b = 0; b < ui.getBubbles().length; b++) {
        //        ui.removeBubble(ui.getBubbles()[b]);
        //    }
        //}
        //myrectangle.addEventListener('pointerenter', OpenBubble, false);
        //myrectangle.addEventListener('pointerleave', CloseBubble, false);
        //myrectangle.addEventListener(
        //  'tap',
        //  function (e) {
        //      ui.removeBubble(infoBubble);
        //      var coord = map.screenToGeo(e.currentPointer.viewportX, e.currentPointer.viewportY);
        //      infoBubble = new H.ui.InfoBubble(coord,
        //          //getCentroid(e.target.getData()),
        //          { content: 'Geozone Name : ' + e.target.getData() });
        //      ui.addBubble(infoBubble);
        //  }
        //);

        polyShapeArray.push(myrectangle);
        geozoneColls.addObject(myrectangle);
    }
}

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

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

    if (isRestricted == 'true' || isRestricted == '1') {
        pFilClr = "rgba(255,0,0,0.5)";
        pLneClr = "rgba(0,0,0,1)";
    }
    else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'M') {
        pFilClr = "rgba(144,238,144, 0.5)";
        pLneClr = "rgba(5,45,0,1)";
    }
    else if ((isRestricted == 'false' || isRestricted == '0') && pageName == 'G') {
        pFilClr = "rgba(65,105,225, 0.5)";
        pLneClr = "rgba(0,0,128,1)";
    }
    polyShape = new H.map.Polygon(polyStrip, {
        style: { strokeColor: pLneClr, lineWidth: 1, fillColor: pFilClr }
    });
    polyShape.setData('geozone;' + sGeoName);
    InfoBubbleSet(polyShape, sGeoName);
    //var bubble = null;
    //var OpenBubble = function (evt) {
    //    bubbleMessage = '<br><table style="direction:ltr" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>Geozone</b></td><td><b>:</b></td></td><td>' + sGeoName + '</td></tr></table>';
    //    var coordinate = map.screenToGeo(evt.pointers[0].viewportX, evt.pointers[0].viewportY);//evt.target.getPosition();
    //    ui.removeBubble(bubble);
    //    bubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
    //    ui.addBubble(bubble);
    //}
    //var CloseBubble = function (evt) {
    //    for (var b = 0; b < ui.getBubbles().length; b++) {
    //        ui.removeBubble(ui.getBubbles()[b]);
    //    }
    //}
    //polyShape.addEventListener('pointerenter', OpenBubble, false);
    //polyShape.addEventListener('pointerleave', CloseBubble, false);
    //polyShape.addEventListener(
    //          'tap',
    //          function (e) {
    //              ui.removeBubble(infoBubble);
    //              var coord = map.screenToGeo(e.currentPointer.viewportX, e.currentPointer.viewportY);
    //              infoBubble = new H.ui.InfoBubble(coord,
    //                  //getCentroid(e.target.getPath()),
    //                  { content: 'Geozone Name : ' + e.target.getData() });
    //              ui.addBubble(infoBubble);
    //          }
    //        );
    geozoneColls.addObject(polyShape);
}

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

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

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

            var lat1 = (PI / 180) * (lat); // radians
            var lng1 = (PI / 180) * (long); // radians

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

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

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

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

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

            circle.setData('geozone;' + sGeoName);
            InfoBubbleSet(circle, sGeoName);
            //circle.addEventListener(
            //  'tap',
            //  function (e) {
            //      ui.removeBubble(infoBubble);
            //      var coord = map.screenToGeo(e.currentPointer.viewportX, e.currentPointer.viewportY);
            //      infoBubble = new H.ui.InfoBubble(coord,
            //          //getCentroid(e.target.getData()),
            //          { content: 'Geozone Name : ' + e.target.getData() });
            //      ui.addBubble(infoBubble);
            //  }
            //);
            geozoneColls.addObject(circle);
        }
    }
    catch (Error) {
        //alert(Error);
    }
}

function InfoBubbleSet(mapObject, sGeoName) {
    var bubble = null;
    var OpenBubble = function (evt) {
        bubbleMessage = '<br><table style="direction:ltr" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>Geozone</b></td><td><b>:</b></td></td><td>' + sGeoName + '</td></tr></table>';
        var coordinate = map.screenToGeo(evt.pointers[0].viewportX, evt.pointers[0].viewportY);//evt.target.getPosition();
        ui.removeBubble(bubble);
        bubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        ui.addBubble(bubble);
    }
    var CloseBubble = function (evt) {
        for (var b = 0; b < ui.getBubbles().length; b++) {
            ui.removeBubble(ui.getBubbles()[b]);
        }
    }
    mapObject.addEventListener('pointerenter', OpenBubble, false);
    mapObject.addEventListener('pointerleave', CloseBubble, false);
}

function drawCircleForLandmark(landmarkEntries, isLandmarkEnable) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        if (landMarkCircles != null && landMarkCircles.getObjects().length > 0) {
            landMarkCircles.removeObjects(landMarkCircles.getObjects());
        }
        //if (map.getObjects().length > 0) {
        //    map.removeObject(objectContainer);
        //    map.removeObjects(map.getObjects());
        //    map.addObject(objectContainer);
        //    //for (var obj in map.getObjects()) {
        //    //    if (map.getObjects()[obj].getData() == 'circle') {
        //    //        map.removeObject(map.getObjects()[obj]);
        //    //    }
        //    //}
        //}
        return;
    }

    landmarkMarkers = new Array();
    for (var iterator = 0; iterator < lanmarkInformation.length; iterator++) {
        if (lanmarkInformation[iterator] == "") {
            break;
        }
        else {
            var landmarkinfo = lanmarkInformation[iterator].split("~#~");
            centerPoint = new H.geo.Point(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new H.map.Marker(centerPoint, {});
            if (isLandmarkEnable) {
                var lndMarks = flagMarker(centerPoint, landmarkinfo[3], landmarkinfo[4], landmarkinfo[0], 'green', 1, landmarkinfo[5])
                landmarkMarkers.push(lndMarks);
                //lndMarks.setData("circleMarker");
                //map.addObject(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) { doDrawCircle(landmarkinfo[3], landmarkinfo[4]); }
        }
    }
}

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

function doDrawCircle(lndName, lndAddr) {
    try {
        if (circle != null && landMarkCircles != null && canClearCircle) {
            landMarkCircles.removeObjects(landMarkCircles.getObjects());
            //map.removeObject(landMarkCircles);
        }
        var center = map.getCenter();
        var circlePoints = Array();

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

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

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

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

            if (d < 1.5678565720686044) {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: "rgba(198,155,204,0.5)" } // "#C69ACC" }
                            }
                        );
            }
            else {
                circle = new H.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                style: { strokeColor: "#5270B2", lineWidth: 4, fillColor: canClearCircle ? '#000000' : "rgba(198,155,204,0.5)" } //'#C69ACC' }
                            }
                        );
            }
            circle.setData("circle;" + lndName);
            var bubble = null;
            var OpenBubble = function (evt) {
                bubbleMessage = '<br><table style="direction:ltr" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>Landmark</b></td><td><b>:</b></td></td><td>' + lndName + '</td></tr><td>'
                     + '<b>Address</b></td><td><b>:</b></td><td>' + lndAddr + '</td></tr></table>';
                var coordinate = map.screenToGeo(evt.pointers[0].viewportX, evt.pointers[0].viewportY);//evt.target.getPosition();
                ui.removeBubble(bubble);
                bubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
                ui.addBubble(bubble);
            }
            var CloseBubble = function (evt) {
                for (var b = 0; b < ui.getBubbles().length; b++) {
                    ui.removeBubble(ui.getBubbles()[b]);
                }
            }
            circle.addEventListener('pointerenter', OpenBubble, false);
            circle.addEventListener('pointerleave', CloseBubble, false);
            //landMarkCircles.setData("circleGrp");
            landMarkCircles.addObject(circle);
            //map.addObject(circle);
            map.addObject(landMarkCircles);
        }
    }
    catch (Error) {
        alert(Error);
    }
}

function identifyMapObjects(coord, isHighlight) {
    var pixelcoord = map.geoToScreen(coord),
    objects = map.getObjectsAt(pixelcoord.x, pixelcoord.y),
	covers = false;
    var circleObj = null;
    var cLandmarkName = '';

    for (var obj in map.getObjects()) {
        if (map.getObjects()[obj].getData() != null && map.getObjects()[obj].getData().indexOf('circle;') != -1) {
            if (isHighlight == true) {
                map.getObjects()[obj].setStyle({ fillColor: 'rgba(198,155,204,0.5)' });
            }
        }
        else if (map.getObjects()[obj].getData() != null && map.getObjects()[obj].getData().indexOf('geozone;') != -1) {
            if (isHighlight == true) {
                map.getObjects()[obj].setStyle({ fillColor: 'rgba(65,105,225, 0.5)' });
            }
        }
    }

    for (var object in objects) {
        if (objects[object].getData() != null && (objects[object].getData().indexOf('circle;') != -1 || objects[object].getData().indexOf('geozone;') != -1)) {
            circleObj = objects[object];
            cLandmarkName =
                ((objects[object].getData().indexOf('geozone;') != -1) ? 'Geozone : ' : 'Landmark : ') + objects[object].getData().split(';')[1].toString();
            if (isHighlight == true) {
                objects[object].setStyle({ fillColor: 'rgba(252, 177, 37,0.5)' });//'rgba(255, 0, 0, 0.5'
            }
            covers = true;
        }
        if (covers)
            break;
    }
    return cLandmarkName;
}

function iconLegendText() {
    var height = '';
    var CurrentPosistion = '';

    var downIconText = "";

    downIconText += "<h3 class='foot'><table><tr>" +
                    "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkShowMarker' style='height:15px;width:15px;' name='chkLandmark' onclick='showMarkers(this.checked);'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                    "  <td style='font:11px arial;color:#333333;vertical-align:middle;' align='left'><b>Show Markers</b></span></td>" +
                    "</tr></table></h3>";

    var legendText = "<div class='panel' align='center' id='lnkLegend' style='width:130px'> <h2><b>Legend</b></h2><div class='panelcontent'><table id='tblLegend' align='right'" + height + " style='direction:ltr;'>" +
                "<tr><td align='right' style='padding: 6px 0px 6px 6px;'>" +
                 "<table cellpadding='2' cellspacing='2' align='right' width='125px' height='45px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/flag_1.png' alt='start' style='height:15px;width:15px' /></td>" +
                 "  <td align='left'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;Start Location</span></td>" +
                 "</tr>" +
                  "<tr>" +
                 "  <td style='padding-left:2px'><svg width=\"20\" height=\"18\" xmlns=\"http://www.w3.org/2000/svg\">" +
                 "  <circle cx=\"8\" cy=\"8\" r=\"8\" stroke=\"black\" stroke-width=\"1\" fill=\"lightgreen\" />" +
                 "  <text x=\"8\" y=\"10\" font-size=\"8pt\" font-family=\"Arial\" font-weight=\"bold\" " +
                 "  text-anchor=\"middle\" fill=\"white\" >a</text></svg>" +
                 "</td>" +
                 "  <td align='left'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;Current location</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/1_.png' alt='moving' style='height:15px;width:15px' /></td>" +
                 "  <td align='left'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;Active</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.png' alt='destination' style='height:15px;width:15px' /></td>" +
                 "  <td align='left'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;Disabled</span></td>" +
                 "</tr></table></td></tr></table></div><b>" + downIconText + "</b></div>";
    return legendText;
}
function iconETAText(html) {
    var height = '';
    var CurrentPosistion = '';

    var legendText = "<div class='panelETA' align='center' id='lnkLegend'> <h2><b>Estimated Time Of Arrival</b></h2><div class='panelcontentETA'><table id='tblLegend' " + height + " style='direction:ltr;'>" +
                "<tr><td align='right' style='padding: 6px 6px 0px 6px;'>" + html
                 + "</td></tr></table></div></div>";
    return legendText;
}

function getMarker(bubbleMessage, lat, lng, cubsIcon, map) {
    var coordinate;
    var OpenBubble = function (evt) {
        coordinate = evt.target.getPosition();
        ui.removeBubble(infoBubble);
        infoBubble = new H.ui.InfoBubble(coordinate, { content: bubbleMessage });
        bubble = ui.addBubble(infoBubble);
    }

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

    map.addEventListener("tap", CloseBubble);

    var marker = new H.map.Marker(new H.geo.Point(lat, lng), { icon: cubsIcon });
    marker.addEventListener("tap", OpenBubble);
    marker.addEventListener("pointermove", OpenBubble);
    return marker;
}

function addMarkersToMap_st(map, start, message, boxid) {
    var isBoxId = objBoxIdColl.indexOf(boxid);
    //alert('BoxId : ' + boxid + '; Index : ' + isBoxId);
    if (isBoxId == -1) {
        objBoxIdColl.push(boxid);
        objectContainer = new H.map.Group();
        objCurrMarkerContainer = new H.map.Group();
        objPolyContainer = new H.map.Group();
        points = new H.geo.Strip();
    }
    else {
        objectContainer = (objContainerColl[isBoxId] != null) ? objContainerColl[isBoxId] : new H.map.Group();
        objPolyContainer = (objPolylineColl[isBoxId] != null) ? objPolylineColl[isBoxId] : new H.map.Group();
        objCurrMarkerContainer = (objCurrMarkerContainerColl[isBoxId] != null) ? objCurrMarkerContainerColl[isBoxId] : new H.map.Group();
        points = (objPolyColl[isBoxId] != null) ? objPolyColl[isBoxId] : new H.geo.Strip();
    }

    //alert('first points ' + points.getPointCount());

    if (objectContainer != null) {
        var lat = start.split(",")[0];
        var lng = start.split(",")[1];
        var datetime = message.split(";")[1];
        var speed = message.split(";")[5];
        var address = message.split(";")[7];
        var svgMarkup = '<svg  width="30" height="30" xmlns="http://www.w3.org/2000/svg">' +
                        '<circle cx="12" cy="12" r="12" stroke="black" stroke-width="1" fill="${FILL}" />' +
                        //'<rect stroke="black" fill="${FILL}" x="1" y="1" width="22" height="22" />' +
                        '<text x="12" y="18" font-size="12pt" font-family="Arial" font-weight="bold" ' +
                        'text-anchor="middle" fill="${STROKE}" >${TEXT}</text></svg>';

        var svgCurrMarkup = '<svg  width="30" height="30" xmlns="http://www.w3.org/2000/svg">' +
                        '<circle cx="12" cy="12" r="12" stroke="black" stroke-width="1" fill="${FILL}" />' +
                        //'<rect stroke="black" fill="${FILL}" x="1" y="1" width="22" height="22" />' +
                        '<text x="12" y="18" font-size="12pt" font-family="Arial" font-weight="bold" ' +
                        'text-anchor="middle" fill="${STROKE}" >${TEXT}</text></svg>';


        //if (objectContainer != null && objectContainer.getObjects().length > 0) {
        //    for (var object in objectContainer.getObjects()) {
        //        if (object != this.polyline) {
        //            objectContainer.removeObjects(object);
        //        }
        //    }
        //}

        bubbleMessage = CreateTabs(true, 'Message', 'Location Update', true, 'Date & Time', datetime, true, 'Address', address, false, '', '', true, 'Speed', speed + ' KMPH');
        // Add the first marker
        var cubsIcon = new H.map.Icon(svgMarkup.replace('${FILL}', 'white').replace('${STROKE}', 'orange').replace('${TEXT}', (objBoxIdColl.indexOf(boxid) + 1).toString()), { anchor: new H.math.Point(9, 12) });
        var marker = getMarker(bubbleMessage, lat, lng, cubsIcon, map);
        var cubsIcon_curr = new H.map.Icon(svgMarkup.replace('${FILL}', 'lightgreen').replace('${STROKE}', 'white').replace('${TEXT}', (objBoxIdColl.indexOf(boxid) + 1).toString()), { anchor: new H.math.Point(9, 12) });
        var marker_curr = getMarker(bubbleMessage, lat, lng, cubsIcon_curr, map);
        marker_curr.setData(boxid);
        //Set marker to a variable.
        var st_marker = null;
        if (objectContainer.getObjects().length == 0) {
            st_marker = new H.map.Marker(new H.geo.Point(parseFloat(lat), parseFloat(lng)), {
                icon: new H.map.Icon("../images/flag_1.png", { anchor: new H.math.Point(2, 22) })
            });
        }
        objectContainer.addObject(marker);
        if (st_marker != null) { objectContainer.addObject(st_marker); }
        identifyMapObjects(new H.geo.Point(parseFloat(lat), parseFloat(lng)), true);
        //map.addObject(objectContainer);
        //objTotalContainer.addObject(marker);

        //if (objTotalContainer != null) {
        //    map.setViewBounds(objTotalContainer.getBounds());
        //}

        points.pushLatLngAlt(lat, lng);
        //pPointsArray.push(new H.geo.Point(parseFloat(lat), parseFloat(lng)));
        //if (pPolylineArray != null && pPolylineArray.length > 0) {
        //    for (var a = 0; a < pPolylineArray.length ; a++) {
        //        map.removeObject(pPolylineArray[a]);
        //    }
        //    pPolylineArray.length = 0;
        //}

        if (points.getPointCount() > 1) {

            var polyline = new H.map.Polyline(
                               points,
                               {
                                   style: { strokeColor: 'rgba(18, 65, 145, 0.7)', lineWidth: 8, lineJoin: "round" },
                                   brush: { color: 'rgba(0, 153, 0, 0.7)' },
                                   arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 }
                               }
                           );
            pPolylineArray.push(polyline);
            if (objPolylineColl[isBoxId] != null) {
                try { objectContainer.removeObject(objPolylineColl[isBoxId]); }
                catch (ex) { }
                objPolylineColl[isBoxId] = polyline;
            }
            else {
                objPolylineColl.push(polyline);
            }
            objectContainer.addObject(polyline);
        }
        if (document.getElementById('chkShowMarker') != null && chkShowMarker.checked == true) {
            map.addObject(objectContainer);
        }
        else {
            if (map.getObjects().length > 0) {
                for (var i = 0; i < map.getObjects().length; i++) {
                    if (map.getObjects()[i] != null && map.getObjects()[i].getData() != null && map.getObjects()[i].getData() == boxid) {
                        try {
                            map.removeObject(map.getObjects()[i]);
                        }
                        catch (ex) { }
                    }
                }
            }
        }
        if (objCurrMarkerContainerColl[isBoxId] != null) {
            //if (objCurrMarkerContainer != null && objCurrMarkerContainer.getObjects() != null && objCurrMarkerContainer.getObjects().length > 0) {
            objCurrMarkerContainer.removeObjects(objCurrMarkerContainer.getObjects());
            //}
            objCurrMarkerContainer.addObject(marker_curr);
            objCurrMarkerContainerColl[isBoxId] = objCurrMarkerContainer;
            map.addObject(objCurrMarkerContainer);
        }
        else { objCurrMarkerContainerColl.push(marker_curr); }
        if (objContainerColl[isBoxId] != null) {
            objContainerColl[isBoxId] = objectContainer;
        } else {
            objContainerColl.push(objectContainer);
        }
        if (objPolyColl[isBoxId] != null) {
            objPolyColl[isBoxId] = points;
        } else {
            //objPolyColl.push(points);
            objPolyColl.splice(isBoxId, 0, points);
        }
        //alert('end points ' + points.getPointCount());
    }
}

function showMarkers(isTrue) {
    if (!isTrue) {
        //for (var b = 0; b < objBoxIdColl.length; b++) {
        //    if (map.getObjects().length > 0) {
        //        for (var i = 0; i < map.getObjects().length; i++) {
        //            if (map.getObjects()[i] != null && map.getObjects()[i].getData() != null && map.getObjects()[i].getData() == objBoxIdColl[b]) {
        //                map.removeObject(map.getObjects()[i]);
        //            }
        //        }
        //    }
        //}
        for (var o = 0; o < objContainerColl.length; o++) {
            map.removeObject(objContainerColl[o]);
        }
        for (var c = 0; c < objCurrMarkerContainerColl.length; c++) {
            map.addObject(objCurrMarkerContainerColl[c]);
        }
    }
    else {
        for (var b = 0; b < objContainerColl.length; b++) {
            //map.removeObject(objContainerColl[b]);
            map.addObject(objContainerColl[b]);
        }
    }
}

function ReceiveServerData(arg, context) {
    //document.getElementById('divGridView').innerHTML = arg;
    console.log('final message -->' + arg);
    var alertStatus = arg.split(';');
    var latlngs = alertStatus[2] + "," + alertStatus[3];
    var boxid = alertStatus[0];
    var code = (alertStatus[8] != null) ? alertStatus[8] : "-1";
    var vehName = (alertStatus[9] != null) ? alertStatus[9] : "";
    if (code != "2" && code != "3") {
        addMarkersToMap_st(map, latlngs, arg, boxid);
    }
    if (code == "0") {
        TrinetraCustomAlerts('Live tracking for "' + vehName + '" has been continued now.');
    }
    else if (code == "1") {
        TrinetraCustomAlerts('Live tracking has been disabled for "' + vehName + '" due to either GPS communication failure / Ignition Off. \nTracking will be continued once GPS communication or Ignition On.');
    }
    else if (code == "2") {
        TrinetraCustomAlerts('Live tracking for "' + vehName + '" has been completed for the selected duration. Live tracking history is available to export for this "' + vehName + '". Once live tracking page closed, history data not available.');
    }
    else if (code == "3") {
        TrinetraCustomAlerts('Live tracking has been disabled for "' + vehName + '"');
    }
}

function CreateTabs(isMessageVisbile, msgCaption, msgdetails, isDateTimeVisible, datetimeCaption,
time, isAddressVisible, addressCaption, address, isLandmarkVisible, landmarkCaption, landmarkName, isSpeedVisible,
 speedCaption, speed) {
    var tabs = [];
    var tableAlign = 'left';
    var tabMessage = '<div style="text-align:' + tableAlign + ';"><table style="direction:ltr;" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>';
    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>';
    }
    tabMessage += '</table></div>';

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

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

/**
 * This function will be called once the Geocoder REST API provides a response
 * @param  {Object} result          A JSONP object representing the  location(s) found.
 *
 * see: http://developer.here.com/rest-apis/documentation/geocoder/topics/resource-type-response-geocode.html
 */
function onSuccess(result) {
    var locations = result.response.view[0].result;
    /*
     * The styling of the geocoding response on the map is entirely under the developer's control.
     * A representitive styling can be found the full JS + HTML code of this example
     * in the functions below:
     */
    for (i = 0; i < locations.length; i += 1) {
        position = {
            lat: locations[i].location.displayPosition.latitude,
            lng: locations[i].location.displayPosition.longitude
        };
        address = locations[i].location.address.label;
    }
}

/**
 * This function will be called if a communication error occurs during the JSON-P request
 * @param  {Object} error  The error message received.
 */
function onError(error) {
    alert('Ooops!');
}

function addStartMarker(lat, lng) {
    var marker = new H.map.Marker(
            new H.geo.Point(parseFloat(lat), parseFloat(lng)), {
                visibility: true,
                icon: new H.map.Icon('../images/flag_5.png', { anchor: new H.math.Point(9, 12) })
            });

    if (bubble) infoBubble.close();
    var contentHtml = 'Start';
    addListenerToMarker(marker, contentHtml);
    objectContainer.addObject(marker);
}


function addMarkersToMap(map, latlngs, message) {
    var lat = latlngs.split("#")[0];
    var lng = latlngs.split("#")[1];
    startRouting(lat + ',' + lng + '$' + destination, 'eta', 1);
    points.pushLatLngAlt(lat, lng);
    pPointsArray.push(new H.geo.Point(lat, lng));
    if (pPolylineArray != null && pPolylineArray.length > 0) {
        map.removeObject(pPolylineArray[0]);
        pPolylineArray.length = 0;
    }
    if (pPointsArray.length > 1) {
        var polyline = new H.map.Polyline(
                           points,
                           {
                               pen: { strokeColor: 'rgba(0, 153, 0, 0.7)', lineWidth: 2 },
                               brush: { color: 'rgba(0, 153, 0, 0.7)' }
                           }
                       );
        pPolylineArray.push(polyline);
        map.addObject(polyline);
        map.addObject(objectContainer);
        map.setViewBounds(objectContainer.getBounds(), true);
    }
}

function GetParameterValues_query(param) {
    var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < url.length; i++) {
        var urlparam = url[i].split('=');
        if (urlparam[0] == param) {
            return urlparam[1];
        }
    }
}

function GetParameterValues(param, content) {
    var url = content.split('&');
    for (var i = 0; i < url.length; i++) {
        var urlparam = url[i].split('=');
        if (urlparam[0] == param) {
            return urlparam[1];
        }
    }
}

var routingManager = platform.getRoutingService();
//Split the lat long values and pass to the routing process.
function startRouting(LatLongs, Page, type) {//LatLongs
    pageName = Page;
    RouteTypeCond = type;
    var points = LatLongs.split('$');
    var waypoints = new Array();
    var prevLatLng = new Array();
    for (var i = 0; i < points.length; i++) {
        var latlng = points[i].split(',');
        var coords = new H.geo.Point(parseFloat(latlng[0]), parseFloat(latlng[1]));
        if (prevLatLng[0] != coords) {
            //prevLatLng.push(coords);
            waypoints.push({ position: coords });
            prevLatLng.push(coords);

        }
    }
    CountLandmark = points.length - 1;
    callroute(waypoints);
    //alert(type + "Hello");

    return;
}
function callroute(waypoints) {
    try {

        var routeRequestParams = {
            mode: 'fastest;car',
            representation: 'display',
            routeattributes: 'waypoints,summary,shape,legs',
            maneuverattributes: 'direction,action',
            //waypoint0: '52.5160,13.3779', // Brandenburg Gate
            //waypoint1: '52.5206,13.3862'  // Friedrichstraße Railway Station
        };

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

        //make a calculateRoute request
        routingManager.calculateRoute(routeRequestParams, routingCallback, onError);
    }
    catch (er) {
        HidePopUp();
        alert("Routing request failed.")
    }
};
function onError(error) {
    HidePopUp();
    alert("The routing request failed.");
}
//Route Call
function routingCallback(observedRouter) {
    try {
        var tab = '';
        routes = observedRouter.response.route[0];
        routeTrafficMode = routes.mode.trafficMode;
        if (routes) {
            tab = DrivingDirection(routes);
        }
        else {
            alert("Routing Request Failed.")
            HidePopUp();
            return;
        }

        routeColor = routeTrafficMode == "enabled" ? "#a000a080" : "#0000f080";

        var strip = new H.geo.Strip(), routeShape = routes.shape, polyline;

        if (rPolylineArray != null && rPolylineArray.length > 0) {
            map.removeObject(rPolylineArray[0]);
            rPolylineArray.length = 0;
        }

        routeShape.forEach(function (point) {
            var parts = point.split(',');
            strip.pushLatLngAlt(parts[0], parts[1]);
        });

        polyline = new H.map.Polyline(strip, {
            style: {
                lineWidth: 8,
                strokeColor: 'rgba(255, 153, 0, 0.7)'
            },
            arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 }
        });
        rPolylineArray.push(polyline);
        // Add the polyline to the map
        map.addObject(polyline);
        // And zoom to its bounding rectangle
        //map.setViewBounds(polyline.getBounds(), true);

        var iconMarkup = '<svg style="left:-15px;top:-30px;"' +
           'xmlns="http://www.w3.org/2000/svg" width="25px" height="35px" >'
       + '<g transform="scale({{{SCALE}}})"><path d="M 19 31 C 19 32.7 16.3 34 13 34 C 9.7 34 7 32.7 7 31 C 7 29.3 9.7 ' +
     '28 13 28 C 16.3 28 19 29.3 19 31 Z" fill="#000" fill-opacity=".2"></path>'
       + '<path d="M 13 0 C 9.5 0 6.3 1.3 3.8 3.8 C 1.4 7.8 0 9.4 0 12.8 C 0 16.3 1.4 ' +
     '19.5 3.8 21.9 L 13 31 L 22.2 21.9 C 24.6 19.5 25.9 16.3 25.9 12.8 C 25.9 9.4 24.6 ' +
     '6.1 22.1 3.8 C 19.7 1.3 16.5 0 13 0 Z" fill="#fff"></path>'
       + '<path d="M 13 2.2 C 6 2.2 2.3 7.2 2.1 12.8 C 2.1 16.1 3.1 18.4 5.2 20.5 L ' +
     '13 28.2 L 20.8 20.5 C 22.9 18.4 23.8 16.2 23.8 12.8 C 23.6 7.07 20 2.2 ' +
     '13 2.2 Z" fill="{{{COLOUR}}}"></path>'
       + '<text transform="matrix( 1 0 0 1 13 18 )" x="0" y="0" fill-opacity="1" '
       + 'fill="#fff" text-anchor="middle" '
       + 'font-weight="bold" font-size="8px" font-family="arial">{{{ZOOM}}}</text></g></svg>';
        var icons = null;


        icons = '../images/fuellow-1_.png';

        for (var i in routes.waypoint) {
            // var coord = routes[0].waypoints[i].mappedPosition;
            if (i == 0) {
                icons = '../images/1_.png';
            }
            else //if (i == routes.waypoint.length - 1)
            {
                icons = '../images/flag.png';
            }
            var marker = new H.map.Marker(
            new H.geo.Point(routes.waypoint[i].mappedPosition.latitude, routes.waypoint[i].mappedPosition.longitude), {
                visibility: true,
                icon: new H.map.Icon(icons, { anchor: new H.math.Point(9, 12) })
            });

            //var marker = new H.map.DomMarker(
            //{ lat: routes.waypoint[i].mappedPosition.latitude, lng: routes.waypoint[i].mappedPosition.longitude }, {
            //    icon: new H.map.DomIcon(
            //    // set icon content and colour
            //    iconMarkup.replace('{{{COLOUR}}}', (i == 0 ? "#008000" : (i == routes.waypoint.length - 1 ? "#FF0000" : "#0055AA")))
            //      .replace('{{{ZOOM}}}', (i == 0 ? "A" : i == routes.waypoint.length - 1 ? "B" : i))
            //      .replace('{{{SCALE}}}', 1)
            //    , { anchor: new H.math.Point(0, 150) })
            //});

            if (Address.length > 0) {
                marker.setData(Address[i]);
            }

            if (bubble) infoBubble.close();
            var contentHtml = ((i == 0) ? tab : 'Destination');
            addListenerToMarker(marker, contentHtml);
            objectContainer.addObject(marker);
        }

        //Zoom to the bounding box of the route
        //map.setViewBounds(mapRoute.getBounds());
        // callservermethod();

        HidePopUp();

    }
    catch (er) {
        alert(er);
        HidePopUp();
        alert("Kindly check your Internet Connection.");
    }
};

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

    marker.addEventListener("pointermove", OpenBubble);
    marker.addEventListener("pointerout", CloseBubble);
}



//Calculate Driving Direction
function DrivingDirection(routes) {

    if (pageName == "AE") {
        document.getElementById("txtDuration").value = calculateTime(routes); //(((parseFloat(routes[0].summary.baseTime)) / (60)).toFixed(3)) + " mins";
        document.getElementById("txtDistance").value = parseFloat(routes.summary.distance) / 1000 + " Kms";
        var distance = 0;
        for (j = 0; j < routes.leg[CountLandmark - 1].maneuver.length; j += 1) {
            distance = distance + routes.leg[CountLandmark - 1].maneuver[j].length;
        }

        document.getElementById("hdnIndDistance").value = distance / 1000;

        var IndTime = (parseFloat((routes.summary.travelTime)) / 3600) % 24;
        var Indmins = '';
        Indmins = Math.ceil(parseInt(routes.summary.travelTime) / 60) % 60 + " min(s)";
        var IndHrs = '';
        IndHrs = IndTime >= 1 ? Math.round(IndTime) + " Hr(s) " : '';
        document.getElementById("hdnDuration").value = IndHrs + Indmins;
        document.getElementById("hdnDurationSec").value = parseInt(routes.summary.travelTime);
        document.getElementById("hdnTrafficDuration").value = calculateTrafficTime(routes);
        document.getElementById("txtTrafficDuration").value = calculateTrafficTime(routes);
        //hdnIndDistanceroutes[0].legs[0].travelTime
        //alert((routes[0].legs[CountLandmark - 1].length) / 1000);
        //routes[0].legs[0].length
    }
    else {
        var temp = '';
        if (Address != null && Address.length > 0) {
            //            for (var i = 0; i < Address.length; i++) {
            //                temp += i == 0 ? "<B>Start :" + Address[i] + " (A)</B></br>" : i == Address.length - 1 ? "<B>Destination :" + Address[i] + " (B)</B></br></br>" : "Via " + i + ":" + Address[i] + "</br>";
            //            }
            temp = FrameAddress(Address);
        }
        temp += "<table cellpadding='5' class='InfoBubble'><tr><td><B>Arrival Time</B> : </td><td>" + calculateTime(routes) + "</td></tr>";  //(((parseFloat(routes[0].summary.baseTime)) / (60)).toFixed(3)) + " mins</br></br>";
        //Access the total lenght of the route in kilometers
        temp += "<tr><td><B>Total distance</B> : </td><td>" + parseFloat(routes.summary.distance) / 1000 + " Kms</td></tr></table></br></br>";
        document.getElementById("map-eta").innerHTML = '';
        //temp += "<table cellpadding='5' class='InfoBubble'>";

        //for (i = 0; i < routes.leg.length; i += 1) {
        //    for (j = 0; j < routes.leg[i].maneuver.length; j += 1) {
        //        // Get the next maneuver.
        //        maneuver = routes.leg[i].maneuver[j];
        //        temp += "<tr><td>" + (i + 1) + ") </td><td>" + maneuver.instruction + "</td></tr>";
        //    }
        //}

        //temp += "</table>";
        document.getElementById("map-eta").innerHTML = iconETAText(temp);
        return temp;
    }
}
//Function for Rounding a decimal number 
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

//Time Calculation for Routing.
function calculateTime(routes) {
    //var Time = (parseFloat(routes[0].summary.baseTime) / (60 * 60));
    //var mins = '';
    //mins = Math.ceil(parseFloat(routes[0].summary.baseTime) / 60) + " min(s)";
    //var Hrs = '';
    //Hrs = Time >= 1 ? Math.round(Time) + " Hr(s) " : '';
    //return (Hrs + mins)
    var seconds = parseFloat(routes.summary.baseTime);
    var hours = parseInt(seconds / 3600) % 24;
    var minutes = parseInt(seconds / 60) % 60;
    var result = (hours < 10 ? "0" + hours : hours) + " Hr(s) " + (minutes < 10 ? "0" + minutes : minutes) + " min(s)";
    return result;
}
function calculateTrafficTime(routes) {
    //var traTime = (parseFloat(routes[0].summary.trafficTime) / (60 * 60));
    //var tramins = '';
    //tramins = Math.ceil(parseFloat(routes[0].summary.trafficTime) / 60) + " min(s)";
    //var traHrs = '';
    //traHrs = traTime >= 1 ? Math.round(traTime) + " Hr(s) " : '';
    //return (traHrs + tramins)
    var seconds = parseFloat(routes.summary.trafficTime);
    var hours = parseInt(seconds / 3600) % 24;
    var minutes = parseInt(seconds / 60) % 60;
    //  var seconds = seconds % 60;
    var result = (hours < 10 ? "0" + hours : hours) + " Hr(s) " + (minutes < 10 ? "0" + minutes : minutes) + " min(s)";
    //+ "-" + (seconds < 10 ? "0" + seconds : seconds);
    return result;
}
function changeTileProvider(MapType, PasLang) {

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

    switch (MapType) {
        case 'N':
            mapType = 'N';
            map.setBaseLayer(defaultLayers.normal.map);
            break;
        case 'S':
            mapType = 'S';
            map.setBaseLayer(defaultLayers.satellite.map);
            break;
        case 'T':
            mapType = 'T';
            map.setBaseLayer(defaultLayers.terrain.map);
            break;
        default:
            mapType = 'N';
            map.setBaseLayer(defaultLayers.normal.map);
            break;
    }
}
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';
        }
    }
}