var map;
var behavior;
var MapObjectGroup, RouteMapObjectGroup, RouteMapPointObjectGroup;
var platform, maptypes, defaultLayers, isSatellite = false, isTraffic = false, isTransit = false;
var MapObject = [];
var MapObjectNotMakani = [];
var RouteMapObject = [];
var calculateBounds = [];
var trafficLayer;
var transitLayer;
var useLiveTrafficCondition = true;//for fastest/ shortest route

//Map initiation section
window.initMap = function () { };
window.onload = function () {
    //alert(document.getElementById("mapContainer"));
    map = new google.maps.Map(document.getElementById("mapContainer"), {
    //map = new google.maps.Map(this.$el.querySelector("mapContainer"), {
        controlSize: 28,
        streetViewControl: false,
        fullscreenControl: false,
        zoomControl: false,
        zoomControlOptions: {
            position: google.maps.ControlPosition.RIGHT_CENTER,
            style: google.maps.ZoomControlStyle.SMALL
        },
        clickableIcons: false,
        mapTypeControl: false,
        //mapTypeControlOptions: {
        //    mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN],
        //    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        //    position: google.maps.ControlPosition.TOP_CENTER
        //}
    });

    initZoomControl();

    trafficLayer = new google.maps.TrafficLayer();
    transitLayer = new google.maps.TransitLayer();

    var dbxLat = '', dbxLon = '';
    var queryUrlValue = getUrlQueryStringParameterByName(window.location.href);
    if (queryUrlValue) {
        if (queryUrlValue.length > 0) {
            if (queryUrlValue[0]) {
                if (queryUrlValue[0] === "landnumber") {//not implemented by Vendor
                    vm.OnSearchItemClick(queryUrlValue[1], "5", "");
                } if (queryUrlValue[0] === "m") {
                    //asd get latlng frm sq and makani number    
                    vm.OnSearchItemClick(queryUrlValue[1], "2", "");
                    //var latlongValues = queryUrlValue[1].split(',');
                    //dbxLat = Number(latlongValues[0]);
                    //dbxLon = Number(latlongValues[1]);
                } if (queryUrlValue[0] === "sn") {
                    var getLocationParam = {
                        InputJson: {
                            DbSeqNo: queryUrlValue[1],
                            UserId: "",
                            sessionid: ""
                        },
                        Token: "l4f76613re4junvvbbd4ufki1j!=+=o6JGpy02dppzxKfVibRYfQ==",
                        Remarks: "MAKANI PHASE 2"
                    };
                    vm.PrepareForAjaxRequest("GetLocationRequest", getLocationParam, "", "", "");
                }
            }
        }
    }
    moveMapToDubai(map, dbxLat, dbxLon);
    setUpMapTapListener(map);
    setUpLongClickListener(map);

    setTimeout(function () {
        setQiblaCompass();
    }, 4000);

    setTimeout(function () {
        sendEventToGoogleAnalytics("Website Initialization", "Loading", "English");
        sendEventToGoogleAnalytics("Using English Website", "Using English Website", "English");
    }, 3000);


};

function initZoomControl() {
    document.querySelector(".zoom-control-in").onclick = function () {
        map.setZoom(map.getZoom() + 1);
    };

    document.querySelector(".zoom-control-out").onclick = function () {
        map.setZoom(map.getZoom() - 1);
    };

    map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(
        document.querySelector(".zoom-control")
    );
}

function SetControls() {
    $(".gmnoprint div div").css('margin', '0px');
    $(".gmnoprint div div").css('width', '28px');
    $(".gmnoprint div").css('width', '28px');
    $(".gmnoprint div button").css('width', '28px');
    $(".gmnoprint div").css('border-radius', '15px');
    $(".gmnoprint div button img").css('width', '15px');
    $(".gmnoprint div button img").css('height', '15px');

}

function moveMapToDubai(map, lat, lon) {
    if (lat && lon) {
    } else {
        //dubai lat and long hardcoded
        map.setCenter({ lat: 25.264600, lng: 55.311793 });
        map.setZoom(18);
    }
}

function getUrlQueryStringParameterByName(url) {
    var Qvalue = [];
    var names = ["m", "sn", "landnumber"];
    if (!url)
        url = window.location.href;

    for (i = 0; i < names.length; i++) {
        var name = names[i];
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (results) {
            if (results[2]) {
                Qvalue[0] = names[i];
                Qvalue[1] = decodeURIComponent(results[2].replace(/\+/g, ' '));
                break;
            }
        }
    }
    return Qvalue;
}

var clickedMapPoint = {};

function setUpMapTapListener(map) {
    if (vm.checkMapTabEnable()) {
        map.addListener('click', function (evt) {
            if (vm.checkMapTabEnable()) {
                clickedMapPoint = evt.latLng;
                var modelBuildingEntrance = {
                    Lat: evt.latLng.lat(),
                    Lng: evt.latLng.lng(),
                    Token: "l4f76613re4junvvbbd4ufki1j!=+=o6JGpy02dppzxKfVibRYfQ==",
                    Remarks: "MAKANI PHASE 2"
                };

                vm.PrepareForAjaxRequest("GetMapTapLocationInfo", modelBuildingEntrance, "", "", "");

                sendEventToGoogleAnalytics("Map Select", "Map Click", "English");
            }
        });
    }
}

function setUpLongClickListener(map) {
    // Attach an event listener to map display
    // obtain the coordinates and display in an alert box.

    if (vm.checkMapTabEnable()) {
        var mousedUp = false;
        map.addListener('mousedown', function (evt) {
            mousedUp = false;
            setTimeout(function () {
                if (mousedUp === false) {
                    if (vm.checkMapTabEnable()) {
                        clickedMapPoint = evt.latLng;
                        var modelBuildingEntrance = {
                            Lat: evt.latLng.lat(),
                            Lng: evt.latLng.lng(),
                            Token: "l4f76613re4junvvbbd4ufki1j!=+=o6JGpy02dppzxKfVibRYfQ==",
                            Remarks: "MAKANI PHASE 2"
                        };

                        vm.PrepareForAjaxRequest("GetMapTapLocationInfo", modelBuildingEntrance, "", "", "", false, true);

                        sendEventToGoogleAnalytics("Map Select", "Map Click", "English");
                    }
                }
            }, 1000);
        });
        map.addListener('mouseup', function (evt) {
            mousedUp = true;
        });
    }
}

