/// <reference path="NewAddBookingTable.js" />
var selectedDriverVMap = "";
var showAssignDialog = true;
var AssignBookDialogIsShown = false;
var AssignBookingIsInProgress = false;
var firstLoad = 1;
var olBookingList;
var AddItem;
var queue;
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    if (ev.target.className == 'row holderOne') {
        ev.dataTransfer.setData("text/plain", ev.target.lastChild.id);
    } else {
        ev.dataTransfer.setData("text/plain", ev.target.id);
    }
}
Number.prototype.pad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) { s = "0" + s; }
    return s;
}

Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

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

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


}
var booking = null;
var map;
var obj;
var TaxiApp = angular.module('NewAddBookingTableApp', ['ngStorage', 'ngDialog', 'angularSpinner', 'ui.bootstrap', 'angularAwesomeSlider', 'angular-growl', 'ngAnimate', 'AxelSoft', 'angular.filter']);

TaxiApp.controller('NewAddBookingTableCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'usSpinnerService', 'growl', 'CancelBooking', 'AddItemBefore', 'AddItemAfter',
    function ($scope, $http, $sessionStorage, ngDialog, usSpinnerService, growl, CancelBooking, AddItemBefore, AddItemAfter) {
        $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 OID = "0";
        var cOID, cName;
        var companyOID = sessionStorage.CompanyOID;
        var carsSource = 'C';
        $scope.logo = sessionStorage.Photo;
        $scope.DisplayName = sessionStorage.UserName;
        $scope.CompanyName = sessionStorage.value;
        var OLDpswd = sessionStorage.password;
        var cityOID = sessionStorage.CityID;
        var UserOID = sessionStorage.UserOID;
        var olBookingList;
        //Check Whether user Logged in or not
        //CheckUserLogged();
        $scope.logo = sessionStorage.Photo;
        var Vehiclename, vehicle;
       
        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);

        }
        if (sessionStorage.length == (undefined || 0)) {

            window.parent.location.href = "../../Index.html";
        }

        $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;      
    
       var notificationLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });

       
        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.Tile({
                source: new ol.source.OSM()
            }), notificationLayer
            ],
            target: 'bookingmap',
            pixelRatio: 1,
            view: new ol.View({
                center: ol.proj.transform([parseFloat(32), parseFloat(31)], 'EPSG:4326', 'EPSG:3857'),
                zoom: 8,
                minZoom: 1,
                maxZoom: 16
            })
        });
        setInterval(function () { map.updateSize(); }, 10);
      

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

            }
        };
        if (sessionStorage.RoleType == "Organization Admin") {
            $('.tele').show();
        }
        else {
            $('.tele').hide();
        }

        //var OnlineBokking = {
        //    HandledBookingIDs : new Array(),
        //    get: function () {
        //        // return $.Deferred().resolve(localStorage.getItem('comments'));

        //        return $.ajax({
        //            url: WebsiteServiceUrl + "GetCustomerAppBookingsForCompany/" + companyOID,
        //            cache: false
        //        });

        //    },
        //    poll: function () {
        //        var self = this;
        //        self.get().done(function (data) {
        //            // data = "0598a856464,0599201920,022423338";
        //             olBookingList = JSON.parse(data.GetCustomerAppBookingsForCompanyResult);
        //            if (olBookingList.length > 0) {
        //                for (c = 0; c < olBookingList.length; c++) {
        //                    if (self.HandledBookingIDs && !self.HandledBookingIDs.contains(olBookingList[c].BookingID)) {
        //                    booking.create({
        //                        driverOID: '',
        //                        DriverName: '',
        //                        CustomerName: olBookingList[c].CustomerName,
        //                        CustomerPhoneN: olBookingList[c].CustomerNo,
        //                        Landmark: olBookingList[c].FromPlace,
        //                        BookingID: olBookingList[c].BookingID,
        //                        IsDuplicate: false,
        //                        booking_id: olBookingList[c].BookingID,
        //                        booking_status: 'W',
        //                        IsOnline: true,
        //                        CustomerLat: olBookingList[c].CustomerLat,
        //                        CustomerLong: olBookingList[c].CustomerLong

        //                    });                          
        //                    self.HandledBookingIDs.push(olBookingList[c].BookingID);
        //                }                            
        //              }
        //            }              
        //        });
        //    },
        //    init: function (UL, interval) {
        //        var self = this;
        //        setInterval(function () {
        //            self.poll(UL);
                   
        //        }, interval);
        //        this.poll(UL);
              
        //    }

        //}
        //OnlineBokking.init('',5000);

        var comments = {
            call: function () {
                return $.ajax({
                    url: 'http://localhost:8090/dial?0599201920',
                    cache: false
                });
            },
            get: function () {
                // return $.Deferred().resolve(localStorage.getItem('comments'));

                return $.ajax({
                    url: 'http://localhost:8090/getcalls',
                    cache: false
                });

            },
            poll: function () {
                var self = this;
                self.get().done(function (data) {
                  //  data = "0598a856464,0599201920,022423338";
                    var callers = data.split(",");
                    for (c = 0; c < callers.length; c++) {
                        if (callers[c].length > 6 && isNumeric(callers[c])) {
                            var number = callers[c];
                            if (number.includes(":")) {
                                var n = number.indexOf(":")+1;
                                number = number.substr(n, number.length - n);
                            }
                            booking.create({
                                driverOID: '',
                                DriverName: '',
                                CustomerName: '',
                                CustomerPhoneN: number,
                                Landmark: '',
                                IsDuplicate: false
                            });
                        }
                    }
                });
            },
            init: function (UL, interval) {
                var self = this;
                setInterval(function () {
                    self.poll(UL);
                }, interval);
                this.poll(UL);
            }
        };

        comments.init('#Urunler', 5000);
   
      
        Dashboard = {
            DriversList: [],
            EnterpriseList: [],
          
            load: function () {
                self = this;
                $.ajax({
                    url: ComonServiceUrl + "getDashboardVehicles/" + companyOID + "/" + userOID + "/" + TokenID + "/" + carsSource,
                    data: {

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

                    success: function (result) {
                      //  var dashlist = JSON.parse(result.getDashboardVehiclesResult);
                        var List = result.getDashboardVehiclesResult;
                        List = List.split("~");
                        var dashlist = JSON.parse(List[1]);
                        self.loadDrivers(dashlist);
                        //booking.create({ driverOID: '', DriverName: '', booking_form_btn: '', CustomerPhoneN: '', Landmark: '', IsDuplicate: false });


                    }
                });

                $.ajax({
                    url: WebsiteServiceUrl + "GetEnterpriseCustomers/" + companyOID,
                    data: {

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

                    success: function (result) {
                        self.EnterpriseList = JSON.parse(result.GetEnterpriseCustomersResult);
                        console.log(self.EnterpriseList+"test")
                        //booking.create({ driverOID: '', DriverName: '', booking_form_btn: '', CustomerPhoneN: '', Landmark: '', IsDuplicate: false });


                    }
                });
            },
            loadDrivers: function (list) {
                this.DriversList = [];
                for (var i = 0; i < list.length; i++) {
                    driver = { DriverOID: list[i].DriverOID, DriverName: list[i].DriverName, IMEINumber: list[i].IMEIno, CorporateMobileNumber: list[i].DriverPhoneNo, RegistrationNo: list[i].VehRegisterNo };
                    this.DriversList.push(driver);
                }

                this.DriversList.push({DriverOID:"0", DriverName: "استفسار", IMEINumber: "0", CorporateMobileNumber:"", RegistrationNo:""});
                this.DriversList.push({ DriverOID: "-1", DriverName: "تحويل", IMEINumber: "0", CorporateMobileNumber: "", RegistrationNo: "" });

            


            }


        }

       

        booking = {

            hideBooking: function (_id) {
                $('#booking_TR' + _id).remove();
                $('#bookingValidation_TR' + _id).remove();
            },
            getEnterprise: function (name, oid) {
                var e = null;
                for (d = 0; d < Dashboard.EnterpriseList.length; d++) {
                    if (Dashboard.EnterpriseList[d].EnterpriseName == name || Dashboard.EnterpriseList[d].EnterpriseCustomerId == oid)
                        return Dashboard.EnterpriseList[d]
                }
                return null;
            },
            validateBookingForm: function (_id) {
                var lm = $('#landmark' + _id).val();
                var driver = $('#drivers_list' + _id).val();
                var driverid = $('#drivers_list' + _id).attr("DriverOID");
                var enterpriseName = $('#txtCompany' + _id).val();
                

                var customerName = $('#txtName' + _id).val();
                if ( driver && customerName && (lm != '' || driverid=='0') && driver != '' && customerName != '')
                    return true;
                return false;
            },
            createNewBooking: function (_id, customerName, customerPhone, fromLong, fromLat, lmOID, lmName, driverInfo, enterprise, isSchedulled, scheduleID,BookingID) {
                var self = this;
                var Bookingid = 0;
                var check = 1;
                if (!fromLong || fromLong == '')
                    fromLong = 0;
                if (!fromLat || fromLat == '')
                    fromLat = 0;
                if (!lmOID || lmOID == '')
                    lmOID = 0;
                var usrobj = {
                    "OID": BookingID,
                    "PhoneNumber": customerPhone,
                    "Name": customerName,
                    "PickUpDateTime": null,
                    "FromLocation": lmName,
                    "ToLocation": "",
                    "Comments": driverInfo.DriverOID == '0' ? "Q" : (driverInfo.DriverOID == '-1' ? "D" : "B"),
                    "CarType": 1,
                    "TelecallerOID": sessionStorage.UserOID,              
                    "CustomerLatTo": 0,
                    "CustomerLongTo": 0,
                    "EmpOID": sessionStorage.UserOID,        
                    "ORGOID": sessionStorage.ORGOID,
                    "CompanyId": sessionStorage.CompanyOID,
                    "EnterpriseCustomerId": (enterprise&&enterprise.EnterpriseCustomerId ? enterprise.EnterpriseCustomerId : null),
                    "Chkd": check,
                    "IMEINO": driverInfo.IMEINumber ? driverInfo.IMEINumber : '',
                    "DriverName": driverInfo.DriverName?driverInfo.DriverName:'',
                    "DriverPhoneNo": driverInfo.CorporateMobileNumber ? driverInfo.CorporateMobileNumber : '',
                    "VehRegisterNo": driverInfo.RegistrationNo ? driverInfo.RegistrationNo : '',
                    "driverOID": driverInfo.DriverOID? driverInfo.DriverOID:null
                };

                var userdata = {};
                userdata["oDSBookingObject"] = usrobj;
                if (Bookingid == 0) {

                    $.ajax({
                        type: "POST",
                        url: WebsiteServiceUrl + "DSCreateBookingFromMaps",
                        data: JSON.stringify(userdata),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        processData: true,
                        success: function (data) {

                            var result = data.DSCreateBookingFromMapsResult.split('~');
                            if (result[0].replace(/"/g, "") == "error") {
                                alert(result[1]);
                                $('#send_btn_' + _id).removeAttr('disabled');
                                return;
                            }
                            var bookingId = parseInt(result[0].replace(/"/g, ""));
                            $("#booking_id" + _id).attr('booking_id', bookingId);
                            $("#booking_id" + _id).attr('booking_status', 'A');
                            if (driverInfo.DriverOID == '0') {
                              
                                $("#booking_id" + _id).attr('booking_status', 'Q');
                                $("#send_btn_" + _id).html("تم");
                                $("#send_btn_" + _id).attr("disabled", '');
                                $('#BookingStatus' + _id).css('background-color', "green");
                            }
                            if (isSchedulled) {
                                BookList.removeSchedual(scheduleID);
                            }                             
                        },
                    });

                }

            },
            getDriverInfo: function (name, oid) {
                for (d = 0; d < Dashboard.DriversList.length; d++) {
                    if (Dashboard.DriversList[d].DriverName == name /*|| Dashboard.DriversList[d].DriverOID==oid*/)
                        return Dashboard.DriversList[d]
                }
                return null;
                return null;
            },
            listDrivers: function (_id) {
                for (d = 0; d < $scope.dashboardList.length; d++) {
                    $('#drivers_list' + _id).append($('<option>',
                    {
                        value: $scope.dashboardList[d].DriverOID,
                        text: $scope.dashboardList[d].DriverName,
                        'data-driver': $scope.dashboardList[d]
                    }));
                }
            },
            setBookingDriver: function (driverOID, _id) {
                $("#drivers_list" + _id).val(driverOID);
            },
            init: function () {
                var self = this;
                setInterval(function () {
                    self.getCreatedBooking();
                }, 5000);
            },
            cancelBooking: function (bookinid, imei, driveroid, _id) {
                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "CancelBookingFromMapView/" + bookinid + "/C",
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    success: function (result) {

                        $.ajax({
                            cache: true,
                            url: WebsiteServiceUrl + "SaveAnnouncementforCancel/" + sessionStorage.CompanyOID + "/" + sessionStorage.ORGOID + "/" + bookinid + "/" + imei + "/" + driveroid,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            error: function () {
                            },
                            success: function (result) {
                                $("#booking_id" + _id).attr('booking_status', 'C');
                                //$("#send_btn_" + _id).html("ارسال");
                                //$("#send_btn_" + _id).removeAttr("disabled");
                                //$scope.$apply();
                            }
                        });
                        
                    }
                })
            },
            getCusomerName: function (number, idx, obj) {
                slef = this;
                $scope.Name = "";
                if (booking.isCallrepeated(number))
                {
                    $("#txtName" + idx).addClass("repeated");
                    $("#txtphnumber1" + idx).addClass("repeated");


                }
                if (number != undefined) {
                    if (number.length >= 0) {

                        $scope.loading = true;
                        $.ajax({
                            cache: true,
                            url: WebsiteServiceUrl + "GetCustomerInfo/" + number + "/" + sessionStorage.CompanyOID,
                            type: 'GET',
                            //jsonpCallback: "loginResponse",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            error: function () {
                                $scope.loading = false;
                            },
                            success: function (result) {
                                var DepitAmount = 2000;
                                $scope.loading = false;
                                $scope.$apply();
                               
                                var response = JSON.parse(result.GetCustomerInfoResult);



                                if (response && response.CustomerName ) {
                                   
                                    $('#txtName' + idx).val(response.CustomerName);
                                    if (response && response.isBlackListed ) {
                                        $('#txtName' + idx).addClass('black_listed');
                                        $('#txtphnumber1' + idx).addClass('black_listed');

                                    }
                                    if (DepitAmount > 0) {
                                       // document.getElementById("DebitDiv").style.display = "inline-block"
                                    }
                                

                                } else  {
                                    $('#txtName' + idx).val("");

                                }

                                if (response && response.pickupAddress) {
                                    $('#landmark' + idx).val(response.pickupAddress);

                                    
                                }
                                else  {
                                    $('#landmark' + idx).val("");
                                }

                             
                                $scope.loading = false;

                            }
                        });
                    }
                }

            },
            CurrentBookingStatus: null,
            updateBookingStatus: function (bookingid, _id, _this) {
                var status = '';
                var dest = '';
                var d = new Date(); // for now
                var currentTime = d.getHours() + ":" + d.getMinutes();
                var bookingTime = $('#booking_time'+_id).val();
               
                var details = this.getBookingDetails(bookingid);
                if (!details)
                    return;

                var duration = ((new moment(currentTime, 'HH:mm')) -  (new moment(bookingTime, 'HH:mm')))/(1000*60);
                if (duration > 30 && details.BookingStatus=='E') {

                    _this.hideBooking(_id);
                }
                if (details.TripDestinationName) {
                    $('#landmark' + _id).val(details.TripDestinationName);
                    $('#landmark' + _id).css("color", "red")

                }
               
                switch (details.BookingStatus) {
                    case "B":
                     
                       $('#BookingStatus' + _id).css('background-color',  "blue");
                      
                       if ($("#booking_id" + _id).attr('booking_status') != 'C') {
                            $("#send_btn_" + _id).html("الغاء");
                            $("#send_btn_" + _id).removeAttr("disabled");
                        }
                        else {

                        }
                        break;
                    case "A":
                        if (details.TripDestination_RegionId == 0 || details.TripDestination_RegionId == null) {
                            $('#BookingStatus' + _id).css('background-color', "purple");
                            $("#booking_id" + _id).attr('booking_status', 'A');
                            $("#send_btn_" + _id).html("الغاء");
                            $("#send_btn_" + _id).removeAttr("disabled");
                        } else {
                            $("#send_btn_" + _id).attr("disabled", "disabled");
                            $('#BookingStatus' + _id).css('background-color', "red");
                            $("#send_btn_" + _id).attr("disabled", '');

                        }
                        
                        break;
                    case "C":
                        $('#BookingStatus' + _id).css('background-color',  "skyblue");
                        $("#booking_id" + _id).attr('booking_status', 'C');
                        $("#send_btn_" + _id).removeAttr("disabled");

                        $("#send_btn_" + _id).html("ارسال");
                        break;
                    case "E":
                        $('#BookingStatus' + _id).css('background-color', "white");
                        $("#booking_id" + _id).attr('booking_status', 'E');
                         $("#send_btn_" + _id).html("تم");
                        $("#send_btn_" + _id).attr("disabled",''); 

                        break;
                    case "R":
                        $('#BookingStatus' + _id).css('background-color',  "#2E2C2E");
                        $("#booking_id" + _id).attr('booking_status', 'R');
                        $("#send_btn_" + _id).removeAttr("disabled");

                        $("#send_btn_" + _id).html("ارسال");
                        break;
                    case "Q":
                        $("#send_btn_" + _id).html("تم");
                        $("#send_btn_" + _id).attr("disabled", '');
                        return "#6100ad";


                        break;
                    default:
                }

              


            },
           
            getBookingDetails: function (id) {
                var booking = null;
                for (var b = 0; (this.CurrentBookingStatus&& b < this.CurrentBookingStatus.length); b++) {
                    if (this.CurrentBookingStatus[b].bookingId == id)
                        return this.CurrentBookingStatus[b];
                }
                return booking;
            },
            bookingList: [],
            getCreatedBooking: function () {
                bookingIds = [];
                this.bookingList = [];
                var i = 0;
                var s = 0;
                var rows = document.getElementById("createdBookingTable").rows;
                for (var r = 1; r < rows.length; r++) {
                    if (rows[r] && rows[r].cells[0] && rows[r].cells[0].children[0] && rows[r].getAttribute('row_type')!='validation') {
                        var id = rows[r].cells[0].children[0].getAttribute('_id');

                        var bookingid = rows[r].cells[0].children[0].getAttribute('booking_id');

                        var bstatus = rows[r].cells[0].children[0].getAttribute('booking_status');
                        var bphone = rows[r].cells[2].children[0].value;
                        var bname = rows[r].cells[3].children[0].value;
                        var bfrom = rows[r].cells[4].children[0].value;
                        var bcompany = rows[r].cells[5].children[0].value;
                        // var bdriver = rows[r].cells[6].children[0].value;
                        var bdriver = $(rows[r].cells[6].children[0]).find("input").val();
                        this.bookingList[s] = { booking_id: bookingid, booking_status: bstatus, phone: bphone, name: bname, from: bfrom, enterprise: bcompany, driver: bdriver };
                        s++;
                        var bookingStatus = rows[r].cells[0].children[0].getAttribute('booking_status');
                        if (bookingid && bookingStatus && bookingStatus != 'U' && bookingStatus != 'E' && bookingStatus != 'Q') {
                            this.updateBookingStatus(bookingid, id, this);
                           
                            bookingIds[i] = bookingid;
                            i++;
                        }
                    }
                }
                sessionStorage.setItem("BookingList", JSON.stringify(this.bookingList));

                

                this.loadInprogressBooking(bookingIds);

            },
            loadInprogressBooking: function (ids) {
                var self = this;
                if (ids.length) {
                    var bookingObj = {};
                    bookingObj.bookingIdsObject = {
                        companyId: sessionStorage.CompanyOID,
                        bookingIdsList: ids
                    };

                    $.ajax({
                        type: "POST",
                        url: WebsiteServiceUrl + "GetBookingsStatus",
                        data: JSON.stringify(bookingObj),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        processData: true,
                        success: function (result) {
                            self.CurrentBookingStatus = JSON.parse(result.GetBookingsStatusResult);


                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {

                        }
                    });
                }
            },
            isCallrepeated: function (number) {
                var repeated = false;
                if (this.bookingList && this.bookingList.length > 0) {
                    for (var b = 0; b < this.bookingList.length; b++) {
                      
                        if (number == this.bookingList[b].phone)
                            return true;

                    }
                }
                return false;
            },
            loadSession: function () {
                var BookingList = JSON.parse(sessionStorage.getItem("BookingList"));
                if (BookingList && BookingList.length > 0) {
                    for (var b = 0; b < BookingList.length; b++) {
                        booking.create({
                            driverOID: '',
                            DriverName: BookingList[b].driver,
                            CustomerName: BookingList[b].name,
                            CustomerPhoneN: BookingList[b].phone,
                            Landmark: BookingList[b].from,
                            IsDuplicate: false,
                            IsSession : true,
                            booking_id: BookingList[b].booking_id,
                            booking_status: BookingList[b].booking_status
                        });

                    }
                    booking.getCreatedBooking();
                }
            },
            create: function (obj) {
           
                var self = this;
                var _id =  new Date().getTime();

                var d = new Date(); // for now
                var time = (d.getHours()>12?(d.getHours()-12).pad():d.getHours()) + ":" + d.getMinutes().pad();


/*------------------------------------------------- Validation TR -------------------------------------------------*/

                var bookingValidation_TR = document.createElement("tr");
                bookingValidation_TR.id = "bookingValidation_TR" + _id;
                bookingValidation_TR.setAttribute('row_type', 'validation');
                bookingValidation_TR.className = "bookingValidation_TR";
               var bookingValidation_td = document.createElement("td");
               var validate_msg = document.createElement("span");
               validate_msg.innerHTML = "الرجاء التاكد من ادخال اسم وعنوان الزبون واسم السائق";
               validate_msg.id = "validate_msg";
               bookingValidation_td.appendChild(validate_msg);
               bookingValidation_td.setAttribute("colspan", "12");
               bookingValidation_TR.appendChild(bookingValidation_td);

/*-----===================-------------------------- NewBooking TR -----------------------------------------------*/



                var booking_TR = document.createElement("tr");
                booking_TR.className = "bookingTR";
                booking_TR.id = "booking_TR" + _id;
                booking_TR.style.border = 0;
              
                var th1 = document.createElement("td");
                var bookingid_input = document.createElement("input");
                bookingid_input.setAttribute('hidden', ''); //
              
                bookingid_input.style.width = "1px";
                bookingid_input.id = 'booking_id' + _id;
                bookingid_input.setAttribute('_id', _id);
                th1.appendChild(bookingid_input);
                booking_TR.appendChild(th1);
                if (obj && obj.booking_id) {
                    bookingid_input.setAttribute('booking_id', obj.booking_id); //
                    bookingid_input.setAttribute('booking_status', obj.booking_status); //bookingValidation_TR
                }
                else {
                    bookingid_input.setAttribute('booking_id', 'U'); //
                    bookingid_input.setAttribute('booking_status', 'U'); //bookingValidation_TR
                }

                if (obj.IsOnline) {
                    bookingid_input.setAttribute('lat', obj.CustomerLat);
                    bookingid_input.setAttribute('long', obj.CustomerLong);
                }
 /*-------------------------------------------------- Time ------------------------------------------------------*/
                var td0 = document.createElement("td");
                var time_input = document.createElement("input");
                time_input.setAttribute('type', 'text');
                time_input.setAttribute('maxLength', '15'); //
                td0.appendChild(time_input);
                time_input.style.height = "38px";
                time_input.className = "form-control";
                time_input.setAttribute("disabled","");
                time_input.style.cursor="default";
                time_input.setAttribute('value', time);
                time_input.id = "booking_time"+_id;
                time_input.setAttribute('rowID', _id);

                booking_TR.appendChild(td0);
/*-------------------------------------------------- phone -------------------------------------------*/
                var td1 = document.createElement("td");
                var phone_input = document.createElement("input");
                phone_input.setAttribute('type', 'text');
                phone_input.setAttribute('maxLength', '15'); //
                phone_input.onkeypress = function () { return onlyNumbers(event); };
                phone_input.setAttribute('value', obj.CustomerPhoneN);
                phone_input.className = "form-control booking_customer_mobile_number";
                phone_input.id = "txtphnumber1" + _id;
                phone_input.setAttribute('rowID', _id);
                phone_input.setAttribute("maxlength","10");
                phone_input.setAttribute("minlength","9");

                td1.appendChild(phone_input);
                phone_input.style.height = "38px";
                booking_TR.appendChild(td1);

 /*----------------------------------------------------- Name----------------------------------------------*/

                var td2 = document.createElement("td");
                var name_input = document.createElement("input");
                name_input.setAttribute('type', 'text');
                name_input.setAttribute('value', (obj.CustomerName == null ? '' : obj.CustomerName));
                name_input.className = "form-control booking_customer_name";
                name_input.id = "txtName" + _id;
                name_input.setAttribute('rowID', _id);
                name_input.style.height = "38px";
                name_input.maxLength = "50";

                var txt = document.createTextNode("2500");
                var DebitDiv = document.createElement("div");
                DebitDiv.className = "DebitDiv";
                DebitDiv.id = "DebitDiv";
                var Debit = document.createElement("span");
                Debit.appendChild(txt);
                
                DebitDiv.appendChild(Debit);

                td2.appendChild(name_input);
                td2.appendChild(DebitDiv);
                booking_TR.appendChild(td2);
              
              
           

 /*--------------------------------------------- land mark -------------------------------------------------*/
                var td4 = document.createElement("td");
                var divselect;
                var landmark_input = document.createElement("input");
                landmark_input.setAttribute('type', 'text');
                landmark_input.setAttribute('value', obj.Landmark);
                landmark_input.className = "form-control Lnfmrk_input booking_customer_landmark";
                landmark_input.style.display = "inline-block";
                landmark_input.id = "landmark" + _id;
                landmark_input.setAttribute('rowID', _id);
                landmark_input.setAttribute('onkeypress', "");
                landmark_input.maxLength = "50";
                landmark_input.style.height = "38px";
                /*-------------- F8 UL ---------------*/

                        function makeUL() {
                            // Create the list element:
                            var list = document.createElement('ul');
                            list.id = "landmark_list" + _id;
                            list.setAttribute("tabindex", "1");
                            list.className = "List";

                 
                   
                            // Finally, return the constructed list:
                            return list;
                        }
                        var list = makeUL();
                        list.style.display = "none";
                        list.className = "AddressList";             
                        var company_input ;
                        landmark_input.onkeydown = function (evt) {
                            if ($(phone_input).val() != "" && list.childNodes.length > 0) {
                                if (evt.keyCode == 119) { // F8
                                   

                                    $(list).find("li").removeClass("selected");
                                    $(list).find("li").removeClass("Choosen");

                                    list.style.display = "block";
                                    list.focus();
                                    var liSelected;
                                    var li = $(list).find(".liEllipsis");
                                    $("#landmark_list" + _id).unbind("keydown");



                                    $("#landmark_list" + _id).on('focus', 'li', function() {
                                        $this = $(this);
                                        $this.addClass('Choosen').siblings().removeClass();
                                        $this.closest($("#landmark_list" + _id)).scrollTop($this.index() * $this.outerHeight());
                                    }).on('keydown', 'li', function(e) {
                                        $this = $(this);
                                        if (e.keyCode == 40) {        
                                            $this.next().focus();
                                           
                                            return false;
                                        } else if (e.keyCode == 38) {        
                                            $this.prev().focus();
                                          
                                            return false;
                                        } else if (e.keyCode === 13) {
                                          
                                            var selectedItem = $(list).find(".Choosen").html();

                                         
                                            landmark_input.value = selectedItem;
                                            list.style.display = "none";
                                            landmark_input.focus();
                                           

                                        }
                                        else if (e.keyCode === 27) {
                                            list.style.display = "none";
                                            landmark_input.focus();
                                        }



                                    }).click(function () {
                                         var selectedItem = $(list).find(".Choosen").html();
                                         landmark_input.value = selectedItem;
                                        list.style.display = "none";
                                        landmark_input.focus();
                                    })
                                    
                                    
                                    .find('li').first().focus();
                                  

                                   

                                }
                              
                            }
                            else {
                          


                            }
                        }
                    
                var lmAwesomplete = null;
                td4.appendChild(landmark_input);
                td4.appendChild(list);
                booking_TR.appendChild(td4);

/*------------------------------------------- Enterprise-----------------------------------------------------*/

                var td3 = document.createElement("td");
                company_input = document.createElement("input");
                company_input.setAttribute('type', 'text');
                company_input.className = "form-control ";
                company_input.id = "txtCompany" + _id;
                company_input.setAttribute('rowID', _id);
                company_input.setAttribute('value', obj.Company?obj.Company:'');


                // company_input.setAttribute('hidden', ''); //
                company_input.maxLength = "50";
                td3.appendChild(company_input);
                booking_TR.appendChild(td3);
                company_input.style.height = "38px";
                var enterpriseAwesomplete = new Awesomplete(company_input, {
                    list: Dashboard.EnterpriseList,
                    data: function (item, input) {
                     
                        return { label: item.EnterpriseName, value: item.EnterpriseCustomerId };
                       
                    },
                    autoFirst: true,
                    minChars: 3
                   
                });
                company_input.addEventListener('awesomplete-selectcomplete', function (item) {
                    $('#txtCompany' + _id).attr("OID", item.text.value);
                });
 /*------------------------------------------------- Driver -------------------------------------------------*/

                var td5 = document.createElement("td");


                var driver_select = document.createElement("input");
                driver_select.className = "col_md_8 form-control   booking_customer_driver_name";
                driver_select.style.width = "100%";
                driver_select.style.padding = "0px";
                driver_select.style.height = "38px";
                //driver_select.style.marginTop = "4px";
                driver_select.style.borderRadius = "5px"
                //driver_select.style.float = "left";
                driver_select.style.display = "inline-block";
                driver_select.id = "drivers_list" + _id;
                driver_select.setAttribute('rowID', _id);
                driver_select.setAttribute('value', obj.DriverName ? obj.DriverName : '');
                driver_select.setAttribute("ondrop", "drop(event,this)");
                driver_select.setAttribute("ondragover", "allowDrop(event)");
                td5.appendChild(driver_select);
                booking_TR.appendChild(td5);
               var Toupdate= document.getElementById("AddBookingTable")
                var driverAwesomplete = new Awesomplete(driver_select, {

                    list: Dashboard.DriversList,
                    data: function (item, input) {
                     
                        return { label: item.DriverName, value: item.DriverOID };
                       
                    },
                    autoFirst: true,
                    minChars: 1
                  
                });
            
                driver_select.addEventListener('awesomplete-selectcomplete', function (item) {
                   
                    $('#drivers_list' + _id).attr("DriverOID", item.text.value);
                    
                });

             


/*------------------------------------------- btn ------------------------------------------------*/

                var td8 = document.createElement("td");
                var BookingStatus = document.createElement("div");
                BookingStatus.className = "BookingStatus";
                BookingStatus.id='BookingStatus'+_id;
                td8.appendChild(BookingStatus);
                booking_TR.appendChild(td8);

/*------------------------------------------ send------------------------------------------------*/

                var Btn_sendDiv = document.createElement("div");
                Btn_sendDiv.className = "col-md-6";
                Btn_sendDiv.style.padding = "0";
                var send_btn = document.createElement("button");
                send_btn.id = "send_btn_" + _id;
                send_btn.setAttribute('rowID', _id);
                var td6 = document.createElement("td");

                send_btn.type = "button";
                send_btn.className = "booking_form_btn booking_customer_send_booking";
                var send_btn_lbl = document.createTextNode("ارسال");
                send_btn.appendChild(send_btn_lbl);

                send_btn.onclick = function () {
                    $("#send_btn_" + _id).attr("disabled", "disabled");
                    var drivername = $('#drivers_list' + _id).val();
                    var driveroid = $('#drivers_list' + _id).attr("DriverOID");

                    var enterpriseName = $('#txtCompany' + _id).val();
                    var driverInfo = self.getDriverInfo(drivername, driveroid);
                    if (driverInfo) {
                        $('#drivers_list' + _id).attr("DriverOID", driverInfo.DriverOID);
                        $('#drivers_list' + _id).attr('IMEINO', driverInfo.IMEINumber);
                    }

                    var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                    var index = fields.index(this);

                 
                    
                    var enterpriseId = $('#txtCompany' + _id).attr("OID");
                    var bookingid = $("#booking_id" + _id).attr('booking_id');
                    var booking_status = $("#booking_id" + _id).attr('booking_status');
                    if (booking_status == 'U' || booking_status == 'C' || booking_status == 'R' || booking_status == 'W') {
                       if (!self.validateBookingForm(_id) || driverInfo == null) {
                           //  alert('الرجاء التاكد من ادخال اسم وعنوان الزبون واسم السائق');
                           bookingValidation_TR.style.display = "table-row";
                           $('#txtName' + _id).css("border-color", "red");
                           $('#landmark' + _id).css("border-color", "red");
                           $('#drivers_list' + _id).css("border-color", "red");

                           $("#send_btn_" + _id).removeAttr("disabled");
                           index = index < 0 ? 0 : index;
                           fields.eq(index).focus();
                           return;
                       }
                     

                       var enterPriseInfo = self.getEnterprise(enterpriseName, enterpriseId);
                       if (enterpriseName && enterpriseName != '' && (!enterPriseInfo || !enterPriseInfo.EnterpriseCustomerId || enterPriseInfo.EnterpriseCustomerId=='')) {
                           bookingValidation_TR.innerHTML = "<td colspan='12' style='color: red;font-weight: 600;'>الرجاء ادخال اسم المؤسسة بشكل صحيح</td>";
                           $('#txtCompany' + _id).css("border-color", "red");
                           bookingValidation_TR.style.display = "table-row";

                           $("#send_btn_" + _id).removeAttr("disabled");
                           index = index < 0 ? 0 : index;
                           fields.eq(index).focus();
                           return;
                       }
                     
                       self.createNewBooking(
                           _id,
                       $('#txtName' + _id).val(),
                       $('#txtphnumber1' + _id).val(),

                       $('#landmark' + _id).attr("long"),
                        $('#landmark' + _id).attr("lat"),
                      $('#landmark' + _id).attr("LandmarkOID"),
                       $('#landmark' + _id).val(),
                           driverInfo,
                           enterPriseInfo, obj.isSchedulled, obj.scheduleID,
                           obj.BookingID ? obj.BookingID : 0
                       );
                       bookingValidation_TR.style.display = "none";
                       $('#txtName' + _id).css("border-color", "#ccc");
                       $('#landmark' + _id).css("border-color", "#ccc");
                       $('#drivers_list' + _id).css("border-color", "#ccc");
                       $('#txtCompany' + _id).css("border-color", "#ccc");

                      /*
                       send_btn.onclick = function () {
                           $scope.CancelBookingItem();
                          
                       }
                      */

                     
                     
                   }
                    else {
                        var driverInfo = self.getDriverInfo(drivername, driveroid);
                        if (driverInfo) {

                        }
                       var imei = $('#drivers_list' + _id).attr('IMEINO');
                       if (bookingid != null && bookingid != '' && driveroid != null && driveroid != '') {

                           self.cancelBooking(bookingid, imei, driveroid, _id);
                           
                       }
                       else {
                         
                           bookingValidation_TR.innerHTML = "تعذر الغاء الطلب";
                           bookingValidation_TR.style.display = "table-row";
                       }
                   }
                    index = index < 0 ? 0 : index;
                    fields.eq(index + 1).focus();
                   
                   
                };
                td6.appendChild(send_btn);
                booking_TR.appendChild(td6);


/*----------------------------------------- close ------------------------------------------------*/


                var td7 = document.createElement("td");

                var Btn_closeDiv = document.createElement("div");
                Btn_closeDiv.className = "col-md-6";
                Btn_closeDiv.style.padding = "0";
                Btn_closeDiv.style.textAlign = "left";
                var close_btn = document.createElement("button");
                close_btn.type = "button";

                close_btn.className = "booking_form_btn";
                close_btn.id = 'close_btn' + _id;
                close_btn.setAttribute('rowID', _id);

                var close_btn_lbl = document.createTextNode("اغلاق");
                close_btn.onclick = function () {
                    var me = $(this).parents('form:eq(0),body');

                    var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                    var index = fields.index(this);
                    
                       // index -= 7
                   
                    self.hideBooking(_id);
                    var fields = me.find('button, input, textarea, select');

                    
                    index = index <= 7 ? (fields.length > 16 ? 16 : 0) : index;
                    index = index > fields.length-7 ? fields.length-7 : index;
                    fields.eq(index).focus();
                };
                close_btn.appendChild(close_btn_lbl);

                Btn_closeDiv.appendChild(close_btn);
                td7.appendChild(close_btn);
                booking_TR.appendChild(td7);

              
                $('table').append(booking_TR);
                $('table').append(bookingValidation_TR);

/*------------------------------------ arrows navigation  ------------------------------------------------*/

                $('input').keypress(function (evt) {
                    if (evt.keyCode == 13) {//enter
                        iname = $(this).val();
                        if (iname !== 'Submit') {
                            var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                            var index = fields.index(this);
                            if (index > -1 && (index + 1) < fields.length) {
                                fields.eq(index + 1).focus();
                            }
                            return false;
                        }
                    }
                   

                });

                $('input').unbind('keydown');
                $('button').unbind('keydown');
                $('input').add('button').keydown(function (evt) {
                   
                    if (evt.keyCode == 37 && !evt.ctrlKey) {//left arrow	
                        evt.stopImmediatePropagation();
                        if (!driverAwesomplete.isOpen() ) {
                            iname = $(this).val();
                            if (iname !== 'Submit') {
                                var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                                var index = fields.index(this);
                                if (index > -1 && (index + 1) < fields.length) {
                                    if (fields.eq(index + 1).attr('disabled') == null) {
                                    fields.eq(index + 1).focus();
                                }
                                    else {
                                        fields.eq(((index + 2) < fields.length?index + 2:index+1)).focus();
                                    }
                                }
                                return false;
                            }
                        }
                    }

                    if (evt.keyCode == 39 && !evt.ctrlKey) {//right arrow	
                         evt.stopImmediatePropagation();
                         if (!driverAwesomplete.isOpen() ) {
                            iname = $(this).val();
                            if (iname !== 'Submit') {
                                var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                                var index = fields.index(this);
                                if (index > -1 && (index - 1) > -1) {
                                    if (fields.eq(index - 1).attr('disabled') == null) {
                                    fields.eq(index - 1).focus();
                                    } else {
                                        fields.eq(((index -2) > -1 ? index - 2 : index -1)).focus();

                                    }
                                }
                                return false;
                            }
                        }
                    }
                   
                    if (evt.keyCode == 119) {//118
                        comments.call();
                    }

                    if (evt.keyCode == 40) {//down arrow	

                        if (!driverAwesomplete.opened ) {

                                iname = $(this).val();
                                if (iname !== 'Submit') {
                                    var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                                    var index = fields.index(this);
                                    if (index > -1 && (index + 14) < fields.length) {
                                        fields.eq(index + 9).focus();
                                       // return true
                                    }
                                    else if ((index + 14) > fields.length) {
                                        booking.create({ driverOID: '', DriverName: '', CustomerName: '', CustomerPhoneN: '', Landmark: '', IsDuplicate: false });
                                        var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                                        fields.eq(index + 9).focus();

                                    }

                                    return false;
                                }
                            }

                        }
                    if (evt.keyCode == 38) { //up arrow
                        if (!driverAwesomplete.opened ) {
                                iname = $(this).val();
                                if (iname !== 'Submit') {
                                    var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                                    var index = fields.index(this);
                                    if (index > -1 && (index - 9) > -1) {
                                        fields.eq(index - 9).focus();
                                    }
                                    return false;
                                }
                            }
                    }
                    if (evt.keyCode == 46) { // Delete
                      
                        if (this.value)
                            this.value = "";

                    }
                    if (evt.keyCode == 121) { // F10
                        booking.create({ driverOID: '', DriverName: '', CustomerName: '', CustomerPhoneN: '', Landmark: '', IsDuplicate: false });
                    
                            return false;
                     

                    }
                    if (evt.keyCode == 120) { // F10

                        var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                        var index = fields.index(this);
                        var rowid = 0;
                        if (fields[index].getAttribute('rowID'))
                            rowid = fields[index].getAttribute('rowID');
                        else
                            return;

                        var customerNo = $('#txtphnumber1' + rowid).val();
                        var customerName = $('#txtName' + rowid).val();
                        var address = $('#landmark' + rowid).val();
                        var company = $('#txtCompany' + rowid).val();

                        booking.create({ driverOID: '', DriverName: '', CustomerName: customerName, CustomerPhoneN: customerNo, Landmark: address, Company: company, IsDuplicate: true });

                        return false;


                    }
                    if (evt.keyCode == 118) { // F7
                        var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
                        var index = fields.index(this);
                        var rowid = 0;
                        if (fields[index].getAttribute('rowID'))
                            rowid = fields[index].getAttribute('rowID');
                        else
                            return;

                        if ($('#txtphnumber1' + rowid).hasClass("online"))
                       {
                           // ViewCustomerCoordinates.open();

                            $('#myModal').modal('toggle');
                           
                            ViewCustomerLocation($("#booking_id" + rowid).attr("lat"), $("#booking_id" + rowid).attr("long"));

                        }


                    }
                  
                });
             
/*-------------------------------------------------- IsDuplicate  --------------------------------------------------*/
             if (!obj.IsDuplicate  && !obj.IsSession && !obj.IsOnline) {
                    $('#txtphnumber1' + _id).change(function () {
                        var no = ($('#txtphnumber1' + _id)).val();
                        obj.CustomerName = self.getCusomerName(no, _id, obj);
                    });

                    if (obj.CustomerPhoneN != '') {
                        $('#txtphnumber1' + _id).change();
                    }
                }
              //  var currentFocusedElement = $(':focus');
             if (obj.IsOnline) {
                 $("#txtName" + _id).addClass("online");
                 $("#txtphnumber1" + _id).addClass("online");
                 $("#landmark" + _id).addClass("online");
                 $("#txtCompany" + _id).addClass("online");
                 $("#drivers_list" + _id).addClass("online");





                
             }
                booking.updateScroll();

             
            },
            updateScroll: function () {
                var element = document.getElementById("AddBookingTable");
                element.scrollTop = element.scrollHeight;
            }
        }


/*-------------------------------------------------- queue  --------------------------------------------------*/
         queue = {
            hashCode: function(str) { // java String#hashCode
                var hash = 0;
                for (var i = 0; i < str.length; i++) {
                    hash = str.charCodeAt(i) + ((hash << 5) - hash);
                }
                return this.intToRGB(hash);
            },

            intToRGB: function(i){
                var c = (i & 0x00FFFFFF)
                    .toString(16)
                    .toUpperCase();

                return "00000".substring(0, 6 - c.length) + c;
            },
            show: function () {
                $("#Order_list").toggle();
                if ($('#Order_list').is(":visible")) {
                    this.refresh();
                }
            },
            hide: function () {
                if ($('#Order_list').is(":visible")) {
                    $("#Order_list").toggle();
                }
            },
            DeleteVehicleFromQueue: function (driverid) {
                var self = this;
                $scope.loading = true;
                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "DeleteVehicleFromQueue/" + driverid + "/" + sessionStorage.CompanyOID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    success: function (result) {
                        self.refresh();
                        $scope.loading = false;
                    },
                    error: function () {
                        $scope.loading = false;
                    }
                });
            },
            populate: function (q) {
                var self = this;
                var div = $("#queue");
              
                var Order_item = document.createElement("div");
                Order_item.setAttribute('action_date', q.Date)
                Order_item.setAttribute('action_time', q.Time)
                Order_item.className = "Order_item ";
                var holderOne = document.createElement("div");
                holderOne.className = "row holderOne";
                holderOne.setAttribute("draggable", "true");
                holderOne.setAttribute("ondragstart", "drag(event)");

                var t = document.createTextNode(q.Order);
                var driver_turn = document.createElement("div");
                driver_turn.appendChild(t);
                driver_turn.className = "driver_turn";
                driver_turn.style.cssText = 'border: 5px double #' + this.hashCode(q.RegionName);
                holderOne.appendChild(driver_turn);
                driver_turn.ondblclick = function (e) {
                    booking.create({

                        driverOID: '',
                        DriverName: '',
                        CustomerName: '',
                        CustomerPhoneN: '',
                        Landmark: '',


                        IsDuplicate: true
                    })


                }
           
                var driver = document.createTextNode(q.Name);
                var Order_dirver_name = document.createElement("option");
                Order_dirver_name.appendChild(driver);
                Order_dirver_name.className = "Order_dirver_name";
                holderOne.appendChild(Order_dirver_name);
                Order_dirver_name.setAttribute("draggable", "true");
                Order_dirver_name.setAttribute("ondragstart", "drag(event)");
                Order_dirver_name.id = q.Name;
                Order_dirver_name.onclick = function () {

                }

              
                var holderTwo = document.createElement("div");
                holderTwo.className = "row holderTwo";

                var d = document.createTextNode(q.Time);
                var date = document.createElement("h6");
                date.className = "col-md-3 turn_date"
                date.appendChild(d);
                holderTwo.appendChild(date);

                var deleteItem = document.createElement("div");
                deleteItem.innerHTML = "<i class='fa fa-minus-circle' style='color:red;    font-size: 15px;' aria-hidden='true'></i>";
                deleteItem.style.display = "inline-block";
                deleteItem.style.padding = "0px";
                deleteItem.style.marginTop = "6px";

                deleteItem.style.cursor = 'pointer';
                deleteItem.className = "col-md-2";
                deleteItem.setAttribute("data-id", q.DriverId);
                holderTwo.appendChild(deleteItem);
                deleteItem.onclick = function () {
                    var id = $(this).attr('data-id');
                    //   alert(id);
                    self.DeleteVehicleFromQueue(id);
                    //self.refresh();


                }
                var CnameTXT = document.createTextNode(q.RegionName);
                var Cname = document.createElement("h6");
                Cname.className = "col-md-5 turn_cname"
                Cname.appendChild(CnameTXT);
                holderTwo.appendChild(Cname);


                var SubMenu = document.createElement("div");

                SubMenu.setAttribute("data-id", q.DriverId);
                SubMenu.className = 'menu';



                SubMenu.id = 'menu' + q.DriverId;
                SubMenu.innerHTML = "<ul><a onclick= AddItem.addBefore(" + q.DriverId + ",'" + q.Date + "','" + q.Time + "')><li>اضافة قبل " + q.Name+ "</li></a></ul>"
                //var Order_num = document.createElement("p");
                //var d = document.createTextNode(q.No);
                //Order_num.appendChild(d);
                //Order_num.className = "col-md-7 Order_num";
                //holderTwo.appendChild(Order_num);



                Order_item.appendChild(holderOne);
                Order_item.appendChild(holderTwo);
                Order_item.appendChild(SubMenu)

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


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


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

                    tick();
                }

                fadeIn(Order_item);

                div.append(Order_item);
            },
            get: function () {
                return $.ajax({
                    url: WebsiteServiceUrl + '/GetVehicleQueueSummary/' + sessionStorage.CompanyOID,
                    cache: false
                });
            },

            refresh: function () {
                $('#queue').empty();
                var self = this;
                self.get().done(function (result) {
                    var queueList = JSON.parse(result.GetVehicleQueueSummaryResult);
                    for (n = 0; n < queueList.length; n++) {
                        self.populate({ Order: n + 1, No: queueList[n].VehicleNumber, Name: queueList[n].DriverName, Time: queueList[n].Time, Date: queueList[n].Date, RegionName: queueList[n].RegionName, DriverId: queueList[n].DriverId });
                    }

                });
            },
            init: function (interval) {
                var self = this;
                setInterval(function () {
                    self.refresh();
                }, interval);
                this.refresh();
            }
      
        }
        AddItem = {
            addBefore: function (id,date,time) {
                AddItemBefore.open(id,date,time);
              //  alert("before"+id)
            },
            addAfter: function (id) {
                
                AddItemAfter.open(id);

          //  alert("after"+id)
        }



        }
        AddNewDriverBooking =function(){
            var today = new Date();
            var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
            var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

            var dateArray = date.split("-");
            var timeArray = time.split(":");

            var formatedTime = timeArray[0] + "~" + timeArray[1] + "~" + timeArray[2];

            var year = dateArray[0];
            var month = dateArray[1];
            var day = dateArray[2];

            if (month < 10) {

                month = "0" + month;
            }

            if (day < 10) {

                day = "0" + day;
            }

            var formatedDate = year + "-" + month + "-" + day;



            AddItemBefore.open(-1, formatedDate, formatedTime);
        }
        $(document).ready(function () {

            $("#queue").on("contextmenu", function (e) {
                //prevent default context menu for right click
                e.preventDefault();
              //  var temp = e.target.id;

                //if()

                var order_item = $(e.target).closest(".Order_item");
               
                var id = order_item.find(".menu").attr('data-id');
                if (!id) {
                   
                  

                } else {
                
                 var menu = $('#menu' + id);

                //hide menu if already shown
                 $(".menu").hide();

                //get x and y values of the click event
                var pageX = e.pageX;
                var pageY = e.pageY;

                //position menu div near mouse cliked area
                menu.css({ top: pageY, left: pageX });

                var mwidth = menu.width();
                var mheight = menu.height();
                var screenWidth = $(window).width();
                var screenHeight = $(window).height();

                //if window is scrolled
                var scrTop = $(window).scrollTop();

                //if the menu is close to right edge of the window
                if (pageX + mwidth > screenWidth) {
                    menu.css({ left: pageX - mwidth });
                }

                //if the menu is close to bottom edge of the window
                if (pageY + mheight > screenHeight + scrTop) {
                    menu.css({ top: pageY - mheight });
                }

                //finally show the menu
                menu.show();
                }
                //alert(id);
               
            });

            $("#queue").on("click", function () {
                $(".menu").hide();
            });
        });
