/********************************************************************
The functions listed below are related to Routing Feature.
Functions and terms used are specific to NavTeq Maps. 
This has been used in Route management Module. 
********************************************************************/

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

var maptype = "normal.day";
var LoadTime = null;
var map = null;
var pageName = null;
var bubbles = null;
var centerCoordinate = new H.geo.Point(20.00, 78.00);
var orgCenter = null;
var orgZoomLevel = null;
var Address = new Array();
var infoBubbleMessage = new Array();
var infoBubble = null;
var infoMarkers = {};
var CountLandmark = null;
var RouteTypeCond = null;
var MarkerArray = new Array();
var dummyVar = 0;

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

function goMap24() {
    LoadMap();
}

//Load Navteq maps.
function LoadMap() {

    //Load NLP nokia.maps NavTeq maps.
    if (document.getElementById('maparea').innerHTML == "" || document.getElementById('maparea').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
        map = new H.Map(document.getElementById("maparea"),
            defaultLayers.raster.normal.map,
            {
                center: orgCenter != null ? orgCenter : centerCoordinate,
                zoom: orgZoomLevel != null ? orgZoomLevel : 4,
                engineType: H.map.render.RenderEngine.EngineType.P2D
            });
        // Set up events for the map:
        mapEvents = new mapsjs.mapevents.MapEvents(map);
        //Behaviour
        behavior = new H.mapevents.Behavior(mapEvents);
        // Create the default UI components
        ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");
        centerCoordinate = map.getCenter();

        if (document.getElementById("hdnlang") != null) {
            if (document.getElementById("hdnlang").value == "LanguageArNew") {
                changeTileProvider(maptype, 'Ar');
                LoadTime = null;
                //map.addObserver("baseMapType", MapTypeObserver);
            }
        }
    }
    orgCenter = null;
    orgZoomLevel = null;
    return true;

    //Disable print description button
    //if (document.getElementById('btnGetDirections') != null) {
    //    document.getElementById('btnGetDirections').click();
    //}
}

/********************************/
var objContainer = new H.map.Group();
var objMkr_Grp = new H.map.Group();
var readInputTraceFile = function () {
    objContainer.removeAll();

    var result = document.getElementById('hdnRouteValue').value;
    var zip = new JSZip();
    zip.file('rme.csv', result);
    var content = zip.generate({ type: "base64", compression: "DEFLATE", compressionOptions: { level: 6 } });

    var url = "https://rme.cit.api.here.com/2/matchroute.json?routemode=car&file=" + encodeURIComponent(content) + "&app_id=i9qgPzpEIq4Rg5S67TjC&app_code=dwJNitpIBnj8_r94B7vYkg";      //"&app_id=S5uqRlhmEQghfMDH5EE5&app_code=6UocH7EhlALgrbJiHoVGZg";
    getJSONP(url, gotRouteMatchResponse);

};