function DrawShapesOnMap(jsonData, jsonRequestData, shapeType, color, noReset) {
    //clear map
    if (!noReset)
        removeAllMapObjects();
    calculateBounds = [];
    //debugger;
    switch (shapeType) {
        case "MAKANI":
            //draw makani point or points on the map

            if (jsonData.hasOwnProperty("BUILDING")) {
                for (i = 0; i < jsonData.BUILDING.length; i++) {
                    if (jsonData.BUILDING[i].hasOwnProperty("SHAPE")) {

                        if (jsonData.BUILDING[i].SHAPE.length != 0) {
                            var shape = jsonData.BUILDING[i].SHAPE;
                            //var polyline = new H.map.Polyline(strip, { style: { lineWidth: 4, strokeColor: '#52b2e5' } });
                            var polyline = DrawPolyline(shape, "BLUE");
                            MapObject.push(polyline);
                        }
                    }
                }
            }

            if (jsonData.hasOwnProperty("MAKANI")) {
                if (jsonData.MAKANI.length != 0) {
                    var shapevalue, longitude, latitude, title, markerOverlayTitle, markerNormal;

                    for (j = 0; j < jsonData.MAKANI.length; j++) {
                        if (jsonData.MAKANI[j].hasOwnProperty("SHAPE")) {
                            if (jsonData.MAKANI[j].SHAPE.length != 0) {

                                shapevalue = jsonData.MAKANI[j].SHAPE.split(",");
                                longitude = shapevalue[0];
                                latitude = shapevalue[1];

                                title = jsonData.MAKANI[j].Makani;
                                if (jsonData.MAKANI[j].EntNameE.length > 4) {
                                    title = jsonData.MAKANI[j].EntNameE;
                                }
                                if (calculateBounds.length == 0)
                                    calculateBounds.push(new google.maps.LatLng(latitude, longitude));
                                markerOverlayTitle = CreateMarker(title, latitude, longitude, true, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);
                                MapObject.push(markerOverlayTitle);
                                markerNormal = CreateMarker(title, latitude, longitude, false, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);

                                MapObject.push(markerNormal);
                                setUpMakaniMarkerClickListener(markerNormal, jsonData.MAKANI[j], "SearchDetailSection");

                            }
                        }

                    }
                }
            }

            SetMapCenterForPolygons();
            break;
        case "POI":
            //draw  building outline and makani points on the map, get shape data from building array, makani data from makani array
            //  MapObjectGroup = new H.map.Group();
            //adding shape object to map group
            if (jsonData.hasOwnProperty("BUILDING")) {
                for (i = 0; i < jsonData.BUILDING.length; i++) {
                    if (jsonData.BUILDING[i].hasOwnProperty("SHAPE")) {

                        if (jsonData.BUILDING[i].SHAPE.length != 0) {
                            var shape = jsonData.BUILDING[i].SHAPE;
                            //var polyline = new H.map.Polyline(strip, { style: { lineWidth: 4, strokeColor: '#52b2e5' } });
                            var polyline = DrawPolyline(shape, "BLUE");
                            MapObject.push(polyline);
                        }
                    }
                }
                SetMapCenterForPolygons();
            }

            if (jsonData.hasOwnProperty("MAKANI")) {
                if (jsonData.MAKANI.length != 0) {
                    var shapevalue, longitude, latitude, title, markerOverlayTitle, markerNormal;
                    for (j = 0; j < jsonData.MAKANI.length; j++) {
                        if (jsonData.MAKANI[j].hasOwnProperty("SHAPE")) {

                            if (jsonData.MAKANI[j].SHAPE.length != 0) {
                                shapevalue = jsonData.MAKANI[j].SHAPE.split(",");
                                longitude = shapevalue[0];
                                latitude = shapevalue[1];
                                title = jsonData.MAKANI[j].Makani;
                                if (jsonData.MAKANI[j].EntNameE.length > 4) {
                                    title = jsonData.MAKANI[j].EntNameE;
                                }

                                markerOverlayTitle = CreateMarker(title, latitude, longitude, true, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);
                                MapObject.push(markerOverlayTitle);
                                markerNormal = CreateMarker(title, latitude, longitude, false, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);
                                MapObject.push(markerNormal);
                                setUpMakaniMarkerClickListener(markerNormal, jsonData.MAKANI[j], "SearchDetailSection");

                            }
                        }

                    }
                }
            }
            break;
        case "COMMUNITY":
            //draw community outline on map ,get shape data from community shape array
            // MapObjectGroup = new H.map.Group();
            for (i = 0; i < jsonData.COMMUNITY.length; i++) {
                if (jsonData.COMMUNITY[i].hasOwnProperty("SHAPE")) {
                    if (jsonData.COMMUNITY[i].SHAPE.length != 0) {
                        var shape = jsonData.COMMUNITY[i].SHAPE;
                        //var polyline = new H.map.Polyline(strip, { style: { lineWidth: 4, strokeColor: '#52b2e5' } });
                        var polyline = DrawPolyline(shape, "RED");
                        MapObject.push(polyline);
                    }
                }
            }
            SetMapCenterForPolygons();
            break;
        case "BUILDINGADDRESS":
            //draw building outline on map take data from duilding array
            //MapObjectGroup = new H.map.Group();
            //adding shape object to map group
            if (jsonData.hasOwnProperty("BUILDING")) {
                for (i = 0; i < jsonData.BUILDING.length; i++) {
                    if (jsonData.BUILDING[i].hasOwnProperty("SHAPE")) {

                        if (jsonData.BUILDING[i].SHAPE.length != 0) {
                            var shape = jsonData.BUILDING[i].SHAPE;
                            //var polyline = new H.map.Polyline(strip, { style: { lineWidth: 4, strokeColor: '#52b2e5' } });
                            var polyline = DrawPolyline(shape, "BLUE");
                            MapObject.push(polyline);
                        }
                    }

                }
                SetMapCenterForPolygons();
            }

            if (jsonData.hasOwnProperty("MAKANI")) {
                if (jsonData.MAKANI.length != 0) {
                    var shapevalue, longitude, latitude, title, markerOverlayTitle, markerNormal;

                    for (j = 0; j < jsonData.MAKANI.length; j++) {
                        if (jsonData.MAKANI[j].hasOwnProperty("SHAPE")) {

                            if (jsonData.MAKANI[j].SHAPE.length != 0) {
                                shapevalue = jsonData.MAKANI[j].SHAPE.split(",");
                                longitude = shapevalue[0];
                                latitude = shapevalue[1];
                                title = jsonData.MAKANI[j].Makani;
                                if (jsonData.MAKANI[j].EntNameE.length > 4) {
                                    title = jsonData.MAKANI[j].EntNameE;
                                }

                                markerOverlayTitle = CreateMarker(title, latitude, longitude, true, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);
                                MapObject.push(markerOverlayTitle);
                                markerNormal = CreateMarker(title, latitude, longitude, false, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);
                                MapObject.push(markerNormal);
                                setUpMakaniMarkerClickListener(markerNormal, jsonData.MAKANI[j], "SearchDetailSection");

                            }
                        }

                    }
                }
            }
            break;
        case "LANDNUMBER":
            //nothing to draw on map as it is a land number
            // MapObjectGroup = new H.map.Group();
            for (i = 0; i < jsonData.PARCEL.length; i++) {
                if (jsonData.PARCEL[i].hasOwnProperty("SHAPE")) {
                    if (jsonData.PARCEL[i].SHAPE.length != 0) {
                        var shape = jsonData.PARCEL[i].SHAPE;
                        //var polyline = new H.map.Polyline(strip, { style: { lineWidth: 4, strokeColor: '#52b2e5' } });
                        var polyline;
                        if (color) {
                            polyline = DrawPolyline(shape, color);
                        } else {
                            polyline = DrawPolyline(shape, "PURPLE");
                        }
                        MapObject.push(polyline);
                    }
                }
            }
            if (jsonData.hasOwnProperty("BUILDINGS")) {
                if (jsonData.BUILDINGS.length !== 0) {
                    for (i = 0; i < jsonData.BUILDINGS.length; i++) {
                        if (jsonData.BUILDINGS[i].hasOwnProperty("SHAPE")) {

                            if (jsonData.BUILDINGS[i].SHAPE.length != 0) {
                                var shape = jsonData.BUILDINGS[i].SHAPE;
                                //var polyline = new H.map.Polyline(strip, { style: { lineWidth: 4, strokeColor: '#52b2e5' } });
                                var polyline = DrawPolyline(shape, "BLUE");
                                MapObject.push(polyline);
                            }
                        }

                    }
                }
                SetMapCenterForPolygons();
            }

            if (jsonData.hasOwnProperty("MAKANI")) {
                if (jsonData.MAKANI.length != 0) {
                    var shapevalue, longitude, latitude, title, markerOverlayTitle, markerNormal;

                    for (j = 0; j < jsonData.MAKANI.length; j++) {
                        if (jsonData.MAKANI[j].hasOwnProperty("SHAPE")) {

                            if (jsonData.MAKANI[j].SHAPE.length != 0) {
                                shapevalue = jsonData.MAKANI[j].SHAPE.split(",");
                                longitude = shapevalue[0];
                                latitude = shapevalue[1];
                                title = jsonData.MAKANI[j].Makani;
                                if (jsonData.MAKANI[j].EntNameE.length > 4) {
                                    title = jsonData.MAKANI[j].EntNameE;
                                }


                                markerOverlayTitle = CreateMarker(title, latitude, longitude, true, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);
                                MapObject.push(markerOverlayTitle);
                                markerNormal = CreateMarker(title, latitude, longitude, false, jsonData.MAKANI[j].EntType, jsonData.MAKANI.length == 2 && jsonData.MAKANI[0].Makani == jsonData.MAKANI[1].Makani ? 1 : jsonData.MAKANI.length);
                                MapObject.push(markerNormal);
                                setUpMakaniMarkerClickListener(markerNormal, jsonData.MAKANI[j], "SearchDetailSection");

                            }
                        }

                    }
                }
            }

            break;
        case "MapLongClickInfoSection":
            console.log(jsonData);
            if (jsonData.hasOwnProperty("BuildingInfo")) {
                var shapevalue, longitude, latitude, title, markerOverlayTitle, markerNormal;
                if (jsonData.hasOwnProperty("EntranceInfo")) {
                    if (jsonData.EntranceInfo.Building.length != 0) {
                        for (i = 0; i < jsonData.EntranceInfo.Building.length; i++) {
                            if (jsonData.EntranceInfo.Building[i].hasOwnProperty("Coord")) {

                                if (jsonData.EntranceInfo.Building[i].Coord.length != 0) {
                                    var shape = jsonData.EntranceInfo.Building[i].Coord;
                                    var polyline = DrawPolyLineMapLongClick(shape, "BLUE");
                                    MapObject.push(polyline);
                                }
                            }
                        }
                        SetMapCenterForPolygons();
                    }
                } if (jsonData.BuildingInfo.Enterance.length != 0) {

                    for (j = 0; j < jsonData.BuildingInfo.Enterance.length; j++) {

                        if (jsonData.BuildingInfo.Enterance[j].hasOwnProperty("LatLng")) {
                            if (jsonData.BuildingInfo.Enterance[j].LatLng.length != 0) {
                                shapevalue = jsonData.BuildingInfo.Enterance[j].LatLng.split(",");
                                latitude = shapevalue[0];
                                longitude = shapevalue[1];
                                title = jsonData.BuildingInfo.Enterance[j].Makani;
                                if (jsonData.BuildingInfo.Enterance[j].EntNameE.length > 4) {
                                    title = jsonData.BuildingInfo.Enterance[j].EntNameE;
                                }

                                markerOverlayTitle = CreateMarker(title, latitude, longitude, true, jsonData.BuildingInfo.Enterance[j].EntType, j);
                                MapObject.push(markerOverlayTitle);
                                markerNormal = CreateMarker(title, latitude, longitude, false, jsonData.BuildingInfo.Enterance[j].EntType, j);
                                MapObject.push(markerNormal);
                                setUpMakaniMarkerClickListener(markerNormal, jsonData.BuildingInfo.Enterance[j], "MapLongClickBuildingInfoSection");
                            }
                        }
                    }
                }
            } else if (jsonData.hasOwnProperty("DbSeqNo")) {
                title = jsonData.CommunityE;
                markerNormal = CreateMarker(title, jsonRequestData.InputJson.Latitude, jsonRequestData.InputJson.Longitude, false, "LongClickPlacePin", 2);

                MapObject.push(markerNormal);

                setUpMakaniMarkerClickListener(markerNormal, jsonData, "MapLongClickBuildingInfoSection");
            }
        case "MakaniMapShareUrlMapSection":
            //draw makani point or points on the map

            if (jsonData.hasOwnProperty("BUILDING")) {
                for (i = 0; i < jsonData.BUILDING.length; i++) {
                    if (jsonData.BUILDING[i].hasOwnProperty("SHAPE")) {
                        if (jsonData.BUILDING[i].SHAPE.length != 0) {
                            var shape = jsonData.BUILDING[i].SHAPE;
                            //var polyline = new H.map.Polyline(strip, { style: { lineWidth: 4, strokeColor: '#52b2e5' } });
                            var polyline = DrawPolyline(shape, "BLUE");
                            MapObject.push(polyline);
                        }
                    }
                }
                SetMapCenterForPolygons();
            }
            if (jsonData.hasOwnProperty("MAKANI")) {
                if (jsonData.MAKANI.length != 0) {
                    var shapevalue, longitude, latitude, title, markerOverlayTitle, markerNormal;

                    for (j = 0; j < jsonData.MAKANI.length; j++) {
                        if (jsonData.MAKANI[j].hasOwnProperty("SHAPE")) {

                            if (jsonData.MAKANI[j].SHAPE.length != 0) {
                                shapevalue = jsonData.MAKANI[j].SHAPE.split(",");
                                longitude = shapevalue[0];
                                latitude = shapevalue[1];
                                title = jsonData.MAKANI[j].Makani;
                                if (jsonData.MAKANI[j].EntNameE.length > 4) {
                                    title = jsonData.MAKANI[j].EntNameE;
                                }

                                markerOverlayTitle = CreateMarker(title, latitude, longitude, true, jsonData.MAKANI[j].EntType, j);
                                MapObject.push(markerOverlayTitle);
                                markerNormal = CreateMarker(title, latitude, longitude, false, jsonData.MAKANI[j].EntType, j);

                                MapObject.push(markerNormal);
                                //setUpMakaniMarkerClickListener(markerNormal, jsonData.MAKANI[j], "UpdateMakaniShareUrlInfo");

                            }
                        }

                    }
                }
            }
            break;
        case "LocationMapShareUrlMapSection":
            if (jsonData.hasOwnProperty("DbSeqNo")) {
                if (jsonData.DbSeqNo.length != 0) {
                    //show share location info
                    //draw marker on map
                    title = jsonData.CommunityE;
                    markerNormal = CreateMarker(title, jsonData.Latitude, jsonData.Longitude, false, "LongClickPlacePin", 2);
                    MapObject.push(markerNormal);

                }
            }
            break;
        case "FallBackMarkerDraw":

            //show share location info
            //draw marker on map
            // title = jsonData.CommunityE;
            title = "";
            markerNormal = CreateMarker(title, global.CurrentSreetLatitude, global.CurrentSreetLongitude, false, "LongClickPlacePin", 2);
            MapObject.push(markerNormal);

            calculateBounds.push(new google.maps.LatLng(markerNormal.getPosition().lat(), markerNormal.getPosition().lng()));
            SetMapCenterForPolygons();
            break;
        default:
    }


}

