/********************************************************************
The functions listed below are related to Routing Feature.
Functions and terms used are specific to NavTeq Maps. Thsi is 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 defaultLayers = platform.createDefaultLayers();
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 = null;
var centerCoordinate = new H.geo.Point(20.00, 78.00);
var Address = new Array();
var infoBubbleMessage = new Array();
var infoBubble = null;
var infoMarkers = {};
var CountLandmark = null;
var RouteTypeCond = null;
var bubble = null;
//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: centerCoordinate,
                zoom: 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
        // Set up events for the map:
        mapEvents = new H.mapevents.MapEvents(map); //mapsjs.mapevents.MapEvents(map);

        //Behaviour
        behavior = new H.mapevents.Behavior(mapEvents); //new H.mapevents.MapEvents(map));

        ui = H.ui.UI.createDefault(map, defaultLayers, "en-US");

        ui.addControl('zoomRectangle', new H.ui.ZoomRectangle());
        ui.getControl('zoomRectangle').setAlignment('bottom-right');
        //ui.removeControl('mapsettings');
        ui.removeControl('scalebar');
        ui.getControl('mapsettings').setAlignment('top-left');
        //ui.removeControl('zoom');
        ui.getControl('zoom').setAlignment('left-middle');
        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);
    }

    //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;
    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.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;
//Route Call
function routingCallback(observedRouter) {
    try {
        routes = observedRouter.response.route[0];
        routeTrafficMode = routes.mode.trafficMode;
        if (routes) {
            DrivingDirection(routes);
        }
        else {
            alert("Routing Request Failed.")
            HidePopUp();
            return;
        }
        if (mapRoute) {
            map.removeObjects(mapRoute);
        }

        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>';
        var icons = null;


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

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

            //icon: new H.map.Icon(icon, { anchor: new H.math.Point(9, 12) })
            //{
            //    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);
            //Adding Circle to the geozone point.
            //           map.addObject(new H.map.Circle(
            //           // The central point of the circle
            //          { lat: routes.waypoint[i].mappedPosition.latitude, lng: routes.waypoint[i].mappedPosition.longitude },
            //          // The radius of the circle in meters
            //         100,
            //         {
            //             style: {
            //                 strokeColor: 'rgba(55, 85, 170, 0.6)', // Color of the perimeter
            //                 lineWidth: 2,
            //                 fillColor: 'rgba(0, 128, 0, 0.7)'  // Color of the circle
            //             }
            //         }
            //));
            marker.addEventListener("pointermove", OpenBubble);
            marker.addEventListener("pointerout", CloseBubble);
            //infoBubbleMessage
        }

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

        if (RouteTypeCond == "1") {
            __doPostBack('btnRoute', 'OnClick');
        }
    }
    catch (er) {
        alert(er);
        HidePopUp();
        alert("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();
        alert("Routing request failed.")
    }
};
function onError(error) {
    HidePopUp();
    alert("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;
        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);  - Sir  i'm commend the script declared the control not available in aspx page;
        //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.destroy();
        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 = 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;
}
//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>A</B></td><td><B>" + Address[i] + " (A)</B></td></tr>" : i == Address.length - 1 ? "<tr><td width='50px'><B>B</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;
}

//LandMark
function AddressForRoute(LandMark) {
    Array.clear(Address);
    Address = LandMark.split('$');
}

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

function Mapit(ltMapIT) {

    var lng = new Array();
    lng = ltMapIT.split("~#~");
    var point = new H.geo.Point(parseFloat(lng[0]), parseFloat(lng[1]));

    MapIT_Marker(point, lng[4], lng[3], lng[5], lng[6], lng[2], lng[2], lng[7], lng[8], lng[9], lng[10], lng[11], lng[12]);
}

function MapIT_Marker(point, heading, speed, VehName, id, addr, dist, msgDetails, landmarkName, driverName, driverPhoto, driverPhno, PhnoCaption) {

    var temp1 = "'" + point + "'";
    var temp = temp1.substring(2, temp1.length - 2);
    temp = "'" + point.latitude + "," + point.longitude + "'";

    var icon = null;

    if (heading == -1) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-1_.png';
        }
        else if (id == '0') {
            icon = '../images/orange-1_.png';
        }
        else if (id == '1') {
            icon = '../images/purple-1_.png';
        }
        else if (id == '3' || id == '8' || id == '9') /*Idling start & end 06-Dec-2011 - Sakthi*/ {
            icon = '../images/pink-1_.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-1_.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-1_.png';
        }
        else if (id == '10') {
            icon = '../images/mapit-9_.png'; /*Sleep mode - 20-Dec-2011 Sakthi*/
        }
        else {
            icon = '../images/1_.png';
        }
    }
    else if (heading >= 0 && heading <= 30) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-3_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-3_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-3_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-3_20.png';
        }
        else {
            icon = '../images/3_20.png';
        }
    }
    else if (heading > 30 && heading <= 70) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-7_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-7_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-7_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-7_20.png';
        }
        else {
            icon = '../images/7_20.png';
        }
    }
    else if (heading > 70 && heading <= 100) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-1_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-1_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-1_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-1_20.png';
        }
        else {
            icon = '../images/1_20.png';
        }
    }
    else if (heading > 100 && heading <= 150) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-5_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-5_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-5_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-5_20.png';
        }
        else {
            icon = '../images/5_20.png';
        }
    }
    else if (heading > 150 && heading <= 200) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-4_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-4_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-4_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-4_20.png';
        }
        else {
            icon = '../images/4_20.png';
        }
    }
    else if (heading > 200 && heading <= 240) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-8_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-8_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-8_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-8_20.png';
        }
        else {
            icon = '../images/8_20.png';
        }
    }
    else if (heading > 240 && heading <= 280) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-2_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-2_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-2_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-2_20.png';
        }
        else {
            icon = '../images/2_20.png';
        }
    }
    else if (heading > 280 && heading <= 330) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-6_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-6_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-6_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-6_20.png';
        }
        else {
            icon = '../images/6_20.png';
        }
    }
    else if (heading > 330 && heading <= 360) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-3_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-3_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-3_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-3_20.png';
        }
        else {
            icon = '../images/3_20.png';
        }
    }
    else {
        var hd = heading.split('-');
        if (hd != null) {
            if (hd[0] == 'A') {
                icon = '../images/fuellow-1_.png';   //+ hd[1] + '-alert.gif';
            }
        }
    }
    //    icon.shadowSize = new GSize(1, 1);
    //    icon.iconAnchor = new GPoint(12, 12);
    //    icon.infoWindowAnchor = new GPoint(12, 5);

    //var marker = new GMarker(point, { draggable: false, icon: icon });
    // TO set Z-index for Marker
    //    var marker = new google.maps.Marker(point, { draggable: false, icon: icon,
    //        zIndexProcess: function(m) {
    //            return 28800001;
    //        }
    //    });

    //<div style="text-align:' + tableAlign + ';">
    var bubbleMessage = '<div style="text-align:' + 'left' + ';"><table style="direction:' + 'left' + '" cellspacing=5 class=\'InfoBubble\'>';
    //<tr><td colspan="2"><u><b>' + ((mainHeading == null || mainHeading == '') ? 'Vehicle Statistics' : mainHeading) + '</b></u></td></tr>';
    //var validlocationImage = addr == 'N/A' ? '<img src="../Images/icn-address-notvalid.gif" />' : '<img src="../Images/icn-address-valid.gif" />';
    var monitorTabs = [];


    bubbleMessage += '<tr><td><b>' + 'Vehicle' + '</b></td><td>' + VehName + '</td>';

    //bubbleMessage += '<td rowspan="3" align="left"><br><img src=" ' + ((driverPhoto == null || driverPhoto == '') ? '../images/default-user.png' : driverPhoto) + '" width="60px" height="60px" alt="Driver" /></td>';        


    bubbleMessage += '<tr><td><b>Address</b></td><td>' + addr + '</td></tr>';

    bubbleMessage += '<tr><td><b>Speed</b></td><td>' + speed + '</td></tr>';

    bubbleMessage += '</tr>';



    bubbleMessage += '</table><div>';
    //</div>  

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

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

    map.addEventListener("tap", CloseBubble);
    var myListener = {
        "pointermove": [OpenBubble, true, null],
        "tap": [OpenBubble, true, null]
    };
    var marker = new H.map.Marker(
            point, {
                visibility: true,
                icon: new H.map.Icon(icon, { anchor: new H.math.Point(9, 12) })
            });
    marker.addEventListener("pointermove", OpenBubble);
    marker.addEventListener("tap", OpenBubble);
    map.addObject(marker);

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

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

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

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

    //return marker;
}
/*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);
}