var routeStrip = new H.geo.LineString();
var currentRouteStrip = new H.geo.LineString();
var lntlngs_hs = new Array();
var playZoom = new Array();
var gotRouteMatchResponse = function (respJsonObj) {
    if (respJsonObj.error != undefined || respJsonObj.faultCode != undefined || respJsonObj.type) {
        alert(respJsonObj.message + "\nStatus: " + respJsonObj.responseCode);
        return;
    }
    lntlngs_hs = new Array();
    playZoom = new Array();
    clusterMarkerArray = new Array();
    currentRouteStrip = new H.geo.LineString();
    // draw the route
    var routeLinks = respJsonObj.RouteLinks;
    var coords2 = new H.geo.LineString();
    for (var l = 0; l < routeLinks.length; l++) {
        var coords1 = routeLinks[l].shape.split(" ");
        for (var c = 0; c < coords1.length; c += 2) {
            coords2.pushLatLngAlt(parseFloat(coords1[c]), parseFloat(coords1[c + 1]), null);
            playZoom.push(new H.geo.Point(parseFloat(coords1[c]), parseFloat(coords1[c + 1])));
            currentRouteStrip.pushLatLngAlt(parseFloat(coords1[c]), parseFloat(coords1[c + 1]), null);
            //currentRouteStrip.pushLatLngAlt.apply(currentRouteStrip, shape[i].split(',').map(function (item) { return parseFloat(item); }));
        }
        if (coords2 != null) {
            objContainer.addObject(new H.map.Polyline(coords2, { zIndex: 3, style: { lineWidth: 8, strokeColor: "rgba(18, 65, 145, 0.7)", lineJoin: "round" }, arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 } }));
        }
    }

    var ltMapIT = document.getElementById('hdnRetValue').value.split('~&~');

    // draw the original and the matched trace points
    routeStrip = new H.geo.LineString();
    tracePoints = respJsonObj.TracePoints;
    for (var l = 0; l < tracePoints.length; l++) {
        var p = tracePoints[l];
        if (ltMapIT[l] != null && ltMapIT[l] != '') {
            var ltnMapIt = ltMapIT[l].split('~#~');
            var point = new H.geo.Point(p.lat, p.lon);
            routeStrip.pushPoint(point);
            lntlngs_hs.push(point);
            var marker = createMarker(point, ltnMapIt[5], ltnMapIt[3], ltnMapIt[4], l, l, ltnMapIt[2], ltnMapIt[6],
                        ltnMapIt[7], ltnMapIt[8], ltnMapIt[9], 'Message Details', true, 'Message', true, 'Date Time', true, 'Address', true, 'Landmark', true, 'Speed', 'Add Landmark');
            objContainer.addObject(marker);
            clusterMarkerArray.push(marker);
            objMkr_Grp.addObject(marker);
        }
        //objContainer.addObject(new H.map.Marker(new H.geo.Point(p.lat, p.lon), { icon: createIcon("#79130a", l) }));
        //objContainer.addObject(new H.map.Marker(new H.geo.Point(p.latMatched, p.lonMatched), { icon: createIcon("#dc143c", l) }));
    }

    //map.addObject(objContainer);
    map.setViewBounds(objContainer.getBounds());
    // should display the warnings … warnings = respJsonObj.Warnings;  if (warnings.length > 0) …
    mapVersion = respJsonObj.mapVersion; // RME's map version. Use it to cross reference with PDE.
    HidePopUp();
};

var createIcon = function (color, text) {
    var div = document.createElement("div");
    var svg = '<svg xmlns="https://www.w3.org/2000/svg" width="28px" height="16px">' +
    '<line x1="14"  y1="16" x2="14" y2="9" stroke="' + color + '"/>' +
    '<text font-size="10" x="14" y="8" text-anchor="middle" fill="' + color + '">' +
    text + '</text>' +
    '</svg>';
    div.innerHTML = svg; //'../images/fuelnormal-1_.png'
    return new H.map.Icon('../images/fuelnormal-1_.png', { anchor: { x: 14, y: 16 } });
};

