var buttons = document.querySelectorAll('.recaptcha');
if (buttons != null) {
    buttons.forEach(btn => {
        enterKeyListener(btn.getAttribute('data-form'));
        btn.addEventListener('click', (e) => {
            var form_id = e.currentTarget.getAttribute('data-form');
            var form = document.getElementById(form_id);
            var recaptcha_site_key = e.currentTarget.getAttribute('data-sitekey');
            var recaptcha_element = document.querySelector('#' + form_id + ' input[name="recaptcha"]');
            var recaptcha_action = document.querySelector('#' + form_id + ' input[name="recaptcha_action"]').value;
            if (form.checkValidity()) {
                grecaptcha.ready(function () {
                    grecaptcha.execute(recaptcha_site_key, { action: recaptcha_action }).then(function (token) {
                        Promise.resolve(recaptcha_element.value = token).then(function () {
                            form.submit();
                        });
                    });
                });
            } else {
                form.reportValidity();
            }
        });
    });
}

function enterKeyListener(form) {
    var inputs = document.querySelectorAll('#' + form + ' input');
    inputs.forEach(input => {
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.querySelector('#' + form + ' .recaptcha').click();
            }
        });
    });
}