var TaxiApp = angular.module('ReservationsApp', ['ngStorage', 'ngDialog', 'angularSpinner', 'angularUtils.directives.dirPagination', 'ui.bootstrap', 'angularAwesomeSlider', 'angular-growl', 'ngAnimate', 'AxelSoft']);
var Reservations;

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

TaxiApp.controller('ReservationsCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'usSpinnerService', 'growl', 'DeleteBooking',
    function ($scope, $http, $sessionStorage, ngDialog, usSpinnerService, growl, DeleteBooking) {
        $scope.loading = false;
        $scope.injectedObject = {};
        var obj
        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;
        $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 enterpriseAwesomplete;
        //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();
        $scope.ScuedualList = [];
      
        Localization(sessionStorage.selectedLanguage, 'mapview', $scope, sessionStorage);

        $scope.value3 = 5;

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

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

        Dashboard = {
            DriversList: [],
            EnterpriseList: [],
            load: function () {
                self = this;
               

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

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

                    success: function (result) {
                        var company_input = document.getElementById("2");



                        self.EnterpriseList = JSON.parse(result.GetEnterpriseCustomersResult);
                        //booking.create({ driverOID: '', DriverName: '', booking_form_btn: '', CustomerPhoneN: '', Landmark: '', IsDuplicate: false });
                        var enterpriseAwesomplete = new Awesomplete(company_input, {

                            list: self.EnterpriseList,
                            data: function (item, input) {
                                return { label: item.EnterpriseName, value: item.EnterpriseCustomerId };
                            },
                            autoFirst: true,
                            minChars: 1

                        });
                        company_input.addEventListener('awesomplete-selectcomplete', function (item) {
                            $('#2').attr("OID", item.text.value);
                        });

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

        }
        $(document).ready(function(){ Dashboard.load();})
        
        getFormattedDate = function (date) {

            var dt = new Date(date);
            var dt1 = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
            return dt1;
        };

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

        Reservations = {
            getCusomerName: function (number) {
                slef = this;
                $scope.Name = "";
                if (number != undefined) {
                    if (number.length >= 0) {

                        $scope.loading = true;
                        $.ajax({
                            cache: true,
                            url: WebsiteServiceUrl + "GetCustomerNameWithLandmark/" + number + "/" + sessionStorage.CompanyOID,
                            type: 'GET',
                            //jsonpCallback: "loginResponse",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            error: function () {
                                $scope.loading = false;
                            },
                            success: function (result) {

                                $scope.loading = false;
                                $scope.$apply();

                                var response = result.GetCustomerNameWithLandmarkResult.split('~');
                                var data = JSON.parse(response[0])
                              
                                $('#1').val(data.CustomerName);
                               


                              
                               
                            }
                        });
                    }
                }

            },
            init: function () {
                this.populate();

            },
            populate: function () {
                this.get().done(function (result) {
                    $scope.ScuedualList = JSON.parse(result.ViewAllBookingScheduleForCompanyResult);
                    // $scope.selectedInstitution = $scope.InstitutionList[0];
                    $scope.loading = false;

                    $scope.$apply();
                });

            },
            refresh: function () {
              // $('#createdBookingTable').empty();
                this.populate();
            },
            get: function () {
                // return $.Deferred().resolve(localStorage.getItem('comments'));

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

            },
            CreateNew: function () {

                    var Is_Repeating;
                    var phoneNo = $("#0").val();
                    var CustomerName = $("#1").val();
                    var fromAddress = $("#3").val();
                    var toAddress = $("#4").val();
                    var Company = $('#2').attr("OID");
                    if ($('input:radio[name=Times]:checked').val() == "once") {
                        var date = getFormattedDate(Date.parse($("#Date").val())).toMSJSON();//$("#Date").val();
                        var onceTime = $("#OnceTime").val();
                        Is_Repeating = false;

                    } else {
                        var SatTime = $("#SatTime").val();
                        var SunTime = $("#SunTime").val();
                        var MonTime = $("#MonTime").val();
                        var TusTime = $("#TusTime").val();
                        var WedTime = $("#WedTime").val();
                        var ThuTime = $("#ThuTime").val();
                        var FriTime = $("#FriTime").val();
                        Is_Repeating = true;

                    }
                    obj = {
                        "bookingSchedule": {
                            "CompanyID": sessionStorage.CompanyOID,
                            "DriverOID": null,
                            "EnterpriseCustomeId": Company,
                            "Is_Repeating": Is_Repeating,
                            "OID": "0",
                            "BookingDate": date,
                            "BookingTime": onceTime,
                            "CustomerCallingNumber": phoneNo,
                            "CustomerName": CustomerName,
                            "SaturdayTime": ((!SatTime || SatTime == '') ? null : SatTime),
                            "SundayTime": ((!SunTime || SunTime == '') ? null : SunTime),
                            "MondayTime": ((!MonTime || MonTime == '') ? null : MonTime),

                            "TusedayTime": ((!TusTime || TusTime == '') ? null : TusTime),
                            "WednesdayTime": ((!WedTime || WedTime == '') ? null : WedTime),
                            "ThursdayTime": ((!ThuTime || ThuTime == '') ? null : ThuTime),

                            "FridayTime": ((!FriTime || FriTime == '') ? null : FriTime),
                            "FromLandMarkOID": "0",
                            "fromAddress": fromAddress,
                            "ToLandMarkOID": "0",
                            "toAddress": toAddress,
                            "Status": "A",
                            "LastSendDate": null
                        }
                    }
                    $.ajax({
                        type: "POST",
                        url: WebsiteServiceUrl + "AddCompanyBookingSchedule",
                        data: JSON.stringify(obj),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        processData: true,
                        success: function (data) {

                            if (data.AddCompanyBookingScheduleResult == "1") {

                                Reservations.refresh();
                                ClearPanel();
                                $("#Hidden").toggle();
                                $("#SuccessAlert").html("تم اضافة الحجز بنجاح");

                                $("#SuccessAlert").show();
                                setTimeout(function () {

                                    $("#SuccessAlert").hide();


                                }, 2000);


                            }
                           

                        },
                        error: function () {
                            $("#Hidden").toggle();
                            $("#SuccessAlert").html('نتعذر ارسال الحجز .. حاول مرة اخرى');
                            $("#SuccessAlert").show();
                            setTimeout(function () {

                                $("#SuccessAlert").hide();


                            }, 1000);

                        }
                    });


                
                
               
                
                 
           
            },
            Save: function () {
                if ($("#oid_hidden").val() == "0") {
                   
                    Reservations.CreateNew();

                } else {
                 
                    Reservations.Update();
                }
             
               
 
              
            },
            Update: function () {
                    var Is_Repeating;
                    var phoneNo = $("#0").val();
                    var CustomerName = $("#1").val();
                    var fromAddress = $("#3").val();
                    var toAddress = $("#4").val();
                    var Company = $('#2').attr("OID");
                    var CompanyBookingID = $("#HiddenOID").val();
                    if ($('input:radio[name=Times]:checked').val() == "once") {


                        var date = getFormattedDate(Date.parse($("#Date").val())).toMSJSON();//$("#Date").val();

                        var onceTime = $("#OnceTime").val();

                        var SatTime = null;
                        var SunTime = null;
                        var MonTime = null;
                        var TusTime = null;
                        var WedTime = null;
                        var ThuTime = null;
                        var FriTime = null;
                        Is_Repeating = false;

                    } else {


                        var SatTime = $("#SatTime").val();
                        var SunTime = $("#SunTime").val();
                        var MonTime = $("#MonTime").val();
                        var TusTime = $("#TusTime").val();
                        var WedTime = $("#WedTime").val();
                        var ThuTime = $("#ThuTime").val();
                        var FriTime = $("#FriTime").val();
                        var date = null;

                        var onceTime = null;


                        Is_Repeating = true;

                    }




                    obj = {
                        "bookingSchedule": {
                            "CompanyID": sessionStorage.CompanyOID,
                            "DriverOID": null,
                            "EnterpriseCustomeId": Company,
                            "Is_Repeating": Is_Repeating,
                            "OID": CompanyBookingID,
                            "BookingDate": date,
                            "BookingTime": onceTime,
                            "CustomerCallingNumber": phoneNo,
                            "CustomerName": CustomerName,
                            "SaturdayTime": ((!SatTime || SatTime == '') ? null : SatTime),
                            "SundayTime": ((!SunTime || SunTime == '') ? null : SunTime),
                            "MondayTime": ((!MonTime || MonTime == '') ? null : MonTime),

                            "TusedayTime": ((!TusTime || TusTime == '') ? null : TusTime),
                            "WednesdayTime": ((!WedTime || WedTime == '') ? null : WedTime),
                            "ThursdayTime": ((!ThuTime || ThuTime == '') ? null : ThuTime),

                            "FridayTime": ((!FriTime || FriTime == '') ? null : FriTime),
                            "FromLandMarkOID": "0",
                            "fromAddress": fromAddress,
                            "ToLandMarkOID": "0",
                            "toAddress": toAddress,
                            "Status": "A",
                            "LastSendDate": null
                        }
                    }
                    $.ajax({
                        type: "POST",
                        url: WebsiteServiceUrl + "UpdateCompanyBookingSchedule",
                        data: JSON.stringify(obj),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        processData: true,
                        success: function (data) {
                         

                            if (data.UpdateCompanyBookingScheduleResult == "1") {

                                Reservations.refresh();
                                ClearPanel();
                                $("#Hidden").toggle();
                                $("#SuccessAlert").html("تم تعديل الحجز بنجاح");

                                $("#SuccessAlert").show();
                                setTimeout(function () {

                                    $("#SuccessAlert").hide();


                                }, 2000);


                            }
                        },
                    });
               
            },
            DeleteRecord: function () {
                
                var OID =$("#HiddenOID").val();
                if (OID && OID != 0 && OID != "")
                {
                  

                     $.ajax({
                         url: WebsiteServiceUrl + "DeleteCompanyBookingSchedule/" + OID + "/" + companyOID,
                        cache: false,
                        success: function () {
                            Reservations.refresh();
                            ClearPanel();
                            $("#Hidden").toggle();
                        }
                    });

                  
                }


            }

        }
        Reservations.init();

        $scope.Edit = function ($event, item) {
            $("#ForEdit").html("تعديل");
            $("#Delete").show();
            var deleteItem = document.getElementById('Delete');
            var oid = deleteItem.getAttribute('oid');
            deleteItem.onclick = function () {
                $scope.DeleteBookingItem(oid);
            };
            if (!$('#Hidden').is(":visible")) {
                $("#Hidden").toggle();
            }
            $("#oid_hidden").val("1");
            //var fieldValue = $($event.currentTarget)[0].cellIndex;

            //$("#" + fieldValue).val(item);
            $("#0").val(item.CustomerCallingNumber);
            $("#1").val(item.CustomerName);
            $("#2").val(item.EnterpriseCustomeName);
            $("#3").val(item.fromAddress);
            $("#4").val(item.toAddress);
            $("#HiddenOID").val(item.OID);
        
            if (item.Is_Repeating == false) {
               
                $('input:radio[id=once]').prop('checked', true);
                $(".ToBeHiddenOnce").show();
                $(".ToBeHiddenAlways").hide();
                $(".ToBeHiddenAlways input").val("");

                $("#OnceTime").val(FormatTime(item.BookingTime));
                var dateOnce = new Date(Date.parse(item.BookingDate));
             
                var str = dateOnce.getFullYear() + "-" + (dateOnce.getMonth() + 1).pad(2) + "-" + dateOnce.getDate().pad(2) ;

               $("#Date").val(str);
              //  alert(str);
               $("input[name='alwaysTime']").prop('disabled', true);
               $("input[name='date']").prop('disabled', false);
               $("input[name='OnceTime']").prop('disabled', false);


            }
            else {
               
                      $('input:radio[id=always]').prop('checked', true);
                      $(".ToBeHiddenOnce").hide();
                      $(".ToBeHiddenAlways").show();
                      $(".ToBeHiddenOnce input").val("");

                      $("#SatTime").val(FormatTime(item.SaturdayTime));
                      $("#SunTime").val(FormatTime(item.SundayTime));
                      $("#MonTime").val(FormatTime(item.MondayTime));
                      $("#TusTime").val(FormatTime(item.TusedayTime));
                      $("#WedTime").val(FormatTime(item.WednesdayTime));
                      $("#ThuTime").val(FormatTime(item.ThursdayTime));
                      $("#FriTime").val(FormatTime(item.FridayTime));
                      $("input[name='alwaysTime']").prop('disabled', false);
                      $("input[name='date']").prop('disabled', true);
                      $("input[name='OnceTime']").prop('disabled', true);
            }

           
        }

        $('#0').change(function () {
            Reservations.getCusomerName($('#0').val());
        });
        var checkNumber = function (no) {
            if(no.length!=9 && no.length!=10)
                return false
            return true
        }


        var FormatTime = function (t) {
            var str = t;
            str = str.slice(0, -3);
          return str;

        }
        var ClearPanel = function () {
            $(".input-field").each(function () {
                $(this).val("");
            });
            $("#once").attr('checked', false);
            $("#always").attr('checked', false);
            $(".ToBeHiddenAlways").hide();
            $(".ToBeHiddenOnce").hide();

            $("#0").parent().removeClass("parsley-success parsley-error");
            $("#1").parent().removeClass("parsley-success parsley-error");
            $("#3").parent().removeClass("parsley-success parsley-error");
            $("#Date").parent().removeClass("parsley-success parsley-error");
            $("#OnceTime").parent().removeClass("parsley-success parsley-error");
            $("#SatTime").parent().removeClass("parsley-success parsley-error");
            $("#SunTime").parent().removeClass("parsley-success parsley-error");
            $("#Mon").parent().removeClass("parsley-success parsley-error");
            $("#TusTime").parent().removeClass("parsley-success parsley-error");
            $("#WedTime").parent().removeClass("parsley-success parsley-error");
            $("#ThuTime").parent().removeClass("parsley-success parsley-error");
            $("#FriTime").parent().removeClass("parsley-success parsley-error");


        }




        $(function () {
            Parsley.addValidator('checkChildren', {
                messages: { en: 'You must correctly fill at least one of these blocks!' },
                requirementType: 'integer',
                validate: function (_value, requirement, instance) {
                    for (var i = 1; i <= requirement; i++)
                        if (instance.parent.isValid({ group: 'block-' + i, force: true }))
                            return true; // One section is filled, this check is valid
                    return false; // No section is filled, this validation fails
                }
            });


            window.Parsley.on('field:error', function () {
               
            });
            $('#NewBookingForm').parsley({ excluded: ' :disabled' }).on('field:validated', function () {
                
                var ok = $('.parsley-error').length === 0;
                $('.bs-callout-info').toggleClass('hidden', !ok);
                $('.bs-callout-warning').toggleClass('hidden', ok);
            })
            .on('form:submit', function () {
                Reservations.Save();
                return false; // Don't submit form for this demo
            }).subscribe('parsley:form:validate', function (formInstance) {
                if($('input:radio[name=Times]:checked').val() != "once"){
                    // If any of these fields are valid
                    if ($("#SatTime").parsley().isValid() ||
                        $("#SunTime").parsley().isValid() ||
                        $("#MonTime").parsley().isValid() ||
                        $("#TusTime").parsley().isValid() ||
                        $("#WedTime").parsley().isValid() ||
                        $("#ThuTime").parsley().isValid() ||
                        $("#FriTime").parsley().isValid()
                        ) {
                        // Remove the error message
                        $('.invalid-form-error-message').html('');

                        // Remove the required validation from all of them, so the form gets submitted
                        // We already validated each field, so one is filled.
                        // Also, destroy parsley's object

                        $("#SatTime").removeAttr('required').parsley().destroy();
                        $("#SunTime").removeAttr('required').parsley().destroy();
                        $("#MonTime").removeAttr('required').parsley().destroy();
                        $("#TusTime").removeAttr('required').parsley().destroy();
                        $("#WedTime").removeAttr('required').parsley().destroy();
                        $("#ThuTime").removeAttr('required').parsley().destroy();
                        $("#FriTime").removeAttr('required').parsley().destroy();

                        return;
                    }

                    // If none is valid, add the validation to them all
                    $("#SatTime").attr('required', 'required').parsley();
                    $("#SunTime").attr('required', 'required').parsley();
                    $("#MonTime").attr('required', 'required').parsley();
                    $("#TusTime").attr('required', 'required').parsley();
                    $("#WedTime").attr('required', 'required').parsley();
                    $("#ThuTime").attr('required', 'required').parsley();
                    $("#FriTime").attr('required', 'required').parsley();



                    // stop form submission
                    //formInstance.submitEvent.preventDefault();
                    formInstance.validationResult = false
                    // and display a gentle message
                    $('.invalid-form-error-message')
                        .html("You must correctly fill the fields of at least one of these two blocks!")
                        .addClass("filled");
                    return;

            }
            });
        });


        $scope.DeleteBookingItem = function (id) {
            DeleteBooking.open(id);



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

        var modalInstance = $modal.open({
            windowClass: 'DeleteBooking',
            templateUrl: 'DeleteBooking.html',
            controller: 'DeleteBookingCtrl',
            resolve: {
                lmid: function () {
                    return lmid;
                }
            }

        });

    };

    return service;

})

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


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



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


    $scope.ClickClose = function () {

        $modalInstance.dismiss('Cancel');

    }


    $scope.DeleteBookingId = function ($lmid) {

        Reservations.DeleteRecord();
        $scope.ClickClose();
    }
})


