var selectedDriverVMap = "";
var showAssignDialog = true;
var AssignBookDialogIsShown = false;
var AssignBookingIsInProgress = false;
var booking = null;
var landmarks = null;
var Messages = null;
var msg_item = null;
var announcement = null;
var ChangeDriverName;
var data;
var selectedItemsToMsg=[];

function allowDrop(ev) {
    ev.preventDefault();
}
var mouseX, mouseY; $(document).mousemove(function (e) { mouseX = e.pageX; mouseY = e.pageY; }).mouseover();
function drag(ev) {
    ev.dataTransfer.setData("text/plain", ev.target.id);
}

function drop(ev,currentObj) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text/plain");
  /* If you use DOM manipulation functions, their default behaviour it not to 
     copy but to alter and move elements. By appending a ".cloneNode(true)", 
     you will not move the original element, but create a copy. */

  $(currentObj).val(data);
  /*var nodeCopy = document.getElementById(data).cloneNode(true);
  nodeCopy.setAttribute("selected", "selected");
  ev.target.appendChild(nodeCopy);*/
  
  
}
Number.prototype.pad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) { s = "0" + s; }
    return s;
}

function isNumeric(value) {
    return /^\d+$/.test(value);
}


var TaxiApp = angular.module('MapviewApp', ['ngStorage', 'ngDialog', 'angularSpinner', 'angularUtils.directives.dirPagination', 'ui.bootstrap', 'angularAwesomeSlider', 'angular-growl', 'ngAnimate', 'AxelSoft','elif']);
TaxiApp.config(['growlProvider', function (growlProvider) {
    growlProvider.globalTimeToLive({ success: 1000, error: 2000, warning: 150000, info: 150000 });
}]);

TaxiApp.run(['customSelectDefaults', function (customSelectDefaults) {
    customSelectDefaults.displayText = 'الرجاء اختيار سائق ...';
}]);

TaxiApp.directive('ngRightClick', function ($parse) {
    return function (scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function (event) {
            scope.$apply(function () {
                event.preventDefault();
                fn(scope, { $event: event });
            });
        });
    };
});

