(function(_, $) {
   
    $(document).ready(function() {
        $('label[for="litecheckout_phone"]').addClass('cm-required');

        $.ceEvent('on', 'ce.commoninit', function(context) {
            $(document).find('#digit-1').addClass('focus-visible').focus();
        });
        $(document).on('keyup', '.otp_input', function(e) {

            $('.focus-visible').removeClass('focus-visible');
            $(this).addClass('focus-visible');
            if (e.keyCode == 8) {
                var id = $(this).parent().find('.focus-visible').attr('id');
                var data_previous = $(this).parent().find('.focus-visible').attr('data-previous');

                $(this).parent().find('#' + data_previous).focus();
                $(this).parent().find('#' + id).focusout();
            } else {
                var data_next = $(this).parent().find('.focus-visible').attr('data-next');
                var data_previous = $(this).parent().find('.focus-visible').attr('data-previous');

                $(this).parent().find('#' + data_next).focus();
                $(this).parent().find('#' + data_previous).focusout();
            }
        });
    });
   
    $(document).find("[name='dispatch\\[profiles.update\\]'],[data-ca-dispatch='dispatch[profiles.update]']").on('click', function() {
        var jelm = $(this),
            form = jelm.closest('form');
        if (!form.ceFormValidator('check')) {
            return;
        }
        
        $.ceEvent('on', 'ce.formpost_' + $(form).attr('name'), function() {
           
            if (!$(form).find("[name='user_data[phone]']").val()) {
                var ec_u_type = $(form).find("[name='user_data[ec_otp_user_type]']").val();

                if (!(ec_u_type == 'A' || ec_u_type == 'V')) {
                    $.ceNotification('show', {
                        type: 'E',
                        title: _.tr('error'),
                        message: _.tr('ec_must_not_be_phone_empty')
                    });
                    return false;
                }
            } else if ($("#ec_phone_verified").val() != 1 || (!(_.current_user_id == 0 || _.current_user_id == undefined) && (_.current_user_phone != $(form).find("[name='user_data[phone]']").val()))) {
                var phone = $(form).find("[name='user_data[phone]']").val();
                $.extend(_, {
                    phone_on_verification: phone
                });

                var email = $(form).find("[name='user_data[email]']").val();
                var url = fn_url('ec_otp_verification.verify_phone&phone=' + encodeURIComponent(phone) + '&email=' + email);
                $('#verify_phone_btn').attr('href', url);
                $('#verify_phone_btn').click();
                return false;
            }
        });
    });


    if ($("#ec_verify_phone_ckt_btn").length) {
        $('input[name="user_data[phone]"]').on('input', function() {
            if (_.current_user_phone.replace(/[^a-zA-Z0-9 ]/g, '') != this.value.replace(/[^a-zA-Z0-9 ]/g, '')) {
                $('#ec_phone_verified').attr('value', "0");
            } else {
                if ($('#ec_phone_verified').attr("data-ca-current-phone-verified") != '0') {
                    $('#ec_phone_verified').attr('value', "1");
                }
            }
        });

        var jelm = $(document).find("[name='dispatch[checkout.place_order]']");
    
        form = jelm.closest('form');
        $.ceEvent('on', 'ce.formpost_' + $(form).attr('name'), function() {  
            if (!$(form).find("[name='user_data[phone]']").val()) {
            
                $.ceNotification('show', {
                    type: 'E',
                    title: _.tr('error'),
                    message: _.tr('ec_must_not_be_phone_empty')
                });
                
                $("#ajax_overlay").css("display", "none");
                $("#ajax_loading_box").css("display", "none");

                return false;
            } else if ($("#ec_phone_verified").val() != 1) {
                var phone = $(form).find("[name='user_data[phone]']").val();
                $.extend(_, {
                    phone_on_verification: phone
                });

                var url = fn_url('ec_otp_verification.verify_phone&phone=' + encodeURIComponent(phone) + "&for_checkout=1");
                $('#ec_verify_phone_ckt_btn').attr('href', url);
                $('#ec_verify_phone_ckt_btn').click();
                return false;
            }
        });
    }

    $.ceEvent('on', 'ce.dialog.before_open', function(dialog_state, params) {
        if (dialog_state.is_opening_allowed === false) {
            return;
        }

        if (params.purpose === 'ec_otp_request') {
            var $clickedButton = $("[href=\"".concat(params.href, "\"]")),
                $form = $clickedButton.closest('form'),
                $existSubmitButton = $form.find('[type=submit], input[type=image]').length;
            if ($existSubmitButton) {
                var result = $form.ceFormValidator('check', true, null, true);
                dialog_state.is_opening_allowed = result;
            }
        }
    });
    $(document).on('click', '#ec_verify_otp_btn', function() {
        var jelm = $(this),
            form = jelm.closest('form');
        form.find('.ec-cm-required').addClass('cm-required');
    })
    $(document).on('click', '#ec_verify_phone_btn', function() {
        var jelm = $(this),
            form = jelm.closest('form');

        form.find('.ec-cm-required').addClass('cm-required');
        if (!form.ceFormValidator('check')) {
            return;
        }
        let form_data = $(form).serializeArray();
        if (form_data.find(item => item.name === 'for_admin_register')) {
            var url = fn_url("auth.ec_verify_otp_register");
        } else {
            const forCheckoutValue = form_data.find(item => item.name === 'for_checkout');
            if (!forCheckoutValue) {
                var url = fn_url("ec_otp_verification.verify_otp_register");
            } else {
                var url = fn_url("ec_otp_verification.verify_checkout_phone");
            }
        }
        $.ceAjax('request', url, {
            data: {
                form_data: form_data,
            },
            method: 'post',
            callback: function callback(response) {
                if (response['verified']) {
                    $('.ui-dialog-titlebar-close').click();
                    $.ceNotification('show', {
                        type: 'N',
                        title: $('.ec_error_text').attr('data-ca-notice-text'),
                        message: $('.ec_error_text').attr('data-verified-text')
                    });
                    $('#ec_phone_verified').val('1');
                    //Updating the current user phone after successfull verification
                    _.current_user_phone = _.phone_on_verification;
                    if ($(document).find("[name='dispatch[checkout.place_order]']").length > 0) {
                        $(document).find("[name='dispatch[checkout.place_order]']").click();
                    } else if ($(document).find("[data-ca-dispatch='dispatch[profiles.update]']").length > 0) {
                        $(document).find("[data-ca-dispatch='dispatch[profiles.update]']").click();
                    } else if ($(document).find("[name='dispatch[profiles.update]']").length > 0) {
                        $(document).find("[name='dispatch[profiles.update]']").click();
                    }
                }
            }
        });
        return false;
    });

})(Tygh, Tygh.$);