function SetMapCenterForPolygons() {
    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < calculateBounds.length; i++) {
        bounds.extend(calculateBounds[i]);
    }
    map.setCenter(bounds.getCenter());
    map.fitBounds(bounds);
}

function CreateMarker(title, latValue, lonValue, isToDrawTitleOverLay, IconType, markerscount) {
    var marker, makaniIcon;
    //draw dom marker with title name
    if (isToDrawTitleOverLay == true) {
        var totalSvgWidth = ((title.length + 2) * 8) + 48;
        var firstElemntWidth = 24;
        var firstElemntXSpacing = 0;
        //this is second element, rectangle using for bg color
        var rectangleWidth = (title.length + 2) * 8;
        var secondElemntXSpacing = (firstElemntWidth + firstElemntXSpacing) - 5;
        var thirdElemntWidth = 24;
        var thirdElemntXSpacing = (rectangleWidth + secondElemntXSpacing) - 5;
        //text is for writing title
        var textXSpacing = thirdElemntXSpacing / 4;
        var SvgMarkup = '<svg width="' + totalSvgWidth + '" height="20" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' +
            //'<image width="24" height="20" x="0" y="1" xlink:href="' + global.hostAddress + "/Images/MapPins/MaknaiPinPlatetail.png" + '"/>' +
            '<image width="24" height="20" x="0" y="1" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADoAAABPCAYAAAC6VNZaAAADSElEQVR42uXcT0iTYRwH8K+pqIj0jwpkICUMikioQwQV1KWLl6KsQ3WJDnWpS3noIHaJKD1YBGvObWEJE0vBzf19X9k7Z38m6UEKNIUM16RLHYy82O95c6LhpmNze9/f+4PdxtiH9/v8eZ/neV9IVlxd/HJ8kfsHoiQb6qLOknH2UFHKM2wffoFu9lBRTU3YMtKFxkx+4PfY/gU9fLBWjblw+n/M/Kh5gc0VXYXtgWmyH7L4kt6RaaGiJtpQNjWAVvbQZH314JIhoCrWh4OJED6yh4r63Ieq7yG8Yg9dqqJZP24bAZqM8klDQFVsL6opyn72UFExC0rjQTxkD03WbADnDAEV9c0N85yMGHuoOnX0oTIhwcEemqx4ADcNAVWjPIBj86P7frCHiprqwx4agvrZQ0XJTSihIeg+e+hylL2oNwR06ZavNiFjmD1U1IwLFdRureyhK2ZT1w0BVbE+HPn5fvcMe6ioT6+xMx5CL3uoKJcLxbNB3GMPXdFuzxgCqs6m3KiZk6Cwh4qatqOcZlNP2UOXo+zHFUNAl6aOdQk5u21N6KWm32Abzaa62UOTa8rUbhuNAP0XZd/qbU22UBXrgSkhQWIPVbc1PSijKLewh65YiLtoCKiKDeI8e+iEGw2sr6inDWXjPXjMuo2+7YRppAsh1r1uxIlT7GdGhLyzFmS9kzO6EQYs2ErI7lSn11hc0bAVh951Mr97GXLicrpziLqHynaUU1SfpPrjmZ5m0yQy1I6aIQfCrNeMwh3MVwHFWeEhe+p13V+xvX90D/W2YwdFtTdX7VGTUIrq4Ukv872XiAPXcjF0aBbqakUFIS2bGdWCQ0MO1NIkIMp6x5vaY32+oloQqOsCiimqzZs1dGgCSldxFw0dvM8ZKR04GleYnxyjqN4oVHvMC9T3CJUUVXs+h468Q5XnMBPyA+vzuooNZ7UU1ZxDLRaUUnt8UMihY9Ohfhuqow54WT8lMWjHCfZPMilO3NJ6VLOC9tlQRb3qS60NHTmF0lTuACF5P21IvWqDloeOrKFiW47uHVv01h4zgspWmAgp6TWqG4JGbJlvy+kNWkQdzl0OUU0JTbctp3fkht+VopeeNS10sH39Y6Ic3sPwF6uFScYCbkwuAAAAAElFTkSuQmCC"/>' +
            '<rect height="20"  width="' + rectangleWidth + '" x="' + secondElemntXSpacing + '" y="1" style="fill:#FFDD3C;"> </rect>' +
            //'<image width="24" height="20" x="' + thirdElemntXSpacing + '" y="1" xlink:href="' + global.hostAddress + "/Images/MapPins/MaknaiPinPlateheader.png" + '"/>' +
            '<image width="24" height="20" x="' + thirdElemntXSpacing + '" y="1" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADYAAABPCAYAAACgaDbUAAAC+ElEQVR42t2cPWhTURTH/2pFg0gRbQUpOAgOIjgo+IEKurjooKC46KSDOuikg0KwDtLBDqJD/aBpjTW+l6QKabRVfEg+3ksMaV9rKyhRJAhWqdQ0LwGXem+4hgwRoyL2/S/81wc/7rnnnHvOuQ9pPwpSKSHrDrqSnfCAYb1/0lKSej3Q7Ehl7yGZ8WGN68Fmc9tn62kkgL2UYFKjQVzUDmIBHZjUyzAiWQ0tdGBSuagnN6JjMx3YD40FcYISrAIXQrfdiyV0YFITYbwQXnMtHVh19zTspwSrwIVxOdOFhXRgUuMhPBYZyyo6MKnJWNsnW8cOOrCakHBafHYeHZgyzbvx21hKB1YJCf0YFqnYOjqwGtM8RAmmspUr0atYRAemzt0z2482OrDqBfY+dlGCVe54IZz95yHhf4Ap09QzGprpwKRe9WMsG8AGOrAar3mEEkzVVq4Z3VhMB6aylVjWj9V0YDUhYQ8lmErFzv9VTXOugql49yDVg+V0YOrcTYxq2EgHVjVNHccowVS8u9Fwm8tNYCpbSWYCDbS53AZWDQn6L9pcbgVTXrPd8KKJDkyV2yN2L1rpwKTePvLk7AC20IHVbXMxgVXOXRC+QdnmYgNTcH10YLkIemy2HfswhFN0Z2zqObZReUXHwsDkU6ykimMC6pJhkGUejol9VLliOQVrOkGW3QuoW/kk2X1MmN5xqhv0N7s178SxiarmIUzvYcHACqoqVdnEBU0jqysWE2SVYGF6sS8Jstp9ycL1dwZZt0Xs1FGq/lg53TRejJF1NMUu6dMxLKPqQZdMnPN6MZ9qamAmgd1Ucx6lFIwpg2wyR0B1vomSzVKJ+HSYavqtnMawOE/rqeYVhSvv+xwnmzAVpneGbia4kMBOqilu4fWGhOlxzd07KXTQvZQQqdEBzNX1h14v8zVG9hpJQPk+DpK9H3NMnIRb1m+48q1w02rA9CJFq06bxs1gjoX2n7Zp3ArmJMlerotcz2yoTeMmsBkTN/Max98hvgOG5pA2q64NpwAAAABJRU5ErkJggg=="/>' +
            '<text id="txt" x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="Dubai" font-size="0.8rem" font-weight="bold" fill="#00000">__line1__</text>' + '</svg>';
        SvgMarkup = SvgMarkup.replace(/__line1__/g, title);
        var div = document.createElement("div");
        div.innerHTML = SvgMarkup;
        //div.style.top = "-83px";
        if (global.DeviceScreenType === "PC")
            div.style.top = "-" + global.makaniPinOverlayTopPC + "px";
        else
            div.style.top = "-" + global.makaniPinOverlayTopMobile + "px";

        div.style.left = "-" + totalSvgWidth / 2 + "px";

        //Draw a makani marker.
        var anchorX;
        if (global.DeviceScreenType === "PC")
            anchorX = global.makaniPinOverlayTopPC;
        else
            anchorX = global.makaniPinOverlayTopMobile;

        makaniIcon = {
            url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(SvgMarkup),
            //url: div,
            //anchor: new google.maps.Point(anchorX, totalSvgWidth / 2),
            anchor: new google.maps.Point(totalSvgWidth / 2, anchorX),
        };
        overLayMarker = new google.maps.Marker({
            position: new google.maps.LatLng(latValue, lonValue),
            map,
            icon: makaniIcon,
            optimized: false,
            customInfo: ""
        });

        return overLayMarker;
    } else {
        switch (IconType) {
            case "Wheelchair":
            case "2":
                if (!vm.IsRoutingDivVisible && vm.IsMakaniInfoSectionVisible && markerscount === 1) {
                    makaniIcon = {
                        url: global.hostAddress + '/Images/MapPins/WheelEntranceClicked.png'
                        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                        //origin: new google.maps.Point(0, 0),
                        //anchor: new google.maps.Point(0, global.makaniPinHeight)
                    };
                }
                else {
                    makaniIcon = {
                        url: global.hostAddress + '/Images/MapPins/MakaniPinWheelchair.png'
                        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                        //origin: new google.maps.Point(0, 0),
                        //anchor: new google.maps.Point(0, global.makaniPinHeight)
                    };
                }
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(latValue, lonValue),
                    map,
                    icon: makaniIcon,
                    customInfo: "2"
                });
                break;
            case "LongClickPlacePin":
                makaniIcon = {
                    url: global.hostAddress + '/Images/MapPins/Pin4.png'
                    //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                    //origin: new google.maps.Point(0, 0),
                    //anchor: new google.maps.Point(0, global.makaniPinHeight)
                };
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(latValue, lonValue),
                    map,
                    icon: makaniIcon,
                    customInfo: "LongClickPlacePin"
                });
                break;
            case "LandNumber":
                makaniIcon = {
                    url: global.hostAddress + '/Images/MapPins/Pin2.png'
                    //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                    //origin: new google.maps.Point(0, 0),
                    //anchor: new google.maps.Point(0, global.makaniPinHeight)
                };
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(latValue, lonValue),
                    map,
                    icon: makaniIcon,
                    customInfo: "LandNumber"
                });
                break;
            case "CurrentLocation":
                makaniIcon = {
                    url: global.hostAddress + '/Images/MapPins/currentlocation.png'
                    //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                    //origin: new google.maps.Point(0, 0),
                    //anchor: new google.maps.Point(0, global.makaniPinHeight)
                };
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(latValue, lonValue),
                    map,
                    icon: makaniIcon,
                    customInfo: "CurrentLocation"
                });
                break;
            default:
                if (!vm.IsRoutingDivVisible && vm.IsMakaniInfoSectionVisible && markerscount === 1) {
                    makaniIcon = {
                        url: global.hostAddress + '/Images/MapPins/GreenEntrance_old.png'
                        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                        //origin: new google.maps.Point(0, 0),
                        //anchor: new google.maps.Point(0, global.makaniPinHeight)
                    };
                }
                else {
                    makaniIcon = {
                        url: global.hostAddress + '/Images/MapPins/MakaniPin_old.png'
                        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                        //origin: new google.maps.Point(0, 0),
                        //anchor: new google.maps.Point(0, global.makaniPinHeight)
                    };
                }
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(latValue, lonValue),
                    map,
                    icon: makaniIcon,
                    customInfo: ""
                });

                break;
        }
        return marker;
    }
}

