Number.prototype.pad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) { s = "0" + s; }
    return s;
}

var TaxiApp = angular.module('AppBooking', ['ngStorage', 'ngDialog', 'ui.bootstrap'])
    .filter('split', function () {
    return function (input, splitChar, splitIndex) {
        // do some bounds checking here to ensure it has that index
        return input.split(splitChar)[splitIndex];
    }
    })
.filter('formatTime', function ($filter) {
    return function (time) {
        var parts = time.split(':');
        var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
        return $filter('date')(date, 'h:mm');
    };
});
var ReviewItem;
var map;
var CancelBooking;
var obj;

var data;
var DriverLocation;
var SelectedCompanyID;
var trackBookingInterval;
TaxiApp.controller('AppBookingCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'ReviewItemScript', 'ReviewCustomerItemScript', 'ReviewDriverItemScript', 'CancelBookingItem',

    function ($scope, $http, $sessionStorage, ngDialog, ReviewItemScript, ReviewCustomerItemScript, ReviewDriverItemScript, CancelBookingItem) {
        Localization(sessionStorage.selectedLanguage, 'allreport', $scope, sessionStorage);
      
        $scope.selectInstitution = function () {
            SelectedEnterprise = $scope.selectedInstitution.BookingStatus;

        }
       
        $scope.NotAcceptedList = [];

        var total = 0;
        var ReviewsBookingList = [];
        var AllHistoryBookingList = [];
     //----------- calculate Total Amount
        $scope.calculateTotalAmount = function (filteredList) {
            total = 0;
            if (filteredList == undefined) {filteredList = []}
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].Amount + filteredList[i].DiscountValue + filteredList[i].FarTripCompensation + filteredList[i].CanceledTripCompensation;
            }
            return Math.round(total * 100) / 100;
        }
    //----------- calculate  Amount     
        $scope.calculateAmount = function (filteredList) {
            total = 0;
            if (filteredList == undefined) { filteredList = [] }
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].Amount;
            }
            return Math.round(total * 100) / 100;
        }
        //----------- calculate  Discount   
        $scope.calculateTotalDiscount = function (filteredList) {
            total = 0;
            if (filteredList == undefined) {filteredList = []}
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].DiscountValue;
            }
            return Math.round(total * 100) / 100;
        }
        //-----------  calculateTotalDistanceCom   
        $scope.calculateTotalDistanceCom = function (filteredList) {
            total = 0;
            if (filteredList == undefined) { filteredList = []}
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].FarTripCompensation;
            }
            return Math.round(total * 100) / 100;
        }
        //-----------  calculateTotalCancelCom   
        $scope.calculateTotalCancelCom = function (filteredList) {
            total = 0;
            if (filteredList == undefined) { filteredList = [] }
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].CanceledTripCompensation;
            }
            return Math.round(total * 100) / 100;
        }
        var fl = [];
        var f2 = [];
        var filteredList = [];
        $scope.calculateCount = [];
        $scope.calcCustomerCount = function (fl) {
             if (fl == undefined) {
                 fl = []

            }
            return fl.length;
        }
        $scope.calcDriverCount = function (f2) {
            if (f2 == undefined) {
                f2 = []

            }
            return f2.length;
        }
        $scope.calculateCount = function (filteredList) {
            if (filteredList == undefined) {
                filteredList = []

            }
            return filteredList.length;
        }
        $scope.calculateKmsBefore= function (filteredList) {
            if (filteredList == undefined) {
                filteredList = []

            }
            var totalkmsbefore=0;
            for (var i = 0; i < filteredList.length; i++) {
                totalkmsbefore += filteredList[i].DistanceBeforeTripStart;
             

            }
            return totalkmsbefore.toFixed(2);
        }
        $scope.calculateKms = function (filteredList) {
            if (filteredList == undefined) {
                filteredList = []

            }
            var totalkms=0;
            for (var i = 0; i < filteredList.length; i++) {
                totalkms += filteredList[i].Distance + filteredList[i].DistanceBeforeTripStart;


            }
            return totalkms.toFixed(2);
        }
        $scope.calculateAppKms = function (filteredList) {
            if (filteredList == undefined) {
                filteredList = []

            }
            var totalkms = 0;
            for (var i = 0; i < filteredList.length; i++) {
                totalkms += filteredList[i].Distance;


            }
            return totalkms.toFixed(2);
        }


        loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);
        $scope.SelectedDistrict = function (districtOid) {
          //  console.log()
        
           $scope.DistrictName = $.grep($scope.DistrictList, function (item) {
               return item.OID == districtOid;
            })[0].value;
           console.log($scope.DistrictListModel)
            $scope.loadDailyBooking();
            
        }


 //-------------------------- Driver Balance Details ---------------------------------------

        //----------- calculate  Amount     
        $scope.calculateDriverAmount = function (filteredList) {
            total = 0;
            if (filteredList == undefined) { filteredList = [] }
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].Amount;
              //  console.log(filteredList[i].FarTripCompensation + "   -- " + filteredList[i][i].CanceledTripCompensation)

            }
            return Math.round(total * 100) / 100;

        }
        //----------- calculate  Discount   
        $scope.calculateDriverTotalDiscount = function (filteredList) {
            total = 0;
            if (filteredList == undefined) {filteredList = []}
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].DiscountValue;
            }
            return Math.round(total * 100) / 100;
        }
        //-----------  calculateTotalDistanceCom   
        $scope.calculateDriverTotalDistanceCom = function (filteredList) {
            total = 0;
            if (filteredList == undefined) { filteredList = []}
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].FarTripCompensation;
            }
            return Math.round(total * 100) / 100;
        }
        //-----------  calculateTotalCancelCom   
        $scope.calculateDriverTotalCancelCom = function (filteredList) {
            total = 0;
            if (filteredList == undefined) { filteredList = [] }
            for (var i = 0; i < filteredList.length; i++) {
                total += filteredList[i].CanceledTripCompensation;
            }
            return Math.round(total * 100) / 100;



        }

        if (sessionStorage.OrderId < 2) {
            window.location.href = "../../Access.html";
        }

        $scope.selectedType = 0;



        $scope.VehicleCurrentLocation = [];
      
        $scope.loading = false;
        $scope.BookingList = "";
        $scope.DisplayName = sessionStorage.UserName;
        $scope.DailyBookingCtrl = "";
        $scope.CompanyName = sessionStorage.value;
        $scope.DistrictOID = sessionStorage.DistrictOID;
        var Vehiclename, vehicle;
        var ShowDistrict;
        if (sessionStorage.length == (undefined || 0)) {
            window.parent.location.href = "../../Index.html";
        }
        else {
            $scope.Role = sessionStorage.RoleType;
            $scope.RoleID = sessionStorage.RoleID;
          
            if (sessionStorage.OrderId >2) {
                $('.tele').show();
                
                $(".districtItem").show();

            }
            else {
                $('.tele').hide();
                $(".districtItem").hide();
            }
            $scope.handler=function(e) {
                //  $scope.Date = e.target.value;
                $scope.loadDailyBooking();
            }

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

        
            $scope.User = sessionStorage.Username;
            //set cureentdate as default date in datepicker
            bookingStatus = '0';
            bookingType = '0';
            selectedCompany = 'undefined';
            var now = new Date();

            var day = ("0" + now.getDate()).slice(-2);
            var month = ("0" + (now.getMonth() + 1)).slice(-2);

            var today = now.getFullYear() + "-" + (month) + "-" + (day);

         $('#fdate').val(today);

            $scope.fdate = new Date()
            $scope.selectCompanydetails = function (obj) {
                sessionStorage.CompanyOID = obj.OID;
                sessionStorage.value = obj.Value;
                window.location.href = "Management.html";
            }

          
            setInterval(function () {
                $scope.loadDailyBooking();
            }, 15000);

          

            $scope.selectStatus = function (st) {
                bookingStatus = st == '' ? '0' : st;
                $scope.loadDailyBooking();
            }
            $scope.selectType = function (st) {
                bookingType = st == '' ? '0' : st;
                $scope.loadDailyBooking();
            }
            $scope.ShowReviews = function (tst) {
               
                if (tst) {
                    $scope.BookingList = ReviewsBookingList;

                } else {

                    $scope.BookingList = AllHistoryBookingList
                }
             
            }
            $scope.selectCompany = function (cmp) {
                selectedCompany = cmp == '' ? '0' : cmp;
            }

            var notificationLayer = new ol.layer.Vector({ source: new ol.source.Vector(), displayInLayerSwitcher: false });
            var taxilayer = 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, taxilayer
                ],
                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.loadDailyBooking = function () {
               
                dayDate = $('#fdate').val();
                todate = $('#fdate').val();
                ReviewsBookingList = [];
               


                $scope.TotalTripsCount = "";
                if (sessionStorage.OrderId >2) {

                    
                    if ($scope.DistrictListModel == undefined) {

                        ShowDistrict = 0
                    } else {

                        ShowDistrict = $scope.DistrictListModel;
                    }



                } else {
                    ShowDistrict = sessionStorage.DistrictOID;

                }
                
            
                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "CustomerAppBookings/" + bookingStatus + "/" + dayDate + "/" + "0" + "/" + ShowDistrict + "/" + sessionStorage.UserOID + "/"+bookingType+"/"+sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {

                     
                        data = JSON.parse(result.CustomerAppBookingsResult);
                     
                        $scope.BookingList = [];
                        if (data.length > 0) {
                            $scope.loading = false;
                        $scope.TotalTripsCount =data.length ;
                       // console.log(data)
                        for (var i = 0; i < data.length; i++) {

                           

                            var date = new Date(Date.parse(data[i].Book_DateTime));
                            data[i].PickUpTime = date.getHours().pad() + ":" + date.getMinutes().pad();
                        
                          
                            switch (data[i].BookingStatus) {
                                case "B":
                                    if (data[i].Trip_Start_DateTime == null) {
                                        data[i].BookingStatusDesc = "بانتظار استلام السائق";
                                        data[i].color = "#d0d0f4";
                                        data[i].colorFont = "#333";

                                    } else {
                                        data[i].BookingStatus = "في الانتظار";
                                        data[i].BookingStatusDesc = "في الانتظار";

                                        data[i].color = "#fff";
                                        data[i].colorFont = "#333";

                                    }
                                    break;
                                case "A":
                                    if (data[i].Trip_Start_DateTime == null) {
                                        data[i].BookingStatusDesc = "باتجاه الزبون";
                                        data[i].color = "#C27ECE";
                                        data[i].colorFont = "#333";

                                    } else {
                                        data[i].BookingStatusDesc = "قيد التوصيل";
                                        data[i].color = "#E56D54";
                                        data[i].colorFont = "#333";

                                    }

                                    break;
                                case "C":
                                   
                                    if (data[i].CustomerReason != null) {
                                        if (data[i].CustomerReason == "Mind Change" || data[i].CustomerReason == "timeout" || data[i].CustomerReason == 'Portal: Auto Cancel after timeout') {
                                            data[i].BookingStatusDesc = "لم يتم الرد";
                                            data[i].color = "#f2f2f2";
                                            data[i].colorFont = "#333";
                                       


                                           


                                        }
                                        else {
                                          
                                            data[i].color = "#80b4e1";
                                            data[i].colorFont = "#333";
                                            data[i].BookingStatusDesc = data[i].CustomerReason;
                                            data[i].BookingStatusDesc = data[i].CustomerReason;

                                            if (data[i].CustomerReason == "canceled_before_accept"){
                                            
                                                data[i].BookingStatusDesc = "الغي قبل القبول";
                                            }


                                        }


                                    } else if (data[i].DriverReason != null) {
                                        if (data[i].DriverReason == "Cancel By Driver") {
                                            data[i].BookingStatusDesc = " ملغي من السائق";
                                            data[i].color = "#80b4e1";
                                            data[i].colorFont = "#333";

                                        }

                                    } 
                                 
                              

                                    break;
                                case "E":
                                    data[i].BookingStatusDesc = "مكتمل";
                                    // data[i].color = "#fff000";
                                    if (data[i].Trip_Rating == 1 || data[i].Trip_Rating == 2 || data[i].Trip_Rating == 3 || data[i].Trip_Review != null) {
                                     ReviewsBookingList.push(data[i]);
                                    }

                                    break;
                                case "R":
                                    data[i].BookingStatusDesc = "مرفوض";
                                    data[i].color = "#AEABAF";
                                    data[i].colorFont = "#333";


                                    break;
                                case "Q":
                                    data[i].BookingStatusDesc = "استعلام";
                                    data[i].color = "green";
                                    data[i].colorFont = "#333";

                                    break;
                                default:
                            }
                         
                            $scope.ReviewItem = {
                                review: function (trip_comment) {
                                    ngDialog.open({
                                        template: 'ReviewItemScript.html',
                                        windowClass: 'ReviewItemScript',
                                        controller: 'ReviewItemScriptCtrl',
                                        resolve: {
                                            trip_comment: function () {
                                                return trip_comment;
                                            }


                                        }

                                    });
                                }
                            }
                            data[i].DistanceDiff = parseFloat(data[i].DistanceBeforeTripStart - data[i].EstimatedDistanceBeforeTripStart).toFixed(2)

                        }
                        $scope.loading = false;
                       
                       
                     
                        if ($scope.IsReviwsChecked) {
                            $scope.BookingList = ReviewsBookingList;
                        } else {
                            $scope.BookingList = data;
                            AllHistoryBookingList = data;
                        }
                        $scope.$apply();
                     }
                    },
                    error: function () {
                        $scope.loading = false;
                        $scope.BookingList = [];
                        $scope.$apply();
                    }
                });
            }
           $scope.SendMsgToCustomer = {
               Wait: function (c_no) {
                    var wait_sms = "نعتذر لعدم توفر مركبات حاليا، سيتم اشعاركم حال توفر مركبة في منطقتك";
                    
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "SendSMS/" + c_no + "/" + wait_sms,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

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

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


                },
                Available: function (c_no) {
                    var Available_sms = "توجد مركبة متوفر في منطقتك، يرجى اعادة المحاولة. نتمنى لك رحلة ممتعة";
                   
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "SendSMS/" + c_no + "/" + Available_sms,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

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


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


                }

            }
            var GetVehicleCurrentLocation = {


                get: function (IMEINo,compid) {
                    
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "GetVehicleCurrentLocation/" + IMEINo + "/" + compid,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            DriverLocation = JSON.parse(result.GetVehicleCurrentLocationResult);
                            DriverLocation = DriverLocation[0]
                            $scope.loading = false;
                            $scope.VehicleCurrentLocation = DriverLocation;
                            $scope.$apply();
                            var long = DriverLocation.Long;
                            var lat = DriverLocation.Lat;
                            taxilayer.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),

                            });


                            if (DriverLocation.ApplicationStatus == 0) {
                                DriverLocation.color = "orange";

                            }
                            else if (DriverLocation.ApplicationStatus == 2) {
                                DriverLocation.color = "black";
                            }
                            else if (DriverLocation.ApplicationStatus == 4) {
                                DriverLocation.color = "gray";
                            }
                            else if (DriverLocation.ApplicationStatus == 1) {

                                if (DriverLocation.DriverStatus == "1" && DriverLocation.IsBooked == "0") {

                                    DriverLocation.color = "green";
                                }
                                else if ((DriverLocation.DriverStatus == "1" && DriverLocation.IsBooked == "1")) {
                                    DriverLocation.color = "red";
                                }
                                else if (DriverLocation.DriverStatus == "4" && DriverLocation.IsBooked == "0"
                                    ) {
                                    DriverLocation.color = "blue";
                                }
                                else if (DriverLocation.DriverStatus == "2" && DriverLocation.IsBooked == "0") {
                                    DriverLocation.color = "skyblue";
                                }
                                else if ((DriverLocation.DriverStatus == "0" && DriverLocation.IsBooked == "0")
                                    || (DriverLocation.DriverStatus == '0' && DriverLocation.IsBooked == '1')
                                   ) {
                                    DriverLocation.color = "black";
                                }
                                else if (DriverLocation.DriverStatus == "3" && DriverLocation.IsBooked == "1") {
                                    DriverLocation.color = "purple";
                                }

                            }


                            iconStyle = [new ol.style.Style({
                                image: new ol.style.Icon({
                                    //anchor: [12, 0.5],
                                    size: [50, 50],
                                    //  scale: 0.037,
                                    rotation: parseInt(DriverLocation.Direction) * Math.PI / 180,
                                    //anchorXUnits: 'pixel',
                                    //anchorYUnits: 'fraction',
                                    src: '../../assets/SVGHelper/GetSVG.aspx?c=' + DriverLocation.color
                                })
                            })];

                            iconFeature.setStyle(iconStyle);

                            taxilayer.getSource().addFeature(iconFeature);

                            var extent = ol.extent.createEmpty();

                            ol.extent.extend(extent, taxilayer.getSource().getExtent());
                            ol.extent.extend(extent, notificationLayer.getSource().getExtent());

                            map.getView().fit(extent, map.getSize());

                            //    map.getView().fit(taxilayer.getSource().getExtent(), map.getSize());


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


                }



            }

            var GetCustomerBookings = {
                get: function (OID) {

                    if ($scope.RoleID < 3) {
                        return;
                    }

                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "GetAllBookingsForCustomer/" + OID+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            Cbookings = JSON.parse(result.GetAllBookingsForCustomerResult);
                            $scope.loading = false;
                            for (var i = 0; i < Cbookings.length; i++) {
                                var str = Cbookings[i].Book_DateTime;

                                var DateTime=  str.split("T")
                                //= new Date(Date.parse(data[i].Book_DateTime));
                                Cbookings[i].date = DateTime[0];
                                Cbookings[i].time = DateTime[1].substring(0,5);
                                //Cbookings[i].PickUpTime = date.getHours().pad() + ":" + date.getMinutes().pad() + "/ " + date.getDay().pad() + "/ " + date.getMonth().pad() + "/ " + date.getYear().pad();
                               
                                switch (Cbookings[i].BookingStatus) {
                                    case "B":
                                        if (Cbookings[i].Trip_Start_DateTime == null) {
                                            Cbookings[i].BookingStatusDesc = "بانتظار استلام السائق";
                                            Cbookings[i].color = "#d0d0f4";
                                            Cbookings[i].colorFont = "#333";

                                        } else {
                                            Cbookings[i].BookingStatus = "في الانتظار";
                                            Cbookings[i].BookingStatusDesc = "في الانتظار";

                                            Cbookings[i].color = "#fff";
                                            Cbookings[i].colorFont = "#333";

                                        }
                                        break;
                                    case "A":
                                        if (Cbookings[i].Trip_Start_DateTime == null) {
                                            Cbookings[i].BookingStatusDesc = "باتجاه الزبون";
                                            Cbookings[i].color = "#C27ECE";
                                            Cbookings[i].colorFont = "#333";

                                        } else {
                                            Cbookings[i].BookingStatusDesc = "قيد التوصيل";
                                            Cbookings[i].color = "#E56D54";
                                            Cbookings[i].colorFont = "#333";

                                        }

                                        break;
                                    case "C":

                                        if (Cbookings[i].CustomerReason != null) {
                                            if (Cbookings[i].CustomerReason == "Mind Change" || Cbookings[i].CustomerReason == "timeout") {
                                                Cbookings[i].BookingStatusDesc = "لم يتم الرد";
                                                Cbookings[i].color = "#f2f2f2";
                                                Cbookings[i].colorFont = "#333";
                                            }
                                            else {

                                                Cbookings[i].color = "#80b4e1";
                                                Cbookings[i].colorFont = "#333";
                                                Cbookings[i].BookingStatusDesc = Cbookings[i].CustomerReason;
                                                Cbookings[i].BookingStatusDesc = Cbookings[i].CustomerReason;

                                                if (Cbookings[i].CustomerReason == "canceled_before_accept") {

                                                    Cbookings[i].BookingStatusDesc = "الغي قبل القبول";
                                                }


                                            }


                                        } else if (Cbookings[i].DriverReason != null) {
                                            if (Cbookings[i].DriverReason == "Cancel By Driver") {
                                                Cbookings[i].BookingStatusDesc = " ملغي من السائق";
                                                Cbookings[i].color = "#80b4e1";
                                                Cbookings[i].colorFont = "#333";

                                            }

                                        }



                                        break;
                                    case "E":
                                        Cbookings[i].BookingStatusDesc = "مكتمل";
                                        // data[i].color = "#fff000";

                                        break;
                                    case "R":
                                        Cbookings[i].BookingStatusDesc = "مرفوض";
                                        Cbookings[i].color = "#AEABAF";
                                        Cbookings[i].colorFont = "#333";


                                        break;
                                    case "Q":
                                        Cbookings[i].BookingStatusDesc = "استعلام";
                                        Cbookings[i].color = "green";
                                        Cbookings[i].colorFont = "#333";

                                        break;
                                    default:
                                }

                                $scope.ReviewCustomeItem = {
                                    review: function (trip_comment) {
                                        ngDialog.open({
                                            template: 'ReviewItemScript.html',
                                            windowClass: 'ReviewItemScript',
                                            controller: 'ReviewCustomerItemScriptCtrl',
                                            resolve: {
                                                trip_comment: function () {
                                                    return trip_comment;
                                                }


                                            }

                                        });
                                    }
                                }

                            }

                            $scope.AllBookingsForCustomer = Cbookings;
                            $scope.TotalCustomerTripsCount = Cbookings.length;

                            $scope.$apply();

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


                
                },
            }
            var GetBookingDetails = {
                get: function (bookingID) {
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "GetNotRespondedAndRejetcedDrivers/" + bookingID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            var bookingsDetails = JSON.parse(result.GetNotRespondedAndRejetcedDriversResult);
                     


                            console.log($scope.BookingDetailsList)
                            $scope.BookingDetailsList = bookingsDetails;
                            $scope.$apply();

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


                }

            }
            var GetDriverBookings = {
                get: function (driverOID) {
                   if ($scope.RoleID < 3) {
                        return;
                    }
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "GetAllAppBookingsForDriver/" + driverOID+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            Dbookings = JSON.parse(result.GetAllAppBookingsForDriverResult);
                            for (var i = 0; i < Dbookings.length; i++) {
                                var str = Dbookings[i].Book_DateTime;

                            var DateTime=  str.split("T")
                            //= new Date(Date.parse(data[i].Book_DateTime));
                            Dbookings[i].date = DateTime[0];
                            Dbookings[i].time = DateTime[1].substring(0, 5);
                            
                            switch (Dbookings[i].BookingStatus) {
                                case "B":
                                    if (Dbookings[i].Trip_Start_DateTime == null) {
                                        Dbookings[i].BookingStatusDesc = "بانتظار استلام السائق";
                                        Dbookings[i].color = "#d0d0f4";
                                        Dbookings[i].colorFont = "#333";

                                    } else {
                                        Dbookings[i].BookingStatus = "في الانتظار";
                                        Dbookings[i].BookingStatusDesc = "في الانتظار";

                                        Dbookings[i].color = "#fff";
                                        Dbookings[i].colorFont = "#333";

                                    }
                                    break;
                                case "A":
                                    if (Dbookings[i].Trip_Start_DateTime == null) {
                                        Dbookings[i].BookingStatusDesc = "باتجاه الزبون";
                                        Dbookings[i].color = "#C27ECE";
                                        Dbookings[i].colorFont = "#333";

                                    } else {
                                        Dbookings[i].BookingStatusDesc = "قيد التوصيل";
                                        Dbookings[i].color = "#E56D54";
                                        Dbookings[i].colorFont = "#333";

                                    }

                                    break;
                                case "C":

                                    if (Dbookings[i].CustomerReason != null) {
                                        if (Dbookings[i].CustomerReason == "Mind Change" || Dbookings[i].CustomerReason == "timeout") {
                                            Dbookings[i].BookingStatusDesc = "لم يتم الرد";
                                            Dbookings[i].color = "#f2f2f2";
                                            Dbookings[i].colorFont = "#333";
                                        }
                                        else {

                                            Dbookings[i].color = "#80b4e1";
                                            Dbookings[i].colorFont = "#333";
                                            Dbookings[i].BookingStatusDesc = Dbookings[i].CustomerReason;
                                            Dbookings[i].BookingStatusDesc = Dbookings[i].CustomerReason;

                                            if (Dbookings[i].CustomerReason == "canceled_before_accept") {

                                                Dbookings[i].BookingStatusDesc = "الغي قبل القبول";
                                            }


                                        }


                                    } else if (Dbookings[i].DriverReason != null) {
                                        if (Dbookings[i].DriverReason == "Cancel By Driver") {
                                            Dbookings[i].BookingStatusDesc = " ملغي من السائق";
                                            Dbookings[i].color = "#80b4e1";
                                            Dbookings[i].colorFont = "#333";

                                        }

                                    }



                                    break;
                                case "E":
                                    Dbookings[i].BookingStatusDesc = "مكتمل";
                                    // data[i].color = "#fff000";

                                    break;
                                case "R":
                                    Dbookings[i].BookingStatusDesc = "مرفوض";
                                    Dbookings[i].color = "#AEABAF";
                                    Dbookings[i].colorFont = "#333";


                                    break;
                                case "Q":
                                    Dbookings[i].BookingStatusDesc = "استعلام";
                                    Dbookings[i].color = "green";
                                    Dbookings[i].colorFont = "#333";

                                    break;
                                default:
                            }

                            $scope.ReviewDriverItem = {
                                review: function (trip_comment) {
                                    ngDialog.open({
                                        template: 'ReviewItemScript.html',
                                        windowClass: 'ReviewItemScript',
                                        controller: 'ReviewDriverItemScriptCtrl',
                                        resolve: {
                                            trip_comment: function () {
                                                return trip_comment;
                                            }


                                        }

                                    });
                                }
                            }
                            }


                            
                            $scope.AllBookingsForDriver = Dbookings;
                            $scope.loading = false;
                            //for (var i = 0 ; i < $scope.AllBookingsForDriver.length; i++) {
                            //console.log($scope.AllBookingsForDriver[i].FarTripCompensation + "   -- " + $scope.AllBookingsForDriver[i].CanceledTripCompensation)


                            //}
                            $scope.TotalDriverTripsCount = Dbookings.length;
                            $scope.$apply();

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


                }
                
            }
            $scope.BookingDetails =
             {
                 get: function (BookingID) {
                     GetBookingDetails.get(BookingID);
                     $('#BookingModal').modal('toggle');
                  


                 }

               }
            $scope.loadDailyBooking();
          
            $scope.GetCustomerLocation = {
                get: function (d) {
                    if (d.OrderDetails != null && d.OrderDetails!="") {
                        $scope.OrderItems = d.OrderDetails.split('	');
                    } else {
                        $('#orderlist').hide;
                        $scope.OrderItems = ["لا يوجد"];
                    }
                    //  SelectedCompanyID= $("#SelectedCompanyID").val();
                    $('#coordinates').text('lat: ' + d.CustomerLat.toFixed(5) + ', long: ' + d.CustomerLong.toFixed(5));
                    clearInterval(trackBookingInterval);
                    $('#myModal').modal('toggle');
                    trackBookingInterval = setInterval(function () { GetVehicleCurrentLocation.get(d.IMEINo, d.CompanyId); }, 5000);
                    ViewCustomerLocation(d.CustomerLat, d.CustomerLong, $scope.VehicleCurrentLocation);


                }
            },
            $scope.CustomerBooking = {
                get: function (obj) {
                    if ($scope.RoleID < 3)
                        return;
                    //  SelectedCompanyID= $("#SelectedCompanyID").val();
                    $('#customerModel').modal('toggle');

                    GetCustomerBookings.get(obj.CustomerOID);


                }
            }
            $scope.DriverBooking = {
                get: function (doid) {
                    //  SelectedCompanyID= $("#SelectedCompanyID").val();
                    if ($scope.RoleID < 3)
                        return;
                    if (doid != null) {
                        GetDriverBookings.get(doid);
                        $('#DriverModel').modal('toggle');
                    }


                }
            }
            $scope.CancelBooking = {
                cancel: function (bookingId, imei, driverOId) {
                    //EditItem.open(id, status, price, isDept);

                    ngDialog.open({
                        template: 'CancelBookingItem.html',
                        windowClass: 'CancelBookingItem',
                        controller: 'CancelBookingItemCtrl',
                        resolve: {
                            bookingId: function () {
                                return bookingId;
                            }
                       ,
                            imei: function () {
                                return imei;
                            }
                       ,
                            driverOId: function () {
                                return driverOId;
                            }

                        }


                    });

                }
            }
           
            function ViewCustomerLocation(lat, long, DriverLocation) {
                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);


            }
        }
     
    
    }])



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


        });

    };



    return service;
})
TaxiApp.controller('ReviewItemScriptCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, trip_comment) {


    $scope.loading = true;
    $scope.ReviewTxt = trip_comment
    $scope.ClickClose = function () {

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

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

    }


})