TaxiApp.controller('MapviewCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'usSpinnerService', 'growl', 'DeleteLandmark',  'EditDriverInfo',
function ($scope, $http, $sessionStorage, ngDialog, usSpinnerService, growl, DeleteLandmark, EditDriverInfo) {
        $scope.loading = false;
        $scope.injectedObject = {};
    
        var TokenID = sessionStorage.TokenID;
        var orgOID = sessionStorage.ORGOID;
        var userOID = sessionStorage.UserOID;
        var roleType = sessionStorage.RoleType;
        var roleID = sessionStorage.RoleID;
        var groupOID = 0, Status = "0,1";
        var cOID, cName;
        var companyOID = sessionStorage.CompanyOID;
        $scope.logo = sessionStorage.Photo;
        $scope.DisplayName = sessionStorage.UserName;
        $scope.CompanyName = sessionStorage.value;
        var OLDpswd = sessionStorage.password;
        var cityOID = sessionStorage.CityID;
        carType = '0';
        //Check Whether user Logged in or not
    //CheckUserLogged();
        if (sessionStorage.OrderId < 2) {
            window.location.href = "../../Access.html";
        }
        $scope.logo = sessionStorage.Photo;
        var Vehiclename, vehicle, Tripid;

        if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
            loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
            GetCompanyCityOID("CompanyCity", userOID, companyOID, orgOID, groupOID);
        }
        $scope.selectCompanydetails = function (obj) {
            sessionStorage.value = obj.Value;
            sessionStorage.value = obj.Value;
            window.location.href = "MapView.html";
        }
        if (sessionStorage.RoleType != "Superadmin" && sessionStorage.AllAdmins != null) {
            $scope.AdminList = JSON.parse(sessionStorage.AllAdmins);
            $scope.firstadmin = JSON.parse(sessionStorage.selectedadmin);

        }

        $scope.User = sessionStorage.Username;
        //set cureentdate as default date in datepicker
        $scope.tdate = new Date();
        $scope.fdate = new Date();

        Localization(sessionStorage.selectedLanguage, 'mapview', $scope, sessionStorage);

        $scope.value3 = 5;

        $scope.options2 = {
            from: 1,
            to: 10,
            floor: true,
            step: 1,
            dimension: " speed",
            vertical: false,
            callback: function (value, elt) {

            }
        };
        if (sessionStorage.OrderId >2)  {
            $('.tele').show();
        }
        else {
            $('.tele').hide();
        }


        $(window).resize(function () {
            clearTimeout(window.resizedFinished);
            window.resizedFinished = setTimeout(function () {
                updateMapSize();
            }, 250);
        });


        function updateMapSize() {
            var width = $('.ol-viewport').width();//temp_map.getSize()[0] - 275;
            var height = $('.ol-viewport').height();;//temp_map.getSize()[1];
            // alert(width);
            $scope.tempMap.setSize([width, height]);
        }
        loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);


        $scope.SelectedDistrict = function (districtOid) {
            //  console.log()

            $scope.DistrictName = $.grep($scope.DistrictList, function (item) {
                return item.OID == districtOid;
            })[0].value;
            console.log($scope.DistrictListModel)
            VehicleDetailsForDashboard(OID, userOID, companyOID, orgOID, groupOID, 1);

        }
    /* --------------------------------------------   Controls  on Map  -----------------------------------*/
        $scope.hideMapPanel = function () {
            if ($("#MapPanel").css("display")=="none") {
                $("#MapPanel").show();
                           $("#Map").addClass("MapHeight");

                $("#MapPanel").addClass("MapHeightSmall");
                var scope = angular.element('[data-ng-controller="MapviewCtrl"]').scope();
                var temp_map = scope.tempMap;
                updateMapSize();

              
            } else {
                $("#MapPanel").hide();
                     $("#Map").removeClass("MapHeight");
                     $("#MapPanel").removeClass("MapHeightSmall"); var scope = angular.element('[data-ng-controller="MapviewCtrl"]').scope();
                     var temp_map = scope.tempMap;
                     updateMapSize();
            }
           

        }
        var bar = {
            showRegionsCtrl: null,
            listRegionsCtrl: null,
            listCustomRegionsCtrl: null,
            messagesCtrl: null,
            trackVehicleCtrl: null,
            bookingCtrl: null,
            bookingHistoryCtrl: null,

        
            removeRegions: function (id) {


            },
            removeRegionsList: function (id) {
                regionsList.hide();

            },
            removeCustoRegionsList: function (id) {
                CustomRegionsList.hide();

            },
          
            removeVehicleTracking: function (id) {
                this.trackVehicleCtrl.setActive(false);
                track = false;

            },
            getBookingControl: function () {
                this.bookingCtrl = new ol.control.Toggle(
            {

            });
                return this.bookingCtrl;
            },
         
            MessagesControl: function () {
                this.messagesCtrl = new ol.control.Toggle(
                    {
                        html: '<i class="fa fa-envelope"></i>',
                        className: "ol-control messages-control ol-unselectable ol-control",
                        title: "الرسائل",
                        active: false,
                        onToggle: function (active) {
                            if (active) {
                                Messages.open();
                                Messages.populate();
                            }
                            else {
                                Messages.close();
                            }
                        }
                    })
                        return this.messagesCtrl;
           },

            load: function () {
                self = this;
             
             
                this.listCustomRegionsCtrl = new ol.control.Toggle({
                       html: '<i id="listCustomRegionsCtrl" class="fa fa-map-marker toggle_control" ></i>',
                       title: "قائمة المناطق",
                       onToggle: function (active) {
                           if (active) {
                               dialog.style.display = "none";

                               CustomRegionsList.show();


                           }
                           else {
                               CustomRegionsList.hide();
                               landmarks.removeInteraction();
                               dialog.style.display = "block";

                           }

                       },
                       active: false
                   });

             
                this.showRegionsCtrl = new ol.control.Toggle({
                      html: '<i id="showRegionsCtrl" class="fa fa-globe toggle_control"></i>',
                      title: "عرض المناطق على الخارطة",
                      onToggle: function (active) {
                          self.removeNotifictions();
                          self.removeRegionsList();
                          if (active)
                              regionsList.init();
                          else
                              regionsList.clear();
                      },
                      active: false
                  });


                this.listRegionsCtrl = new ol.control.Button({
                       html: '<i id="listRegionsCtrl" class="fa fa-bars" ></i>',
                       title: "قائمة المناطق",
                       handleClick: function () {
                           self.removeNotifictions();
                          if (!regionsList.getState())
                               regionsList.init();
                           regionsList.show();
                       },
                       active: true
                   });


                this.trackVehicleCtrl = new ol.control.Toggle({
                       html: '<i id="trackVehicleCtrl" class="fa fa-taxi toggle_control" ></i>',
                       title: "متابعة المركبات",
                       onToggle: function (active) {
                           self.removeNotifictions();
                           self.removeRegionsList();
                           track = !track;
                       },
                       active: false
                   });

                var mainbar = new ol.control.Bar();
                mainbar.setPosition('bottom-left')
                mainbar.addControl(this.trackVehicleCtrl);
                mainbar.addControl(this.showRegionsCtrl);
                mainbar.addControl(this.listRegionsCtrl);
                mainbar.addControl(this.listCustomRegionsCtrl);


                return mainbar;
            }
        }
    /* --------------------------------------------  Land marks -----------------------------------*/
        landmarks = {
            draw: null,
            // add interaction  on map 
            addInteraction: function (value) {
                map.getInteractions().forEach(function (interaction) {
                    if (interaction instanceof ol.interaction.Draw) {
                        map.removeInteraction(interaction);
                    }
                });

                if (value !== 'None') {
                    var geometryFunction, maxPoints = 1;
                    if (value === 'Square') {
                        value = 'Circle';
                        geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
                    } else if (value === 'Box') {
                        value = 'LineString';
                        maxPoints = 2;
                        geometryFunction = function (coordinates, geometry) {
                            if (!geometry) {
                                geometry = new ol.geom.Polygon(null);
                            }
                            var start = coordinates[0];
                            var end = coordinates[1];
                            geometry.setCoordinates([
                              [start, [start[0], end[1]], end, [end[0], start[1]], start]
                            ]);
                            return geometry;
                        };
                    }
                    this.draw = new ol.interaction.Draw({
                        source: interactionLayer.getSource(),
                        type: /** @type {ol.geom.GeometryType} */ (value),
                        geometryFunction: geometryFunction,
                        maxPoints: maxPoints
                    });
                    this.draw.on('drawstart', function () {
                        interactionLayer.getSource().clear();
                    });
                    map.addInteraction(this.draw);
                }
            },
            //  rremove interaction on map 
            removeInteraction: function () {
                interactionLayer.getSource().clear();
                map.removeInteraction(this.draw);

            },
            //  return coordinates on map 

            getGeometry: function () {
                var g = null;
                interactionLayer.getSource().getFeatures().forEach(function (feature) {
                    g = feature.getGeometry().getCoordinates();
                });
                return g;
            },

            //  delete landmark on map 
            deleteLandmark: function (id, landMarkBlock) {
                var self = this;
                $.ajax({
                    url: WebsiteServiceUrl + '/DeleteCompanyLandmarkOnMap/' + id,
                    data: {

                    },
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    async: false,
                    success: function (result) {
                        var result = JSON.parse(result.DeleteCompanyLandmarkOnMapResult);
                        if (result) {
                            self.remove(id);
                            landMarkBlock.closest(".CustomRegion_item").remove();
                           // alert('deleted');
                        } else
                            alert("not deleted");

                    }
                });
            },
            //  creatte landmark on map 
            createLandmark: function (name, g) {
                var self = this;
                var id = null;
                if (g && name) {
                    pt = g;
                    long = pt[0];
                    lat = pt[1];
                    $.ajax({
                        url: WebsiteServiceUrl + '/AddCompanyLandmarksOnMap/' + name + '/' + lat + '/' + long + '/' + sessionStorage.CompanyOID + '/' + sessionStorage.ORGOID,
                        data: {

                        },
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",
                        async: false,
                        success: function (result) {
                            var result = JSON.parse(result.AddCompanyLandmarksOnMapResult);
                            if (result != 0) {
                                self.add(name, long, lat, result);
                                id = result;
                                CustomRegionsList.populate(name, id, g[0], g[1]);
                                return id;
                            }

                        }
                    });

                }

            },
            remove: function (id) {
                var f = LandmarksLayer.getSource().getFeatureById(id);
                if (f) {
                    LandmarksLayer.getSource().removeFeature(f);
                }
            },
            add: function (name, long, lat, id) {

                var myLatLng = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');
                var iconFeature = new ol.Feature({
                    geometry: new ol.geom.Point(myLatLng)

                });
                iconFeature.setId(id);

                iconStyle = [
                    new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 5,
                            fill: new ol.style.Fill({
                                color: 'rgba(230,120,30,0.7)'
                            })
                        })
                    }),
                 new ol.style.Style({
                     text: new ol.style.Text({
                         font: ' 10px JF Flat Regular,sans-serif',
                         text: name,
                         textAlign: 'center',
                         textBaseline: 'top',
                         fill: new ol.style.Fill({ color: 'black' }),
                         stroke: new ol.style.Stroke({ color: 'white', width: 1 }),
                         offsetX: 0,
                         offsetY: 10,
                         rotation: 0,
                         maxreso: 1

                     })
                 })];

                iconFeature.setStyle(iconStyle);

                LandmarksLayer.getSource().addFeature(iconFeature);


            },

            load: function (name, long, lat) {
                this.add("عمر", 35.204269, 31.89804)

            },
            get: function () {
                // return $.Deferred().resolve(localStorage.getItem('comments'));

                return $.ajax({
                    url: WebsiteServiceUrl + '/GetCompanyLandmarksForMap/' + sessionStorage.CompanyOID + '/' + sessionStorage.ORGOID,
                    cache: false
                });

            },
            poll: function () {
                var self = this;
                self.get().done(function (data) {
                    var landmarks = JSON.parse(data.GetCompanyLandmarksForMapResult);
                    for (l = 0; l < landmarks.length; l++) {
                        self.add(landmarks[l].LandmarkName, parseFloat(landmarks[l].Long), parseFloat(landmarks[l].Lat), landmarks[l].LandmarkOID);
                    }

                });
            },
            init: function (UL, interval) {

                this.poll(UL);

            }
        };
    /* --------------------------------------------  CustomRegionsList -----------------------------------*/

        var CustomRegionsList = {

            populate: function (name, id, Long, Lat) {

                var div = $("#CustomRegions_list");
                var CustomRegion = document.createElement("div");
                var dialog = $("#dialog");
                var dialogBTN = $("#dialogBTN");
                var dialogInput = $("#dialogInput");
                var successMSG = $("#successMSG");
                var deleteItem = document.createElement("div");
                deleteItem.innerHTML = "<i class='fa fa-minus-circle' style='color:red;    font-size: 15px;' aria-hidden='true'></i>";
                var txt = document.createTextNode(name);
                var CustomRegion_name = document.createElement("h7");
                CustomRegion_name.appendChild(txt);
                var CustomRegion_name_item = document.createElement("h7");
                CustomRegion.className = "CustomRegion_item";
                CustomRegion_name_item.appendChild(CustomRegion_name);
                CustomRegion_name_item.appendChild(deleteItem);

                CustomRegion_name_item.className = "CustomRegion_Name";
                deleteItem.onclick = function () {
                    $scope.DeleteLandmarkItem(id, $(this));
                };
                CustomRegion.appendChild(CustomRegion_name_item);

                CustomRegion.onclick = function () {

                    map.getView().setCenter(ol.proj.transform([parseFloat(Long), parseFloat(Lat)], 'EPSG:4326', 'EPSG:3857'))
                    map.getView().setZoom(18);

                }

                function fadeIn(item) {
                    item.style.opacity = 0;


                    var tick = function () {
                        item.style.opacity = +item.style.opacity + 0.01;


                        if (+item.style.opacity < 1) {
                            (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
                        }
                    };

                    tick();
                }

                fadeIn(CustomRegion);
                div.append(CustomRegion);

            },
            show: function () {
                var self = this;
                if (!$('#CustomRegions_list').is(":visible")) {
                    $("#CustomRegions_list").toggle();
                }
            },
            hide: function () {
                if ($('#CustomRegions_list').is(":visible")) {
                    $("#CustomRegions_list").toggle();
                }
            },
            init: function () {
                var self = this;
                $.ajax({
                    url: WebsiteServiceUrl + '/GetCompanyLandmarksForMap/' + "1" + '/' + sessionStorage.ORGOID,
                    data: {

                    },
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    async: false,

                    success: function (result) {
                        var landmarks = JSON.parse(result.GetCompanyLandmarksForMapResult);
                       // console.log(landmarks)
                        for (var r = 0; r < landmarks.length; r++) {
                            self.populate(landmarks[r].LandmarkName, landmarks[r].LandmarkOID, landmarks[r].Long, landmarks[r].Lat);

                        }


                        //  $('#CustomRegions_list').empty();


                    }
                });




            }
        };
        

    /* --------------------------------------------  regionsList -----------------------------------*/

        var regionsList = {
            state: false,
            locationUpdateTime: {},
            getOsmRegion: function (lng, lat, obj) {
                var self = this;
                $.ajax({
                    type: "GET",
                    url: 'http://nominatim.openstreetmap.org/reverse',
                    data: {
                        format: 'json',
                        lat: lat,
                        lon: lng,
                        "accept-language": 'ar',
                        limit: 1
                    },
                    dataType: "json",
                    success: function (r) {
                        HebrewChars = new RegExp("[\u0590-\u05FF]+$")
                        self.locationUpdateTime[obj].address =


                              ((r.address.hamlet && !HebrewChars.test(r.address.hamlet)) ? r.address.hamlet : (
                                 ((r.address.village && !HebrewChars.test(r.address.village)) ? r.address.village :
                                     ((r.address.town && !HebrewChars.test(r.address.town)) ? r.address.town :
                                      ((r.address.city && !HebrewChars.test(r.address.city)) ? r.address.city : r.address.state_district)
                              ))
                              )
                          );
                        self.locationUpdateTime[obj].address = ((!self.locationUpdateTime[obj].address || self.locationUpdateTime[obj].address == '') ?
                         ((r.address.road && !HebrewChars.test(r.address.road)) ? r.address.road : 'خارجي') : self.locationUpdateTime[obj].address
                         );
                    },
                    error: function (r, text, exception) {
                        $('#' + obj).html('خارجي');
                    }
                });

            },
            getRegionAtCoordinate: function (long, lat, obj) {


                var point = ol.proj.transform([parseFloat(long), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')
                var features = regionsLayerForPosition.getSource().getFeaturesAtCoordinate(point);
                var region = null;
                var min = 0;
                if (features.length > 0) {
                    for (var f = 0; f < features.length; f++) {
                         var area_m = 0;
                        var geometry = features[f].getGeometry();
                        if (geometry.getType() == 'Circle') {
                            area_m = geometry.getRadius() * geometry.getRadius()/4*22/7
                        }else

                         area_m = features[f].getGeometry().getArea();
                        if (min == 0) {
                            min = area_m;
                            region = features[f];
                        } else if (min > area_m) {
                            min = area_m;
                            region = features[f];
                        }
                    }
                    return region.get('name');
                }
                
                //alert(obj);
                var t = null;
                if (this.locationUpdateTime[obj] == null) {
                    this.locationUpdateTime[obj] = { id: obj, time: 0 };
                }

                t = this.locationUpdateTime[obj].time;
                n = new Date();
                if ((n - t) > 30000) {
                    this.getOsmRegion(long, lat, obj);
                    this.locationUpdateTime[obj] = { id: obj, time: new Date(), address: this.locationUpdateTime[obj].address };
                }
             //   console.log(this.locationUpdateTime[obj])
                return this.locationUpdateTime[obj].address;



            },
            getState: function () {

                return this.state;
            },
            getCount: function (arr) {
                var a = [], b = [], prev;

                arr.sort();
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i] !== prev) {
                        a.push(arr[i]);
                        b.push(1);
                    } else {
                        b[b.length - 1]++;
                    }
                    prev = arr[i];
                }

                return [a, b];
            },

            getCheckedStyle: function (ocuurance) {
                var _eStrokeStyle = new ol.style.Stroke({
                    color: 'rgba(255,0,0,1.0)',
                    width: 1
                });

                var opicity = ocuurance * 0.1 * 2;
                var _eFillStyle = new ol.style.Fill({
                    color: 'rgba(255,0,0,' + opicity + ')'
                });

                var _eTextStyle = new ol.style.Text({
                    font: 'bold 13px JF Flat Regular,sans-serif',
                    // text: (rg != null ? rg.Name : ''),

                    rotation: 0,
                    offsetY: 20,
                    stroke: new ol.style.Stroke({
                        color: '#ffc83e',
                        width: 6
                    })
                })

                return new ol.style.Style({
                    stroke: _eStrokeStyle,
                    fill: _eFillStyle,
                    text: _eTextStyle
                });
            },
            getUncheckedStyle: function (rg) {
                var _eStrokeStyle = new ol.style.Stroke({
                    color: 'rgba(255,0,0,1.0)',
                    width: 1
                });
                var _eFillStyle = new ol.style.Fill({
                    color: 'rgba(0,255,0,0.1)'
                });

                var _eTextStyle = new ol.style.Text({
                    font: 'bold 13px JF Flat Regular,sans-serif',
                    text: (rg != null ? rg.Name : ''),
                    rotation: 0,
                    offsetY: 20,
                    stroke: new ol.style.Stroke({
                        color: '#ffc83e',
                        width: 6
                    })
                })

                return new ol.style.Style({
                    stroke: _eStrokeStyle,
                    fill: _eFillStyle,
                    text: _eTextStyle
                });
            },
            populate: function (q) {
                for (i = 0; i < q.length; i++) {



                    var div = $("#Regions_list");
                    var region = document.createElement("div");
                    region.className = "Region_item";


                    var region_name = document.createTextNode(q[i].get('name'));
                    var region_name_item = document.createElement("h7");
                    $(region).attr({
                        'id': q[i].get('id')

                    });

                    region_name_item.appendChild(region_name);
                    region_name_item.className = "Region_Name";

                    region.onclick = function () {
                        var f = regionsLayer.getSource().getFeatureById(this.id);
                        map.getView().fit(f.getGeometry(), map.getSize());
                        $("#Regions_list").toggle();

                    };

                    region.appendChild(region_name_item);



                    function fadeIn(item) {
                        item.style.opacity = 0;


                        var tick = function () {
                            item.style.opacity = +item.style.opacity + 0.01;


                            if (+item.style.opacity < 1) {
                                (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
                            }
                        };

                        tick();
                    }

                    fadeIn(region);

                    div.append(region);
                }
            },
            show: function () {
                if (!$('#Regions_list').is(":visible")) {
                    $("#Regions_list").toggle();
                }
            },
            hide: function () {
                if ($('#Regions_list').is(":visible")) {
                    $("#Regions_list").toggle();
                }
            },
            clear: function () {
                regionsLayer.getSource().clear();
                this.state = false;
            },
            loadregionsLayerForPosition: function () {

                var self = this;

            

                $.ajax({
                    url: ComonServiceUrl + "GetDriverRegionsByCompany/" + sessionStorage.CompanyOID,
                    data: {

                    },
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    async: false,

                    success: function (result) {
                        var regions = JSON.parse(result.GetDriverRegionsByCompanyResult);
                        for (var r = 0; r < regions.length; r++) {
                            //  alert(regions[r].Name);
                            if (regions[r].GeoLocation) {
                                var format = new ol.format.WKT();

                                var g = format.readGeometry(regions[r].GeoLocation, {

                                    dataProjection: 'EPSG:4326',
                                    featureProjection: 'EPSG:3857'
                                });
                                var f1 = new ol.Feature({
                                    name: regions[r].Name,
                                    id: regions[r].OID,
                                    geometry: g
                                });
                                f1.setId(regions[r].OID);
                                // f1.setStyle(self.getUncheckedStyle(regions[r]));
                                regionsLayerForPosition.getSource().addFeature(f1);

                            }
                        }


                    }
                });

                $.ajax({
                    url: WebsiteServiceUrl + "GetCompanyRegionDetails/" + sessionStorage.CompanyOID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    async: false,
                    success: function (result) {

                        var data = JSON.parse(result.GetCompanyRegionDetailsResult);
                        for (var d = 0; d < data.length; d++) {
                            var circle = new ol.geom.Circle([data[d].CenterLong, data[d].CenterLat], data[d].Radius / 100000);
                            circle = circle.clone().transform('EPSG:4326', 'EPSG:3857');;

                            var features;
                            features = (new ol.Feature({
                                name: data[d].RegionName,
                                id: 'O'+d, geometry: circle
                            }));


                            var f1 = new ol.Feature({
                                name: data[d].RegionName,
                                id: 'O' + d,
                                geometry: circle
                            });
                            f1.setId('O' + d);
                            var _strokeStyle = new ol.style.Stroke({
                                color: 'rgba(233,147,10,1.0)',
                                width: 1
                            });
                            var _fillStyle = new ol.style.Fill({
                                color: 'rgba(238,235,228,0.8)'
                            });
                            var rStyle = new ol.style.Style({
                                stroke: _strokeStyle,
                                fill: _fillStyle
                            });
                             f1.setStyle(rStyle);
                            companyRegionLayer.getSource().addFeature(f1);
                            regionsLayerForPosition.getSource().addFeature(f1);
                        }


                    }
                });


               
            }
                    ,
            init: function (regions) {
                var self = this;
                $.ajax({
                    url: ComonServiceUrl + "GetDriverRegionsByCompany/" + sessionStorage.CompanyOID,
                    data: {

                    },
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    async: false,

                    success: function (result) {
                        regionsLayer.getSource().clear();
                        var regions = JSON.parse(result.GetDriverRegionsByCompanyResult);
                        for (var r = 0; r < regions.length; r++) {
                            //  alert(regions[r].Name);
                            if (regions[r].GeoLocation) {
                                var format = new ol.format.WKT();

                                var g = format.readGeometry(regions[r].GeoLocation, {

                                    dataProjection: 'EPSG:4326',
                                    featureProjection: 'EPSG:3857'
                                });
                                var f1 = new ol.Feature({
                                    name: regions[r].Name,
                                    id: regions[r].OID,
                                    geometry: g
                                });
                                f1.setId(regions[r].OID);
                                // f1.setStyle(self.getUncheckedStyle(regions[r]));
                                regionsLayer.getSource().addFeature(f1);
                                bar.showRegionsCtrl.setActive(true);

                            }
                        }


                        $('#Regions_list').empty();
                        self.populate(regionsLayer.getSource().getFeatures());
                        self.refresh();
                        self.state = true;


                    }
                });

            },
            refresh: function (selected) {
                if (!bar.showRegionsCtrl.getActive())
                    return;
                var regions = regionsLayer.getSource().getFeatures();

                for (var r = 0; r < regions.length; r++) {
                    if ($.inArray(regions[r].getId(), selected) > -1) {
                        var occurances = selected.filter(function (val) {
                            return val === regions[r].getId();
                        }).length;
                        regions[r].setStyle(this.getCheckedStyle(occurances));
                    }
                    else {
                        regions[r].setStyle(this.getUncheckedStyle(regions[r]));
                    }

                }
            }
        }

       
   
  
    /* --------------------------------------------   Messages   -----------------------------------*/

        Messages = {  
            driversList: null,
            listDrivers: function () {
                var drivers = [];
                for (var d = 0; d < $scope.dashboardList.length; d++) {
                    drivers[d] = { label: $scope.dashboardList[d].DriverName, value: $scope.dashboardList[d].DriverOID, 'imei': $scope.dashboardList[d].IMEIno };
                }
                return drivers;
            },
            update: function () {
                this.driversList = $("#DriverMEssage").mSelectDBox().set("list",this.listDrivers())
            },
            init: function () {


                this.driversList =  $("#DriverMEssage").mSelectDBox({
                    "list": this.listDrivers(),
                    "multiple": true,
                    "autoComplete": true,
                    "name": "a",
                    "onselect": function (msdbContext, event) {

                        var isSelected = arguments[1].listItem.selected;

                        var driverId = arguments[1].listItem.value;
                        //console.log(arguments[1].listItem);
                        if (!isSelected) {
                            $.each(selectedItemsToMsg, function (key, value) {

                                if (value == driverId) {

                                    selectedItemsToMsg.splice(key, 1);
                                 //   arguments[1].listItem.selected = false;


                                }

                            });

                        }
                    }
                });
              
            },
            selectAll: function (v) {
                if (v)
                    this.driversList.selectAll();
                else {
                    this.driversList.deselectAll();
                    selectedItemsToMsg = [];
                }
            },
            deselectall: function () {
              
                this.driversList.deselectAll();
                selectedItemsToMsg = [];

            },
            sendMessage: function (driverid, imei, mesg) {
                var self = this;
                var message = {};
                message.companyOID = sessionStorage.CompanyOID;
                message.messageToSend = mesg;
                message.driversList = [{ driverOID: driverid, IMEINo: imei }];

                var annObj = {
                    "annObj": message
                };

              
                $scope.loading = true;
                $.ajax({
                    type: "POST",
                    url: WebsiteServiceUrl + "SendAnnouncementToVehicleList",
                    data: JSON.stringify(annObj),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (result) {
                        if (result.SendAnnouncementToVehicleListResult == 1) {
                            $('#messagebody').val('');
                            self.selectAll(false);
                            se

                        } else {
                            alert('لم يتم ارسال الرد');
                        }

                        $scope.loading = false;

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $scope.loading = false;
                        alert("Status: " + textStatus); alert("Error: " + errorThrown);
                    }
                });
            },
            setMessage: function (msg) {
                $('#messagebody').val(msg);
            },
            addToMessage: function (msg) {
                var text = $('#messagebody').val();
                text = text + ' ' + msg;
                $('#messagebody').val(text);
            },
            CustomSelect: function () {
              
               

                $("#DriverMEssage").mSelectDBox('select', {

                    "value": selectedItemsToMsg
                   
                });


            },
            clearMessage: function (msg) {
               
                $('#messagebody').val("");
            },
            send: function (obj) {
                var self = this;
                var drivers = [];
                var selectedKeys = Messages.driversList.getSelectedItems();
                if (selectedKeys) {
                    for (var s = 0; s < selectedKeys.length; s++) {
                        drivers[s] = { driverOID: selectedKeys[s].value, IMEINo: selectedKeys[s].imei };

                    }
                }
                $('#DriverMEssage :selected').each(function (i, selected) {
                });



                var message = {};
                message.companyOID = sessionStorage.CompanyOID;
                message.messageToSend = $('#messagebody').val();
                message.driversList = drivers;

                var annObj = {
                    "annObj": message
                };

                if (message.messageToSend == null || message.messageToSend == '' || drivers.length == 0) {
                    alert('الرجاء ادخال نص التعميم واختيار السائقين');
                    return;
                }
                $scope.loading = true;
                $.ajax({
                    type: "POST",
                    url: WebsiteServiceUrl + "SendAnnouncementToVehicleList",
                    data: JSON.stringify(annObj),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (result) {
                        if (result.SendAnnouncementToVehicleListResult == 1) {
                            $('#messagebody').val('');
                            self.driversList.deselectAll();
                            selectedItemsToMsg=[]

                        } else {
                            alert('فشل ارسال التعميم');
                        }



                        $scope.loading = false;
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $scope.loading = false;
                        alert("Status: " + textStatus); alert("Error: " + errorThrown);
                    }
                });
                $('.sol-option').each(function () {
                    $('input').attr('checked', false);
                });
                $('.sol-current-selection').empty();
            },
            open: function () {
               
                if ($(".messages_sidebar").is(":visible"))
                    return;
               
                this.clearMessage();
                //booking.open();
                bar.messagesCtrl.setActive(true);
                this.init();
                $(".messages_sidebar").toggle(500, function () {
                    if ($(this).is(':visible')) {
                        $(this).css('display', 'inline-block');

                        var scope = angular.element('[data-ng-controller="MapviewCtrl"]').scope();
                        var temp_map = scope.tempMap;
                        updateMapSize();

                    } else {

                        var scope = angular.element('[data-ng-controller="MapviewCtrl"]').scope();
                        var temp_map = scope.tempMap;
                        updateMapSize();

                    }

                });
              
            },
            close: function () {
                if (!$(".messages_sidebar").is(":visible"))
                    return;
                bar.messagesCtrl.setActive(false);

                var scope = angular.element('[data-ng-controller="MapviewCtrl"]').scope();
                var temp_map = scope.tempMap;




                $(".messages_sidebar").toggle(500, function () {
                    if ($(this).is(':visible'))
                        $(this).css('display', 'inline-block');
                    updateMapSize();

                });
            },
            populate: function () {
                var ul;
                var companyID = sessionStorage.CompanyOID;
                $.ajax({
                    type: "GET",
                    url: ManagementServiceUrl + "GetLastHourBookingWithoutCars/" + userOID + "/" + TokenID,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (data) {
                        $scope.BookingsWithoutCars=[];
                        $scope.BookingsWithoutCars = JSON.parse(data.GetLastHourBookingWithoutCarsResult);
                       // console.log($scope.BookingsWithoutCars)
                   

                        for (var i = 0; i < $scope.BookingsWithoutCars.length; i++) {
                            var date = $scope.BookingsWithoutCars[i].RequestTime;
                            date = date.split("T");
                            $scope.BookingsWithoutCars[i].FormatedDate = date[1].slice(0, 5)
                        }

                      
                


                       
                    },

                });
              
              
            },
          
        }
       
        $scope.SendMsgToCustomer = {
            Wait: function (c_no) {
                var wait_sms = "نعتذر لعدم توفر مركبات حاليا، سيتم اشعاركم حال توفر مركبة في منطقتك";

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "SendSMS/" + c_no + "/" + wait_sms,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        var data = JSON.parse(result.SendSMSResult);
                        $scope.loading = false;
                        alert("لقد تم ارسال الرسالة بنجاح")
                        $scope.$apply();


                    },
                    error: function () {
                        $scope.loading = false;
                        $scope.BookingList = [];
                        $scope.$apply();
                    }
                });


            },
            Available: function (c_no) {
                var Available_sms = "توجد مركبة متوفر في منطقتك، يرجى اعادة المحاولة. نتمنى لك رحلة ممتعة";

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "SendSMS/" + c_no + "/" + Available_sms,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        var data = JSON.parse(result.SendSMSResult);
                        $scope.loading = false;
                        alert("لقد تم ارسال الرسالة بنجاح")
                        $scope.$apply();


                    },
                    error: function () {
                        $scope.loading = false;
                        $scope.BookingList = [];
                        $scope.$apply();
                    }
                });


            }

        }
      
        CustomRegionsList.init();

    /* --------------------------------------------   tripHistoryDetails   -----------------------------------*/

        var tripHistoryDetails = {
            tripDetailsControl: null,
            animating: false,
            routeCoords: null,
            slider: null,
            timer: null,
            index: 0,
            feature: null,
            initSlider: function (routeCoords) {
                this.index = 0;
                this.routeCoords = routeCoords;
                this.slider.noUiSlider.updateOptions({
                    range: {
                        'min': 0,
                        'max': routeCoords.length
                    }
                });
                this.slider.noUiSlider.set(0);

            },
            animate: function () {
                var slef = this;
                if (tripHistoryDetails.index >= tripHistoryDetails.routeCoords.length) {
                    tripHistoryDetails.stopAnimation(true);

                    return;
                }
                this.setCurrent(null);
                tripHistoryDetails.index++;
                var zoom = map.getView().getZoom();
                var delay = zoom * zoom * 4;
                this.timer = setTimeout(function () {
                    tripHistoryDetails.animate();
                    $('.start_icon').css('color', "#ffc83e");
                }, delay);
            },
            startAnimation: function () {
                var self = this;
                if (!this.animating) {

                    self.animate();
                    /*
                    this.timer = setTimeOut(function () {
                        self.animate();
                        $('.start_icon').css('color', "#ffc83e");
                    }, 100);
                    */
                    this.animating = true;

                }

            },
            stopAnimation: function (ended) {

                if (this.animating) {
                    clearInterval(this.timer);
                    this.animating = false;
                    $('.start_icon').css('color', "green");
                }


            },
            show: function () {
                map.addControl(tripDetailsControl);
                $('.start_icon').css('color', "green");

            },
            hide: function () {
                map.removeControl(tripDetailsControl);
                this.stopAnimation();
                if (liveTrackingLayer.getSource().getFeatureById(206))
                    liveTrackingLayer.getSource().removeFeature(liveTrackingLayer.getSource().getFeatureById(206));
            },
            setDetails: function (trip) {
                $('#info_driver_name_id').html(trip.Driver);
                $('#info_trip_time_id').html(trip.Duration + ' ساعة');
                $('#info_date_id').html(trip.Date);
                $('#info_distance_id').html(trip.Distance + ' كم');
                //  $('#info_car_id').html('<i class="fa fa-car" aria-hidden="true"></i>' + trip.CarType);
                $('#info_movement_start_id').html(trip.MovementStart);
                $('#info_movement_end_id').html(trip.MovementEnd);
                $('#info_speed_max_id').html(trip.SpeedMAX + '  كم/س');
                $('#info_speed_avg_id').html(trip.SpeedAVG + '  كم/س');

            },
            changeIndex: function (newindex) {
                if (liveTrackingLayer.getSource().getFeatureById(206))
                    liveTrackingLayer.getSource().removeFeature(liveTrackingLayer.getSource().getFeatureById(206));

                if (newindex) {
                    this.index = Math.round(newindex);
                    this.setCurrent();
                }
            },
            getOrdinates: function (ar) {
                var points = [];
                for (var j = 0; j < ar.length; j++) {
                    var pt = ol.proj.transform([ar[j].Longitude, ar[j].Latitude], 'EPSG:4326', 'EPSG:3857');
                    points.push(pt);
                }
                return points;
            },
            setCurrent: function () {

                tripHistoryDetails.slider.noUiSlider.set(tripHistoryDetails.index);
                if (liveTrackingLayer.getSource().getFeatureById(206))
                    liveTrackingLayer.getSource().removeFeature(liveTrackingLayer.getSource().getFeatureById(206));
                var currentPoint = ol.proj.transform([tripHistoryDetails.routeCoords[tripHistoryDetails.index].Longitude, tripHistoryDetails.routeCoords[tripHistoryDetails.index].Latitude], 'EPSG:4326', 'EPSG:3857');
                if (tripHistoryDetails.index > 0) {
                    if (historyPathLayer.getSource().getFeatureById(205))
                        historyPathLayer.getSource().removeFeature(historyPathLayer.getSource().getFeatureById(205));

                    var ar2 = this.getOrdinates(tripHistoryDetails.routeCoords.slice(0, tripHistoryDetails.index + 1));
                    var lineStyle = new ol.style.Style({
                        stroke: new ol.style.Stroke(({
                            width: 10
                        }))
                    });
                    var lineString = new ol.geom.LineString(ar2);
                    // transform to EPSG:3857
                    var feature = new ol.Feature({
                        geometry: lineString,
                        name: 'Line'
                    });
                    var style = new ol.style.Style({//  My style definition 
                        fill: new ol.style.Fill({
                            color: 'red'
                        }),
                        stroke: new ol.style.Stroke({
                            color: 'red',
                            width: 3

                        })
                    });
                    feature.setStyle(style);
                    feature.setId(205);
                    historyPathLayer.getSource().addFeature(feature);

                }
                if (track)
                    map.getView().setCenter(ol.proj.transform([tripHistoryDetails.routeCoords[tripHistoryDetails.index].Longitude, tripHistoryDetails.routeCoords[tripHistoryDetails.index].Latitude], 'EPSG:4326', 'EPSG:3857'));

                this.feature = new ol.Feature({
                    id: 206,
                    geometry: new ol.geom.Point(currentPoint),
                    name: '',
                });
                this.feature.setId(206);
              
                var style = new ol.style.Style({
                    image: new ol.style.Icon({
                        //anchor: [12, 0.5],
                        //size: [1000, 1000],
                        //scale: 0.037,
                        rotation: parseInt(tripHistoryDetails.routeCoords[tripHistoryDetails.index].Direction) * Math.PI / 180,
                        //anchorXUnits: 'pixel',
                        //anchorYUnits: 'fraction',
                        src: '../../assets/SVGHelper/GetSVG.aspx?c=' + color
                    })
                });
                this.feature.setStyle(style);

                /*var style = new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: 7,
                        snapToPixel: false,
                        fill: new ol.style.Fill({ color: 'black' }),
                        stroke: new ol.style.Stroke({
                            color: 'white', width: 2
                        })
                    })
                });*/
                liveTrackingLayer.getSource().addFeature(this.feature);
                var d = new Date(Date.parse(tripHistoryDetails.routeCoords[tripHistoryDetails.index].DateTime));
                var currentTime = d.getHours().pad() + ':' + d.getMinutes().pad();

                $('#info_time_id').html(currentTime);
                $('#info_speed_id').html(tripHistoryDetails.routeCoords[tripHistoryDetails.index].Speed);
                var connectSlider = document.getElementById('slider_connect');



            },
            init: function () {
                /* --------------------     InfoList      ------------------------------------*/
                var Info_Div = document.createElement("div");
                Info_Div.className = "Info_Div";
                var Info_Element = document.createElement("div");
                Info_Element.className = "Info_Element";
                Info_Div.appendChild(Info_Element);

                // driver name
                var info_driver_name = document.createElement("h4");
                Info_Element.appendChild(info_driver_name);
                info_driver_name.className = "info_driver_name";
                info_driver_name.id = "info_driver_name_id";

                // car date
                var datelbl = document.createElement("h6");
                datelbl.innerHTML = '<i class="icon-calendar" aria-hidden="true"></i>' + "التاريخ : ";
                var info_date = document.createElement("h6");
                Info_Element.appendChild(datelbl);
                datelbl.style.display = "inline-block";
                datelbl.style.width = "25%";
                Info_Element.appendChild(info_date);
                info_date.className = "info_date";
                info_date.id = "info_date_id";


                // trip time
                var info_trip_time = document.createElement("h6");
                var timelbl = document.createElement("h6");
                timelbl.innerHTML = '<i class="fa fa-clock-o" aria-hidden="true"></i>' + "المدة : ";
                timelbl.style.display = "inline-block";
                Info_Element.appendChild(timelbl);
                timelbl.style.width = "25%";

                Info_Element.appendChild(info_trip_time);
                info_trip_time.className = "info_trip_time";
                info_trip_time.id = "info_trip_time_id";



                // car distance        
                var info_distance = document.createElement("h6");
                var distancelbl = document.createElement("h6");
                distancelbl.innerHTML = '<i class="fa fa-tachometer" aria-hidden="true"></i>' + "المسافة : ";
                Info_Element.appendChild(distancelbl);
                Info_Element.appendChild(info_distance);
                info_distance.className = "info_distance";
                info_distance.id = "info_distance_id";
                distancelbl.style.display = "inline-block";
                distancelbl.style.width = "77%";
                distancelbl.style.textAlign = "left";



                // movement
                txt = document.createTextNode("الحركة");
                var info_movement = document.createElement("h6");
                info_movement.appendChild(txt);
                Info_Element.appendChild(info_movement);
                info_movement.className = "info_movement";


                // start movement

                var div = document.createElement("div");
                div.className = "start_div";

                txt = document.createTextNode("بداية");
                var info_movement_startLBL = document.createElement("h6");
                info_movement_startLBL.appendChild(txt);
                Info_Element.appendChild(info_movement_startLBL);
                info_movement_startLBL.className = "info_movement_startLBL";


                var info_movement_start = document.createElement("h5");
                Info_Element.appendChild(info_movement_start);
                info_movement_start.className = "info_movement_start";
                info_movement_start.id = "info_movement_start_id";



                div.appendChild(info_movement_startLBL);
                div.appendChild(info_movement_start);

                Info_Element.appendChild(div);
                //end movement

                div = document.createElement("div");
                div.className = "end_div";

                txt = document.createTextNode("نهاية");
                var info_movement_endLBL = document.createElement("h6");
                info_movement_endLBL.appendChild(txt);
                Info_Element.appendChild(info_movement_endLBL);
                info_movement_endLBL.className = "info_movement_endLBL";

                var info_movement_end = document.createElement("h5");
                Info_Element.appendChild(info_movement_end);
                info_movement_end.className = "info_movement_end";
                info_movement_end.id = "info_movement_end_id";

                div.appendChild(info_movement_endLBL);
                div.appendChild(info_movement_end);

                Info_Element.appendChild(div);


                // Speed

                txt = document.createTextNode("السرعة");
                var info_speed = document.createElement("h6");
                info_speed.appendChild(txt);
                Info_Element.appendChild(info_speed);
                info_speed.className = "info_speed";

                //avg  Speed

                var div = document.createElement("div");
                div.className = "avg_div";

                txt = document.createTextNode("معدل");
                var info_speed_avgLBL = document.createElement("h6");
                info_speed_avgLBL.appendChild(txt);
                Info_Element.appendChild(info_speed_avgLBL);
                info_speed_avgLBL.className = "info_speed_avgLBL";


                var info_speed_avg = document.createElement("h5");
                Info_Element.appendChild(info_speed_avg);
                info_speed_avg.className = "info_speed_avg";
                info_speed_avg.id = "info_speed_avg_id";

                div.appendChild(info_speed_avgLBL);
                div.appendChild(info_speed_avg);

                Info_Element.appendChild(div);

                //max Speed    
                div = document.createElement("div");
                div.className = "max_div";

                txt = document.createTextNode("القصوى");
                var info_speed_maxLBL = document.createElement("h6");
                info_speed_maxLBL.appendChild(txt);
                Info_Element.appendChild(info_speed_maxLBL);
                info_speed_maxLBL.className = "info_speed_maxLBL";

                var info_speed_max = document.createElement("h5");
                Info_Element.appendChild(info_speed_max);
                info_speed_max.className = "info_speed_max";
                info_speed_max.id = "info_speed_max_id";

                div.appendChild(info_speed_maxLBL);
                div.appendChild(info_speed_max);
                Info_Element.appendChild(div);

                //seperator 
                var divSep = document.createElement("div");
                divSep.className = "divSep";
                Info_Element.appendChild(divSep);

                var PanelDiv = document.createElement("div");
                PanelDiv.className = "PanelDiv";

                // Speed    
                div = document.createElement("div");
                div.className = "speed_div";

                txt = document.createTextNode("السرعة");
                var info_speedLBL = document.createElement("h6");
                info_speedLBL.appendChild(txt);
                PanelDiv.appendChild(info_speedLBL);
                info_speedLBL.className = "info_speedLBL";

                var info_speed = document.createElement("h5");
                PanelDiv.appendChild(info_speed);
                info_speed.className = "info_speed";
                info_speed.id = 'info_speed_id';
                div.appendChild(info_speedLBL);

                div.appendChild(info_speed);
                PanelDiv.appendChild(div);

                // time    
                div = document.createElement("div");
                div.className = "time_div";

                txt = document.createTextNode("الساعة");
                var info_timeLBL = document.createElement("h6");
                info_timeLBL.appendChild(txt);
                PanelDiv.appendChild(info_timeLBL);
                info_timeLBL.className = "info_timeLBL";

                var info_time = document.createElement("h5");
                PanelDiv.appendChild(info_time);
                info_time.className = "info_time";
                info_time.id = 'info_time_id';
                div.appendChild(info_timeLBL);
                div.appendChild(info_time);
                PanelDiv.appendChild(div);

                // Start and Stop panel   
                var SSPanel = document.createElement("div");
                SSPanel.className = "SSPanel";

                var start_icon = document.createElement("div");
                start_icon.addEventListener('click', function () {
                    tripHistoryDetails.startAnimation();
                });
                start_icon.innerHTML = '<i class="fa fa-play-circle" aria-hidden="true"></i>';
                SSPanel.appendChild(start_icon);
                start_icon.className = "start_icon";
                start_icon.style.cursor = "pointer";

                var stop_icon = document.createElement("div");
                stop_icon.addEventListener('click', function () {
                    tripHistoryDetails.stopAnimation();
                });
                stop_icon.innerHTML = '<i class="fa fa-stop-circle" aria-hidden="true"></i>';
                SSPanel.appendChild(stop_icon);
                stop_icon.className = "stop_icon";
                stop_icon.style.cursor = "pointer";

                var slider = document.createElement("div");
                slider.id = "slider_connect";

                noUiSlider.create(slider, {
                    start: 0,
                    connect: [true, false],
                    range: {
                        'min': 0,
                        'max': 100
                    }
                });
                slider.noUiSlider.on('slide', function () {
                    if (tripHistoryDetails.slider)
                        tripHistoryDetails.changeIndex(tripHistoryDetails.slider.noUiSlider.get())
                });
                slider.noUiSlider.on('start', function () {
                    if (tripHistoryDetails.slider)
                        tripHistoryDetails.stopAnimation(tripHistoryDetails.slider.noUiSlider.get());
                });

                this.slider = slider;
                SSPanel.appendChild(slider);

                PanelDiv.appendChild(SSPanel);
                Info_Element.appendChild(PanelDiv);

                tripDetailsControl = new ol.control.Control({
                    element: Info_Div
                });

            }
        }

        function moreThanThirtyMin(dateString) {
            if (dateString.length > 0) {
                if (dateString.indexOf("h") !== -1)
                    return true;
                if (dateString.indexOf("d") !== -1)
                    return true;
                if (dateString.indexOf("m") !== -1) {
                    var str = dateString.split(" ");
                    var num = str[0];
                    if (num.length > 0) {
                        if (num > 30) {
                            return true;

                        }
                        else {
                            return false;;
                        }
                    }
                }

            }
            else {
                return true;
            }
            return false;
        }
        function ResizeMap() {
            setTimeout(function () {
                map.setVisibility(true);
                map.update();


            }, 3000);
        }
        var interactionLayer = null;
        var LandmarksLayer = null;
        var liveTrackingLayer = null;
        var MissedCustomerLocationLayer = null;
        var tripHistoryLayer = null;
        var historyPathLayer = null;
        var regionsLayer = null;
        var ovMagnify = null;
        var track = false;
        function clearLayers() {
            liveTrackingLayer.getSource().clear();
            MissedCustomerLocationLayer.getSource().clear();
            tripHistoryLayer.getSource().clear();
            historyPathLayer.getSource().clear();
            $(".checkTripId").prop('checked', false);

        }


        function loadRegionDetails() {
            $.ajax({
                url: WebsiteServiceUrl + "GetCompanyRegionDetails/" + sessionStorage.CompanyOID,
                type: "GET",
                contentType: "application/javascript",
                dataType: "jsonp",
                async: false,
                success: function (result) {

                    var data = JSON.parse(result.GetCompanyRegionDetailsResult);
                    var circle = new ol.geom.Circle([data.CenterLong, data.CenterLat], data.Radius / 100000);
                    circle = circle.clone().transform('EPSG:4326', 'EPSG:3857');;

                    var features = [];
                    features.push(new ol.Feature({ geometry: circle }));
                    companyRegionLayer.getSource().addFeatures(features);


                    map.getView().fit(companyRegionLayer.getSource().getExtent(), map.getSize());
                }
            });
        }

        function ViewLivemap(lat, lng) {
            if (!lat)
                lat = 31.89804;
            if (!lng)
                lng = 35.204269;
            liveTrackingLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            MissedCustomerLocationLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });           
            tripHistoryLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            historyPathLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            regionsLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            companyRegionLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            LandmarksLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            interactionLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            regionsLayerForPosition = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });




            //  var element = document.getElementById('mapdiv');
            var art_map = new ol.layer.Tile({
                extent: [2799561.5, 2511529.72, 4107682.73, 3952777.48],
                preload: Infinity,
                visible: true,
                source: new ol.source.TileWMS(({
                    url: 'http://13.94.213.151:8080/geoserver/gwc/service/wms',
                    params: {
                        'LAYERS': 'artmaps:map_ar', 'TILED': true, 'VERSION': '1.3.0',
                        'FORMAT': 'image/png', 'SRS': 'EPSG:900913'
                    },
                    serverType: 'geoserver'
                }))
            });

            var raster_map = new ol.layer.Tile({
                extent: [2799561.5, 2511529.72, 4107682.73, 3952777.48],
                preload: Infinity,
                visible: true,
                source: new ol.source.TileWMS(({
                    url: 'http://13.94.213.151:8080/geoserver/gwc/service/wms',
                    title: 'OSM',
                    params: {
                        'LAYERS': 'art_hyprid_2', 'TILED': true, 'VERSION': '1.1.0',
                        'FORMAT': 'image/png', 'SRS': 'EPSG:900913'
                    },
                    serverType: 'geoserver'
                }))
            });

            globalMap = map;




     

            map = new ol.Map({
                logo: {
                    src: 'assets/img/logo.png',
                    href: 'http://www.arttech.ps'
                },
                controls: ol.control.defaults({ attribution: true }).extend([
                       new ol.control.FullScreen()
                ]),
                interactions: ol.interaction.defaults({ doubleClickZoom: false }),

                layers: [
                 /* new ol.layer.Group({
                      title: 'Raster',
                      baseLayer: true,
                      combine: true,
                      visible: false,
                      preview: "assets/img/mosaic-image.gif",

                      layers: [raster_map]
                  }),*/
                  new ol.layer.Group({
                      title: 'OSM',
                      baseLayer: true,
                      combine: true,
                      visible: true,
                      //  preview: "assets/img/vector-image.jpg",
                      layers: [new ol.layer.Tile({
                          source: new ol.source.OSM()
                      })]
                  }),
                     /* new ol.layer.Group({
                          title: 'Vector',
                          baseLayer: true,
                          combine: true,
                          visible: false,
                          preview: "assets/img/vector-image.jpg",
                          layers: [art_map]
                      }),*/
                      tripHistoryLayer, historyPathLayer, regionsLayer, companyRegionLayer, liveTrackingLayer, LandmarksLayer, interactionLayer, MissedCustomerLocationLayer
                ],
                target: 'dvmap',
                pixelRatio: 1,
                view: new ol.View({
                    center: ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857'),
                    zoom: 8,
                    minZoom: 9,
                    maxZoom: 18
                })
            });

            landmarks.init();
            regionsList.loadregionsLayerForPosition();


            ovMagnify = new ol.Overlay.Magnify(
			{
			    id: '11206',
			    layers: [new ol.layer.Tile({
			        source: new ol.source.OSM()
			    }), liveTrackingLayer],
			    zoomOffset: 4
			});
            ovMagnify.setActive(false);
            map.addOverlay(ovMagnify);
            map.getViewport().addEventListener('contextmenu', function (evt) {

                evt.preventDefault();
                pixel = [evt.offsetX, evt.offsetY];
                var feature = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
                    return feature;
                }, null, function (layer) {
                    return layer == liveTrackingLayer;
                });
                if (feature) {
                
                    if (selectedItemsToMsg.length > 0) {

                        var userDeleted = false;

                        $.each(selectedItemsToMsg, function (key, value) {
                            
                            if (value == feature.T.driverOID) {

                                selectedItemsToMsg.splice(key,1);
                                userDeleted = true;
                               

                            }
                            
                        });

                        if (!userDeleted) {
                            selectedItemsToMsg.push(feature.T.driverOID);
                           
                        }

                    } else {
                        selectedItemsToMsg.push(feature.T.driverOID)
                    }
                    

                   
                    Messages.CustomSelect();
                  
                } else {
                  
                }

            });

            $scope.tempMap = map;
            // Main control bar

            
            var zoomslider = new ol.control.ZoomSlider();
            map.addControl(zoomslider);
            var layerSwitcher = new ol.control.LayerSwitcherImage();
            map.addControl(layerSwitcher);


            map.addControl(bar.load());

            map.addControl(bar.MessagesControl());


            map.addControl(bar.getBookingControl());


            tripHistoryDetails.init();
       

            /* --------------------      Custom Regions (Landmarks)     ------------------------------------*/

            var div = document.createElement("CustomRegions");
            div.className = "CustomRegions_list";
            div.id = "CustomRegions_list";
            var CustomRegionTitle = document.createElement("div");
            CustomRegionTitle.style.display = "flex";

            var addItem = document.createElement("div");
            addItem.id = "addItem";
            addItem.innerHTML = "<i class='fa fa-plus-square' style='font-size: 24px;color: #555;' aria-hidden='true'></i>";

            var Filter = document.createElement("div");
            Filter.style.cssText = 'margin-top:0;width:100%;margin: 3px;border-radius: 0;display: inline;';
            var FilterInput = document.createElement("input");
            FilterInput.style.cssText = 'width: 96%;padding: 0;margin: 0;height: 20px;color: #fff;width: 100%;';
            Filter.appendChild(FilterInput);
            FilterInput.className = "form-control";
            Filter.className = "RegionFilter SerachBox input-group";
            CustomRegionTitle.appendChild(addItem);
            CustomRegionTitle.appendChild(Filter);
            FilterInput.oninput = function () {


                var listItems = $("#CustomRegions_list .CustomRegion_item");

                listItems.each(function () {

                    var currentListItem = $(this);
                    var text = currentListItem.find(".CustomRegion_Name h7").html();

                    if (text.indexOf(FilterInput.value) >= 0) {

                        currentListItem.show();
                    } else {
                        currentListItem.hide();
                    }

                });

            }
            var dialog;
            dialog = document.createElement("div");
            dialog.style.display = "none";
            dialog.id = "dialog";
            dialog.className = "dialog";

            var dialogInput = document.createElement("input");
            dialogInput.id = "dialogInput";

            var dialogBTN = document.createElement("button");
            dialogBTN.innerHTML = "اضافة";
            dialogBTN.id = "dialogBTN";

            dialog.appendChild(dialogInput);
            dialog.appendChild(dialogBTN);

            var successMSG = document.createElement("div");
            successMSG.style.display = "none";
            successMSG.id = "successMSG";

            div.appendChild(CustomRegionTitle);
            div.appendChild(dialog);
            div.appendChild(successMSG);

            var CustomRegionCtl = new ol.control.Control({
                element: div
            });
            map.addControl(CustomRegionCtl);
            addItem.onclick = function () {

                if (dialog.style.display == "block") {
                    dialog.style.display = "none";
                    landmarks.removeInteraction();
                }
                else {
                    dialog.style.display = "block";
                    landmarks.addInteraction('Point');
                }


            };

            dialogBTN.onclick = function () {
                if (dialogInput.value == "") {
                    if (landmarks.getGeometry() == null) {
                        successMSG.innerHTML = "اختر نقطة اولا";
                        successMSG.style.display = "block";
                        successMSG.style.color = "red";


                    }
                    else {
                        successMSG.innerHTML = "اكتب اسم المنطقة";
                        successMSG.style.display = "block";
                        successMSG.style.color = "red";


                    }

                } else {
                    if (landmarks.getGeometry() == null) {
                        successMSG.innerHTML = "اختر نقطة اولا";
                        successMSG.style.display = "block";
                        successMSG.style.color = "red";

                        landmarks.addInteraction('Point');

                    } else {
                        if (landmarks.getGeometry()) {
                            coord = landmarks.getGeometry();
                            var coord = ol.proj.transform([coord[0], coord[1]], 'EPSG:3857', 'EPSG:4326');

                            var id = landmarks.createLandmark(dialogInput.value, coord);
                            // CustomRegionsList.populate(dialogInput.value, id, coord[0], coord[1]);
                        }
                        successMSG.innerHTML = "تم الاضافة بنجاح";
                        dialogInput.value = "";
                        dialog.style.display = "none";
                        successMSG.style.display = "block";
                        successMSG.style.color = "green";

                        landmarks.removeInteraction();
                        setTimeout(function () {
                            $('#successMSG').fadeOut('fast');
                        }, 2000); // <-- time in milliseconds
                    }

                }




            };




            /* --------------------      Regions      ------------------------------------*/

            var div = document.createElement("Regions");
            div.className = "Regions_list";
            div.id = "Regions_list";

            var RegionCtl = new ol.control.Control({
                element: div
            });
            map.addControl(RegionCtl);

            /* --------------------      Search      ------------------------------------*/

            var div = document.createElement("search");
            div.className = "Search_Div";
            div.id = "Search_Div";
            div.innerHTML = "<div class='SerachBox input-group' style='margin-top: 0;border-radius: 4px;background: #555;width: 100%;'><input type='text' id='map_search' class='form-control' style='color: #fff;width: 100%;border:0' /> </div>";
            var SearchCtl = new ol.control.Control({
                element: div
            });
            map.addControl(SearchCtl);

            var options = {
                url: function (phrase) {
                    return WebsiteServiceUrl + "GetLandmarksAutoCompleteResult/" + sessionStorage.ORGOID + "/" + sessionStorage.CompanyOID + "/" + sessionStorage.CityID + "/" + phrase + "/0";
                },
                getValue: function (element) {
                    return element.PlaceName;
                },
                highlightPhrase: false,
                listLocation: "GetLandmarksAutoCompleteResultResult",


                theme: "plate",
                list: {
                    maxNumberOfElements: 10,
                    match: {
                        enabled: false
                    },
                    onChooseEvent: function () {
                        var feature = LandmarksLayer.getSource().getFeatureById('LMHL');
                        if (feature)
                            LandmarksLayer.getSource().removeFeature(feature);

                        var selectedItemValue = $("#map_search").getSelectedItemData();
                        if (selectedItemValue.Lng && selectedItemValue.Lng != 0 && selectedItemValue.Lat && selectedItemValue.Lat != 0) {
                            map.getView().setCenter(ol.proj.transform([parseFloat(selectedItemValue.Lng), parseFloat(selectedItemValue.Lat)], 'EPSG:4326', 'EPSG:3857'));
                            map.getView().setZoom(17);


                            var myLatLng = ol.proj.transform([parseFloat(selectedItemValue.Lng), parseFloat(selectedItemValue.Lat)], 'EPSG:4326', 'EPSG:3857');
                            var iconFeature = new ol.Feature({
                                geometry: new ol.geom.Point(myLatLng)

                            });
                            iconFeature.setId("LMHL");

                            iconStyle = [
                                new ol.style.Style({
                                    image: new ol.style.Circle({
                                        radius: 10,
                                        fill: new ol.style.Fill({
                                            color: 'rgba(108,211,294,0.7)'
                                        })
                                    })
                                })
                             ];

                            iconFeature.setStyle(iconStyle);

                            LandmarksLayer.getSource().addFeature(iconFeature);


                        }
                    },
                }

            };

            $("#map_search").easyAutocomplete(options);




        }

        ViewLivemap(sessionStorage.Latvalue, sessionStorage.Lngvalue);


        if (sessionStorage.length == (undefined || 0)) {
            window.parent.location.href = "../../Index.html";
        }
        else {
            function openDialog(text) {
                var dialog = ngDialog.open({
                    template:
                        '<p>' + text + '</p>' +
                        '<div class="ngdialog-buttons"><button type="button" class="ngdialog-button ngdialog-button-Success" ng-click="closeThisDialog(1)">Ok</button></div>',
                    plain: true
                });
                dialog.closePromise.then(function (data) {
                    console.log('ngDialog closed' + (data.value === 1 ? ' using the button' : '') + ' and notified by promise: ' + data.id);


                });
            }




            $scope.PeriodValues = [
               { 'id': 1, 'label': 'اخر ساعة' },
               { 'id': 2, 'label': 'اخر ساعتين' },
               { 'id': 3, 'label': 'اليوم' },
            ];


            $scope.Role = sessionStorage.RoleType;
            $scope.RoleID = sessionStorage.RoleID;


            checkUserLogin(userOID, TokenID);

            map.on('click', function (evt) {
                if ($('#Notificcation_Div').is(":visible")) {
                    $('#Notificcation_Div').toggle();
                }
                if ($('#Regions_list').is(":visible")) {
                    $('#Regions_list').toggle();
                }


            });

            map.on('dblclick', function (evt) {
                var coordinate = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
                if (coordinate && coordinate.length) {
                    Messages.open();
                    Messages.addToMessage("POINT(" + (Math.round(coordinate[0] * 1000000) / 1000000) + ',' + (Math.round(coordinate[1] * 1000000) / 1000000) + ")");
                }

            });

            map.on('moveend', function (evt) {
                varbbx = map.getView().calculateExtent(map.getSize());
                if (map.getView().getZoom() > 14)
                    LandmarksLayer.setVisible(true);
                else
                    LandmarksLayer.setVisible(false);
            });


            var movingmarkers = [];
            var idlemarkers = [];
            var overspeedmarkers = [];
            var stoppedmarkers = [];
            var marker = [];
            var latlngobj = [];
            var triplatlngobj = [];

            var hismovinglist = [];
            var hisoverspeedlist = [];
            var hisstoppedlist = [];
            var hismarker = [];

            var hismovingmarkers = [];

            var hisoverspeedmarkers = [];
            var hisstoppedmarkers = [];

            var MapArray = [];
            var checkArray = [];
            var path = [];
            var movinglist = [];
            var idlelist = [];
            var GeoRegion;
            var overspeedlist = [];
            var stoppedlist = [];
            $scope.nearvehiclelist = [];
            var SelectedLat;
            var SelectedLong;
            var line, interval, googlemap, openmap, str, map, startmarker, endmarker, selectedchkID, historymap, location, triphistorymap;
            $scope.selectedKms = 50;
            var livemarker = [];
            var newArray = [];
            var livegmap;
            var liveomap, datetime;
            var mapflag = "open", status = "0,1";
            var dashbdlst;
            $scope.OnVehicleList = [];
            $scope.OffVehicleList = [];
            $scope.IdleVehicleList = [];
            $scope.OutOffNWVehicleList = [];
            $scope.TowedVehicleList = [];
            $scope.dashboardList = [];
            var OID = "0";
            var TokenID = sessionStorage.TokenID;
            var orgOID = sessionStorage.ORGOID;
            var userOID = sessionStorage.UserOID;
            var roleType = sessionStorage.RoleType;
            var roleID = sessionStorage.RoleID;
            var groupOID = 0;
            var loadonce = true;
            var companyOID = sessionStorage.CompanyOID;
            $scope.logo = sessionStorage.Photo;
            $scope.DisplayName = sessionStorage.UserName;
            var OLDpswd = sessionStorage.password
            var currentMap = 1;
            $scope.searchName = "All Vehicles";



            if (sessionStorage.selectedLanguage == "ar-AE") {
                $scope.searchName = 'جميع المركبات';
            }
            else if (sessionStorage.selectedLanguage == "en-US") {
                $scope.searchName = 'All Vehicles';
            }

            var checkstatus = 0;
            function setAllMap(map) {
                for (var i = 0; i < livemarker.length; i++) {
                    livemarker[i].setMap(map);
                }
            }
            var newarrays = [];
            $scope.selectType = function (st) {
                carType = st == '' ? '0' : st;
                VehicleDetailsForDashboard(OID, userOID, companyOID, orgOID, groupOID, 1);
            }
            var selectedVehicles = sessionStorage.getItem("SelectedVehicles");
            if (selectedVehicles && selectedVehicles != 'undefined') {
                newArray = JSON.parse(selectedVehicles);
            }

            $scope.getGridList = function (status) {
                $scope.nearvehiclelist = [];
                newarrays = [];
                $('.chkselectall').prop('checked', false);
                $('.AllVehicle').prop('checked', false);
                
                switch (status) {
                    case "0,1":
                        $scope.dashboardList = $scope.All;
                        $scope.searchName = "All Vehicles";
                        checkstatus = 0;

                        break;
                    case "0,0":
                        $scope.dashboardList = $scope.Absent;
                        $scope.searchName = "Absent";
                        checkstatus = 6;

                        break;
                    case "1,0":
                        $scope.dashboardList = $scope.Available;
                        $scope.searchName = "Available";
                        checkstatus = 1;

                        break;
                    case "1,1":
                        $scope.dashboardList = $scope.Busy;
                        $scope.searchName = "Busy ";
                        checkstatus = 2;

                        break;
                    case "2,0":
                        $scope.dashboardList = $scope.Break;
                        $scope.searchName = "Break ";
                        checkstatus = 3;

                        break;
                    case "3,1":
                        $scope.dashboardList = $scope.Accept;
                        $scope.searchName = "Accept ";
                        checkstatus = 4;

                        break;
                    case "4,0":
                        $scope.dashboardList = $scope.Assigned;
                        $scope.searchName = "Assigned";
                        checkstatus = 5;

                        break;
                    case "5,0":
                        $scope.dashboardList = $scope.OutOfNetwork;
                        $scope.searchName = "Out Of Network";
                        checkstatus = 7;

                        break;
                    default:

                }

                Messages.update();
                angular.forEach(newArray, function (value, key) {
                    var check = document.getElementById("chk" + value.VehicleOID);
                    if (check)
                        check.Checked = true;
                    opensteetMarker(value, true);
                });
                $scope.$apply();

            }
            $scope.Available = [];
            $scope.Busy = [];
            $scope.Assigned = [];
            $scope.Break = [];
            //var Disconnect = [];
            $scope.Absent = [];
            $scope.Accept = [];
            $scope.All = [];
            $scope.OutOfNetwork = [];
            var allist = [];
            var refresh = 0;
            var color, datetime;
            var carpath = "M162 1077 c8 -5 3 -7 -14 -3 -62 14 -77 -74 -70 -408 l5 -238 -22 7 c-27 8 -29 -20 -2 -35 18 -9 19 -19 15 -115 -5 -115 5 -153 47 -192 65 -58 264 -58 327 0 48 44 55 73 49 189 -5 100 -4 109 14 118 27 15 26 43 -2 35 -20 -7 -21 -7 -13 227 7 252 -2 359 -36 401 -17 21 -25 22 -164 23 -90 0 -141 -3 -134 -9z m-15 -119 c-1 -51 2 -104 5 -119 7 -25 9 -25 73 -18 35 3 91 4 122 0 l58 -6 3 -142 c2 -137 2 -142 -19 -154 -33 -17 -160 -14 -197 5 -31 16 -32 19 -32 82 0 36 -3 63 -8 61 -4 -3 -8 21 -8 54 -1 32 -4 73 -6 89 -3 17 -6 40 -7 53 -2 21 -3 21 -10 2 -5 -11 -4 -28 1 -39 7 -12 7 -21 0 -25 -7 -4 -11 -76 -10 -201 0 -185 1 -192 14 -140 7 30 14 71 15 90 2 34 2 34 6 6 6 -42 -27 -194 -43 -200 -10 -4 -14 3 -14 19 0 15 -7 26 -20 30 -11 3 -20 11 -20 16 0 6 8 5 21 -1 l20 -11 -3 291 c-1 198 1 293 8 298 6 4 16 17 23 30 22 41 29 23 28 -70z m307 66 c6 -10 16 -22 21 -26 6 -5 9 -113 8 -298 -3 -287 -2 -290 17 -280 26 14 26 -1 0 -18 -11 -7 -20 -22 -20 -34 0 -19 -2 -20 -14 -8 -17 19 -46 143 -45 190 0 22 6 6 15 -45 20 -112 34 -116 28 -9 -3 49 -5 153 -5 232 0 132 -8 174 -23 120 -9 -36 -7 -50 7 -42 9 6 9 5 0 -7 -7 -8 -14 -44 -16 -79 -2 -36 -3 24 -3 132 1 192 5 217 30 172z";
            $scope.lastUpdate = sessionStorage.getItem("lastUpdate");
            if ($scope.lastUpdate && $scope.lastUpdate!='undefined')
                $scope.lastUpdate = JSON.parse($scope.lastUpdate);
            else
                $scope.lastUpdate = [];

            var countdown = 0;

            function secondsToString(seconds) {
                var numyears =Math.round( Math.floor(seconds / 31536000));
                var numdays = Math.round(Math.floor((seconds % 31536000) / 86400));
                var numhours = Math.round(Math.floor(((seconds % 31536000) % 86400) / 3600));
                var numminutes = Math.round(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60));
                var numseconds = Math.round((((seconds % 31536000) % 86400) % 3600) % 60);
                var d = '';
                d = numyears? numyears + " سنة ":
                       
                numdays?numdays + " يوم ":
                numhours ? numhours + " ساعة " :
                numminutes ? numminutes + " دقيقة " : numseconds? numseconds + " ثانية":'';

                return d;

            }

            function VehicleDetailsForDashboard(OID, UserOID, companyId, OrgOID, groupOID, refresh) {
                if (sessionStorage.OrderId > 2) {


                    if ($scope.DistrictListModel == undefined) {

                        ShowDistrict = 0
                    } else {

                        ShowDistrict = $scope.DistrictListModel;
                    }



                } else {
                    ShowDistrict = sessionStorage.DistrictOID;

                }
                countdown += 1;
                $.ajax({
                    url: ManagementServiceUrl + "GetCustomerAppVehicles/" + "0" + "/" + ShowDistrict + "/" + carType + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID,
                    data: {

                    },
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    async: false,

                    success: function (result) {
                        $scope.Available = [];
                        $scope.Busy = [];
                        $scope.Assigned = [];
                        $scope.Break = [];
                        //var Disconnect = [];
                        $scope.Absent = [];
                        $scope.Accept = [];
                        $scope.All = [];
                        $scope.OutOfNetwork = [];
                        var List = result.GetCustomerAppVehiclesResult;
                        List = List.split("~");

                        var dashlist = JSON.parse(List[1])
                  
                        MapArray = [];
                        regions = [];
                        if (dashlist.length != 0) {



                            for (var i = 0; i < dashlist.length; i++) {
                                regions.push(dashlist[i].TripDestination_RegionId);
                                var datetimeStr = dashlist[i].LocationDateTime;

                               //console.log(new Date)

                                var DateTimeDiff = DateDiff(datetimeStr, List[0])

                                dashlist[i].interval = DateTimeDiff;
                                if (dashlist[i].ApplicationStatus == 1) {
                                    if (dashlist[i].Speed == 0 && ($scope.lastUpdate[i] == 'undefined' || $scope.lastUpdate[i] == null)) {
                                        $scope.lastUpdate[i] = new Date();;
                                    }
                                    else if (dashlist[i].Speed > 0) {
                                        $scope.lastUpdate[i] = null;
                                        dashlist[i].StoppingDuration = null;
                                    }

                                    if ($scope.lastUpdate[i]) {
                                        dashlist[i].StoppingDuration = secondsToString((new Date() - Date.parse($scope.lastUpdate[i])) / 1000);
                                    }
                                } else {
                                    dashlist[i].StoppingDuration = null;
                                }
                                sessionStorage.setItem("lastUpdate", JSON.stringify($scope.lastUpdate));

                                //dashlist[i] = lastUpdate[i].StoppingDuration;
                                dashlist[i].Location = regionsList.getRegionAtCoordinate(dashlist[i].Long, dashlist[i].Lat, dashlist[i].DriverOID, dashlist[i].LastLocationUpdate);;

                                /*  if (dashlist[i].ApplicationStatus == 0) {
                                      dashlist[i].color = "orange";
                                      dashlist[i].Order = 5;
  
                                      $scope.Available.push(dashlist[i]);
                                      $scope.All.push(dashlist[i]);
                                  }
                                  else*/ if (dashlist[i].ApplicationStatus == 2) {
                                    dashlist[i].color = "black";
                                    dashlist[i].Order = 9;

                                    $scope.Absent.push(dashlist[i]);
                                    $scope.All.push(dashlist[i]);
                                }
                                else if (dashlist[i].ApplicationStatus == 4) {
                                    dashlist[i].color = "gray";
                                    dashlist[i].Order = 10;

                                    $scope.Absent.push(dashlist[i]);
                                    $scope.All.push(dashlist[i]);
                                }
                                else if (dashlist[i].ApplicationStatus == 1 || dashlist[i].ApplicationStatus == 0) {
                                    if (moreThanThirtyMin(DateTimeDiff)) {
                                        if ((dashlist[i].DriverStatus == "0" && dashlist[i].IsBooked == "0")) {
                                            dashlist[i].color = "black";
                                            dashlist[i].Order = 9;

                                            $scope.Absent.push(dashlist[i]);
                                        }
                                        else {
                                            dashlist[i].DriverStatus = "5";
                                            dashlist[i].IsBooked = "0";
                                            dashlist[i].color = "grey";
                                            dashlist[i].Order = 10;

                                            $scope.OutOfNetwork.push(dashlist[i]);

                                        }
                                        $scope.All.push(dashlist[i]);
                                    }

                                    else if (dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "0") {



                                        dashlist[i].color = "green";
                                        dashlist[i].Order = 1;

                                        $scope.Available.push(dashlist[i]);
                                        $scope.All.push(dashlist[i]);
                                    }
                                    else if ((dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "1")) {

                                        dashlist[i].color = "red";
                                        dashlist[i].Order = 4;

                                        $scope.Busy.push(dashlist[i]);
                                     //   $scope.Available.push(dashlist[i]);
                                        $scope.All.push(dashlist[i]);

                                    }
                                    else if (dashlist[i].DriverStatus == "4" && dashlist[i].IsBooked == "0") {
                                        dashlist[i].color = "blue";
                                        dashlist[i].Order = 2;

                                        $scope.Assigned.push(dashlist[i]);
                                     //   $scope.Available.push(dashlist[i]);
                                        $scope.All.push(dashlist[i]);
                                    }
                                    else if (dashlist[i].DriverStatus == "2" && dashlist[i].IsBooked == "0") {
                                        dashlist[i].color = "skyblue";
                                        dashlist[i].Order = 5;

                                        $scope.Break.push(dashlist[i]);
                                        $scope.All.push(dashlist[i]);
                                    }
                                    else if ((dashlist[i].DriverStatus == "0" && dashlist[i].IsBooked == "0")
                                          || (dashlist[i].DriverStatus == '0' && dashlist[i].IsBooked == '1')) {
                                        dashlist[i].color = "black";
                                        dashlist[i].Order = 9;

                                        $scope.Absent.push(dashlist[i]);
                                        $scope.All.push(dashlist[i]);
                                    }
                                    else if (dashlist[i].DriverStatus == "3" && dashlist[i].IsBooked == "1") {
                                        dashlist[i].color = "purple";
                                        dashlist[i].Order = 3;

                                        $scope.Accept.push(dashlist[i]);
                                        //$scope.Available.push(dashlist[i]);
                                        $scope.All.push(dashlist[i]);

                                    }
                                }


                            }
                            regionsList.refresh(regions);
                        }
                        if (countdown == 1) {
                            $scope.dashboardList = $scope.All;
                            if (sessionStorage.viewmap != undefined) {
                                alert(sessionStorage.viewmap);
                                dashbdlst = JSON.parse(sessionStorage.viewmap);
                                for (var k = 0; k < dashlist.length; k++) {
                                    if (dashlist[k].DriverOID == dashbdlst.DriverOID) {
                                        newArray.push(dashlist[k]);
                                        MapArray.push(dashlist[k]);
                                    }
                                }
                                if (newArray.length != 0) {
                                    opensteetMarker(newArray, true);

                                    for (var k = 0; k < dashlist.length; k++) { //omar


                                        if (dashlist[k].DriverOID == newArray[0].DriverOID) {

                                            dashlist[k].isChecked = true;
                                        }
                                        else {
                                            dashlist[k].isChecked = false;
                                        }
                                    }
                                }

                                $scope.nearvehiclelist = [];
                                selectedLatlng(dashbdlst.Lat, dashbdlst.Long);

                            }
                        }
                        else {
                            switch (checkstatus) {
                                case 0:
                                    $scope.dashboardList = $scope.All;
                                    
                                    break;
                                case 1:
                                    $scope.dashboardList = $scope.Available;
                                    break;
                                case 2:
                                    $scope.dashboardList = $scope.Busy;
                                    break;
                                case 3:
                                    $scope.dashboardList = $scope.Break;
                                    break;
                                case 4:
                                    $scope.dashboardList = $scope.Accept;
                                    break;
                                case 5:
                                    $scope.dashboardList = $scope.Assigned;
                                    break;
                                case 6:
                                    $scope.dashboardList = $scope.Absent;
                                    break;
                                case 7:
                                    $scope.dashboardList = $scope.OutOfNetwork;
                                    break;

                                default:
                            }
                            if ($scope.dashboardList.length != 0) {
                                if (countdown == 1) {
                                    $scope.sortType = 'RegistrationNo'; // set the default sort type
                                    $scope.sortReverse = false;  // set the default sort order
                                }
                                allist = [];
                                for (var k = 0; k < $scope.dashboardList.length; k++) {
                                    for (var j = 0; j < newArray.length; j++) {
                                        if ((newArray[j].DriverOID) == ($scope.dashboardList[k].DriverOID)) {
                                            $scope.dashboardList[k].isChecked = true;
                                            allist.push($scope.dashboardList[k]);
                                        }

                                    }
                                }
                                opensteetMarker(allist, false);

                            }


                        }
                        //Pagination  
                        $scope.nearest = "No Vehicles Found";
                        $scope.currentPage = 1;
                        $scope.pageSize = 10;
                        $scope.$apply();



                    }
                });
            };



            VehicleDetailsForDashboard(OID, userOID, companyOID, orgOID, groupOID, refresh);

            window.setInterval(function () {
                if (currentMap == 1) {
                    VehicleDetailsForDashboard(OID, userOID, companyOID, orgOID, groupOID, 1);
                   // $scope.selectBookingPeriod();
                }
                Messages.populate(); 
            }, 5000);

            //Load allMarker at same time by clicking select all checkbox
            $scope.AllMarker = function () {

                MapArray = [];
                $scope.nearvehiclelist = [];

                var status = checkstatus;
                var check = $(".chkselectall").prop("checked");
                if (check) {
                    $('.AllVehicle').prop('checked', false);

                    switch (status) {

                        case 0:
                            checkArray = $scope.dashboardList;
                            break;
                        case 1:
                            checkArray = $scope.Available;
                            break;
                        case 2:
                            checkArray = $scope.Busy;

                            break;
                        case 3:
                            checkArray = $scope.Break;
                            break;
                        case 4:
                            checkArray = $scope.Accept;
                            break;
                        case 5:
                            checkArray = $scope.Assigned;
                            break;
                        case 6:
                            checkArray = $scope.Absent;

                            break;
                        case 7:
                            checkArray = $scope.OutOfNetwork;

                            break;
                        default:
                            $scope.$apply();


                    }
                    for (var i = 0; i < checkArray.length; i++) {

                        MapArray.push(checkArray[i]);
                        newArray.push(checkArray[i]);
                    }
                }
                else {
                    MapArray = [];
                    newArray = [];
                }
                newarrays = [];
                opensteetMarker(newArray, true);

            }
            $(".hrfmoving,.hrfallvehicle,.hrfstopped,.hrfidle,.hrfnetwork,.hrftowed").click(function () {
                clearitem();
            });
            function clearitem() {
                MapArray = [];
                // GoogleMap();
                //    OpenstreetMap();

            }



            $scope.ChangeDriverName = {
                edit: function (obj) {
                    ngDialog.open({
                        windowClass: 'EditDriverInfo',
                        templateUrl: 'EditDriverInfo.html',
                        controller: 'EditDriverInfoCtrl',
                        resolve: {
                            obj: function () {
                                return obj;
                            }


                        }
                       
                       
                    }); 
              } 
            }


            $scope.zoomTovehicle = function (vehicle) {
                if (track) {
                    track = false;
                    setTimeout(function () {
                        track = bar.trackVehicleCtrl.getActive();
                    }, 10000);
                }
                map.getView().setCenter(ol.proj.transform([vehicle.Long, vehicle.Lat], 'EPSG:4326', 'EPSG:3857'));
                map.getView().setZoom(18);
            }
            //Load Marker based on the checkbox selection
            $scope.isSelected = function (dashlist) {

                // delete sessionStorage.viewmap;
                var radiobtn = document.getElementById("chk" + dashlist.DriverOID + "");
                if ((radiobtn.checked == true)) {
                    var idx = newArray.indexOf(dashlist);
                    if (idx == -1) {
                        newArray.push(dashlist);
                    }
                }
                else {
                    //Remove Object from array based on value
                    $.each(newArray, function (i, el) {
                        if (this.DriverOID == dashlist.DriverOID) {
                            newArray.splice(i, 1);
                        }
                    });
                }

                loadonce = true;
                newarrays = newArray;
                sessionStorage.setItem("SelectedVehicles", JSON.stringify(newArray));

                //VehicleDetailsForDashboard(OID, userOID, companyOID, orgOID, groupOID,1);
                opensteetMarker(newArray, false);
            }
            CustomerArray = [];
            $scope.AddCustomer = function (obj) {
                CustomerArray = [];
              
                $('#' + obj.OID).attr('value', 'selected');


               
                var flag=false;
             

                for (var i = 0; i < CustomerArray.length; i++) {
                    if (CustomerArray[i].$id == obj.$id) {
                        flag = true;

                    }
                }
                if (!flag) {
                    CustomerArray.push(obj);

                }
              //  console.log(CustomerArray)
                CustomerMarker(CustomerArray, false);
            }
            var markerlive = null;

            var intobj = null;
            $scope.getRandomNumber = function (n) {
                return Math.floor((Math.random() * n) + 1);
            }

            function animateIcon(marker, currentDirection, latLng, color) {
                var rorateno = $scope.getRandomNumber(360);
                var count = 1;

                intobj = window.setInterval(function () {
                    currentDirection = (currentDirection + count) % rorateno;
                    //var icon = marker.get('icon');
                    var icon = {
                        path: "M29.395,0H17.636c-3.117,0-5.643,3.467-5.643,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759   c3.116,0,5.644-2.527,5.644-5.644V6.584C35.037,3.467,32.511,0,29.395,0z M34.05,14.188v11.665l-2.729,0.351v-4.806L34.05,14.188z    M32.618,10.773c-1.016,3.9-2.219,8.51-2.219,8.51H16.631l-2.222-8.51C14.41,10.773,23.293,7.755,32.618,10.773z M15.741,21.713   v4.492l-2.73-0.349V14.502L15.741,21.713z M13.011,37.938V27.579l2.73,0.343v8.196L13.011,37.938z M14.568,40.882l2.218-3.336   h13.771l2.219,3.336H14.568z M31.321,35.805v-7.872l2.729-0.355v10.048L31.321,35.805z",
                        scale: .60,
                        rotation: parseFloat(currentDirection),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(30, 30),
                        scaledSize: new google.maps.Size(40, 40),
                        size: new google.maps.Size(10, 10),
                        fillColor: color,
                        fillOpacity: 1
                    }
                    marker.set('icon', icon);

                    //viewLivemarkerMap.panTo(latLng);
                    // markerlive.setMap(viewLivemarkerMap);
                    if ((rorateno - 1) == currentDirection) {
                        clearInterval(intobj);
                    }
                }, 10);
            }
             function CustomerMarker(MapArray, mode) {
                            /*     EDITED BY ALI  **/
                 MissedCustomerLocationLayer.getSource().clear();
                            if (MapArray.length > 0) {
                             

                                for (var i = 0; i < MapArray.length; i++) {
                                    var data = MapArray[i];
                               

                                    var myLatLng = ol.proj.transform([data.CustomerLng, data.CustomerLat], 'EPSG:4326', 'EPSG:3857');




                                    var iconFeature = new ol.Feature({
                                        geometry: new ol.geom.Point(myLatLng),                                     
                                        Name: data.CustomerName,
                                        customerphno: data.CustomerMobile,
                                        customerOID: data.OID,
                                   
                                     
                                    });

                                    iconStyle = [new ol.style.Style({
                                        image: new ol.style.Icon({                           
                                            src: '../../assets/img/user.png' 
                                        })
                                    }),
                                     new ol.style.Style({
                                         text: new ol.style.Text({
                                             font: 'bold 13px JF Flat Regular,sans-serif',
                                             text: data.CustomerName,                                     
                                             fill: new ol.style.Fill({
                                                 color: '#FFCE00'
                                             }),
                                             stroke: new ol.style.Stroke({
                                                 color: '#fff',
                                                 width: 6
                                             }),
                                             offsetY: -20
                                         })
                                     })];
                              
                                    iconFeature.setStyle(iconStyle);
                                    MissedCustomerLocationLayer.getSource().addFeature(iconFeature);

                                  

                                }

                  


                                map.getView().fit(MissedCustomerLocationLayer.getSource().getExtent(), map.getSize());
                              



                            }
                           
                        }
            function opensteetMarker(MapArray, mode) {
                /*     EDITED BY ALI  **/
                liveTrackingLayer.getSource().clear();
                if (MapArray.length > 0) {
                    /*   if (livemarker != null) {
                           setAllMap(null);
                           livemarker = [];
                       }
                       var infoWindow = new google.maps.InfoWindow();
                       var latlngbounds = new google.maps.LatLngBounds();
                       */

                    for (var i = 0; i < MapArray.length; i++) {
                        var data = MapArray[i];
                        // var myLatLng = new google.maps.LatLng(data.Latitude, data.Longitude);

                        var myLatLng = ol.proj.transform([data.Long, data.Lat], 'EPSG:4326', 'EPSG:3857');




                        var iconFeature = new ol.Feature({
                            geometry: new ol.geom.Point(myLatLng),
                            vehno: data.VehRegisterNo,
                            Imei: data.IMEIno,
                            Name: data.DriverName,
                            driverphno: data.DriverPhoneNo,
                            driverOID: data.DriverOID,
                            drvstatus: data.DriverStatus,
                            isbooked: data.IsBooked
                        });

                        iconStyle = [new ol.style.Style({
                            image: new ol.style.Icon({
                                //anchor: [12, 0.5],
                                //size: [1000, 1000],
                                //scale: 0.5,
                                rotation: parseInt(data.Direction) * Math.PI / 180,
                                //anchorXUnits: 'pixel',
                                //anchorYUnits: 'fraction',
                                src: '../../assets/SVGHelper/GetSVG.aspx?c=' + data.color
                            })
                        }),
                         new ol.style.Style({
                             text: new ol.style.Text({
                                 font: 'bold 13px JF Flat Regular,sans-serif',
                                 text: data.DriverName,
                                 rotation: parseInt(data.Direction > 130 && data.Direction <230? data.Direction - 180 : data.Direction) * Math.PI / 180,
                             offsetY: -30 * Math.cos(parseInt(data.Direction) * Math.PI / 180),
                                 offsetX: 30*Math.sin(parseInt(data.Direction) * Math.PI / 180),
                                 fill: new ol.style.Fill({
                                     color: data.color
                                 }),
                                 stroke: new ol.style.Stroke({
                                     color: '#fff',
                                     width: 6
                                 })
                             })
                         })];
                      
                        iconFeature.setStyle(iconStyle);
                        liveTrackingLayer.getSource().addFeature(iconFeature);

                        if (data.TripDestination_RegionId != null) {

                            var _strokeStyle = new ol.style.Stroke({
                                color: 'rgba(255,0,0,1.0)',
                                width: 1
                            });

                            var _fillStyle = new ol.style.Fill({
                                color: 'rgba(255,0,0,0.1)'
                            });

                            var _textStyle = new ol.style.Text({
                                font: 'bold 13px JF Flat Regular,sans-serif',
                                text: data.DriverName,
                                rotation: 0,
                                offsetY: 20,
                                stroke: new ol.style.Stroke({
                                    color: '#ffc83e',
                                    width: 6
                                })
                            })

                            var rStyle = new ol.style.Style({
                                stroke: _strokeStyle,
                                fill: _fillStyle,
                                text: _textStyle
                            });
                            var region = regionsLayer.getSource().getFeatureById(data.TripDestination_RegionId);
                            if (region) {
                                region.setStyle(rStyle);
                            }

                        }
                        


                        /*
                        markerlive = new google.maps.Marker({
                            position: myLatLng,
                            map: viewLivemarkerMap,
                            icon: {
                                path: carpath,
                                strokeColor: "black",
                                scale: 0.035,
                                rotation: parseInt(data.Direction),
                                fillColor: data.color,
                                fillOpacity: 1,
                                strokeWeight: 0.9,
                                strokeColor: '#000000',
                            },

                        });
                        allist = [];
                        markerlive.setMap(viewLivemarkerMap);
                        livemarker.push(markerlive);
                        latlngbounds.extend(markerlive.position);
                        openinfowindow(MapArray[i], markerlive, viewLivemarkerMap, MapArray[i].RegistrationNo);
                        */
                    }

                  


                    if (track || mode) {
                        map.getView().fit(liveTrackingLayer.getSource().getExtent(), map.getSize());
                    }
                    // viewLivemarkerMap.fitBounds(latlngbounds);

                    if (loadonce == true) {
                        //  viewLivemarkerMap.setCenter(latlngbounds.getCenter());
                        loadonce = false;
                    }




                }
                else {
                    openedInfoWindow = null;
                    if (livemarker != null)
                        for (var j = 0; j < livemarker.length; j++) {
                            livemarker[j].setMap(null);
                        }

                }
            }
            var tepInt = null;
            $scope.generalDelay = function (marker, direction, latlng, color) {

                var i = 0;
                tepInt = window.setInterval(function () {
                    if (i % 10 == 0) {
                        animateIcon(marker, direction, latlng, color);
                    }
                    if (i > 10000) i = 0;
                    i++;
                    //clearInterval(tepInt);
                }, 1000);
            }

            //Show History List
            $('.histroydiv').hide();
            tripHistoryDetails.hide();
            // $('.tripNumbersTable').hide();
            var Hischeckstatus = 0;
            $scope.HisAvailable = [];
            $scope.HisBusy = [];
            $scope.HisAssigned = [];
            $scope.HisBreak = [];
            //var Disconnect = [];
            $scope.HisAbsent = [];
            $scope.HisAccept = [];
            $scope.HisAll = [];
            $scope.HisOutOfNetwork = [];
            var tripLength = [];
            var satuts;
            var tripidString;
            $('.HistoryTrack').click(function () {
                currentMap = 2; //Tracking Tab
                clearLayers();
                // $('.TripHisopenstreet').hide();
                // $('.Hisopenstreet').show();
                //$('.openstreet').hide();
                // $('.livediv').hide();
                $('.histroydiv').show();

                if (vehicle != undefined) {
                    var check = document.getElementById("hischk" + vehicle + "");
                    check.checked = true;
                    if (success == 1) {
                        $('.triplist').show();
                        satuts = 1;
                    }
                    else {
                        // $('.TripHisopenstreet').hide();
                        $('#radio_container').empty();
                    }
                }
                else {

                    //ViewhistoryTabmap(sessionStorage.Latvalue, sessionStorage.Lngvalue);
                    $(".status").prop('checked', false);
                    //$('.TripHisopenstreet').hide();
                    $('#radio_container').empty();
                    $.ajax({
                        url: ManagementServiceUrl + "GetCustomerAppVehicles/" + "0" + "/" + cityOID+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",
                        async: false,
                        success: function (result) {


                            $scope.HisAvailable = [];
                            $scope.HisBusy = [];
                            $scope.HisAssigned = [];
                            $scope.HisBreak = [];
                            //var Disconnect = [];
                            $scope.HisAbsent = [];
                            $scope.HisAccept = [];
                            $scope.HisAll = [];
                            $scope.HisOutOfNetwork = [];
                            var List = result.GetCustomerAppVehiclesResult;
                            List = List.split("~");

                            var Hisdashlist = JSON.parse(List[1])
                           // console.log(Hisdashlist)
                            if (Hisdashlist.length != 0) {

                                for (var i = 0; i < Hisdashlist.length; i++) {
                                    var datetimeStr = Hisdashlist[i].LocationDateTime;
                                    var DateTimeDiff = DateDiff(datetimeStr, List[0])

                                    Hisdashlist[i].interval = DateTimeDiff;
                                    if (moreThanThirtyMin(DateTimeDiff)) {
                                        if ((Hisdashlist[i].DriverStatus == "0" && Hisdashlist[i].IsBooked == "0")) {
                                            Hisdashlist[i].color = "black";
                                            Hisdashlist[i].Order = 9;

                                            $scope.HisAbsent.push(Hisdashlist[i]);
                                        }
                                        else {
                                            Hisdashlist[i].DriverStatus = "5";
                                            Hisdashlist[i].IsBooked = "0";
                                            Hisdashlist[i].color = "grey";
                                            Hisdashlist[i].Order = 8;

                                            $scope.HisOutOfNetwork.push(Hisdashlist[i]);

                                        }
                                        $scope.HisAll.push(Hisdashlist[i]);
                                    }


                                    else if (Hisdashlist[i].DriverStatus == "1" && Hisdashlist[i].IsBooked == "0") {
                                        Hisdashlist[i].color = "green";
                                        Hisdashlist[i].Order = 1;

                                        $scope.HisAvailable.push(Hisdashlist[i]);
                                        $scope.HisAll.push(Hisdashlist[i]);
                                    }
                                    else if ((Hisdashlist[i].DriverStatus == "1" && Hisdashlist[i].IsBooked == "1")) {
                                        Hisdashlist[i].color = "red";
                                        Hisdashlist[i].Order = 2;

                                        $scope.HisBusy.push(Hisdashlist[i]);
                                        $scope.HisAll.push(Hisdashlist[i]);
                                    }
                                    else if (Hisdashlist[i].DriverStatus == "4" && Hisdashlist[i].IsBooked == "0") {
                                        Hisdashlist[i].color = "blue";
                                        Hisdashlist[i].Order = 3;

                                        $scope.HisAssigned.push(Hisdashlist[i]);
                                        $scope.HisAll.push(Hisdashlist[i]);
                                    }
                                    else if (Hisdashlist[i].DriverStatus == "2" && Hisdashlist[i].IsBooked == "0") {
                                        Hisdashlist[i].color = "skyblue";
                                        Hisdashlist[i].Order = 10;

                                        $scope.HisBreak.push(Hisdashlist[i]);
                                        $scope.HisAll.push(Hisdashlist[i]);
                                    }
                                    else if ((Hisdashlist[i].DriverStatus == "0" && Hisdashlist[i].IsBooked == "0")
                                          || (Hisdashlist[i].DriverStatus == '0' && Hisdashlist[i].IsBooked == '1')) {
                                        Hisdashlist[i].color = "black";
                                        Hisdashlist[i].Order = 9;

                                        $scope.HisAbsent.push(Hisdashlist[i]);
                                        $scope.HisAll.push(Hisdashlist[i]);
                                    }
                                    else if (Hisdashlist[i].DriverStatus == "3" && Hisdashlist[i].IsBooked == "1") {
                                        Hisdashlist[i].color = "purple";
                                        Hisdashlist[i].Order = 4;

                                        $scope.HisAccept.push(Hisdashlist[i]);
                                        $scope.HisAll.push(Hisdashlist[i]);

                                    }
                                }

                            }
                            else {
                                ViewhistoryTabmap(sessionStorage.Latvalue, sessionStorage.Lngvalue);
                            }


                            switch (Hischeckstatus) {
                                case 0:
                                    $scope.HisdashboardList = $scope.HisAll;
                                    break;
                                case 1:
                                    $scope.HisdashboardList = $scope.HisAvailable;
                                    break;
                                case 2:
                                    $scope.HisdashboardList = $scope.HisBusy;
                                    break;
                                case 3:
                                    $scope.HisdashboardList = $scope.HisBreak;
                                    break;
                                case 4:
                                    $scope.HisdashboardList = $scope.HisAccept;
                                    break;
                                case 5:
                                    $scope.HisdashboardList = $scope.HisAssigned;
                                    break;
                                case 6:
                                    $scope.HisdashboardList = $scope.HisAbsent;
                                    break;
                                case 7:
                                    $scope.HisdashboardList = $scope.HisOutOfNetwork;
                                    break;

                                default:
                            }

                            //Pagination 
                            if ($scope.HisdashboardList.length == 0) {
                                $scope.Hisnearest = "No Vehicles Found";
                            }
                            //$scope.HiscurrentPage = 1;
                            //$scope.HispageSize = 10;
                            $scope.$apply();



                        }
                    });

                }
            });
            $scope.HisgetGridList = function (status) {
                clearl();
                $('.triplist').hide();
                //$('.playoptiondiv').hide();
                $("input[type=radio][name=trackradio]").prop("checked", false);
                $("input[type=radio][name=SomeRadio]").prop("checked", false);
                vehicle = undefined;
                switch (status) {
                    case "0,1":
                        $scope.HisdashboardList = $scope.HisAll;
                        $scope.searchName = "All Vehicles";
                        Hischeckstatus = 0;

                        break;
                    case "0,0":
                        $scope.HisdashboardList = $scope.HisAbsent;
                        $scope.searchName = "Absent";
                        Hischeckstatus = 6;

                        break;
                    case "1,0":
                        $scope.HisdashboardList = $scope.HisAvailable;
                        $scope.searchName = "Available";
                        Hischeckstatus = 1;

                        break;
                    case "1,1":
                        $scope.HisdashboardList = $scope.HisBusy;
                        $scope.searchName = "Busy ";
                        Hischeckstatus = 2;

                        break;
                    case "2,0":
                        $scope.HisdashboardList = $scope.HisBreak;
                        $scope.searchName = "Break ";
                        checkstatus = 3;

                        break;
                    case "3,1":
                        $scope.HisdashboardList = $scope.HisAccept;
                        $scope.searchName = "Accept ";
                        Hischeckstatus = 4;

                        break;
                    case "4,0":
                        $scope.HisdashboardList = $scope.HisAssigned;
                        $scope.searchName = "Assigned";
                        Hischeckstatus = 5;

                        break;
                    case "5,0":
                        $scope.HisdashboardList = $scope.OutOfNetwork;
                        $scope.searchName = "Out Of Network";
                        Hischeckstatus = 7;

                        break;
                    default:

                }
                if ($scope.HisdashboardList.length == 0) {
                    $scope.Hisnearest = "No Vehicles Found";
                }
                $scope.$apply();
            }
            $('.LiveTrack').click(function () {
                currentMap = 1; //Live Tracking Tab
                clearLayers();
                $('.histroydiv').hide();
                tripHistoryDetails.hide();
            });
            $scope.tripfdate = new Date();
            $('.tripHistoryTrack').click(function () {
                currentMap = 3; //Trip Tracking Tab
                clearLayers();
                $('.histroydiv').hide();
                $('.triphistorydiv').show();
                if (tripVehicleArray.length == 0) {
                    // ViewTripHistorymap(sessionStorage.Latvalue, sessionStorage.Lngvalue);
                }
                else {

                    if (selectTripId.length != 0) {
                        $.each(selectTripId, function (i, val) {
                            $("input[value='" + val + "']").prop('checked', true);
                        });
                        //for (var i = 0; i < tripVehicleArray.length; i++) {
                        //    var radiobtn = document.getElementById("TripCheckId" + tripVehicleArray[i] + "");
                        //    radiobtn.checked = true;
                        //}
                    }
                }
            });
            $scope.tripHistoryPagination = function () {

                if (selectTripId.length != 0) {
                    $.each(selectTripId, function (i, val) {

                        $("input[value='" + val + "']").prop('checked', true);
                    });
                    //for (var i = 0; i < tripVehicleArray.length; i++) {
                    //    var radiobtn = document.getElementById("TripCheckId" + tripVehicleArray[i] + "");
                    //    if (radiobtn != null)
                    //        radiobtn.checked = true;
                    //}
                }
            }
            $('input[name="chk[]"]').change(function () {
                $scope.nearvehiclelist = [];
            });
            function selectedLatlng(Lat, Long) {
                SelectedLat = Lat;
                SelectedLong = Long;
            }







            //Create Dynamic dropdown for mins 
            for (var i = 0; i <= 59; i++) {
                if (i > 9) {
                    jQuery('.Selectmins').append(jQuery("<option></option>").val([i]).text([i]))
                } else {
                    jQuery('.Selectmins').append(jQuery("<option></option>").val('0' + [i]).text('0' + [i]))
                }
            }

            //get vehicle Id onclick the check the check box
            var vehicleimei;
            $scope.HistoryCheckClick = function (DriverOID) {


                var radiobtn = document.getElementById("hischk" + DriverOID + "");
                if ((radiobtn.checked == true)) {
                    $scope.DriverOID = DriverOID;
                   
                }
                else {
                    $scope.DriverOID = undefined;
                   
                }
                $('.triplist').hide();
                tripHistoryDetails.hide();
                $('.checkTripId').attr('checked', false);
                $('.list').attr('checked', false);
                clearLayers();
            }
            //bind dynamic Back Tracking Records  based on datetime selection
            $scope.GetHistoryData = function () {
                $('.triplist').hide();
                $scope.TripNumber = "";
                clearLayers();
                if ($scope.DriverOID == undefined) {
                    openDialog("Please Select a Vehicle");

                }
                else {

                    var fromMilliSeconds = $range.data("from");
                    var toMilliSeconds = $range.data("to");

                    var FromTime = moment.unix(fromMilliSeconds).format("HH:mm");
                    var ToTime = moment.unix(toMilliSeconds).format("HH:mm");

                    // var FromTime = $('#selectedfromhrs').val();
                    // var ToTime = $('#selectedtohrs').val();

                    FromTime = FromTime.replace(':', '~');
                    ToTime = ToTime.replace(':', '~');

                    date1 = new Date($('#fromdate').val().split(' '));
                    d = [date1.getFullYear() + '-' + (date1.getMonth() + 1).pad() + '-' + date1.getDate().pad() + ' ' + FromTime,
                            date1.getFullYear() + '-' + (date1.getMonth() + 1).pad() + '-' + date1.getDate().pad() + ' ' + ToTime];
                  
                   // getroutelatlng(d, vehicleimei, 0, "hisMap", 0)


                }
            };



            Date.prototype.toMSJSON = function () {
                var date = '/Date(' + this.getTime() + ')/'; //CHANGED LINE
                return date;
            };

            String.prototype.replaceAll = function (search, replacement) {
                var target = this;
                return target.replace(new RegExp(search, 'g'), replacement);
            };
            getFormattedDate = function (t) {

                var dt = new Date(t);
                var dt1 = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
                return dt1;
            };
            Date.prototype.toMSJSON = function () {
                var date = 'Date(' + this.getTime() + ')';
                return date;
            };
            var success, tripsuccess;
            //get latlng from DB for history tracking
            var histriparray = [], historyArray = [];
            var historyTripArray = [], historyString;
            var clickonce = true;
            var Tripclickonce = true;
            var linetrip;
            var lines = [], startmarkers = [], endmarkers = [];
            var m = 0;
            var n = 0;
            var checked = 1;
            function formatAMPM(t) {
                var date = new Date(t);
                var hours = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
                var am_pm = date.getHours() >= 12 ? "PM" : "AM";
                hours = hours < 10 ? "0" + hours : hours;
                var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                var strTime = hours + "~" + minutes + "~" + seconds + " " + am_pm;

                return strTime;
            }
  
            function removeRoute(BKID) {
                historyPathLayer.getSource().removeFeature(historyPathLayer.getSource().getFeatureById(BKID));
                liveTrackingLayer.getSource().removeFeature(liveTrackingLayer.getSource().getFeatureById('s' + BKID));
                liveTrackingLayer.getSource().removeFeature(liveTrackingLayer.getSource().getFeatureById('e' + BKID));



            }
            //Draw route on both google map and openstreet map
            function DrawRouteOnOpenStreetMap(latlng, str, BKID, valarray) {
                latlng.reverse();
                var points = [];
                var maxSpeed = 0, averageSpeed = 0; averSpeedCounter = 0;
                var driverName = '';
                var startTime = null, endTime = null, date = null;
                var tripDuration = 0, tripDistance = 0;
                for (var j = 0; j < latlng.length; j++) {
                    driverName = latlng[j].DriverName;
                    var pt = ol.proj.transform([latlng[j].Longitude, latlng[j].Latitude], 'EPSG:4326', 'EPSG:3857');
                    maxSpeed = (latlng[j].Speed > maxSpeed ? latlng[j].Speed : maxSpeed);
                    date = new Date(Date.parse(latlng[j].DateTime));
                   // date = new Date(date.getTime() + date.getTimezoneOffset() * 60000);


                    if (latlng[j].Speed > 0) {
                        startTime = (startTime == null ? date : startTime);
                        endTime = (endTime == null ? date : endTime);
                        startTime = (date < startTime ? date : startTime);
                        endTime = (date > endTime ? date : endTime);
                        averageSpeed += latlng[j].Speed;
                        averSpeedCounter++;
                    }
                    points.push(pt);
                }
                if (averSpeedCounter > 0)
                    averageSpeed /= averSpeedCounter;
                averageSpeed = Math.round(averageSpeed);
                tripDuration = Math.round((endTime - startTime) / 3600000);

                var startPoint = new ol.proj.transform([latlng[latlng.length - 1].Longitude, latlng[latlng.length - 1].Latitude], 'EPSG:4326', 'EPSG:3857');
                var startPointFeature = new ol.Feature({
                    BKID: BKID,
                    geometry: new ol.geom.Point(startPoint),
                    name: '',
                });
                startPointFeature.setId('s' + BKID);

                startPointIconStyle = [new ol.style.Style({
                    image: new ol.style.Icon({
                        rotation: 0,
                        src: 'assets/img/destinationmarker.png'
                    })
                })];

                startPointFeature.setStyle(startPointIconStyle);
                liveTrackingLayer.getSource().addFeature(startPointFeature);

                var endPoint = new ol.proj.transform([latlng[0].Longitude, latlng[0].Latitude], 'EPSG:4326', 'EPSG:3857');
                var endPointFeature = new ol.Feature({
                    id: BKID,
                    geometry: new ol.geom.Point(endPoint),
                    // name: '',
                });
                endPointFeature.setId('e' + BKID);

                endPointIconStyle = [new ol.style.Style({
                    image: new ol.style.Icon({
                        rotation: 0,
                        src: 'assets/img/sourcemarker.png'
                    })
                })];

                endPointFeature.setStyle(endPointIconStyle);
                liveTrackingLayer.getSource().addFeature(endPointFeature);

                var featureLine = new ol.Feature({
                    id: BKID,
                    geometry: new ol.geom.LineString(points)
                });
                featureLine.setId(BKID);
                var geometry = featureLine.getGeometry();

                tripDistance = Math.round(geometry.getLength());

                var iconStyle_line = new ol.style.Style({//  My style definition 
                    fill: new ol.style.Fill({
                        color: 'rgba(25, 25, 112, 0.5)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: 'rgba(72,61,139, 0.9)',
                        width: 3,
                        lineDash: [8, 8] // <-Here is the change. first line then space. try [40,40] if not shown as dash
                    })
                });
                featureLine.setStyle(iconStyle_line);
                historyPathLayer.getSource().addFeature(featureLine);
                map.getView().fit(historyPathLayer.getSource().getExtent(), map.getSize());

                var trip = {
                    Driver: driverName,
                    Duration: tripDuration,
                    Date: date == null ? 'لا يوجد' : (date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear()),
                    Distance: Math.round(tripDistance / 1000),
                    //    CarType: 'scoda',
                    MovementStart: startTime == null ? 'لا يوجد' : (startTime.getHours().pad() + ":" + startTime.getMinutes().pad()),
                    MovementEnd: endTime == null ? 'لا يوجد' : (endTime.getHours().pad() + ":" + endTime.getMinutes().pad()),
                    SpeedAVG: averageSpeed,
                    SpeedMAX: maxSpeed

                };
                tripHistoryDetails.show();

                tripHistoryDetails.setDetails(trip);
                tripHistoryDetails.initSlider(latlng);
            }


            function pageload() {


                slidval = $scope.value3;

                interval = window.setInterval(function () {
                    count = (count + 1) % 200;
                    icons = polyline.get('icons');
                    icons[0].offset = (count / 2) + '%';
                    historyLine.set('icons', icons);
                }, 100 - slidval * 10);


            }
            //forward,backward,stop,play click
            var clicks = true;

            //show marker on polyline on map based on vehicel status section
            $("#checkAll").change(function () {
                $(".status").prop('checked', $(this).prop("checked"));
                if ($(this).prop('checked')) {
                    movingstatusicon(true);
                    overspeedstatusicon(true);
                    stoppedstatusicon(true);
                }
                else {
                    movingstatusicon(false);
                    overspeedstatusicon(false);
                    stoppedstatusicon(false);
                }

            });
            $("#movingchk").change(function () {
                if ($(this).prop('checked')) {
                    movingstatusicon(true);
                }
                else {
                    movingstatusicon(false);
                }

            });
            $("#overspeedchk").change(function () {
                if ($(this).prop('checked')) {
                    overspeedstatusicon(true);
                }
                else {
                    overspeedstatusicon(false);
                }
            });
            $("#stoppedchk").change(function () {
                if ($(this).prop('checked')) {
                    stoppedstatusicon(true);
                }
                else {
                    stoppedstatusicon(false);
                }
            });


            $("#triphischeck").change(function () {
                //$('.playoptiondiv').hide();
                $(".triphisstatus").prop('checked', $(this).prop("checked"));
                if ($(this).prop('checked')) {
                    hismovingstatusicon(true);
                    hisoverspeedstatusicon(true);
                    hisstoppedstatusicon(true);
                }
                else {
                    m, n, o = 0;
                    hismovingstatusicon(false);
                    hisoverspeedstatusicon(false);
                    hisstoppedstatusicon(false);
                }
            });
            $("#hisMoving").change(function () {
                if ($(this).prop('checked')) {
                    hismovingstatusicon(true);
                }
                else {
                    m = 0;
                    hismovingstatusicon(false);
                }
            });
            $("#hisOverSpeed").change(function () {


                if ($(this).prop('checked')) {
                    hisoverspeedstatusicon(true);
                }
                else {
                    n = 0;
                    hisoverspeedstatusicon(false);
                }

            });
            $("#hisStopped").change(function () {


                if ($(this).prop('checked')) {
                    hisstoppedstatusicon(true);
                }
                else {
                    o = 0;
                    hisstoppedstatusicon(false);
                }

            });


            function movingstatusicon(chkboxstatus) {


                var latlng = movinglist;
                if (chkboxstatus == true) {
                    for (var i = 0; i < latlng.length; i++) {
                        marker = new google.maps.Marker({
                            position: { lat: parseFloat(latlng[i].Latitude), lng: parseFloat(latlng[i].Longitude) },
                            map: historymap,
                            icon: 'assets/img/vehiclestatusicon/Runningicon.png'
                        });

                        movingvehinfowindow(latlng[i], marker, historymap, latlng[i].RegistrationNo);
                        movingmarkers.push(marker);
                    }
                }
                else {
                    popmarker(movingmarkers);
                    movingmarkers = [];
                }

            }
            function overspeedstatusicon(chkboxstatus) {


                var latlng = overspeedlist;
                if (chkboxstatus == true) {
                    for (var i = 0; i < latlng.length; i++) {
                        marker = new google.maps.Marker({
                            position: { lat: parseFloat(latlng[i].Latitude), lng: parseFloat(latlng[i].Longitude) },
                            map: historymap,
                            icon: 'assets/img/vehiclestatusicon/overspeedicon.png'
                        });
                        movingvehinfowindow(latlng[i], marker, historymap, latlng[i].RegistrationNo);
                        overspeedmarkers.push(marker);
                    }
                }
                else {
                    popmarker(overspeedmarkers);
                    overspeedmarkers = [];
                }

            }
            function stoppedstatusicon(chkboxstatus) {

                var latlng = stoppedlist;
                if (chkboxstatus == true) {
                    for (var i = 0; i < latlng.length; i++) {
                        marker = new google.maps.Marker({
                            position: { lat: parseFloat(latlng[i].Latitude), lng: parseFloat(latlng[i].Longitude) },
                            map: historymap,
                            icon: 'assets/img/vehiclestatusicon/stoppedicon.png'
                        });
                        stoppedvehinfowindow(latlng[i], marker, historymap);
                        stoppedmarkers.push(marker);
                    }
                }
                else {

                    popmarker(stoppedmarkers);
                    stoppedmarkers = [];
                }
            }
            function popmarker(markerarry) {

                for (var i = 0; i < markerarry.length; i++) {
                    markerarry[i].setMap(null); //Remove the marker from the map
                }

            }

            var hisMovearray = [];
            var hisStoparray = [];
            var hisOverSpeedarray = [];
            function hismovingstatusicon(chkboxstatus) {

                var latlng = hismovinglist;
                if (chkboxstatus == true) {
                    if (checked == 1) {
                        if (hisMovearray[0].length != 0) {
                            hispopmarker(hisMovearray[0], hismovingmarkers, "m");
                        }
                        if (hisMovearray[0].length > 0) {
                            hisMovearray.length = 0;
                            hisMovearray = [];
                        }
                        for (var i = 0; i < latlng.length; i++) {
                            hismovingmarkers[i] = [];
                            for (var k = 0; k < latlng[i].length; k++) {
                                hismarker = new google.maps.Marker({
                                    position: { lat: parseFloat(latlng[i][k].Latitude), lng: parseFloat(latlng[i][k].Longitude) },
                                    map: triphistorymap,
                                    icon: 'assets/img/vehiclestatusicon/Runningicon.png'
                                });

                                openwindowforTipHistory(latlng[i][k], hismarker, triphistorymap, latlng[i][k].RegistrationNo);
                                hismovingmarkers[i].push(hismarker);
                            }


                        }
                        hisMovearray[0].push(hismovingmarkers);

                    }
                }
                else {

                    if (hisMovearray[0] == undefined) {
                        hispopmarker("undefined", hismovingmarkers, "m");
                    }
                    else {
                        hispopmarker(hisMovearray[0], hismovingmarkers, "m");
                    }
                }

            }
            function hisoverspeedstatusicon(chkboxstatus) {
                var latlng = hisoverspeedlist;
                if (chkboxstatus == true) {
                    if (checked == 1) {
                        if (hisMovearray[0].length != 0) {
                            hispopmarker(hisOverSpeedarray[0], hisoverspeedmarkers, "o");
                        }
                        if (hisOverSpeedarray[0].length > 0) {
                            hisOverSpeedarray.length = 0;
                            hisOverSpeedarray = [];
                        }
                        for (var i = 0; i < latlng.length; i++) {
                            hisoverspeedmarkers[i] = [];
                            for (var k = 0; k < latlng[i].length; k++) {
                                hismarker = new google.maps.Marker({
                                    position: { lat: parseFloat(latlng[i][k].Latitude), lng: parseFloat(latlng[i][k].Longitude) },
                                    map: triphistorymap,
                                    icon: 'assets/img/vehiclestatusicon/overspeedicon.png'
                                });
                                openwindowforTipHistory(latlng[i][k], hismarker, triphistorymap, latlng[i][k].RegistrationNo);
                                hisoverspeedmarkers[i].push(hismarker);
                            }
                        }
                        hisOverSpeedarray[0].push(hisoverspeedmarkers);
                    }

                }
                else {

                    if (hisOverSpeedarray[0] == undefined) {
                        hispopmarker("undefined", hisoverspeedmarkers, "o");
                    }
                    else {
                        hispopmarker(hisOverSpeedarray[0], hisoverspeedmarkers, "o");

                    }
                }
            }
            function hisstoppedstatusicon(chkboxstatus) {
                var latlng = hisstoppedlist;
                if (chkboxstatus == true) {
                    if (checked == 1) {
                        if (hisMovearray[0].length != 0) {
                            hispopmarker(hisStoparray[0], hisstoppedmarkers, "s");
                        }
                        if (hisStoparray[0].length > 0) {
                            hisStoparray.length = 0;
                            hisStoparray = [];
                        }
                        for (var i = 0; i < latlng.length; i++) {
                            hisstoppedmarkers[i] = [];
                            for (var k = 0; k < latlng[i].length; k++) {
                                hismarker = new google.maps.Marker({
                                    position: { lat: parseFloat(latlng[i][k].Latitude), lng: parseFloat(latlng[i][k].Longitude) },
                                    map: triphistorymap,
                                    icon: 'assets/img/vehiclestatusicon/stoppedicon.png'
                                });
                                openwindowforTipHistory(latlng[i][k], hismarker, triphistorymap, latlng[i][k].RegistrationNo);
                                hisstoppedmarkers[i].push(hismarker);
                            }

                        }
                        hisStoparray[0].push(hisstoppedmarkers);
                    }


                }
                else {

                    if (hisStoparray[0] == undefined) {
                        hispopmarker("undefined", hisstoppedmarkers, "s");
                    }
                    else {
                        hispopmarker(hisStoparray[0], hisstoppedmarkers, "s");
                    }
                }
            }
            function hispopmarker(markerarry, array, type) {

                if (markerarry.length != 0)
                    if (markerarry != undefined && markerarry != "undefined") {
                        if (markerarry[0].length != 0) {
                            for (var j = 0; j < markerarry[0].length; j++) {
                                for (var k = 0; k < markerarry[0][j].length; k++) {
                                    markerarry[0][j][k].setMap(null); //Remove the marker from the map
                                }
                            }

                            switch (type) {
                                case "m":
                                    if (markerarry[0].length == 1) {
                                        hismovingmarkers.length = 0;
                                        hisMovearray.length = 0;
                                        hisMovearray[0] = [];
                                        hismovingmarkers[0] = [];

                                    }
                                    else {
                                        hisMovearray.length = 0;
                                        hisMovearray[0] = [];
                                        hismovingmarkers.length = 0;
                                    }
                                    break;
                                case "o":
                                    if (markerarry[0].length == 1) {
                                        hisoverspeedmarkers.length = 0;
                                        hisOverSpeedarray.length = 0;
                                        hisoverspeedmarkers[0] = [];
                                        hisOverSpeedarray[0] = [];
                                    }
                                    else {
                                        hisOverSpeedarray.length = 0;
                                        hisOverSpeedarray[0] = [];
                                        hisoverspeedmarkers.length = 0;
                                    }
                                    break;
                                case "s":
                                    if (markerarry[0].length == 1) {
                                        hisstoppedmarkers.length = 0;
                                        hisStoparray.length = 0;
                                        hisStoparray[0] = [];
                                        hisstoppedmarkers[0] = [];
                                    }
                                    else {
                                        hisStoparray.length = 0;
                                        hisstoppedmarkers.length = 0;
                                        hisStoparray[0] = [];
                                    }
                                    break;
                            }
                        }
                    }

            }

            function clearalltriphisStatusmarker(hismovingmarkers, hisoverspeedmarkers, hisstoppedmarkers) {
                for (var i = 0; i < hismovingmarkers.length; i++) {
                    hismovingmarkers[i].setMap(null); //Remove the marker from the map
                }
                for (var i = 0; i < hisoverspeedmarkers.length; i++) {
                    hisoverspeedmarkers[i].setMap(null); //Remove the marker from the map
                }
                for (var i = 0; i < hisstoppedmarkers.length; i++) {
                    hisstoppedmarkers[i].setMap(null); //Remove the marker from the map
                }
            }
            //<!---------------FOR BOTH HISTORY AND LIVE TRACKING-------------->
            //Content for moving and stopped infowindow
            function movingvehinfowindow(list, marker, historymap, Vehiclename) {

                //  
                var vehnam = Vehiclename;
                openinfowindow(list, marker, historymap, vehnam);
            }
            function stoppedvehinfowindow(list, marker, historymap) {

                var vehnam = Vehiclename;
                openinfowindow(list, marker, historymap, vehnam);

            }

            // open info window on click on marker on history map
            var openedInfoWindow = null;
            var infowindow;
            var Content;
            function openinfowindow(list, marker, map, vehiclename) {
                //    
                openedInfoWindow = null;
                infowindow = new google.maps.InfoWindow();
                google.maps.event.addListener(marker, 'click', (function () {


                    if (openedInfoWindow != null) {
                        openedInfoWindow.close();
                        openedInfoWindow = null;
                    } else {
                        loadaddress(list, marker, map, vehiclename);
                        //end
                        google.maps.event.addListener(infowindow, 'closeclick', function () {
                            openedInfoWindow = null;
                        });
                    }
                }));
                //  

            }
            function openwindowforTipHistory(list, marker, map, vehiclename) {

                //    
                var TripWindow = null;
                var Tripinfowindow = new google.maps.InfoWindow();
                google.maps.event.addListener(marker, 'click', (function () {


                    if (TripWindow != null) {
                        TripWindow.close();
                        TripWindow = null;
                    } else {
                        Triploadaddress(list, marker, map, vehiclename, TripWindow, Tripinfowindow);
                        //end
                        google.maps.event.addListener(Tripinfowindow, 'closeclick', function () {
                            TripWindow = null;
                        });
                    }
                }));
                //  

            }
            function Triploadaddress(list, marker, map, vehiclename, TripWindow, Tripinfowindow) {
                //by selvi


                var s = document.createElement('script');
                if (sessionStorage.selectedLanguage == "ar-AE")
                    s.src = 'http://nominatim.openstreetmap.org/reverse?json_callback=Getaddress&accept-language=ar&format=json&lat=' + list.Latitude + '&lon=' + list.Longitude + '&zoom=27&addressdetails=1';
                else
                    s.src = 'http://nominatim.openstreetmap.org/reverse?json_callback=Getaddress&accept-language=en&format=json&lat=' + list.Latitude + '&lon=' + list.Longitude + '&zoom=27&addressdetails=1';

                document.getElementsByTagName('head')[0].appendChild(s);

                window.Getaddress = function Getaddress(json) {

                    var location;
                    if (json.address) {
                        location = returnFormattedAddress(json.address);
                    }
                    else {
                        location = "Unable to get Address";
                    }
                    if (list.DateTime != null) {
                        var datetimeStr = list.DateTime;
                        var date = new Date(datetimeStr);
                        date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
                    }

                    Content = '<table class="infowind"><tr><td><img src="assets/img/icons/vehicleicon.png"/></td><td>Vehicle</td><td>&nbsp;' + vehiclename + '</td></tr>' +
      '<tr><td><img src="assets/img/icons/overspeedBT.png"/></td><td>Speed</td><td>&nbsp;' + list.Speed + 'kmph</td></tr>' +
      '<tr><td><img src="assets/img/icons/timeBT.png"/></td><td>Time</td><td>&nbsp;' + date + '</td></tr>' +
                   '<tr><td><img src="assets/img/icons/locationBT.png"/></td><td>Location</td><td>&nbsp;' + location + '</td></tr>';
                    if (status == "0") {
                        Tripinfowindow.setContent(Content);
                        Tripinfowindow.setPosition({ lat: list.Latitude, lng: list.Longitude });
                        Tripinfowindow.open(map);
                        TripWindow = Tripinfowindow;
                    }
                    else {
                        Tripinfowindow.setContent(Content);
                        Tripinfowindow.open(map, marker);
                        TripWindow = Tripinfowindow;
                    }


                }
                //by selvi
            }
            function loadaddress(list, marker, map, vehiclename, status) {
                //by selvi

                var s = document.createElement('script');
                if (sessionStorage.selectedLanguage == "ar-AE")
                    s.src = 'http://nominatim.openstreetmap.org/reverse?json_callback=Getaddress&accept-language=ar&format=json&lat=' + list.Latitude + '&lon=' + list.Longitude + '&zoom=27&addressdetails=1';
                else
                    s.src = 'http://nominatim.openstreetmap.org/reverse?json_callback=Getaddress&accept-language=en&format=json&lat=' + list.Latitude + '&lon=' + list.Longitude + '&zoom=27&addressdetails=1';

                document.getElementsByTagName('head')[0].appendChild(s);

                window.Getaddress = function Getaddress(json) {
                    var location;
                    if (json.address) {
                        location = returnFormattedAddress(json.address);
                    }
                    else {
                        location = "Unable to get Address";
                    }
                    if (list.DateTime != null) {
                        var datetimeStr = list.DateTime;
                        var date = new Date(datetimeStr);
                        date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
                    }

                    Content = '<table class="infowind"><tr><td><img src="assets/img/icons/vehicleicon.png"/></td><td>Vehicle</td><td>&nbsp;' + vehiclename + '</td></tr>' +
      '<tr><td><img src="assets/img/icons/overspeedBT.png"/></td><td>Speed</td><td>&nbsp;' + list.Speed + 'kmph</td></tr>' +
      '<tr><td><img src="assets/img/icons/timeBT.png"/></td><td>Time</td><td>&nbsp;' + date + '</td></tr>' +
                   '<tr><td><img src="assets/img/icons/locationBT.png"/></td><td>Location</td><td>&nbsp;' + location + '</td></tr>';
                    if (status == "0") {
                        infowindow.setContent(Content);
                        infowindow.setPosition({ lat: list.Latitude, lng: list.Longitude });
                        infowindow.open(map);
                        openedInfoWindow = infowindow;
                    }
                    else {
                        infowindow.setContent(Content);
                        infowindow.open(map, marker);
                        openedInfoWindow = infowindow;
                    }


                }
                //by selvi
            }
            function GetAddress(Latitude, Longitude) {

                var lat = parseFloat(document.getElementById("txtLatitude").value);
                var lng = parseFloat(document.getElementById("txtLongitude").value);
                var latlng = new google.maps.LatLng(lat, lng);
                var geocoder = geocoder = new google.maps.Geocoder();
                geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[1]) {
                            alert("Location: " + results[1].formatted_address);
                        }
                    }
                });

            }
            //Move some some to top to dropdown in history tracking
            /*   $('#selectedfromhrs').val('12');
               $('#selectedtohrs').val('11');
               $('#selectedtomin').val('59');
               $('#selectedtonoon').val('PM');*/

            //Trip History    
            function getFormattedFromDate(tDate) {

                var year = tDate.getFullYear();
                var month = (1 + tDate.getMonth()).toString();
                month = month.length > 1 ? month : '0' + month;
                var day = tDate.getDate().toString();
                day = day.length > 1 ? day : '0' + day;
                DatePart = year + month + day;
                return year + '-' + month + '-' + day;

            }
            var triphistoryfdate;
            var tripPath = [];
            var tripArray = [];
            var tripVehicleArray = [];
            var selectTripId = [];
            var VehicleBookingArray = [];
            var BookIdindex;
            var tripstartmarker, tripendmarker, tripline;
       /*     $scope.GetTripHistoryData = function () {
                date = getFormattedFromDate($scope.tripfdate);
                selectTripId = [];
                tripVehicleArray = [];
                TripHisList = [];
                hisMovearray = [];
                hisStoparray = [];
                hisOverSpeedarray = [];
                Clearhistripmarkers();
                $('#triphischeck').prop('checked', false);
                $('#triphischeck').trigger('change');
                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "TripDataForReport/" + date + "/" + date + "/" + 0 + "/" + 0 + "/" + sessionStorage.CompanyOID + "/" + orgOID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {

                        if (result.TripDataForReportResult != "[]") {
                            $scope.tripHistoryList = JSON.parse(result.TripDataForReportResult);
                            if ($scope.tripHistoryList.length > 10) {
                                $('.historytripRecords').show();
                            }
                            else {
                                $('.historytripRecords').hide();
                            }
                            angular.forEach($scope.tripHistoryList, function (value, key) {
                                //by selvi
                                $scope.tripHistoryList[key].StartTripDt = new Date($scope.tripHistoryList[key].TripStartTime);
                                $scope.tripHistoryList[key].EndTripDt = new Date($scope.tripHistoryList[key].TripEndTime);
                                //by selvi
                                VehicleBookingArray.push($scope.tripHistoryList[key].BookingID);

                            });
                            $scope.msortType = 'BookingID'; // set the default sort type
                            $scope.msortReverse = false;  // set the default sort order
                        }
                        else {
                            $scope.tripHistoryList = '';
                            $('.historytripRecords').hide();
                            $('.historytriplist').hide();
                        }
                        $scope.tripcurrentPage = 1;
                        $scope.trippageSize = 10;
                        $scope.$apply();
                    }
                });
            }*/
            $scope.TripIDCheckClick = function (obj, vehName, BKID, DateTime, imei, SDate, EDate) {
                //$('.playoptiondiv').hide();
                Vehiclename = vehName;

                // vehicle = imei;
                var radiobtn = document.getElementById("TripCheckId" + BKID + "");
                if ((radiobtn.checked == true)) {
                    $('#triphischeck').prop('checked', false);
                    $('#triphischeck').trigger('change');

                    //tripVehicleArray = [];
                    //selectTripId.push(BKID);


                    //tripVehicleArray.push(BKID);
                    //tripArray.push(obj);
                    $('.historytriplist').show();
                    $('.triplist').show();
                    satuts = 0;
                   // getroutelatlng("test", imei, obj, "TripMap", tripArray, 'sTrip', BKID, 0, SDate, EDate, obj);
                }
                else {
                    //Remove Object from array based on value
                    /*
                    $.each(tripVehicleArray, function (i, el) {
                        if (this == BKID) {
                            tripVehicleArray.splice(i, 1);
                        }
                    });
                    

                    BookIdindex = selectTripId.indexOf(BKID); // 1
                   // if (BookIdindex != 0) {
                        removePolyline(BookIdindex);
                   // }
                    $.each(tripArray, function (i, el) {
                        if (this == obj) {
                            tripArray.splice(i, 1);
                        }
                    });
                     */
                    removeRoute(BKID);
                }
            }

            function Clearhistripmarkers() {

                if (startmarkers != null) {
                    $("input[name='triphis']:checkbox").prop('checked', false);
                    for (i = 0; i < lines.length; i++) {
                        lines[i].setMap(null); //or line[i].setVisible(false);
                    }
                    for (var i = 0; i < startmarkers.length; i++) {
                        startmarkers[i].setMap(null);
                    }
                    startmarkers = [];
                    for (var i = 0; i < endmarkers.length; i++) {
                        endmarkers[i].setMap(null);
                    }
                    endmarkers = [];

                    for (var i = 0; i < hismovingmarkers.length; i++) {
                        for (var j = 0; j < hismovingmarkers[i].length; j++) {
                            hismovingmarkers[i][j].setMap(null); //Remove the marker from the map
                        }
                    }


                    for (var j = 0; j < hisstoppedmarkers.length; j++) {
                        for (var i = 0; i < hisstoppedmarkers[j].length; i++) {
                            hisstoppedmarkers[j][i].setMap(null); //Remove the marker from the map
                        }
                    }


                    for (var l = 0; l < hisoverspeedmarkers.length; l++) {
                        for (var i = 0; i < hisoverspeedmarkers[l].length; i++) {
                            hisoverspeedmarkers[l][i].setMap(null); //Remove the marker from the map
                        }
                    }
                    hisMovearray.length = 0;
                    hisStoparray.length = 0;
                    hisOverSpeedarray.length = 0;
                    hisMovearray[0] = [];
                    hisOverSpeedarray[0] = [];
                    hisStoparray[0] = [];
                    hismovingmarkers.length = 0;
                    hisstoppedmarkers.length = 0;
                    hisoverspeedmarkers.length = 0;
                    m = 0;
                }
            }

            function removePolyline(index) {


                if (startmarkers[index] != null) {
                    lines[index].setMap(null); //or line[i].setVisible(false);
                    startmarkers[index].setMap(null);
                    endmarkers[index].setMap(null);

                    if (hisMovearray[0].length != 0) {
                        for (var i = 0; i < hisMovearray[0][0][index].length; i++) {
                            // if (hisMovearray[index].length != 0)
                            hismovingmarkers[index][i].setMap(null); //Remove the marker from the map
                        }
                    }
                    if (hisStoparray[0].length != 0) {
                        for (var j = 0; j < hisStoparray[0][0][index].length; j++) {
                            //if (hisstoppedmarkers[index].length != 0)
                            hisstoppedmarkers[index][j].setMap(null); //Remove the marker from the map
                        }
                    }
                    if (hisOverSpeedarray[0].length != 0) {
                        for (var l = 0; l < hisOverSpeedarray[0][0][index].length; l++) {
                            // if (hisoverspeedmarkers[index].length != 0)
                            hisoverspeedmarkers[index][l].setMap(null); //Remove the marker from the map
                        }
                    }



                    TripHisList.splice(index, 1);
                    selectTripId.splice(index, 1);
                    lines.splice(index, 1);
                    startmarkers.splice(index, 1);
                    endmarkers.splice(index, 1);
                    hismovinglist.splice(index, 1);
                    hisoverspeedlist.splice(index, 1);
                    hisstoppedlist.splice(index, 1);
                    if (hisMovearray[0].length != 0) {
                        hismovingmarkers.splice(index, 1);
                        hisstoppedmarkers.splice(index, 1);
                        hisoverspeedmarkers.splice(index, 1);
                    }
                    m = selectTripId.length;
                }
            }
            $scope.CustomDate = 0;
            $scope.hisCustomDate = 0;
            $scope.triptdate = new Date();
            var TripHisList = [];
            $scope.CustomDateChange = function (value) {

                var dt = new Date();
                if (value == '0') {
                    $('input.trpDt').prop('disabled', false);
                } else {
                    $('input.trpDt').prop('disabled', true);
                }
                $scope.tripfdate = new Date();
                $scope.triptdate = new Date();
                switch (parseInt(value)) {
                    case 1://Today
                    case 0://Coustom
                        $scope.triptdate = new Date();
                        break;
                    case 2://this week
                        $scope.tripfdate = new Date(dt.setDate(dt.getDate() - dt.getDay()));
                        break;
                    case 3://this month
                        $scope.tripfdate = new Date(dt.getFullYear(), dt.getMonth(), 1);
                        break;
                }
            }
            $scope.HistoryCustomDateChange = function (value) {
                var dt = new Date();
                if (value == '0') {
                    $(".histrpDt :input").attr("disabled", false);
                } else {
                    $(".histrpDt :input").attr("disabled", true);
                }
                $scope.fdate = new Date();
                $scope.tdate = new Date();
                switch (parseInt(value)) {
                    case 1://Today
                    case 0://Coustom
                        $scope.tdate = new Date();
                        break;
                    case 2://this week
                        $scope.fdate = new Date(dt.setDate(dt.getDate() - dt.getDay()));
                        break;
                    case 3://this month
                        $scope.fdate = new Date(dt.getFullYear(), dt.getMonth(), 1);
                        break;
                }
            }
            function GetFormattedDt(date, value) {

                var d = new Date(date);
                var res;
                switch (value) {
                    case 'd':
                        res = d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDate();
                }
                return res;
            }
            $scope.ShowSelectTrip = function (TripId, imei, BookID) {
                angular.forEach(TripHisList, function (value, key) {
                    if ((value.TripId == TripId) && (value.imeino == imei) && (value.BkId == BookID)) {
                        //  var bounds = new google.maps.LatLngBounds();
                        //var myLatlng1 = new google.maps.LatLng(value.eLat, value.eLong);
                        //bounds.extend(myLatlng1);
                        // var myLatlng = new google.maps.LatLng(value.sLat, value.sLong);
                        //  bounds.extend(myLatlng);
                        //  triphistorymap.fitBounds(bounds);
                        // loadaddress(value, 0, value.map, value.name, "0");
                    }
                });



            }

        

            ////// ____________ for dropdown by Abid ________________ \\\\\\
            function loadDropDown(tableName, UserOID, companyId, OrgOID, groupOID, CARTYPE, VehicleStatus, BookingStatus) {


                $.ajax({
                    cache: true,
                    url: ComonServiceUrl + "GetDropDownListMaster/" + tableName + "/" + UserOID + "/" + companyId + "/" + OrgOID + "/" + groupOID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    error: function () {

                    },
                    success: function (result) {

                        if (result.length != 0) {
                            $scope.BookingStatus = result;
                            $scope.selectedBookedStatus = result[0].Value;
                        }
                        $scope.$apply();


                    }
                });
            }
            loadDropDown("BookingStatusForMapView", userOID, companyOID, orgOID, groupOID);

          
            $scope.ReplayToMsgItem = function (id, driver, imei) {
                ReplayToMsg.open();
            }
            $scope.DeleteMsgItem = function (id) {
                DeleteMsg.open();
            }
            $scope.DeleteLandmarkItem = function (id, elm) {
                DeleteLandmark.open(id, elm);

            }

        }
    }])

