/* update on 27/3/2018 */
$(document).on('ready', function() {
    App.bindCateringEvents();

    $('#catringform').click(function(){
        if($(window).width() < 991){               
                $('.link_mobilemenu').removeClass('active');
                $('.dropdown_mobile').removeClass('active');
            }
        App.popupshow();
        var tmpl = _.template($("#tmpl-catering").html());
        $('.t-popupdata').html(tmpl());
        $(".close").on('click',function(){           
            App.popuphide();
            
        });
        //ga('send', 'event', 'Catering', "Click_on_Catering", 1, true);
        dataLayer.push({
            'event': 'Catering',
            'restname': App.currentRestaurant.name,
            'ev_label': 'Click_on_Catering',
            'RestaurantID':restId
        });
        App.bindCateringEvents();
         $('.contactsubmit').on( "click", function() {
            App.contactsubmit();
        });
        App.catering_datepicker();

    });
});


/* update on 27/3/2018 */
$(document).on('ready', function() {
    App.bindCateringEvents();
    $(".a_modal-dialog").on( 'scroll', function(){
        $('.nc_days').datetimepicker('hide');
           $('.nc_time').datetimepicker('hide');  
        });
});


$(function () {
    /***Contact form***/
        App.showCatering =  function(){
            if($('.form_contact').hasClass('hide')){
                $('.form_contact').removeClass('form_disable hide');
                $('.form_thankyou').addClass('hide');
                $('.catering_booking .txt_astrick_checkout').removeClass('hide');
                // $("html,body").stop().animate({scrollTop: $('.catering_booking').offset().top});
                $(".a_modal-dialog").stop().animate({scrollTop: 0});


            }

        }
        App.validateContactName = function(){
            var hasError = false,
            name = $("[name=contact_firstname]");
            var errorMessage = name.closest("div").find(".error-message");
            if ($.trim(name.val()) === "") {
                errorMessage.removeClass("hide");
                hasError = true;
            } else {
                 errorMessage.closest(".error-message").addClass("hide");
            }
            var value = $.trim(name.val());
            name.val(value);
            return hasError;
        };
        App.validateContactPhoneNo = function(){
            var hasError = false,
                phoneNo = $("[name=contact_phonenumber]"),
                errorMessage = phoneNo.closest("div").find(".error-message"),
                phoneVal = $.trim(phoneNo.val().replace(/([*()'-\/ ])/g, ''));
            if (phoneVal === '') {
                errorMessage.html("We promise; No prank calls").removeClass("hide");
                hasError = true;
            } else if (phoneVal.length < 10) {
                errorMessage.html('You know, there\'s a cadence to phone numbers. They usually go xxx-xxx-xxxx').removeClass("hide");
                hasError = true;
            } else {
               errorMessage.html("").addClass("hide");
            }
            return hasError;
        };
        App.validateContactEmail = function(){
            var hasError = false,
            email = $("[name=contact_email]"),
            errorMessage = email.closest("div").find(".error-message");
            var emailFormat = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
            if ($.trim(email.val()) === "") {
                errorMessage.html('Hey, you forgot something').removeClass("hide");
                hasError = true;
            } else {
                if (!emailFormat.test(email.val())) {
                    errorMessage.html('That don\'t look like any e-mail I ever seen. Maybe the "@" or the "." are in the wrong spot. This isn\'t cubism, put things where they belong!').removeClass("hide");
                    hasError = true;
                } else {
                    errorMessage.html('').addClass("hide");
                }
            }
            return hasError;
        };
        App.validateContactEvent = function(){
            var hasError = false,
            describe_event = $("[name=contact_describe_event]");
            var errorMessage = describe_event.closest("div").find(".error-message");
            if ($.trim(describe_event.val()) === "") {
                errorMessage.removeClass("hide");
                hasError = true;
            } else {
                 errorMessage.closest(".error-message").addClass("hide");
            }
            var value = $.trim(describe_event.val());
            describe_event.val(value);
            return hasError;
        };
        App.validateContactLokingfor = function(){
            var hasError = false,
            food_looking = $("[name=contact_food_looking]");
            var errorMessage = food_looking.closest("div").find(".error-message");
            if ($.trim(food_looking.val()) === "") {
                errorMessage.removeClass("hide");
                hasError = true;
            } else {
                 errorMessage.closest(".error-message").addClass("hide");
            }
            var value = $.trim(food_looking.val());
            food_looking.val(value);
            return hasError;
        };

        App.validateDate = function(){
            var hasError = false,
                name = $("[name=nc_days]");
            var errorMessage = name.closest("div").find(".error-message");
            if ($.trim(name.val()) === "") {
                errorMessage.removeClass("hide");
                hasError = true;
            } else {
                if(!App.timeElapseError){
                  errorMessage.closest(".error-message").addClass("hide");  
                }
            }
            var value = $.trim(name.val());
            name.val(value);
            return hasError;
        };
        App.validateTime = function(){
            var hasError = false,
                name = $("[name=nc_time]");
            var errorMessage = name.closest("div").find(".error-message");
            if ($.trim(name.val()) === "") {
                errorMessage.removeClass("hide");
                hasError = true;
            } else {
                if(!App.timeElapseError){
                  errorMessage.closest(".error-message").addClass("hide");  
                }
            }
            var value = $.trim(name.val());
            name.val(value);
            return hasError;
        };

        App.validateNoOfPeople = function(){
            var hasError = false,
                phoneNo = $("[name=number_of_people]"),
                errorMessage = phoneNo.closest("div").find(".error-message"),
                phoneVal = $.trim(phoneNo.val().replace(/([*()'-\/ ])/g, ''));
            if (phoneVal === '') {
                errorMessage.html("Hey, you forgot something").removeClass("hide");
                hasError = true;
            } else {
                errorMessage.html("").addClass("hide");
            }
            return hasError;
        };

        App.validateNoOfPeopleblur = function(e){

            var hasError = false,
                phoneNo = $("[name=number_of_people]"),
                errorMessage = phoneNo.closest("div").find(".error-message"),
                phoneVal = $.trim(phoneNo.val().replace(/([*()'-\/ ])/g, ''));
            if (phoneVal.length > 0) {
                errorMessage.html("").addClass("hide");
                hasError = true;
            }
            return hasError;
        };

        App.catering_datepicker = function(){
            var minDateTime = new Date();
            if(App.currentRestaurant.current_dateTime){
                var minDateTime = App.parseDate(App.currentRestaurant.current_dateTime);
            }
            App.currentDateTime=minDateTime;

            var maxDate = new Date(minDateTime.getTime()+(60*24*60*60*1000));
            maxDate.setHours(maxDate.getHours()-1);
            var minDate = [('0' + (minDateTime.getMonth() + 1)).slice(-2),('0' + minDateTime.getDate()).slice(-2),minDateTime.getFullYear()].join('-');

            var dateCale = $('.nc_days').datetimepicker({
                minDate: 0,
                minDateTime: minDateTime,
                maxDate: maxDate,
                format: 'm-d-Y',
                todayButton: true,
                timepicker: false,
                closeOnWithoutClick: true,
                scrollInput: false,
                scrollMonth : false,
                closeOnDateTimeSelect: true,
                useCurrent: false,
                value:minDate,
                defaultTime: minDateTime.getHours() + ":" + minDateTime.getMinutes(),
                onSelectDate:function(data){

                    $('.nc_time').datetimepicker('destroy');
                    $('.nc_days').blur();
                    var reset =0;
                    var selectedDate = [('0' + (data.getMonth() + 1)).slice(-2),('0' + data.getDate()).slice(-2),data.getFullYear()].join('-');

                    setTimeout(function(){
                        if(minDate === selectedDate){
                            var selTime = $('.nc_time').val();
                            reset =0;
                            if(selTime < minDateTime.getHours()+":00" ){
                                reset =2;
                                $('.nc_time').val('');
                            }
                        }else{
                            reset =1;
                        }

                        App.catering_timepicker(data,reset);
                    },300);
                    var name = $("[name=nc_days]");
                    var errorMessage = name.closest("div").find(".error-message");
                    errorMessage.closest(".error-message").addClass("hide");
                }
            });
            dateCale.on('blur', function () {
               dateCale.datetimepicker('hide');
            });
            App.catering_timepicker(minDateTime,0);

        };
        App.catering_timepicker = function(minDateTime,reset){
            var maxDate = new Date(minDateTime.getTime()+(60*24*60*60*1000));
            maxDate.setHours(maxDate.getHours()-1);
            var defaultValue = (minDateTime.getHours()+1) +":00";
            if(reset){
               minDateTime = new Date('00:00:00');
               defaultValue = "01:00";
               $('.nc_time').val(defaultValue);
            }
            if(reset==2){
               var minDateTime = new Date();
                if(App.currentRestaurant.current_dateTime){
                    var minDateTime =  App.parseDate(App.currentRestaurant.current_dateTime);
                }
               defaultValue = (minDateTime.getHours()+1) +":00";
            }

            var timeCalender = $('.nc_time').datetimepicker({
                minDate: 0,
                minDateTime:minDateTime,
                maxDate: maxDate,
                format: 'H:00',
                todayButton: false,
                datepicker: false,
                closeOnWithoutClick: true,
                scrollInput: false,
                value:defaultValue,
                closeOnDateTimeSelect: true,
                defaultTime: defaultValue,
                onSelectTime:function(){
                    $('.nc_time').blur();
                    var name = $("[name=nc_days]");
                    var errorMessage = name.closest("div").find(".error-message");
                    errorMessage.closest(".error-message").addClass("hide");
                }

            });
            timeCalender.off('blur');
            timeCalender.on('blur', function () {
               timeCalender.datetimepicker('hide');
            });

        };
        App.bindCateringEvents = function() {

            $(".y-show-catering").on('click', $.proxy(App.showCatering, App));
            $("input[name=contact_phonenumber]").on('keypress', $.proxy(App.phoneNumberFormat, App));
            $("input[name=contact_firstname]").on('keypress', $.proxy(App.validateName, App));
            $("input[name=contact_firstname]").on('blur', $.proxy(App.validateContactName, App));
            $("input[name=contact_phonenumber]").on('blur', $.proxy(App.validateContactPhoneNo, App));
            $("input[name=nc_days]").on('blur', $.proxy(App.validateDate, App));
            $("input[name=nc_time]").on('blur', $.proxy(App.validateTime, App));
            $("input[name=contact_email]").on('blur', $.proxy(App.validateContactEmail, App));
            $("input[name=number_of_people]").on('blur', $.proxy(App.validateNoOfPeople, App));

            $("input[name=number_of_people]").on('keyup', $.proxy(App.validateNoOfPeopleblur, App));
            $("input[name=number_of_people]").on('keypress', $.proxy(App.phoneNumberFormat, App));
            $("textarea[name=contact_describe_event]").on('blur', $.proxy(App.validateContactEvent, App));
            //$("textarea[name=contact_food_looking]").on('blur', $.proxy(App.validateContactLokingfor, App));

            $("#catering").on('click', function(){
                if (/iPad|iPhone|iPod/i.test(navigator.userAgent)) {
                    $('.nc_days').blur();
                    $('.nc_time').blur();
                }
            });


        }  ;


        App.successContact = function(){
            $("[name=contact_firstname]").val('');
            $("[name=contact_phonenumber]").val('');
            $("[name=contact_email]").val('');
            $("[name=contact_describe_event]").val('');
            //$("[name=nc_days]").val('');
            $("[name=number_of_people]").val('');
            //$("[name=contact_food_looking]").val('');
            $(".error-message").addClass('hide');
        };
        App.contactsubmit = function(){
            var name = $("[name=contact_firstname]").val(),
            phone = $("[name=contact_phonenumber]").val(),
            email = $("[name=contact_email]").val(),
            //best_time = $("#best_time").val(),
            nc_days = $("[name=nc_days]").val()+" "+ $("[name=nc_time]").val(),
            number_of_people = $("[name=number_of_people]").val(),
            best_way = $("[name=contact_reachway]:checked").val(),
            describe_event = $("[name=contact_describe_event]").val(),
            //food_type = $("[name=contact_food_looking]").val(),
            evant_venue = $("[name=contact_eventvenue]:checked").val();
            var hasError = App.validateContactName(),
            hasError1 = App.validateContactPhoneNo(),
            hasError2 = App.validateContactEmail(),
            hasError3 = App.validateContactEvent(),
            hasError4 = App.validateDate(),
            hasError5 = App.validateTime(),
            hasError6 = App.validateNoOfPeople();

            var errorTimeDiv = $("[name=nc_days]").closest("div").find(".error-message");
            errorTimeDiv.closest(".error-message").addClass("hide")

            if(hasError || hasError1 || hasError2 || hasError3 || hasError4 || hasError5 || hasError6){
                if($('body').hasClass('landingsite')){
                    $("html,body").scrollTop(0);
                }else{
                    // $("html,body").stop().animate({scrollTop: $('.error-message:not(.hide):first').offset().top - 100});
                    $(".a_modal-dialog").stop().animate({scrollTop: 0});
                }

                return false;
            }else{
                $('.catering_booking  .lineloader').removeClass('hide');
                $('.form_contact').addClass('form_disable');
                var submitdata = {
                    'name' : name,
                    'phone_number' : phone,
                    'email' : email,
                    'date_/_time_of_party'  : nc_days,
                    'best_way_to_reach' : best_way,
                    'describe_your_event': describe_event,
                    'number_of_people' : number_of_people,
                    'do_you_need_an_event_venue': evant_venue,
                    'to_email' : toMailIdForCatering,
                    'token' : $.jStorage.get('oauth.token'),
                    'restaurant_id' : restId,
                    'subject':App.currentRestaurant.name+' Catering Booking'
                };
                var selected_dateTime= App.parseDate(nc_days);
                //var selected_dateTime= App.parseDate("03-27-2018 04:00");
                $.ajax({
                url:apiUrl+'/currenttime/'+restId+'?token='+$.jStorage.get('oauth.token'),
                cache: false,
                type: 'get',
                success: function(data) {
                        var currentDateTime = App.parseDate(data.city_date_time);

                        if(selected_dateTime.getTime() < currentDateTime.getTime()){
                            errorTimeDiv.removeClass("hide").html('selected time gone . select another slot!');
                            // $("html,body").stop().animate({scrollTop: errorTimeDiv.offset().top - 100});
                            $(".a_modal-dialog").stop().animate({scrollTop: 0});
                            App.timeElapseError=1;
                            $('.catering_booking  .lineloader').addClass('hide');
                            $('.form_contact').removeClass('form_disable');
                            return false;
                        } else {
                            $.ajax({
                                url: apiUrl + '/home/macatering',
                                type: 'post',
                                data: JSON.stringify(submitdata),
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function() { },
                                beforeSend: function() {
                                    setTimeout(function(){
                                        $('.catering_booking .lineloader').addClass('hide');
                                        $('.form_contact').removeClass('form_disable').addClass('hide');
                                        $('.form_thankyou').removeClass('hide');
                                        $('.catering_booking .txt_astrick_checkout').addClass('hide');
                                        // $("html,body").stop().animate({scrollTop: $('.catering_booking').offset().top});
                                        $(".a_modal-dialog").stop().animate({scrollTop: 0});
                                        dataLayer.push({
                                            'event': 'Catering Booking',
                                            'restname': App.currentRestaurant.name,
                                            'ev_label': 'Click_on_Submit_Button_in_Catering_Booking',
                                            'RestaurantID':restId
                                        });
                                        App.successContact();
                                    },2500);
                                },
                                error: function() {
                                    return false;
                                }
                            });
                        }
                    }
                });
            }
        };

        $('.contactsubmit').on( "click", function() {
            App.contactsubmit();
        });
});