<?php
// Copyright 1999-2025. WebPros International GmbH. All rights reserved.

$elementsIds = array_map(function ($element) {
    return $this->element->getElement($element)->getId();
}, $this->children);

$parents = array_map(function ($e) {
    /** @var Zend_Form_Element $parent */
    $parent = $this->element->getElement($e);
    $resourceElement = $parent->getDecorator('ResourceElement');
    $checkbox = $resourceElement->getOption('checkboxField') ?: 'unlimited';
    return [
        'id' => $parent->getId() . '-' . $checkbox,
        'reverse' => !is_null($rc = $resourceElement->getOption('reverseCheckbox')) && $rc,
    ];
}, $this->parents);

if (!count($parents)) {
    return;
}

?>

<script type="text/javascript">
//<![CDATA[
(function () {
    var parents = <?=Zend_Json::encode($parents)?>,
        elementIds = <?=Zend_Json::encode($elementsIds)?>;

    function parentStatus () {
        return this.el.checked? this.reverse : !this.reverse;
    }

    function parentsStatusIsOn() {
        var result = false;

        parents.forEach(function (parent) {
            if (parent.status()) {
                result = true;
            }
        });

        return result;
    }

    function updateElementValues () {
        var status = parentsStatusIsOn();
        elementIds.forEach(function (id) {
            var el = document.getElementById(id);
            if (el.hasOwnProperty('updateElementValueFunction')) {
                el.updateElementValueFunction(null, status);
            } else if (status) {
                el.disabled = false;
            } else {
                el.disabled = true;
            }
        });
    }

    parents.forEach(function (parent) {
        parent.el = document.getElementById(parent.id);
        parent.status = parentStatus;
        parent.el.addEventListener('click', updateElementValues);
    });

    updateElementValues();
})();
//]]>
</script>