TaxiApp.service('DeleteLandmark', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (lmid, landMarkBlock) {

        var modalInstance = $modal.open({
            windowClass: 'Delete_Landmark',
            templateUrl: 'DeleteLandmark.html',
            controller: 'DeleteLandmarkCtrl',
            resolve: {
                lmid: function () {
                    return lmid;
                },
                landMarkBlock: function () {
                    return landMarkBlock;
                }
            }

        });

    };

    return service;

})
TaxiApp.controller('DeleteLandmarkCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, $modalInstance, lmid, landMarkBlock) {


    $scope.loading = true;
    //sessionStorage.selectcompany = "Group";



    // LoadlanMark(orgOID, companyOID, sessionStorage.CityID);


    $scope.ClickClose = function () {

        $modalInstance.dismiss('Cancel');

    }


    $scope.DeleteLandmark = function ($lmid) {

        landmarks.deleteLandmark(lmid, landMarkBlock);
        $scope.ClickClose();

        // landmarks.delete(id);
    }
})

TaxiApp.service('EditDriverInfo', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (idd) {
        var modalInstance = $modal.open({
            windowClass: 'EditDriverInfo',
            templateUrl: 'EditDriverInfo.html',
            controller: 'EditDriverInfoCtrl',


        });

    };



    return service;
})
TaxiApp.controller('EditDriverInfoCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window,obj) {
    $scope.DriverPhoneNo = obj.DriverPhoneNo;
    var str = obj.DriverName;
    var name = str.split(" ");
    $scope.LastName=""
    $scope.FirstName = name[0];
    for (var i = 1; i < name.length; i++) {
        $scope.LastName+= name[i]+" ";
    }




    $scope.ClickClose = function () {

        // $modalInstance.dismiss('Cancel');

        $(".ngdialog-close").trigger("click");

    }
  //  console.log(obj);
    $scope.EditItem = function () {
            var fname = $('#changed_driver_first_name').val();
            var lname = $('#changed_driver_family_name').val();
            var no = $('#changed_driver_number').val();
            var name;
            if (fname != "" && lname != "" && no != "") {
                name = fname + " " + lname

                if ( name && no) {
                    $.ajax({
                        cache: true,
                        url: WebsiteServiceUrl + "UpdateDriverNameAndPhone/" + obj.DriverOID + "/" + sessionStorage.CompanyOID + "/" + name + "/" + no,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",
                        success: function (result) {
                            var res = result.UpdateDriverNameAndPhoneResult;


                            if (res >0) {
                                $(".ngdialog-close").trigger("click");

                            } else if (res == -1) {
                                alert("الرقم المدخل مستخدم لدى سائق اخر")

                            }
                            else if (res == -2) {
                                alert("حدث خطأ يرجى التأكد من المعلومات المدخلة")

                            }
                        }
                    });
                }

            }
            else
                alert("يرجى ادخال الاسم  كاملا والرقم ")


     

    }





})
function DateDiff(dt, now) {
    if (dt != "") {

     //   var converted = dt;
        var convertedNow = convertDateTimeFromAMPMTo24(now);
        convertedNow = convertedNow.slice(1, -1)

        var converted = dt;


        var recent_dt = new Date(converted);
        var now_dt = new Date(convertedNow);


        //var difference = now - recent_dt;

        //var newDate = new Date(difference);



        var timeDiff = Math.abs(now_dt.getTime() - recent_dt.getTime());


        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
        var diffMin = Math.ceil(timeDiff / (1000 * 60));


        if (timeDiff != "") {
            //var days = timeDiff.getDay();
            //var hours =newDate.getHours();
            var minutes = diffMin;
            //var seconds = newDate.getSeconds();

            //if (days > 0)
            //{
            //    return days + " ي";
            //}
            //if (hours > 0)
            //{
            //    return hours + " س";
            //}
            if (minutes > 0) {
                return minutes + " د";
            }
            else if (minutes < 0) {
                return "1 د";
            }
            //if (seconds > 0)
            //{
            //    return seconds + " ث";
            //}
            //else
            //{
            //    return "1 ث";
            //}
        }

    }
    else {
        return "N/A"
    }

    return "N/A";
}

function convertDateTimeFromAMPMTo24(dateString) {


    if (dateString.slice(-2) == "AM" || dateString.slice(-2) == "PM") {

        var dateArray = dateString.split(" ");

        var hour = dateArray[4];




        var hourArray = hour.split(":");

        var hourValue = parseInt(hourArray[0]);

        var AMPM = dateString.slice(-2);

        if (AMPM == "PM" && hourValue < 12)
            hourValue += 12;

        if (AMPM == "AM" && hourValue == 12)
            hourValue = 0;
        var convertedDateTime = dateArray[0] + " " + dateArray[1] + ", " + dateArray[2] + " " + hourValue + ":" + hourArray[1].substring(0, 2);

        return convertedDateTime;

    } else {
        var dateArray = dateString.split(" ");



        var convertedDateTime = dateArray[0] + " " + dateArray[1] + ", " + dateArray[2] + " " + dateArray[3];

        return convertedDateTime;
    }

}
