<?php
/**
 * 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    design
 * @package     default_default
 * @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)
 */
?>
<script type="text/javascript">
//<![CDATA[
var couponTypeSpecific = '<?php echo Mage_SalesRule_Model_Rule::COUPON_TYPE_SPECIFIC ?>';
var tmpButtonsActionsStorage = [];

function disableEnableCouponsTabContent(disable) {
    var containerId = 'promo_catalog_edit_tabs_coupons_section_content';
    if($(containerId)){
        var dataFields = $(containerId).select('input', 'select', 'textarea', 'button');
        for(var i = 0; i < dataFields.length; i++) {
            disable ? dataFields[i].disable().addClassName('disabled')
                : dataFields[i].enable().removeClassName('disabled');
        }
    }
    disable ? $('rule_coupon_code').enable() : $('rule_coupon_code').disable();
}

function handleCouponsTabContentActivity() {
    disableEnableCouponsTabContent(!$('rule_use_auto_generation').checked);
}

function handleCouponTypeChange() {
    $('rule_coupon_type').observe('change', function() {
        var disable = $('rule_coupon_type').value != couponTypeSpecific;
        if (!disable) {
            disable = !$('rule_use_auto_generation').checked;
        }
        disableEnableCouponsTabContent(disable);
    });
}

function refreshCouponCodesGrid(grid, gridMassAction, transport) {
    grid.reload();
    gridMassAction.unselectAll();
}

function generateCouponCodes(idPrefix, generateUrl, grid) {
    $(idPrefix + 'information_fieldset').removeClassName('ignore-validate');
    var validationResult = $(idPrefix + 'information_fieldset').select('input',
            'select', 'textarea').collect( function(elm) {
        return Validation.validate(elm, {
            useTitle :false,
            onElementValidate : function() {
            }
        });
    }).all();
    $(idPrefix + 'information_fieldset').addClassName('ignore-validate');

    if (!validationResult) {
        return;
    }
    var elements = $(idPrefix + 'information_fieldset').select('input', 'select', 'textarea');

    elements = elements.concat(
        $$('#rule_uses_per_coupon'),
        $$('#rule_uses_per_customer'),
        $$('#rule_to_date')
    );

    var params = Form.serializeElements(elements, true);
    params.form_key = FORM_KEY;
    $('messages').update();
    var couponCodesGrid = eval(grid);
    new Ajax.Request(generateUrl, {
        parameters :params,
        method :'post',
        onComplete : function (transport, param){
            var response = transport.responseJSON || transport.responseText.evalJSON(true) || {};

            if (couponCodesGrid) {
                couponCodesGrid.reload();
            }
            if (response && response.messages) {
                $('messages').update(response.messages);
            }
            if (response && response.error) {
                alert(response.error.stripTags().toString());
            }
        }
    });
}

Ajax.Responders.register({
    onComplete: function() {
        if ($('promo_catalog_edit_tabs_coupons_section_content')
            && $('promo_catalog_edit_tabs_coupons_section_content').visible()
            && Ajax.activeRequestCount == 0
        ) {
            handleCouponsTabContentActivity();
        }
    }
});

document.observe("dom:loaded", handleCouponsTabContentActivity);
document.observe("dom:loaded", handleCouponTypeChange);
//]]>
</script>