/*----------------------------------------------------  BookList ------------------------------------------------------*/
        var BookList = {     
            populate: function (obj) {
                var self = this;
                obj.CustomerName = !obj.CustomerName || obj.CustomerName == 'null' ? '' : obj.CustomerName;

                obj.CustomerPhoneN = !obj.CustomerPhoneN || obj.CustomerPhoneN == 'null' ? '' : obj.CustomerPhoneN;
                obj.FromLocation = !obj.FromLocation || obj.FromLocation == 'null' ? '' : obj.FromLocation;
                obj.Time = !obj.Time || obj.Time == 'null' ? '' : obj.Time;

              
                var div = $("#BookList");
                var BookList_item = document.createElement("div");
                BookList_item.className = "BookList_item ";


                var holderOne = document.createElement("div");
                holderOne.className = "row holderOne";

                var number = document.createTextNode(obj.CustomerPhoneN);
                var customer_no = document.createElement("h6");
                customer_no.appendChild(number);
                customer_no.className = "col-md-4 customer_no";
                holderOne.appendChild(customer_no);

                var t = document.createTextNode(!obj.EnterpriseCustomeName || obj.EnterpriseCustomeName == '' ? obj.CustomerName : obj.CustomerName + '/' + obj.EnterpriseCustomeName);
                var customer_name = document.createElement("h6");
                customer_name.appendChild(t);
                customer_name.className = "col-md-8 customer_name";
                holderOne.appendChild(customer_name);
            

                var holderTwo = document.createElement("div");
                holderTwo.className = "row holderTwo";


                var controls = document.createElement("div");
                controls.className = "col-md-2 controls";

                var delete_Item = document.createElement("div");
                delete_Item.innerHTML = "<i class='fa fa-minus-circle' style='color:red;    font-size: 15px;' aria-hidden='true'></i>";
                delete_Item.style.display = "inline-block";
                delete_Item.style.padding = "0px";
                delete_Item.style.marginTop = "6px";
                delete_Item.style.cursor = 'pointer';
                delete_Item.className = "col-md-6";
                delete_Item.onclick = function () {
                    self.removeSchedual(obj.OID);

                }
                controls.appendChild(delete_Item);
              

               
                var send = document.createElement("div");
                send.innerHTML = "<i class='fa fa-plus-circle' style='color:green;    font-size: 15px;' aria-hidden='true'></i>";
                send.style.display = "inline-block";
                send.style.padding = "0px";
                send.style.marginTop = "6px";
                send.style.cursor = 'pointer';
                send.className = "col-md-6";
                send.onclick = function () {
                    booking.create({
                        driverOID: '',
                        DriverName: '',
                        CustomerName: !obj.CustomerName || obj.CustomerName == 'null' ? '' : obj.CustomerName,
                        CustomerPhoneN: !obj.CustomerPhoneN||obj.CustomerPhoneN == 'null' ? '' : obj.CustomerPhoneN,
                        Landmark: !obj.FromLocation || obj.FromLocation == 'null' ? '' : obj.FromLocation,
                        IsDuplicate: true,
                        Company: !obj.EnterpriseCustomeName || obj.EnterpriseCustomeName == 'null' ? '' : obj.EnterpriseCustomeName,
                        isSchedulled: true,
                        scheduleID: obj.OID
                    });

                }
                controls.appendChild(send);
                holderTwo.appendChild(controls);


                var o = document.createTextNode("الساعة "+obj.Time);
                var organization = document.createElement("h6");
                organization.className = "col-md-4 organization";
                organization.appendChild(o);
                holderTwo.appendChild(organization);

              
                var d = document.createTextNode(obj.FromLocation);
                var address = document.createElement("h6");
                address.className = "col-md-6 address";
                address.appendChild(d);
                holderTwo.appendChild(address);

                BookList_item.appendChild(holderOne);
                BookList_item.appendChild(holderTwo);


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


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


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

                    tick();
                }

                fadeIn(BookList_item);

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

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

            },
            removeSchedual: function (id) {
                var self = this;
                $.ajax({
                    cache: true,
                    url: WebsiteServiceUrl + "ModifiyBookingScheduleLastSendDate/" + id + "/" + sessionStorage.CompanyOID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    success: function (result) {
                        self.poll();
                    },
                    error: function () {
                    }
                });
            },
            poll: function () {
                var self = this;
                $('#BookList').empty();
                self.get().done(function (data) {
                    var schedul = JSON.parse(data.GetCompanyBookingScheduleResult);
                  
                    for (s = 0; s < schedul.length; s++) {
                        var schd = {
                            OID:schedul[s].OID,
                           CustomerName: schedul[s].CustomerName,
                           CustomerPhoneN: schedul[s].CustomerCallingNumber,
                           FromLocation: schedul[s].fromAddress,
                           Time: '',
                           EnterpriseCustomeName: schedul[s].EnterpriseCustomeName
                       };

                       if (schedul[s].Is_Repeating) {
                           var day = (new Date()).getDay();

                           switch (day) {
                               case 0:
                                   var time = schedul[s].SundayTime.split(":");
                                   schd.Time = time[0]+":"+time[1];
                                   break;
                               case 1:
                                   var time = schedul[s].MondayTime.split(":");
                                   schd.Time = time[0] + ":" + time[1];
                                   break;
                               case 2:
                                   var time = schedul[s].TusedayTime.split(":");
                                   schd.Time = time[0] + ":" + time[1];
                                   break;
                               case 3:
                                   var time = schedul[s].WednesdayTime.split(":");
                                   schd.Time = time[0] + ":" + time[1];
                                   break;
                               case 4:
                                   var time = schedul[s].ThursdayTime.split(":");
                                   schd.Time = time[0] + ":" + time[1];
                                   break;
                               case 5:
                                   var time = schedul[s].FridayTime.split(":");
                                   schd.Time = time[0] + ":" + time[1];
                                   break;
                               case 6:
                                   var time = schedul[s].SaturdayTime.split(":");
                                   schd.Time = time[0] + ":" + time[1];
                                   break;
                           }
                       } else {
                           var time = schedul[s].BookingTime.split(":");
                           schd.Time = time[0] + ":" + time[1];

                       }
                       self.populate(schd);

                    }

                });
            },
            init: function (interval) {
                var self = this;
                setInterval(function () {
                    self.poll();
                }, interval);

                this.poll();

            }

        }
 /*----------------------------------------------------  Driver Panel ------------------------------------------------------*/
        var DriverList = {
            populate: function () {
                var diver_listPanel = document.getElementById('RegionsPanel');



            },
            hide: function () {

                if ($('#RegionsPanel').is(":visible")) {
                    $("#RegionsPanel").css('display', 'none');
                }

            },
            show:function(){
                if (!$('#RegionsPanel').is(":visible")) {
                    $("#RegionsPanel").css('display', 'inline-block');
                }

            },
          
        
        }
