jQuery(function($){

    $('#access-pass').on('input', function(){
        if($(this).val() == ''){
            $('#request_access_to_media').prop('disabled', true);
        }else{
            $('#request_access_to_media').prop('disabled', false);
        }
    });

    function IsEmail(email) {
        if (!email.trim().includes('@') || email.trim().includes(',')) {
            return false;
        }
        else {
            return true;
        }
    }

    $('#request_access_to_media').on('submit click', function(e){
        e.preventDefault();
        var $this = $(this);
        
        if( formipay_thankyou.access_method == 'magic_link' && IsEmail($('#access-pass').val()) == false){
            Swal.fire({
                html: formipay_thankyou.email_validation.error.message,
                icon: 'error'
            });
            return false;
        }

        $.ajax({
            type: 'post',
            url: formipay_thankyou.ajax_url,
            data: {
                action: 'request_access_link',
                pass: $('#access-pass').val(),
                method: formipay_thankyou.access_method,
                order: formipay_thankyou.order_id,
                _wpnonce: formipay_thankyou.nonce
            },
            beforeSend: function() {
                $this.text('Processing...').prop('disabled', true);
            },
            success: function (res) {
                $this.text('Get Access Link').prop('disabled', false);
                if(res.action == 'reload'){
                    window.location.reload();
                }else{
                    Swal.fire({
                        title: res.title,
                        html: res.message,
                        icon: res.icon
                    });
                }
            }
        });
    });

});