/**
 * OpenMage
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available at https://opensource.org/license/afl-3-0-php
 *
 * @category    Mage
 * @package     js
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
 * @copyright   Copyright (c) 2022 The OpenMage Contributors (https://www.openmage.org)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
var Captcha = Class.create();
Captcha.prototype = {
    initialize: function(url, formId){
        this.url = url;
        this.formId = formId;
    },
    refresh: function(elem) {
        formId = this.formId;
        if (elem) Element.addClassName(elem, 'refreshing');
        new Ajax.Request(this.url, {
            onSuccess: function (response) {
                if (response.responseText.isJSON()) {
                    var json = response.responseText.evalJSON();
                    if (!json.error && json.imgSrc) {
                        $(formId).writeAttribute('src', json.imgSrc);
                        if (elem) Element.removeClassName(elem, 'refreshing');
                    } else {
                        if (elem) Element.removeClassName(elem, 'refreshing');
                    }
                }
            },
            method: 'post',
            parameters: {
                'formId'   : this.formId
            }
        });
    }
};

document.observe('billing-request:completed', function(event) {
    if (typeof window.checkout != 'undefined') {
        if (window.checkout.method == 'guest' && $('guest_checkout')){
            $('guest_checkout').captcha.refresh();
        }
        if (window.checkout.method == 'register' && $('register_during_checkout')){
            $('register_during_checkout').captcha.refresh();
        }
    }
});


document.observe('login:setMethod', function(event) {
    var switchCaptchaElement = function(shown, hidden) {
        var inputPrefix = 'captcha-input-box-', imagePrefix = 'captcha-image-box-';
        if ($(inputPrefix + hidden)) {
            $(inputPrefix + hidden).hide();
            $(imagePrefix + hidden).hide();
        }
        if ($(inputPrefix + shown)) {
            $(inputPrefix + shown).show();
            $(imagePrefix + shown).show();
        }
    };

    switch (event.memo.method) {
        case 'guest':
            switchCaptchaElement('guest_checkout', 'register_during_checkout');
            break;
        case 'register':
            switchCaptchaElement('register_during_checkout', 'guest_checkout');
            break;
    }
});
