<?php $this->extend('form_row'); ?>

<?php $this->block('field'); ?>
    <?php if ($this->hasErrors()): ?>
        <p class="error"><?= $this->getErrorAsString() ?></p>
    <?php endif; ?>

    <div class="g-recaptcha" 
        id="recaptcha-<?= $this->strCaptchaKey ?>"
        data-sitekey="<?= $this->publicKey ?>"
        data-callback="onSubmit_<?= $this->strCaptchaKey ?>"
        <?php if ($this->recaptchaType == 'invisible'): ?> data-size="invisible" <?php endif; ?>
    ></div>

    <script src="https://www.google.com/recaptcha/api.js?onload=onRecaptchaLoadCallbackField<?= $this->strCaptchaKey ?><?php if ($this->recaptchaType == 'recaptcha3'): ?>&render=<?= $this->publicKey ?><?php endif; ?>" defer async></script>
    <script type="text/javascript" defer async>
        function onRecaptchaLoadCallbackField<?= $this->strCaptchaKey ?> () {
            window.onSubmit_<?= $this->strCaptchaKey ?> = function () { };

            <?php if ($this->recaptchaType == 'invisible'): ?>
                var node = document.getElementById('recaptcha-<?= $this->strCaptchaKey ?>');
                while (node && node.tagName !== 'FORM') node = node.parentNode;

                if (node) {
                    node.addEventListener('submit', function (e) {
                        e.preventDefault();
                        grecaptcha.execute();
                    });
                }

                window.onSubmit_<?= $this->strCaptchaKey ?> = function () { node.submit(); }
            <?php elseif ($this->recaptchaType == 'recaptcha3'): ?>
                grecaptcha
                    .execute('<?= $this->publicKey ?>', {action: '<?= $this->recaptchaAction ?>'})
                    .then(function (token) {
                        var node = document.getElementById('recaptcha-<?= $this->strCaptchaKey ?>');

                        var input = document.createElement('input');
                        input.setAttribute('type', 'hidden');
                        input.setAttribute('name', 'g-recaptcha-response');
                        input.setAttribute('value', token);

                        node.replaceWith(input);
                    });
            <?php endif; ?>
        }
    </script>
<?php $this->endblock(); ?>