<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php
/**
 * @methods
 *  getTitle() - string
 *  getSaveUrl() - string
 *  getSections() - array
 *  getForm() - html
 */
?>
<form action="<?php /* @escapeNotVerified */ echo $block->getSaveUrl() ?>" method="post" id="config-edit-form" enctype="multipart/form-data">
    <?php echo $block->getBlockHtml('formkey')?>
    <div class="accordion">
        <?php echo $block->getChildHtml('form') ?>
    </div>
</form>
<script>
require([
    "jquery",
    "uiRegistry",
    "jquery/jquery.hashchange",
    "mage/mage",
    "prototype",
    "mage/adminhtml/form",
    "domReady!"
], function(jQuery, registry){

    var adminSystemConfig = {
        getUp: function (element, tag) {
            var $element = Element.extend(element);
            if (typeof $element.upTag == 'undefined') {
                $element.upTag = {};
            }
            if (typeof $element.upTag[tag] == 'undefined') {
                $element.upTag[tag] = Element.extend($element.up(tag));
            }
            return $element.upTag[tag];
        },
        getUpTd: function (element) {
            return this.getUp(element, 'td');
        },
        getUpTr: function (element) {
            return this.getUp(element, 'tr');
        },
        getScopeElement: function(element) {
            var $element = Element.extend(element);
            if (typeof $element.scopeElement == 'undefined') {
                var scopeElementName = element.getAttribute('name').replace(/\[value\]$/, '[inherit]');
                $element.scopeElement = this.getUpTr(element).select('input[name="' + scopeElementName + '"]')[0];
                if (typeof $element.scopeElement == 'undefined') {
                    $element.scopeElement = false;
                }
            }
            return $element.scopeElement;
        },
        getDeleteElement: function(element) {
            var $element = Element.extend(element);
            if (typeof $element.deleteElement == 'undefined') {
                $element.deleteElement = this.getUpTd(element)
                    .select('input[name="'+ element.getAttribute('name') + '[delete]"]')[0];
                if (typeof $element.deleteElement == 'undefined') {
                    $element.deleteElement = false;
                }
            }
            return $element.deleteElement;
        },
        mapClasses: function(element, full, callback, classPrefix) {
            if (typeof classPrefix == 'undefined') {
                classPrefix = 'shared'
            }
            element.classNames().each(function(className) {
                if (className.indexOf(classPrefix + '-') == 0
                    || (full && className.indexOf(classPrefix + '_') == 0)
                    ) {
                    callback(className);
                }
            });
        },
        getRegisteredEvents: function(element) {
            var events = [];
            var registry = Element.retrieve(Element.extend(element), 'prototype_event_registry');
            if (!registry) {
                return events;
            }
            registry.each(function(pair) {
                var eventName = pair.key;
                if (!eventName) {
                    return;
                }
                var responders = registry.get(eventName);
                if (!responders) {
                    return;
                }
                responders.each(function(responder) {
                    if (!responder.handler) {
                        return;
                    }
                    events.push({
                        'eventName': eventName,
                        'handler': responder.handler
                    });
                });
            });
            return events;
        },
        onchangeSharedElement: function(event) {
            var element = Element.extend(Event.element(event));
            adminSystemConfig.mapClasses(element, true, function(className) {
                $$('.' + className).each(function(el) {
                    if (element == el) {
                        return;
                    }

                    var tagName = el.tagName.toLowerCase();
                    if (tagName == 'input' && el.getAttribute('type') == 'file') {
                        var $el = Element.extend(el);
                        var events = adminSystemConfig.getRegisteredEvents(el);
                        $el.stopObserving('change');
                        var elId = $el.id;
                        $el.replace($el.outerHTML);
                        events.each(function(event) {
                            Event.observe(Element.extend(document.getElementById(elId)), event.eventName, event.handler);
                        });
                    } else {
                        el.stopObserving('change', adminSystemConfig.onchangeSharedElement);
                        if (tagName == 'input' && el.getAttribute('type') == 'checkbox') {
                            if (el.checked != element.checked) {
                                Element.extend(el).click();
                            }
                        } else if (tagName == 'select') {
                            var $el = Element.extend(el);
                            Element.extend(element).select('option').each(function(option) {
                                var relatedOption = $el.select('option[value="' + option.value + '"]')[0];
                                if (typeof relatedOption != 'undefined') {
                                    relatedOption.selected = option.selected;
                                }
                            });
                        } else {
                            el.value = element.getValue();
                        }
                        if (Element.extend(el).requiresObj) {
                            Element.extend(el).requiresObj.indicateEnabled();
                        }
                        fireEvent(el, 'change');
                        Event.observe(el, 'change', adminSystemConfig.onchangeSharedElement);
                    }
                });
            });
        },
        checkRequired: function(element, callback) {
            var tagName = this.tagName.toLowerCase();
            if (tagName != 'fieldset') {
                if (adminSystemConfig.getUpTr(this).visible()) {

                    if (this.hasClassName('not-required')) {
                        return;
                    }

                    var typeAttr = null;
                    if (tagName == 'input') {
                        typeAttr = this.getAttribute('type').toLowerCase();
                    }
                    var valueIsEmpty = false;
                    var scopeElement = adminSystemConfig.getScopeElement(this);
                    if (!scopeElement || !scopeElement.checked) {
                        if (typeAttr == 'file') {
                            var deleteUploadedElement = adminSystemConfig.getDeleteElement(this);
                            valueIsEmpty = !deleteUploadedElement && this.value == ''
                                || deleteUploadedElement && deleteUploadedElement.checked;
                        }
                        valueIsEmpty = valueIsEmpty
                            || (typeAttr == 'text' || typeAttr == 'password') && this.value == ''
                            || (tagName == 'select') && (this.getAttribute('multiple') != null)
                            && this.getValue().length == 0
                            || (tagName == 'select') && (this.getAttribute('multiple') == null)
                            && this.getValue() == null;
                    }

                    if (valueIsEmpty) {
                        if (element.value != 0) {
                            element.value = 0;
                            fireEvent(element, 'change');
                        }
                        element.disable();
                    }
                }
            } else {
                this.select('input,select').each(function(inputElement) {
                    adminSystemConfig.checkRequired.call(Element.extend(inputElement), element, callback);
                });
            }
            callback(this);
        }
    };

    window.configForm = jQuery('#config-edit-form').mage('form').mage('validation', {
        submitHandler: function(form)
        {
            $$('.requires').each(function(element) {
                var scopeElement = adminSystemConfig.getScopeElement(element);
                if (!scopeElement || !scopeElement.checked) {
                    Element.extend(element).disabled = false;
                }
            });
            jQuery(form).trigger('afterValidate');
            form.submit();
        }
    });

    $$('.shared').each(function(element){
        Event.observe(element, 'change', adminSystemConfig.onchangeSharedElement);

        // scope should be shared together with the field
        var scopeElement = adminSystemConfig.getScopeElement(element);
        if (scopeElement) {
            adminSystemConfig.mapClasses(element, false, function(className) {
                scopeElement.addClassName('shared_scope-' + className.substr(7));
            });
            Event.observe(scopeElement, 'change', adminSystemConfig.onchangeSharedElement);
        }

        // file fields should share deletion
        if (element.tagName.toLowerCase() == 'input' && element.getAttribute('type') == 'file') {
            var deleteUploadedElement = adminSystemConfig.getDeleteElement(element);
            if (deleteUploadedElement) {
                adminSystemConfig.mapClasses(element, false, function(className) {
                    deleteUploadedElement.addClassName('shared_delete-' + className.substr(7));
                });
                Event.observe(deleteUploadedElement, 'change', adminSystemConfig.onchangeSharedElement);
            }
        }

        // process situation, when control is complex
        adminSystemConfig.mapClasses(element, true, function(className) {
            var controls = adminSystemConfig.getUpTd(element).select('.' + className);
            if (controls.length < 2) {
                return;
            }

            var counter = 0;
            controls.each(function(controlElement) {
                controlElement.removeClassName(className);
                controlElement.addClassName('shared_' + counter + className.substr(6));
                counter++;
            });
        });
    });

    $$('.requires').each(function(element) {
        var eventObj = {
            'element': Element.extend(element),
            'requires': [],
            'callback': function(required) {},
            checkRequirements: function() {
                var scopeElement = adminSystemConfig.getScopeElement(eventObj.element);
                if (!scopeElement || !scopeElement.checked) {
                    eventObj.element.enable();
                    eventObj.requires.each(function(required) {
                        adminSystemConfig.checkRequired.call(Element.extend(required), eventObj.element, eventObj.callback);
                    }.bind(this));
                }
            },
            keydownCheckRequirements: function() {
                window.setTimeout(eventObj.checkRequirements, 1);
            },
            bindCheckingObserver: function(element) {
                if (element.tagName.toLowerCase() == 'fieldset') {
                    Element.extend(element).select('input,select').each(function(subElement) {
                        eventObj.bindCheckingObserver(subElement);
                    })
                } else {
                    var scopeElement = adminSystemConfig.getScopeElement(element);
                    if (scopeElement) {
                        Event.observe(scopeElement, 'click', eventObj.checkRequirements);
                    }
                    Event.observe(element, 'change', eventObj.checkRequirements);
                    Event.observe(element, 'keydown', eventObj.keydownCheckRequirements);
                }
            },
            indicateEnabled: function() {
                var labelElement = adminSystemConfig.getUpTr(eventObj.element).select('td.label label')[0];
                if (typeof labelElement != 'undefined') {
                    if (eventObj.element.value == 1) {
                        labelElement.addClassName('enabled');
                    } else {
                        labelElement.removeClassName('enabled');
                    }
                }
            }
        };

        // fill eventObj with required elements
        adminSystemConfig.mapClasses(element, false, function(className) {
            var requiredElement = Element.extend(document.getElementById(className.substr(9)));
            if (requiredElement) {
                eventObj.requires.push(requiredElement);
            }
        }, 'requires');
        Element.extend(element).requiresObj = eventObj;

        // replacing "Use Default" action with checking requirements
        var scopeElement = adminSystemConfig.getScopeElement(element);
        if (scopeElement) {
            Event.stopObserving(scopeElement, 'click');
            Event.observe(scopeElement, 'click', function(event) {
                toggleValueElements(scopeElement, Element.previous(scopeElement.parentNode));
                eventObj.checkRequirements();
            });
        }

        // binding events
        eventObj.requires.each(function(required) {
            eventObj.bindCheckingObserver(required);
        });
        Event.observe(eventObj.element, 'change', eventObj.indicateEnabled);
        eventObj.checkRequirements();
        eventObj.indicateEnabled();
    });

    var handleHash = function () {
        if (window.location.hash == '') {
            return false;
        }
        try {
            var hashString = window.location.hash.replace('#', ''),
                containerId = hashString.replace('-link', ''),
                state = jQuery('#' + containerId + '-state'),
                head = jQuery('#' + containerId + '-head');
            if (state.length) {
                state.val(1);
            }
            if (head.length) {
                head.collapsed = 0;
            }
            Fieldset.applyCollapse(containerId);
        } catch(err) {
        }
        return false;
    };

    jQuery(window).hashchange(handleHash);
    handleHash();

    registry.set('adminSystemConfig', adminSystemConfig);
});
</script>