/*----------------------------------------------------  Driver Panel ------------------------------------------------------*/
        var OrderReservationPanel = {
            populate: function () {
                var order_reservationPanel = document.getElementById('OrderReservationPanel');



            },

            hide: function () {

                if ($('#OrderReservationPanel').is(":visible")) {
                    $("#OrderReservationPanel").css('display', 'none');
                }

            },
            show: function () {
                if (!$('#OrderReservationPanel').is(":visible")) {
                    $("#OrderReservationPanel").css('display', 'inline-block');
                }

            },





        }
        /*----------------------------------------------------  Regions Panel ------------------------------------------------------*/
        var Regions = {
          
            hide: function () {

                if ($('#Regions').is(":visible")) {
                    $("#Regions").css('display', 'none');
                }

            },
            show: function () {
                if (!$('#Regions').is(":visible")) {
                    $("#Regions").css('display', 'inline-block');
                }

            },






        }

      
      
        Dashboard.load();
        booking.loadSession();
        BookList.init(30000);
        queue.init(30000);
        booking.init();
        $(document).on("focus", '#table tr:last-child td:nth-child(5)', function () {

            //append the new row here.
           // booking.create({ driverOID: '', DriverName: '', CustomerName: '', CustomerPhoneN: '', Landmark: '', IsDuplicate: false });
         
            
        });
       
        $scope.reload = function (type) {
            carsSource = type;
            Dashboard.load();
        }
        $scope.CancelBookingItem = function () {
            CancelBooking.open();
        }
       
        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;
        }



     
        var regionsLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
        var regionsLayerForPosition = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
       
        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, lastUpdate) {


                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);
                return 'خارجي';
                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].address)
                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];
            },

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

                            }
                        }


                    }
                });


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

                            }
                        }



                    }
                });

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

                }
            }
        }

        regionsList.init();
        regionsList.loadregionsLayerForPosition();
       
        function VehicleDetailsForDashboard(OID, UserOID, companyId, OrgOID, groupOID, refresh) {
            $.ajax({
                url: ComonServiceUrl + "getDashboardVehicles/" + companyOID + "/" + userOID + "/" + TokenID / carsSource,
                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 dashlist = JSON.parse(result.getDashboardVehiclesResult);
                    //  ViewLivemap(sessionStorage.Latvalue, sessionStorage.Lngvalue);

                    var List = result.getDashboardVehiclesResult;
                    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;
                            var DateTimeDiff = DateDiff(datetimeStr, List[0])
                            dashlist[i].interval = DateTimeDiff;

                            if (dashlist[i].ApplicationStatus == 1) {

// -----------------------------------------  Driver Status

                                if (dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "0") {
                                    dashlist[i].color = "green";
                                }
                                else if ((dashlist[i].DriverStatus == "1" && dashlist[i].IsBooked == "1")) {
                                    if (dashlist[i].CutsomerDestination) {
                                        dashlist[i].color = "red";
                                    } else {
                                        dashlist[i].color = "green";
                                    }
                                }
                                else if (dashlist[i].DriverStatus == "4" && dashlist[i].IsBooked == "0") {
                                    dashlist[i].color = "blue";
                                }

                                else if (dashlist[i].DriverStatus == "3" && dashlist[i].IsBooked == "1") {
                                    dashlist[i].color = "purple";

                                }
                            
// -----------------------------------------  Current Location

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

                                  if (dashlist[i].TripDestination_RegionId) {
                                      var d = JSON.parse(JSON.stringify(dashlist[i]));
                                      if (d.CutsomerDestination == dashlist[i].Location) {
                                          d.LocationType = 'B';
                                          $(".BothIcon").css("display", "block");
                                      } else {
                                          d.Location = d.RegionName;

                                          // d.color = 'yellow';
                                          d.LocationType = 'D';

                                          dashlist[i].LocationType = 'L';
                                          $scope.All.push(dashlist[i]);
                                      }
                                      $scope.All.push(d);

                                  }
                                  else {

                                    dashlist[i].LocationType = 'L';
                                  $scope.All.push(dashlist[i]);

                                  }


                            }

                                
                            
                                   
                                    
                            }
                        $scope.dashboardList = $scope.All;


                      
                    }
                   
                    $scope.$apply();
                   
                    
                    $('#RegionsPanel').masonry({
                        // options
                        itemSelector: '.NewRegionsDiv',
                    }).masonry('reloadItems');
                    if (firstLoad == 0) {

                        $('#RegionsPanel').masonry('destroy');

                        $('#RegionsPanel').masonry({
                            // options
                            itemSelector: '.NewRegionsDiv',
                        }).masonry('reloadItems');
                    }
                    else {
                        setTimeout(function () {
                            $('#RegionsPanel').masonry({
                                itemSelector: '.NewRegionsDiv',
                            }).masonry('reloadItems');
                        }, 400);
                    }
                   
                    firstLoad = 0;
                       

                }

                   
                
            });
        };

        window.setInterval(function () {
            if (true) {
                VehicleDetailsForDashboard('0', userOID, companyOID, orgOID, groupOID, 1);
                //$scope.selectBookingPeriod();
            }
        }, 5000);


      
        var currentPannelKey = 1;
        $(document).keydown(function (e) {
            if (e.keyCode == 37 && e.ctrlKey) {
                showNextPanel();
            }
        });

        $('#switch').click(function () {
            showNextPanel();
        });

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

            });


            iconStyle = [new ol.style.Style({
                image: new ol.style.Icon({
                    //anchor: [12, 0.5],
                    size: [50, 50],
                  //  scale: 0.037,
                   // rotation: parseInt(data[n].Direction) * Math.PI / 180,
                    //anchorXUnits: 'pixel',
                    //anchorYUnits: 'fraction',
                    src: 'assets/img/CustomerIcon.png'
                })
            })];

            iconFeature.setStyle(iconStyle);

            notificationLayer.getSource().addFeature(iconFeature);
            map.getView().fit(notificationLayer.getSource().getExtent(), map.getSize());
                    //  setInterval(function () { map.updateSize(); }, 500);


        }
        function showNextPanel() {
            if (currentPannelKey >= 3) {
                currentPannelKey = 0;
            }

            switch (currentPannelKey) {
                case 0:
                    DriverList.hide();
                    Regions.hide();
                    OrderReservationPanel.show();
                    break;
                case 1:
                    OrderReservationPanel.hide();
                    Regions.hide();
                    DriverList.show();
                    break;
                case 2:
                    DriverList.hide();
                    OrderReservationPanel.hide();
                    Regions.show();
                    break;
            }

            currentPannelKey++;
        }
        
    }
        
    ])

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

        });

    };

    return service;

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


    $scope.loading = true;
    $(document).keydown(function (e) {
        if (e.keyCode == 13) {
            alert("clicked");
            $scope.ClickClose2();
        }
        if (e.keyCode == 27) {
            alert("cancelled");
            $scope.ClickClose();
        }
    });

    $scope.ClickClose = function () {
        $(document).on("keydown");
        $(document).on("keypress");
        $(document).on("keyup");
        $modalInstance.dismiss('Cancel');
        $(document).off("keypress");
        $(document).off("keyup");
        $(document).off("keydown");
    }
    $scope.ClickClose2 = function () {
        $(document).off("keypress");
        $(document).off("keyup");
        $(document).off("keydown");
        $modalInstance.dismiss('Cancel');
      
   

    }


    $scope.CancelBooking = function () {

      
        $scope.ClickClose(); 

    }
    var ValidateForm = function () {

        alert('delete');

        return true
    }
})