function removeAllMapObjects() {
    for (let i = 0; i < MapObject.length; i++) {
        MapObject[i].setMap(null);
    }
}

function removeAllMapObjectsNotMakani() {
    for (let i = 0; i < MapObjectNotMakani.length; i++) {
        MapObjectNotMakani[i].setMap(null);
    }
}

function DrawPolyLineMapLongClick(shape, color) {
    var polylineColor = "#52b2e5";
    var shapes = shape.split(";");
    //------------- draw the polylines ----------------//
    var lon = "", lat = "";
    var lineSegment = [];
    for (j = 0; j < shapes.length; j++) {
        var latlong = shapes[j].split(",");
        lat = latlong[0];
        lon = latlong[1];
        if (lat && lon) {
            if (lon.length != 0 && lat.length != 0) {
                lineSegment.push(new google.maps.LatLng(lat, lon));
                calculateBounds.push(new google.maps.LatLng(lat, lon));
                lon = ""; lat = "";
            }
        }

    }
    switch (color) {
        case "BLUE":
            polylineColor = "#000088";
            break;
        case "RED":
            polylineColor = "#bf3e3b";
            break;
        case "GREEN":
            polylineColor = "#00e500";
            break;
        default:
            polylineColor = color;
            break;
    }
    var polyline = new google.maps.Polygon({
        path: lineSegment,
        geodesic: true,
        strokeColor: polylineColor,
        fillOpacity: 0.0
    });
    polyline.setMap(map);
    return polyline;
}