TaxiApp.service('ReviewCustomerItemScript', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (trip_comment) {
        var modalInstance = $modal.open({
            windowClass: 'ReviewItemScript',
            templateUrl: 'ReviewItemScript.html',
            controller: 'ReviewCustomerItemScriptCtrl',


        });

    };



    return service;
})
TaxiApp.controller('ReviewCustomerItemScriptCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, trip_comment) {


    $scope.loading = true;
    $scope.ReviewTxt = trip_comment
    $scope.ClickClose = function () {

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

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

    }


})

TaxiApp.service('ReviewDriverItemScript', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (trip_comment) {
        var modalInstance = $modal.open({
            windowClass: 'ReviewItemScript',
            templateUrl: 'ReviewItemScript.html',
            controller: 'ReviewDriverItemScriptCtrl',


        });

    };



    return service;
})
TaxiApp.controller('ReviewDriverItemScriptCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, trip_comment) {


    $scope.loading = true;
    $scope.ReviewTxt = trip_comment
    $scope.ClickClose = function () {

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

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

    }


})


TaxiApp.service('CancelBookingItem', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (bookingId, imei, driverOId) {
        var modalInstance = $modal.open({
            windowClass: 'CancelBookingItem',
            templateUrl: 'CancelBookingItem.html',
            controller: 'CancelBookingItemCtrl',
            resolve: {
                bookingId: function () {
                    return bookingId;
                }
                    ,
                imei: function () {
                    return imei;
                }
                    ,
                driverOId: function () {
                    return driverOId;
                }

            }


        });

    };



    return service;
})
TaxiApp.controller('CancelBookingItemCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, bookingId, imei, driverOId) {


    $scope.loading = true;



    $scope.ClickClose = function () {

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

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

    }


    $scope.cancelCurrentBooking = function (bookinid, imei, driveroid) {
        $.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) {
                        $scope.loadDailyBooking();

                    }
                });

            }
        })
    };
    $scope.CancelBtn = function () {
        // alert(bookingId + "---" + imei + "---" + driverOId);
        $scope.cancelCurrentBooking(bookingId, imei, driverOId);
        $scope.ClickClose();

    }
})