function getJSONP(url, callback) {
    var cbnum = "s" + getJSONP.counter++;
    var cbname = "getJSONP." + cbnum;
    url += "&callback=" + cbname;
    var script = document.createElement("script");
    getJSONP[cbnum] = function (response) {
        try {
            callback(response);
        }
        finally {
            delete getJSONP[cbnum];
            script.parentNode.removeChild(script);
            playBack(lntlngs_hs, currentRouteStrip);
        }
    };
    script.src = url;
    script.onerror = function (data) {
        alert("Could not connect to RME.\nCheck connectivity and trace size.");
    }
    document.body.appendChild(script);
} getJSONP.counter = 0;
/*******************************/
var polyline = null;
function drawRoute(isChecked, type) {
    var latLngs = document.getElementById('hdnRouteValue').value;

    if (type == 'r') {
        //var lnt = '';
        //var ltln = latLngs.split('*')[0].split('~&~');
        //for (var i = 0; i < ltln.length; i++)
        //{
        //    lnt += ltln[i].split('~#~')[0] + ',' + ltln[i].split('~#~')[1] + '$';
        //}
        try { if (objMkr_Grp != null) { objMkr_Grp.removeObjects(objMkr_Grp.getObjects()); } } catch (ex) { }
        try { if (objContainer != null) { objContainer.removeObjects(objContainer.getObjects()); } } catch (ex) { }
        //try { if (map != null) { map.removeObjects(map.getObjects()); } } catch (ex) { }
        if (isChecked) {
            //try { if (mkr_group != null) { mkr_group.removeObjects(mkr_group.getObjects()); } } catch (ex) { }
            document.getElementById("playbackControls").setAttribute("class", "ControlShow");
            readInputTraceFile();
            drawRoute(true, 'l');
        }
        else {
            document.getElementById("playbackControls").setAttribute("class", "ControlHide");
            if (mkr_group != null) {
                map.addObject(mkr_group);
                drawRoute(true, 'l');
            }
            HidePopUp();
        }
        //drawRoute('l');
        //drawRoute('s');

    }
    else if (type == 's') {
        latLngs = document.getElementById('hdnRouteValue_adv').value;
        //if (objContainer != null) { objContainer.removeAll(); }
        //if (mkr_group != null) { map.removeObject(mkr_group); }
        startRouting_hs(latLngs, 'H', '2');
    }
    else {
        latLngs = document.getElementById('hdnRetValue').value;
        objContainer.removeAll();
        var lt = latLngs.split('*')[0].split('~&~');
        var polyStrip = new H.geo.LineString();
        for (var i = 0; i < lt.length; i++) {
            if (lt[i] != null && lt[i].length > 0) {
                var lng;
                lng = lt[i].split('~#~');
                var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));
                polyStrip.pushPoint(point);
            }
        }

        if (polyStrip.getPointCount() > 1) {
            polyline = new H.map.Polyline(
                        polyStrip,
                        {
                            style: { strokeColor: '#980900', lineWidth: 2, color: '#980900' }
                            //style: { lineWidth: 8, strokeColor: "rgba(18, 65, 145, 0.7)", lineJoin: "round" },
                            //arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 }
                        }
                    );
            objContainer.addObject(polyline);
        }
        map.addObject(objContainer);
        if (objMkr_Grp != null) { map.addObject(objMkr_Grp); }
    }
    capture(resultContainer, map, ui);
}

//Split the lat long values and pass to the routing process.
function startRouting_hs(LatLongs, Page, type) {//LatLongs
    pageName = Page;
    RouteTypeCond = type;
    var points = LatLongs.split('$');
    var itrPoints = 0;
    var collPoints = '';
    clearRoute();
    for (var i = 0; i < points.length; i++) {
        itrPoints++;
        if (itrPoints <= 200) {
            collPoints += points[i] + (((i != points.length - 1) || itrPoints < 200) ? '$' : '');
            if (itrPoints == 200 || (i == points.length - 1)) { itrPoints = 0; wayPoints_fn(collPoints.split('$')); collPoints = ''; }
        }
    }
    return;
}