function DrawPolyline(shape, color) {

    var polylineColor = "#52b2e5";
    var shapes = shape.split(",");
    //------------- draw the polylines ----------------//
    var lon = "", lat = "";
    var lineSegment = [];

    for (j = 0; j < shapes.length; j++) {

        if ((j % 2) == 0) {
            lon = shapes[j];
        } else {
            lat = shapes[j];
        }
        if (lon.length != 0 && lat.length != 0) {
            lineSegment.push(new google.maps.LatLng(lat, lon));
            calculateBounds.push(new google.maps.LatLng(lat, lon));
            lon = ""; lat = "";
        }

    }

    switch (color) {
        case "BLUE":
            polylineColor = "#000088";
            break;
        case "RED":
            polylineColor = "#bf3e3b";
            break;
        case "GREEN":
            polylineColor = "#00e500";
            break;
        default:
            polylineColor = color;
            break;
    }
    var polyline = new google.maps.Polygon({
        path: lineSegment,
        geodesic: true,
        strokeColor: polylineColor,
        fillOpacity: 0.0
    });
    polyline.setMap(map);
    return polyline;
}

function movetoCurrentLocation(latval, lngval, locationchanged) {
    addDraggableMarker("", latval, lngval, true, true, false, locationchanged);
}

function addDraggableMarker(model, latVal, lngVal, notDraggable, isCurrentLocation, isMakani, calculateRoute) {
    if (isCurrentLocation && global.currentLocationMarker) {
        //if (!RouteMapPointObjectGroup.contains(global.currentLocationMarker))
        //    RouteMapPointObjectGroup.addObject(global.currentLocationMarker);

        var markerIcon = {
            url: global.hostAddress + '/Images/MapPins/currentlocation.png',
            size: new google.maps.Size(global.currentLocationIconSize, global.currentLocationIconSize),
            //origin: new google.maps.Point(0, 0),
            //anchor: new google.maps.Point(0, global.makaniPinHeight)
        };
        global.currentLocationMarker.setIcon(markerIcon);
        global.currentLocationMarker.setPosition({ lat: latVal, lng: lngVal });
        if (calculateRoute)
            vm.calculateRoute();
        return;
    }

    var draggable = true;
    if (notDraggable)
        draggable = false;

    var markerIcon;
    if (isCurrentLocation) {
        markerIcon = {
            url: global.hostAddress + '/Images/MapPins/currentlocation.png',
            size: new google.maps.Size(global.currentLocationIconSize, global.currentLocationIconSize),
            //origin: new google.maps.Point(0, 0),
            //anchor: new google.maps.Point(0, global.makaniPinHeight)
        };
    } else {

        markerIcon = {
            url: global.hostAddress + '/Images/MapPins/Pin2.png',
            size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
            //origin: new google.maps.Point(0, 0),
            //anchor: new google.maps.Point(0, global.makaniPinHeight)
        };
    }
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(latVal, lngVal),
        map,
        icon: markerIcon,
    });

    // Ensure that the marker can receive drag events
    marker.draggable = draggable;
    if (!RouteMapPointObjectGroup) {
        //RouteMapPointObjectGroup = new H.map.Group();
        //map.addObject(RouteMapPointObjectGroup);
    }


    if (isMakani || !draggable)
        marker.setVisible(false);


    //RouteMapPointObjectGroup.addObject(marker);

    if (isCurrentLocation)
        global.currentLocationMarker = marker;
}

