/********************************************************************
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({
//    app_id: 'UdwAigBKPRhu01vbIGkI',
//    app_code: 'PzCfyYAsV98qvfU8gusqRg',
//    useCIT: true,
//    useHTTPS: true
//});
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();
}
//-- -------Created by Mr. Savio for Route Assignmnet -----------//
function RouteAssignMap() {
    ClearOverlay();
    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);
        mapEvents = new H.mapevents.MapEvents(map);
        //Behaviour
        behavior = new H.mapevents.Behavior(mapEvents);
        // Create the default UI components
        ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");
        centerCoordinate = map.getCenter();

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

        RouteContextMenu(map);
    }
    orgCenter = null;
    orgZoomLevel = null;
    return true;

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

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

    if (pageName == 'RA') {
        Assigncallroute(waypoints)
    }
    else {
        callroute(waypoints);
    }

    //alert(type + "Hello");

    return;
}

//-------------------------------------------------------------------------------------------------------------
//////////////////////////////////////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.getGeometry(); //evt.currentTarget.coordinate;
        var ad = evt.target.getData().split(',');
        console.log(ad[0]);
        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) { }
}
//function OpenOrderModal(address) {
//    alert(address);
//}

//msg += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + address + '\');' +
//       'document.getElementById(\'txtLocationName\').focus();" style="color:white">' + 'Add Order Info' + '<\/a></td></tr>';
//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;
//Route Call
function routingCallback(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;
        }
        if (mapRoute) {
            map.removeObjects(mapRoute);
            for (var i = 0; i < MarkerArray.length; i++) {
                map.removeObject(MarkerArray[i]);
            }
        }

        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(0, 128, 255, 0.7)'
            },
            arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 }
        });
        // Add the polyline to the map
        map.addObject(polyline);
        // 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 coord = routes[0].waypoints[i].mappedPosition;

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



            //{
            //    text: i == 0 ? "A" : i == routes.waypoint.length - 1 ? "B" : i,
            //    name: i,
            //    //eventListener: myListener,
            //    brush: {
            //        //fillcolor of brush
            //        color: i == 0 ? "#008000" : i == routes.waypoint.length - 1 ? "#FF0000" : "#0055AA"
            //    }
            //});
            if (Address.length > 0) {
                marker.setData(Address[i]);
            }
            map.addObject(marker);
            marker.addEventListener("pointerenter", OpenBubble);
            marker.addEventListener("pointerleave", CloseBubble);

            MarkerArray.push(marker);

            //infoBubbleMessage
        }

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


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

//var routingManager = new nokia.maps.advrouting.Manager();
//routingManager.addObserver("state", routingCallback);

var routingManager = platform.getRoutingService();

function callroute(waypoints) {
    try {
        //    var modes = [
        //{
        //    type: "fastest",
        //    transportModes: ["car"],
        //    trafficMode: "default"
        //}];

        //var routeRequest = new nokia.maps.advrouting.CalculateRouteRequest();
        //routeRequest.set("modes", modes.slice(0));
        //routeRequest.set("representationOptions", {
        //    language: "en-US",
        //    representationMode: "overview",
        //    routeAttributes: ["wp", "sc", "sm", "sh", "bb", "lg", "no"],
        //    legAttributes: ["wp", "mn", "li", "le", "tt"],
        //    maneuverAttributes: ["po", "sh", "tt", "le", "ti", "li", "pt", "pl", "eq", "la", "rn", "nr"],
        //    linkAttributes: ["sh", "le", "sl", "ds", "ic", "tr", "er"],
        //    corridorDepth: 2,
        //    instructionFormat: "html"
        //});
        //routeRequest.set("departure", "2010-04-01T17:00:00Z");
        //routeRequest.set("alternatives", 2);
        //routeRequest.set("metaInfo", { requestId: "sampleRequest" });
        //routeRequest.set("waypoints", waypoints);

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


        //add map objects if they are not added
        // if (!objectContainer.isAdded(map))
        //map.objects.add(objectContainer);
        //make a calculateRoute request
        routingManager.calculateRoute(routeRequestParams, routingCallback, onError);
    }
    catch (er) {
        HidePopUp();
        TrinetraCustomAlerts("Routing request failed.");
    }
};
function onError(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 {
        if (map != null) {
            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('$');
        //--- Route Assignment ---//
        if (page == 'RA') {
            startRouting(LandRoute[0], "RA", '2');
            //HidePopUp();
        }
        else {
            startRouting(LandRoute[0], "AE", '2');
            //HidePopUp();
        }
        HidePopUp();
    }
    else {
        Array.clear(Address);
        Address = LandMark.split('$');
    }
}

function clearRoute() {
    try {
        if (mapRoute) map.removeObjects(mapRoute);
        if (MarkerArray) {
            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]));
        applyFleetLayer_NV(map, platform);
    }

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

$rs = jQuery.noConflict();
function EnableReorder(enable) {
    if (enable) {
        $rs("#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) {
                //$rs("#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 {
        $rs("#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");
    //});
}

/*Show POI's*/
function applyFleetLayer_NV(map, platform) {
    var mapTileService = platform.getMapTileService({ 'type': 'base' });

    // Create a tile layer which requests map tiles with an additional 'style'
    // URL parameter set to 'fleet':
    var parameters = { style: 'default', pois: true, ppi: '72' };

    var fleetStyleLayer = mapTileService.createTileLayer(
        'maptile',
        'normal.day',
        256,
        'png8',
        parameters);

    // Set the new fleet style layer as a base layer on the map:
    map.setBaseLayer(fleetStyleLayer);
}
//------------------- Map click open the context menu-----------------//
var mkr_group = new H.map.Group();
var geocoder = platform.getGeocodingService();
var notReverseGeocoded = true;
var address = ''