function wayPoints_fn(points) {
    var waypoints = new Array();
    var prevLatLng = new Array();
    for (var i = 0; i < points.length; i++) {
        if (points[i] != null && points[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);
}

//-------------------------------------------------------------------------------------------------------------
//////////////////////////////////////Routing with LBSP nokia.maps NavTeq//////////////////////////////////////////

//Event to open info bubble.
var OpenBubble = function (evt) {
    try {
        //if (bubbles) infoBubble.closeAll();
        //if (Address.length > 0 && infoBubbleMessage.length > 0) {
        //    var coordinate = evt.target.getPosition(); //evt.currentTarget.coordinate;
        //    var msg = "<table cellpadding='5' class='InfoBubble'>";
        //    msg += evt.currentTarget.text == "A" ? "<tr><td width='113px'><B>Landmark Name</B></td><td>" + Address[0] + "</td></tr>" + "<tr><td width='113px'><B>Address</B></td><td>" + infoBubbleMessage[0] + "</br></td></tr>" : evt.currentTarget.text == "B" ? "<tr><td width='113px'><B>Landmark Name</B></td><td>" + Address[infoBubbleMessage.length - 1] + "</td></tr>" + "<tr><td width='113px'><B>Address</B></td>" + "<td>" + infoBubbleMessage[infoBubbleMessage.length - 1] + "</td></tr>" : "<tr><td width='113px'><B>Landmark Name</B></td><td>" + Address[parseInt(evt.currentTarget.text)] + "</td></tr>" + "<tr><td width='113px'><B>Address</B></td><td>" + infoBubbleMessage[parseInt(evt.currentTarget.text)] + "</td></tr>";
        //    msg += "</table>";
        //    ui.removeBubble(infoBubble);
        //    infoBubble = new H.ui.InfoBubble(coordinate, { content: msg });
        //    ui.addBubble(infoBubble);
        //    //bubbles = infoBubble.openBubble(msg, coordinate);
        //}
        //else if (Address.length > 0) {
        //infoBubble.Bubble.prototype.defaultWidth = 200;
        var coordinate = evt.target.getPosition(); //evt.currentTarget.coordinate;
        var msg = "<table cellpadding='5' class='InfoBubble'>";
        //msg += evt.currentTarget.text == "A" ? "<tr><td width='80px'><B>Landmark</B></td><td>" + Address[0] + "</td></tr>" : evt.currentTarget.text == "B" ? "<tr><td width='80px'><B>Landmark</B></td><td>" + Address[Address.length - 1] + "</td></tr>" : "<tr><td width='80px'><B>Landmark</B></td><td>" + Address[parseInt(evt.currentTarget.text)] + "</td></tr>";
        msg += "<tr><td width='80px'><B>Landmark</B></td><td>" + evt.target.getData() + "</td></tr>";
        msg += "</table>";
        ui.removeBubble(infoBubble);
        infoBubble = new H.ui.InfoBubble(coordinate, { content: msg });
        ui.addBubble(infoBubble);
        //bubbles = infoBubble.openBubble(msg, coordinate);
        //}
    }
    catch (er) { }
}

//Event to close info bubble.
var CloseBubble = function (evt) {
    //if (bubbles)
    //infoBubble.closeAll();
    ui.removeBubble(infoBubble);
}

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

//Variable Declaration.
var objectContainer = new H.map.Group(); //nokia.maps.map.Container();
var routingRequest, routes, mapRoute, routeId, routeColor, routeTrafficMode, polylineRoute;
//Route Call
function routingCallback_hs(observedRouter) {
    try {
        routes = observedRouter.response.route[0];
        routeTrafficMode = routes.mode.trafficMode;
        if (routes) {
            //for (var k = 0; k < CountLandmark; k++) {
            //    dummyVar = k;
            //    DrivingDirection(routes);
            if (RouteTypeCond == "1") {
                __doPostBack('btnRoute', 'OnClick');
            }
            //}
        }
        else {
            alert("Routing Request Failed.")
            HidePopUp();
            return;
        }


        routeColor = routeTrafficMode == "enabled" ? "#a000a080" : "#0000f080";
        //create the default map representation of a route
        //mapRoute = new nokia.maps.routing.component.RouteResultSet(routes[0]).container;
        //            mapRoute.set("visibility",
        //			(routeTrafficMode == "enabled"));
        //map.objects.add(mapRoute);
        //map.addObject(routes);

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

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

        polyline = new H.map.Polyline(strip, {
            style: {
                lineWidth: 8,
                strokeColor: 'rgba(3, 116, 48, 0.7)'
            },
            arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 }
        });
        polylineRoute = polyline;
        objContainer.addObject(polyline);
        // Add the polyline to the map
        map.addObject(objContainer);
        // And zoom to its bounding rectangle
        //map.setViewBounds(polyline.getBounds(), true);
        map.getViewModel().setLookAtData({
            bounds: polyline.getBoundingBox()
        });

        //   var iconMarkup = '<svg style="left:-15px;top:-30px;"' +
        //'xmlns="https://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>';

        //   for (var i in routes.waypoint) {

        //       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 ? "Start" : i == routes.waypoint.length - 1 ? "End" : i))
        //                 .replace('{{{SCALE}}}', 1)
        //               , { anchor: new H.math.Point(0, 150) })
        //           });

        //       if (Address.length > 0) {
        //           marker.setData(Address[i]);
        //       }
        //       map.addObject(marker);
        //       marker.addEventListener("pointerenter", OpenBubble);
        //       marker.addEventListener("pointerleave", CloseBubble);

        MarkerArray.push(polyline);
        //   }

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


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

var routingManager = platform.getRoutingService();

function callroute(waypoints) {
    try {

        var routeRequestParams_hs = {
            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_hs["waypoint" + i] = waypoints[i].position.lat + ',' + waypoints[i].position.lng;
        }

        //make a calculateRoute request
        routingManager.calculateRoute(routeRequestParams_hs, routingCallback_hs, onError_hs);
    }
    catch (er) {
        HidePopUp();
        TrinetraCustomAlerts("Routing request failed.");
    }
};
function onError_hs(error) {
    HidePopUp();
    TrinetraCustomAlerts("The routing request failed.");
}
//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;
        var trtTime = 0;
        for (j = 0; j < routes.leg[dummyVar].maneuver.length; j += 1) {
            distance = distance + routes.leg[dummyVar].maneuver[j].length;
            trtTime = trtTime + routes.leg[dummyVar].maneuver[j].travelTime;
        }

        //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((trtTime)) / 3600);  //(parseFloat((routes.summary.travelTime)) / 3600) % 24;
        var Indmins = '';
        Indmins = parseFloat(parseInt(trtTime) / 60) + " min(s)"; //Math.ceil(parseInt(routes.summary.travelTime) / 60) % 60 + " min(s)";
        var IndHrs = '';
        IndHrs = IndTime >= 1 ? parseFloat(IndTime) + " Hr(s) " : '';
        document.getElementById("hdnDuration").value = IndHrs + Indmins;
        document.getElementById("hdnDurationSec").value = parseInt(trtTime); // 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>Time Taken to Travel</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("directions").innerHTML = '';
        temp += "<table cellpadding='5' class='InfoBubble'>";

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

        //for (var i = 0; i < routes.getManeuvers().length; i++) {
        //    var j = parseInt(i) + 1;
        //    temp += "<tr><td>" + j + ") </td><td>" + routes.getManeuvers()[i].instruction + "</td></tr>";
        //}
        temp += "</table>";
        document.getElementById("directions").innerHTML = temp;
        temp = '';

        //for (i = 0; i < routes.leg.length; i += 1) {
        //    for (j = 0; j < route.leg[i].maneuver.length; j += 1) {
        //        // Get the next maneuver.
        //        maneuver = route.leg[i].maneuver[j];
        //        // Add a marker to the maneuvers group
        //        var marker = new H.map.Marker({
        //            lat: maneuver.position.latitude,
        //            lng: maneuver.position.longitude
        //        },
        //          { icon: dotIcon });
        //        marker.instruction = maneuver.instruction;
        //        group.addObject(marker);
        //    }
        //}
    }
}

//Clear Overlays in the maps
function ClearOverlay() {
    try {
        map.removeObjects(map.getObjects());
        //if (mapRoute) map.objects.remove(mapRoute);
        map.setZoom(4);
        if (centerCoordinate)
            map.setCenter(centerCoordinate);
    }
    catch (er) {
        alert("Please check your Internet Connection. Map cannot be loaded.");
    }
}

//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 = parseFloat(seconds / 3600);// % 24;
    var minutes = parseFloat(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;
}
//Assign the Address and Landmark Name
function AssignAddress(Addr, info) {
    Array.clear(Address);
    Array.clear(infoBubbleMessage);
    Address = Addr.split('$');
    infoBubbleMessage = info.split('$');
}


function ClearArray() {
    //    Array.clear(Address);
    //    Array.clear(infoBubbleMessage);
}

function FrameAddress(Address) {
    var Temp = '';
    Temp += "<table cellpadding='5' class='InfoBubble'>";
    for (var i = 0; i < Address.length; i++) {
        Temp += i == 0 ? "<tr><td width='50px'><B>Start</B></td><td><B>" + Address[i] + " (A)</B></td></tr>" : i == Address.length - 1 ? "<tr><td width='50px'><B>End</B></td><td><B>" + Address[i] + " (B)</B></td></tr>" : "<tr><td width='50px'>Via " + i + "</td><td>" + Address[i] + "</td></tr>";
    }
    Temp += "</table></br></br>";
    return Temp;
}

var Alert_Route = 'No route found for this vehicle.';
function setAlertForRoute(AlertRoute) {
    Alert_Route = (AlertRoute == null || AlertRoute == '') ? Alert_Route : AlertRoute;
}

//LandMark
function AddressForRoute(LandMark, page) {
    if (page == 'H') {
        if (LandMark == '') {
            //document.getElementById("chkRoute").checked = false;
            HidePopUp();
            TrinetraCustomAlerts(Alert_Route)
            return;
        }
        var LandRoute = LandMark.split('~#~');
        Address = LandRoute[1].split('$');
        startRouting_hs(LandRoute[0], "AE", '2');
        HidePopUp();
    }
    else {
        Array.clear(Address);
        Address = LandMark.split('$');
    }
    capture(resultContainer, map, ui);
}

function clearRoute() {
    try {
        if (mapRoute != null) map.removeObjects(mapRoute);
        if (polylineRoute != null && objContainer != null) objContainer.removeObject(polylineRoute);
        if (MarkerArray != null) {
            for (var i = 0; i < MarkerArray.length; i++) {
                map.removeObject(MarkerArray[i]);
            }
        }
    }
    catch (er) {
    }
    HidePopUp();
}

/***********************************Maps in Arabic******************************************/
function changeTileProvider(MapType, PasLang) {
    if (LoadTime == null) {
        if (PasLang == "Ar") {
            Plang = 'ARA';
        }
        else if (PasLang == "hin") { Plang = 'hin'; }
        else {
            Plang = 'En';
        }
        defaultLayers = platform.createDefaultLayers(256, 72, Plang);

        switch (MapType) {
            case 'N':
                mapType = 'N';
                map.setBaseLayer(defaultLayers.raster.normal.map);
                break;
            case 'S':
                mapType = 'S';
                map.setBaseLayer(defaultLayers.raster.satellite.map);
                break;
            case 'T':
                mapType = 'T';
                map.setBaseLayer(defaultLayers.raster.terrain.map);
                break;
            default:
                mapType = 'N';
                map.setBaseLayer(defaultLayers.raster.normal.map);
                break;
        }

        //var server_rr = 0;
        //var token = "rUx1XDKfl8JPUTnWuM2tcg";
        //var appId = "dPiRUN4pTa6p9mp63F-8";

        //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=", "ARA",
        //			"&token=",
        //			token,
        //			"&app_id=",
        //			appId
        //        ].join("");
        //    }
        //});
        // very evil to overwrite the base provider for minimap provider
        // nokia.maps.map.js.nokiaTileProviders.base[0] = baseMapProvider;
        LoadTime = 1;
        //map.set("baseMapType", baseMapProvider);
    }
    else {
        LoadTime = null;
    }
}
/***********************************End of Maps in Arabic******************************************/

/***********************************Functions for MAPIT******************************************/

//Set Center to its org country.
function SetOrgCenter(coord) {
    var point = coord.split(',')
    if (map) {
        map.setCenter(new H.geo.Point(parseFloat(point[0]), parseFloat(point[1])));
        map.setZoom(parseFloat(point[2]));
    }
    orgCenter = new H.geo.Point(parseFloat(point[0]), parseFloat(point[1]));
    orgZoomLevel = point[2];
}

//$(function () {
//    $("#gvLandMarks tbody").sortable();
//    $("#sortable").disableSelection();
//});
//$(document.ready(function () { $("#gvLandMarks tbody").sortable(); }));

//function swapStops() {
//    var fixHelperModified = function (e, tr) {
//        var $originals = tr.children();
//        var $helper = tr.clone();
//        $helper.children().each(function (index) {
//            $(this).width($originals.eq(index).width())
//        });
//        return $helper;
//    },
//    updateIndex = function (e, ui) {
//        $('td.index', ui.item.parent()).each(function (i) {
//            $(this).html(i + 1);
//        });
//    };

//    $("#gvLandMarks tbody").sortable({
//        helper: fixHelperModified,
//        stop: updateIndex
//    }).disableSelection();
//}

//$(document).ready(function () {
//    $(function sortgridrows() {
//        $(".GridView1").sortable({
//            items: 'tr:not(tr:first-child)',
//            cursor: 'crosshair',
//            connectWith: '.GridView1',
//            axis: 'y',
//            dropOnEmpty: true,
//            receive: function (e, ui) {
//                $(this).find("tbody").append(ui.item);
//            }
//        });
//        $("[id*=gvLandMarks] tr:not(tr:first-child)").remove();
//    });
//});

//$(document).ready(function () {    
//    $('#gvLandMarks').tableDnD();
//});

//var prm = Sys.WebForms.PageRequestManager.getInstance();
//prm.add_endRequest(function () {
//    $(document).ready(function () {
//$("#gvLandMarks").tableDnD({
//    onDragClass: "myDragClass",
//    onDrop: function (table, row) {
//        var rows = table.tBodies[0].rows;
//        var debugStr = "";
//        var IsDuplicate = document.getElementById("IsDuplicate");
//        var Value = null;
//        for (var i = 0; i < rows.length; i++) {
//            if (Value == rows[i].id) {
//                IsDuplicate.value = true;
//                break;
//            }
//            debugStr += rows[i].id + "*" + (i) + "$";
//            Value = rows[i].id;
//        }
//        $("#hdnOrder").val(debugStr.replace("gvLandMarks_", ""));
//        document.getElementById("hdnOrder").value = debugStr.replace("gvLandMarks_", "");
//        document.getElementById("btnAdd").click();
//        __doPostBack('btnAdd', '');
//    }
//});
//    });
//});

function EnableReorder(enable) {
    if (enable) {
        $("#gvLandMarks").rowSorter({
            handler: "td.sorter",
            //onBeforeMove: function (tbody, row, new_index, old_index) {
            //    if (old_index === 0 || new_index === 0) {            
            //        return false;                
            //    }
            //    else {
            //        return true;
            //    }
            //},
            onDrop: function (tbody, row, new_index, old_index) {
                //$("#log").html(old_index + " row moved to " + new_index);            
                //old_index = old_index + 1;
                //new_index = new_index + 1;
                document.getElementById("hdnOrder").value = old_index + '$' + new_index;
                __doPostBack('btnTest', 'OnClick');
            }
        });
    }
    else {
        $("#gvLandMarks").rowSorter({
            handler: "td.asfsdafsdafsa",
            onDrop: function (tbody, row, new_index, old_index) {
                document.getElementById("hdnOrder").value = old_index + '$' + new_index;
                __doPostBack('btnTest', 'OnClick');
            }
        });
    }
    //$('#gvLandMarks tr').each(function (index) {
    //    if (index === 1)
    //        $(this).addClass("nodrag");
    //});
}