function setBaseMap(baseMapType) {
    //map.setMapTypeId('roadmap');
    //map.setMapTypeId('hybrid');

    switch (baseMapType) {
        case "normal":
            if (!isSatellite) {
                map.setMapTypeId("hybrid");
                isSatellite = true;
                vm.isMapTypeSatelliteVisible = false;
                vm.isMapTypeNormalVisible = true;
            } else {
                map.setMapTypeId("roadmap");
                isSatellite = false;
                vm.isMapTypeSatelliteVisible = true;
                vm.isMapTypeNormalVisible = false;
            }
            break;
        case "satellite":
            if (!isSatellite) {
                map.setMapTypeId("hybrid");
                isSatellite = true;
                vm.isMapTypeSatelliteVisible = false;
                vm.isMapTypeNormalVisible = true;
            } else {
                map.setMapTypeId("roadmap");
                isSatellite = false;
                vm.isMapTypeSatelliteVisible = true;
                vm.isMapTypeNormalVisible = false;
            }
            break;
        case "traffic":
            if (trafficLayer.getMap() == undefined)
                trafficLayer.setMap(map);
            else
                trafficLayer.setMap(null);
            break;
        case "transit":
            if (transitLayer.getMap() == undefined)
                transitLayer.setMap(map);
            else
                transitLayer.setMap(null);
            break;
    }
}

function setUpMakaniMarkerClickListener(marker, data, UITypes) {
    marker.addListener('click', function (evt) {
        if (data.LatLng) {
            var latLong = data.LatLng.split(",");
            global.MakaniLatitude = Number(latLong[0]);
            global.MakaniLongitude = Number(latLong[1]);
            global.MakaniRouteNumber = data.Makani;
        }

        if (data.SHAPE) {
            var latLong = data.SHAPE.split(",");
            global.MakaniLatitude = Number(latLong[1]);
            global.MakaniLongitude = Number(latLong[0]);
            global.MakaniRouteNumber = data.Makani;
        }

        if (vm.IsRoutingDivVisible) {
            var empty_search_model = "";
            if (UITypes == "SearchDetailSection" && vm.currentRouteSearchBox != "") {
                empty_search_model = vm.currentRouteSearchBox;
                vm.currentRouteSearchBox = "";
            }
            else
                empty_search_model = vm.getEmptyRouteSearchBox();
            if (empty_search_model) {
                vm.SetRoutingLatLongData(empty_search_model, [global.MakaniLongitude, global.MakaniLatitude]);
                if (global.MakaniRouteNumber)
                    vm[empty_search_model] = global.MakaniRouteNumber;

                addDraggableMarker(empty_search_model, global.MakaniLatitude, global.MakaniLongitude, true, false, true);

                vm.IsMapSingleTapInfoSectionVisible = false;
                vm.IsMapclickMakaniPlateVisible = false;
                vm.calculateRoute();
            }
            return;
        }

        vm.favorite_name_input_value = "";
        if (data.EntNameE)
            vm.favorite_name_input_value += data.EntNameE + "-";
        if (data.BldgNameEn)
            vm.favorite_name_input_value += data.BldgNameEn;
        if (!data.BldgNameEn && data.CommEn)
            vm.favorite_name_input_value += data.CommEn;



        switch (UITypes) {

            case "SearchDetailSection":
                vm.UpdateMakaniSearchDetailValues(data);
                // document.getElementById('StreetIframeMapInDetail').contentWindow.location.reload(true);
                // document.getElementById("IFrameHappiness").src = "";

                updateMarkerIcon(marker);
                break;

            case "MapLongClickBuildingInfoSection":
                vm.UpdateMapSingleTapPopUpDetailValues(data);
                // document.getElementById('streetIFrameMapTap').contentWindow.location.reload(true);
                setTimeout(function () {
                    if (document.getElementById('streetIFrameMapTap'))
                        document.getElementById('streetIFrameMapTap').src = global.hostAddress + "/Home/StreetLevelPreview";
                }, 200);

                updateMarkerIcon(marker);
                break;
        }

    });
}

function updateMarkerIcon(marker) {
    removeAllMapObjectsNotMakani();
    if (marker.customInfo == "2" || marker.customInfo == "WheelChair") {
        makaniIcon = {
            url: global.hostAddress + '/Images/MapPins/WheelEntranceClicked.png',
            //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
            //origin: new google.maps.Point(0, 0),
            //anchor: new google.maps.Point(0, global.makaniPinHeight)
        };
    } else {
        if (marker) {
            if (marker.customInfo == "LongClickPlacePin") {
                makaniIcon = {
                    url: global.hostAddress + '/Images/MapPins/pin4.png',
                    //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                    //origin: new google.maps.Point(0, 0),
                    //anchor: new google.maps.Point(0, global.makaniPinHeight)
                };
            } else {
                if (marker.customInfo == "2" || marker.customInfo == "WheelChair") {
                    makaniIcon = {
                        url: global.hostAddress + '/Images/MapPins/WheelEntranceClicked.png',
                        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                        //origin: new google.maps.Point(0, 0),
                        //anchor: new google.maps.Point(0, global.makaniPinHeight)
                    };
                } else {
                    makaniIcon = {
                        url: global.hostAddress + '/Images/MapPins/GreenEntrance_old.png',
                        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                        //origin: new google.maps.Point(0, 0),
                        //anchor: new google.maps.Point(0, global.makaniPinHeight)
                    };
                }
            }
        }
    }
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(marker.getPosition().lat(), marker.getPosition().lng()),
        map,
        icon: makaniIcon,
        customInfo: marker.customInfo
    });
    MapObject.push(marker);
    MapObjectNotMakani.push(marker);
}