function RouteContextMenu(map) {
    map.addEventListener('contextmenu', function (e) {
        isDisabled = document.getElementById("pnlRouteInformations").className == "ControlShow" ? false : true;

        if (notReverseGeocoded) {
            clickCoords = map.screenToGeo(e.viewportX, e.viewportY);
            var coord = clickCoords.lat + "," + clickCoords.lng;
            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 {
            e.items.push(
                new H.util.ContextItem({
                    label: address,

                }),

                H.util.ContextItem.SEPARATOR,
                new H.util.ContextItem({
                    label: 'Add a way point',
                    disabled: isDisabled,
                    callback: function () {
                        var Clat = Math.round(clickCoords.lat * 1000000) / 1000000;
                        var Clng = Math.round(clickCoords.lng * 1000000) / 1000000;
                        var st = '0' + '$' + address + '$' + Clat + '$' + Clng;
                        var data = Array();
                        data = st.split('$');
                        hdnRoutedts.value = st;
                        __doPostBack('btnhdn', 'OnClick');
                    }
                })
            );
            notReverseGeocoded = true;
        }

    });
}

function LocateMapCoordinatesForMap(lat, lng) {

    var latlong = lat + ',' + lng;

    var reverseGeocodingParameters = {
        prox: latlong + ",200",
        mode: 'retrieveAddresses',
        maxresults: 1,
        language: 'en'
    };
    geocoder.reverseGeocode(reverseGeocodingParameters, function (result) {
        try {
            address = result.Response.View[0].Result[0].Location.Address.Label;
            var st = '0' + '$' + address + '$' + lat + '$' + lng;
            var data = Array();
            data = st.split('$');
            hdnRoutedts.value = st;
            __doPostBack('btnhdn', 'OnClick');

            document.getElementById('txtSearchBox').value = '';

        }
        catch (e) {
            console.log(e);
        }
        //document.getElementById('hdnAddress').value = address;
        //infoBubble = new H.ui.InfoBubble(lcPoint, { content: '<span>' + address + '</span>' });
        //ui.addBubble(infoBubble);
    });
    //, function (e) {
    //    console.log(e);
    //});



}


/*****************************Route Assignment Js*************************/

// --- Open Infowindow----//
var OrderOpenBubble = function (evt) {
    try {
        var coordinate = evt.target.getGeometry();
        var adds = evt.target.getData().split(',');
        console.log(adds[0]);
        var msg = "<table cellpadding='5' class='InfoBubble'>";
        msg += "<tr><td width='80px'><B>Landmark</B></td><td>" + adds[0] + "</td></tr>";
        msg += '<tr><td colspan="2"><a href="javascript:OpenModal(' + '\'' + adds[0] + '\'' + ',\'' + adds[1] + '\');"' +
              '" style="color:white">' + 'Add Order Info' + '<\/a></td></tr>';
        msg += "</table>";
        //msg += '<tr><td colspan="2"><a href="javascript:OpenOrderModal();"' +
        //      '" style="color:white">' + 'Add Order Info' + '<\/a></td></tr>';
        ui.removeBubble(infoBubble);
        infoBubble = new H.ui.InfoBubble(coordinate, { content: msg });
        ui.addBubble(infoBubble);
        //bubbles = infoBubble.openBubble(msg, coordinate);
        //}
    }
    catch (er) { }
}

function Assigncallroute(waypoints) {
    try {
        var routeRequestParams = {
            mode: 'fastest;car',
            representation: 'display',
            routeattributes: 'waypoints,summary,shape,legs',
            maneuverattributes: 'direction,action',
        };

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

        routingManager.calculateRoute(routeRequestParams, OnSuccess, onError);
    }
    catch (er) {
        HidePopUp();
        TrinetraCustomAlerts("Routing request failed.");
    }
};

function OnSuccess(observedRouter) {
    try {
        routes = observedRouter.response.route[0];
        routeTrafficMode = routes.mode.trafficMode;
        if (routes) {

            if (RouteTypeCond == "1") {
                __doPostBack('btnRoute', 'OnClick');
            }
            //}
        }
        else {
            alert("Routing Request Failed.")
            HidePopUp();
            return;
        }
        if (mapRoute) {
            map.removeObjects(mapRoute);
            for (var i = 0; i < MarkerArray.length; i++) {
                map.removeObject(MarkerArray[i]);
            }
        }

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

        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(0, 128, 255, 0.7)'
            },
            arrows: { fillColor: 'white', frequency: 2, width: 1, length: 1 }
        });
        // Add the polyline to the map
        map.addObject(polyline);
        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);
            //map.addObject(MarkerHigh);
            marker.addEventListener("pointerenter", OrderOpenBubble);

            MarkerArray.push(marker);
        }

        HighlightedMarker(document.getElementById('hdnPoints').value);

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

function HighlightedMarker(latlng) {
    console.log(latlng);

    var Coorde = latlng.split('$');
    var LatLng;

    for (var i = 0; i <= Coorde.length - 1; i++) {
        if (Coorde[i] == "") {
        }
        else {
            var icon = "../images/marker-highlight.png";
            LatLng = Coorde[i].split(',');
            var MarkerHigh = new H.map.Marker({ lat: LatLng[0], lng: LatLng[1] }, {
                icon: new H.map.Icon(icon, { anchor: new H.math.Point(20, 40) })
            });

            map.addObject(MarkerHigh);
        }

        // var LatLng = latlng.split(',');
    }
}