TaxiApp.service('AddItemBefore', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (idd,date,time) {
        var modalInstance = $modal.open({
            windowClass: 'AddItemBefore',
            templateUrl: 'AddItemBefore.html',
            controller: 'AddItemBeforeCtrl',
            resolve: {
                idd: function () {
                    return idd;
                },
                date: function () {
                    return date;
                },
                time: function () {
                    return time;
                }
            }

        });

    };

    return service;

})
TaxiApp.controller('AddItemBeforeCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, $modalInstance, idd,date,time) {
    //alert(date + "--" + time);
    time = time.replace(/:/g, '~');
    var array = date.split("-");
    date = array[1] + '-' + array[0] + '-' + array[2];
    AddDriverToQueue = function (driverName, type) {
        var driver = booking.getDriverInfo(driverName, 0);
        console.log(driver)
        $.ajax({
            url: WebsiteServiceUrl + "AddVehicleToQueueManually/0/" + driver.DriverOID + "/" + date + "/" + time + "/" + sessionStorage.CompanyOID + "/" + driver.IMEINumber,
            cache: false,
            success: function(){
                queue.refresh();
                $scope.ClickClose();
        }
        });
    

    }

    setTimeout(function () {



        var driver_select = document.getElementById("driver_select_before");
        var driverAwesomplete = new Awesomplete(driver_select, {

            list: Dashboard.DriversList,
            data: function (item, input) {

                return { label: item.DriverName, value: item.DriverOID };

            },
            autoFirst: true,
            minChars: 1

        });

        driver_select.addEventListener('awesomplete-selectcomplete', function (item) {

       //     $('#drivers_list' + _id).attr("DriverOID", item.text.value);

        });



        $scope.ClickClose = function () {

            $modalInstance.dismiss('Cancel');
        }
      

        $scope.addNow = function () {

            AddDriverToQueue($scope.driver_select,'before');

        }

        $("#driver_select_before").focus();

       /* $("#driver_select_before").keypress(function (e) {  // to submit the dialog when pressing enter by omar
            if (e.which == 13) {


                if (AssignBookDialogIsShown == true) {

        }
            }
        });*/


    }, 150);
    
})


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

        });

    };

    return service;

})
TaxiApp.controller('AddItemAfterCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, $modalInstance,idd) {
    setTimeout(function () {



        var driver_select = document.getElementById("driver_select_after");
        var driverAwesomplete = new Awesomplete(driver_select, {

            list: Dashboard.DriversList,
            data: function (item, input) {

                return { label: item.DriverName, value: item.DriverOID };

            },
            autoFirst: true,
            minChars: 1

        });

        driver_select.addEventListener('awesomplete-selectcomplete', function (item) {

            $('#drivers_list' + _id).attr("DriverOID", item.text.value);

        });



        $scope.ClickClose = function () {

            $modalInstance.dismiss('Cancel');
        }
     

        $scope.addNow = function () {


            alert("Done")

        }

    }, 150);

})


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 seconds = Math.floor((now_dt - (recent_dt)) / 1000);
        var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60);
        var days = Math.floor(hours / 24);

        hours = hours - (days * 24);
        minutes = minutes - (days * 24 * 60) - (hours * 60);
        seconds = seconds - (days * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);

        if (days > 0)
            return days + "ي";

        if (hours > 0)
            return hours + "س";

        if (minutes > 0)
            return minutes + "د";

        if (seconds > 0)
            return seconds + "ث";



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

}