//Directions
var routeInstructionsContainer, travelModeTemp;
function calculateRouteOnMap(destinations, routeMode) {



    vm.makaniLoading = true;
    global.destinations = destinations;
    removeAllRouteMapObjects();
    removeAllMapObjects();

    routeInstructionsContainer = document.getElementById('route_summary_panel_content');

    //var routeType = vm.toggle_routing_type_model == 0 ? "fastest" : "shortest";
    //var routeType = vm.toggle_routing_type_model == 0 ? "pessimistic" : "optimistic";// DrivingOptions.trafficModel
    var routeType = vm.toggle_routing_type_model == 0 ? "bestguess" : "optimistic";// DrivingOptions.trafficModel

    var provideRouteAlternatives = false;
    var drivingOptions;
    if (useLiveTrafficCondition) {
        provideRouteAlternatives = true;
        drivingOptions = {
            departureTime: new Date(Date.now()),  // for the time N milliseconds from now. //it will bill more
            trafficModel: routeType
        };
    } else {
        provideRouteAlternatives = false;
        drivingOptions = {
            departureTime: new Date(Date.now()),
            trafficModel: routeType
        }
    }

    var directionsService = new google.maps.DirectionsService();
    var directionsRenderer = new google.maps.DirectionsRenderer();

    directionsRenderer.setMap(map);
    const waypts = [];

    for (var i = 0; i < destinations.length; i++) {
        waypts.push({
            location: new google.maps.LatLng(destinations[i].split(',')[0], destinations[i].split(',')[1]),
            stopover: true,
        });
    }

    global.routing_start_point = destinations[0];
    global.routing_end_point = destinations[destinations.length - 1];
    if (destinations.length > 2) {
        if (destinations.length == 3)
            updateMapPointMarkerIcon(destinations[1].split(',')[0], destinations[1].split(',')[1], 1);
        else if (destinations.length == 4) {
            updateMapPointMarkerIcon(destinations[1].split(',')[0], destinations[1].split(',')[1], 1);
            updateMapPointMarkerIcon(destinations[2].split(',')[0], destinations[2].split(',')[1], 2);
        } else if (destinations.length == 5) {
            updateMapPointMarkerIcon(destinations[1].split(',')[0], destinations[1].split(',')[1], 1);
            updateMapPointMarkerIcon(destinations[2].split(',')[0], destinations[2].split(',')[1], 2);
            updateMapPointMarkerIcon(destinations[3].split(',')[0], destinations[3].split(',')[1], 3);
        }
    }


    //shortestRoute(new google.maps.LatLng(global.routing_start_point.split(',')[0], global.routing_start_point.split(',')[1]), new google.maps.LatLng(global.routing_end_point.split(',')[0], global.routing_end_point.split(',')[1]), map);
    //return;

    var TravelMode;
    var avoidTolls = false;
    switch (routeMode) {
        case "car":
            TravelMode = google.maps.TravelMode.DRIVING;
            travelModeTemp = TravelMode;
            break;
        case "walk":
            TravelMode = google.maps.TravelMode.WALKING;
            travelModeTemp = TravelMode;
            break;
        case "noSalik":
            avoidTolls = true;
            TravelMode = travelModeTemp;
            break;
    }

    directionsService.route(
        {
            origin: new google.maps.LatLng(global.routing_start_point.split(',')[0], global.routing_start_point.split(',')[1]),
            destination: new google.maps.LatLng(global.routing_end_point.split(',')[0], global.routing_end_point.split(',')[1]),
            waypoints: waypts,
            optimizeWaypoints: true,
            provideRouteAlternatives: provideRouteAlternatives,
            travelMode: TravelMode,
            avoidTolls: avoidTolls,
            drivingOptions: drivingOptions
        },
        (response, status) => {
            vm.makaniLoading = false;
            if (status === "OK") {

                if (routeInstructionsContainer)
                    clearRoutingDetails();

                var route = response.routes[0];
                removeAllRouteMapObjects();

                addRouteShapeToMap(route);

                addWaypointsToPanel(route.legs);

                addSummaryToPanel(route.legs);

                addManueversToPanel(route);

                if (routeInstructionsContainer)
                    $(routeInstructionsContainer).show();

                /*directionsRenderer.setDirections(response);
                const route = response.routes[0];
                const summaryPanel = document.getElementById("directions-panel");
                summaryPanel.innerHTML = "";

                // For each route, display summary information.
                for (let i = 0; i < route.legs.length; i++) {
                    const routeSegment = i + 1;
                    summaryPanel.innerHTML +=
                        "<b>Route Segment: " + routeSegment + "</b><br>";
                    summaryPanel.innerHTML += route.legs[i].start_address + " to ";
                    summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
                    summaryPanel.innerHTML +=
                        route.legs[i].distance.text + "<br><br>";
                }*/
            } else {
                window.alert("Directions request failed due to " + status);
            }
        }
    );
}

function addManueversToPanel(route) {

    var jnodeOL = $(routeInstructionsContainer).find('#nodeOL');
    if (jnodeOL)
        jnodeOL.empty();

    var nodeOL = jnodeOL[0], i, j;
    nodeOL.style.fontFamily = 'Dubai-font';
    nodeOL.style.textAlign = "left";

    // Add a marker for each maneuver
    for (i = 0; i < route.legs.length; i += 1) {
        for (j = 0; j < route.legs[i].steps.length; j += 1) {
            // Get the next maneuver.
            maneuver = route.legs[i].steps[j];

            var spanArrow = document.createElement('span'),
                spanInstruction = document.createElement('span');
            var maneuverContainerDiv = document.createElement('div');
            var arrowDiv = document.createElement('div');
            var instructionDiv = document.createElement('div');
            arrowDiv.appendChild(spanArrow);
            instructionDiv.appendChild(spanInstruction);
            maneuverContainerDiv.appendChild(arrowDiv);
            maneuverContainerDiv.appendChild(instructionDiv);

            maneuverContainerDiv.style.width = "100%";
            //maneuverContainerDiv.style.height = "65px";
            maneuverContainerDiv.style.minHeight = "45px";
            maneuverContainerDiv.style.marginBottom = "5px";

            arrowDiv.style.width = "10%";
            arrowDiv.style.align = "center";
            arrowDiv.style.cssFloat = "left";
            instructionDiv.style.width = "90%";
            instructionDiv.style.height = "100%";
            instructionDiv.style.overflowY = "hidden";
            instructionDiv.style.textAlign = "left";
            instructionDiv.style.cssFloat = "right";

            spanInstruction.style.fontSize = "0.9rem";

            spanArrow.className = 'material-icons';
            var direction = maneuver.maneuver;
            if (direction === "forward" || direction === "bearRight" || direction === "bearLight" || direction == "straight" || direction == "") {
                spanArrow.innerHTML = 'arrow_upward';
            }
            if (maneuver.direction === "left" || direction === "lightLeft" || direction == "turn-left" || direction == "turn-slight-left" || direction == "turn-sharp-left" || direction == "uturn-left" || direction == "fork-left" || direction == "roundabout-left" || direction == "ramp-left" || direction == "keep-left") {
                spanArrow.innerHTML = 'arrow_back';
            }
            if (maneuver.direction === "right" || direction === "lightRight" || direction == "turn-right" || direction == "turn-slight-right" || direction == "turn-sharp-right" || direction == "uturn-right" || direction == "fork-right" || direction == "roundabout-right" || direction == "ramp-right" || direction == "keep-right") {
                spanArrow.innerHTML = 'arrow_forward';
            }
            if (direction == "merge")
                spanArrow.innerHTML = 'merge_type';

            console.log(direction + ":" + maneuver.instructions);
            spanInstruction.innerHTML = maneuver.instructions + " (" + maneuver.distance.text + ")";

            nodeOL.appendChild(maneuverContainerDiv);
        }
    }
}

function addWaypointsToPanel(legs) {
    var nodeH3 = $("#RouteMenuHeading")[0];
    $("#RouteMenuHeading").css('font-size', '0.8rem');
    if (routeInstructionsContainer)
        clearRoutingDetails();

    //nodeH3.textContent = 'To: ' + legs[0].start_address.split('-')[0] + legs[legs.length - 1].end_address.split('-')[0];
    nodeH3.innerHTML = 'From: ' + legs[0].start_address + '<br/>';
    nodeH3.innerHTML += 'To: ' + legs[legs.length - 1].end_address;

    //setReadSpeakerLink("#readspeaker_button_directions a", "route_summary_panel_content");
}

function addSummaryToPanel(summary) {

    var summaryDiv = document.createElement('div');

    var totalDistance = 0;
    var totalDuration = 0;
    for (var i = 0; i < summary.length; i++) {
        totalDistance += summary[i].distance.value;
        totalDuration += summary[i].duration.value;
    }


    var totalDs = totalDistance / 1000;

    var spanDistance = document.createElement('div');
    var spanTravelTime = document.createElement('div');

    spanDistance.innerHTML = "<h4 style='font-size: 0.8rem'>" + "Total distance: " + " " + totalDs.toFixed(2) + " KM " + "</h4>";
    spanTravelTime.innerHTML = "<h4 style='font-size: 0.8rem'>" + "Travel time: " + " " + timeConversion(totalDuration) + "</h4>" + "<br/><br/>";

    summaryDiv.style.fontFamily = 'Dubai-font';
    summaryDiv.style.fontSize = '15px';
    summaryDiv.style.marginLeft = '1%';

    // summaryDiv.innerHTML = content;
    summaryDiv.appendChild(spanDistance);
    summaryDiv.appendChild(spanTravelTime);

    var summaryContainerDiv = $('#summaryContainerDiv');
    if (summaryContainerDiv)
        summaryContainerDiv.empty();


    if (summaryContainerDiv) {
        summaryContainerDiv.append(summaryDiv);
    }
}

function timeConversion(timediff) {
    var seconds = Math.floor(timediff % 60);
    var minutes = Math.floor((timediff / 60) % 60);
    var hours = Math.floor((timediff / 3600) % 24);
    if (hours > 0)
        time = hours + " Hr " + minutes + " Min";
    else if (minutes > 0)
        time = minutes + " Min " + seconds + " Sec"
    else if (seconds > 0)
        time = seconds + " Sec";

    return time;
}

function shortestRoute(origin, destination, map) {

    directionsService = new google.maps.DirectionsService();
    var routesResponses = [];
    //avoiding tolls
    directionsService.route({
        origin: origin,
        destination: destination,
        provideRouteAlternatives: true,
        avoidTolls: true,
        travelMode: google.maps.TravelMode.DRIVING
    }, function (response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            routesResponses.push(response);
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
    //avoiding highways
    directionsService.route({
        origin: origin,
        destination: destination,
        provideRouteAlternatives: true,
        avoidHighways: true,
        travelMode: google.maps.TravelMode.DRIVING
    }, function (response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            routesResponses.push(response);
        } else {
            window.alert('Directions request failed due to ' + status);
        }

        //Results analysis and drawing of routes
        var fastest = Number.MAX_VALUE,
            shortest = Number.MAX_VALUE;

        routesResponses.forEach(function (res) {
            res.routes.forEach(function (rou, index) {
                console.log("distance of route " + index + ": ", rou.legs[0].distance.value);
                console.log("duration of route " + index + ": ", rou.legs[0].duration.value);
                if (rou.legs[0].distance.value < shortest) shortest = rou.legs[0].distance.value;
                if (rou.legs[0].duration.value < fastest) fastest = rou.legs[0].duration.value;

            })
        })
        console.log("shortest: ", shortest);
        console.log("fastest: ", fastest);
        //painting the routes in green blue and red
        routesResponses.forEach(function (res) {
            res.routes.forEach(function (rou, index) {
                //shortest
                if (fastest != rou.legs[0].duration.value) {
                    new google.maps.DirectionsRenderer({
                        map: map,
                        directions: res,
                        routeIndex: index,
                        polylineOptions: {
                            strokeColor: rou.legs[0].duration.value == fastest ? "red" : rou.legs[0].distance.value == shortest ? "darkgreen" : "blue",
                            strokeOpacity: rou.legs[0].duration.value == fastest ? 0.8 : rou.legs[0].distance.value == shortest ? 0.9 : 0.5,
                            strokeWeight: rou.legs[0].duration.value == fastest ? 9 : rou.legs[0].distance.value == shortest ? 8 : 3,
                        }
                    });
                }
                ////fastest
                //if (fastest == rou.legs[0].duration.value) {
                //    new google.maps.DirectionsRenderer({
                //        map: map,
                //        directions: res,
                //        routeIndex: index,
                //        polylineOptions: {
                //            strokeColor: rou.legs[0].duration.value == fastest ? "red" : rou.legs[0].distance.value == shortest ? "darkgreen" : "blue",
                //            strokeOpacity: rou.legs[0].duration.value == fastest ? 0.8 : rou.legs[0].distance.value == shortest ? 0.9 : 0.5,
                //            strokeWeight: rou.legs[0].duration.value == fastest ? 9 : rou.legs[0].distance.value == shortest ? 8 : 3,
                //        }
                //    });
                //}
            });
        });
    });
    vm.makaniLoading = false;
}

function addRouteShapeToMap(route) {
    var routeStrip = [],
        routeShape = route.overview_path,
        routePolyline;

    routeShape.forEach(function (point) {
        //var parts = point.split(',');
        routeStrip.push(new google.maps.LatLng(point.lat(), point.lng()));
        calculateBounds.push(new google.maps.LatLng(point.lat(), point.lng()));
    });

    routePolyline = new google.maps.Polyline({
        path: routeStrip,
        geodesic: true,
        strokeColor: 'rgba(0, 128, 255, 0.7)',
        strokeWeight: 4
    });
    routePolyline.setMap(map);
    RouteMapObject.push(routePolyline);
    //start icon
    routeStartIcon = {
        url: global.hostAddress + '/Images/MapPins/pin2.png',
        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
        //origin: new google.maps.Point(0, 0),
        //anchor: new google.maps.Point(0, global.makaniPinHeight)
    };
    marker = new google.maps.Marker({
        position: routeStrip[0],
        map,
        icon: routeStartIcon,
        customInfo: "routeStartIcon"
    });
    MapObject.push(marker);

    //end icon
    routeEndIcon = {
        url: global.hostAddress + '/Images/MapPins/destination.png',
        //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
        //origin: new google.maps.Point(0, 0),
        //anchor: new google.maps.Point(0, global.makaniPinHeight)
    };
    marker = new google.maps.Marker({
        position: routeStrip[routeStrip.length - 1],
        map,
        icon: routeEndIcon,
        customInfo: 'routeEndIcon'
    });
    MapObject.push(marker);



    SetMapCenterForPolygons();
}

function clearRoutingDetails() {
    $(routeInstructionsContainer).find('h3').empty();
    $(routeInstructionsContainer).hide();
}

function removeAllRouteMapObjects() {
    //removeAllMapObjects();

    if (RouteMapObject) {
        for (var i = 0; i < RouteMapObject.length; i++) {
            RouteMapObject[i].setMap(null);
        }
    }


}

function removeMapPointMarker(model) {

    //removeAllMapObjects();
    //return true;
    for (var i = 0; i < MapObject.length; i++) {
        if (model == "routingsearch_model0") {
            if (MapObject[i].customInfo == "routeStartIcon")
                MapObject[i].setMap(null);
        }
        if (model == "routingsearch_model1" || model == "routingsearch_model2" || model == "routingsearch_model3") {
            if (MapObject[i].customInfo == "routeEndIcon")
                MapObject[i].setMap(null);
        }
    }
}

function removeAllRouteMapPointMarkers() {
    if (!RouteMapPointObjectGroup)
        return false;

    removeAllRouteMapObjects();
}

function updateMapPointMarker(model, lat, lng) {
    if (!RouteMapPointObjectGroup)
        return false;

    return false;

}

function updateMapPointMarkerIcon(lat, lng, dest) {
    var markerIcon = null;
    switch (dest) {
        case 1:
            //markerIcon = new H.map.Icon(global.hostAddress + '/Images/MapPins/destination1.png', { size: { w: global.makaniPinWidth, h: global.makaniPinHeight } });
            markerIcon = {
                url: global.hostAddress + '/Images/MapPins/destination1.png',
                //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                //origin: new google.maps.Point(0, 0),
                //anchor: new google.maps.Point(0, global.makaniPinHeight)
            };
            break;
        case 2:
            //markerIcon = new H.map.Icon(global.hostAddress + '/Images/MapPins/destination2.png', { size: { w: global.makaniPinWidth, h: global.makaniPinHeight } });
            markerIcon = {
                url: global.hostAddress + '/Images/MapPins/destination2.png',
                //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                //origin: new google.maps.Point(0, 0),
                //anchor: new google.maps.Point(0, global.makaniPinHeight)
            };
            break;
        case 3:
            //markerIcon = new H.map.Icon(global.hostAddress + '/Images/MapPins/destination3.png', { size: { w: global.makaniPinWidth, h: global.makaniPinHeight } });
            markerIcon = {
                url: global.hostAddress + '/Images/MapPins/destination3.png',
                //size: new google.maps.Size(global.makaniPinWidth, global.makaniPinHeight),
                //origin: new google.maps.Point(0, 0),
                //anchor: new google.maps.Point(0, global.makaniPinHeight)
            };
            break;

    }

    marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map,
        icon: markerIcon,
        customInfo: 'markerIcon' + dest
    });
    MapObject.push(marker);
    return true;
}

