<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * 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 through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * @methods
 *  getTitle() - string
 *  getSaveUrl() - string
 *  getSections() - array
 *  getForm() - html
 */
?>

<div class="content-header">
    <table cellspacing="0">
        <tr>
            <td>
                <h3<?php if($this->getHeaderCss()): ?> class="<?php echo $this->getHeaderCss()?>"<?php endif; ?>><?php echo Mage::helper('adminhtml')->__($this->getTitle()) ?></h3>
            </td>
            <td class="form-buttons"><?php echo $this->getSaveButtonHtml() ?></td>
         </tr>
    </table>
</div>
<form action="<?php echo $this->getSaveUrl() ?>" method="post" id="config_edit_form" enctype="multipart/form-data">
    <?php echo $this->getBlockHtml('formkey')?>
    <?php echo $this->getChildHtml('form') ?>
</form>
<script type="text/javascript">
//<![CDATA[
    var configForm = new varienForm('config_edit_form');
    configForm.validator.options.onFormValidate = function(result, form) {
        if (result) {
            $$('.requires').each(function(element) {
                var scopeElement = adminSystemConfig.getScopeElement(element);
                if (!scopeElement || !scopeElement.checked) {
                    $(element).disabled = false;
                }
            });
        }
    };

    var adminSystemConfig = {
        getUp: function (element, tag) {
            var $element = $(element);
            if (typeof $element.upTag == 'undefined') {
                $element.upTag = {};
            }
            if (typeof $element.upTag[tag] == 'undefined') {
                $element.upTag[tag] = $($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);
            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);
            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), '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 = $(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 = $(el);
                        var events = adminSystemConfig.getRegisteredEvents(el);
                        $el.stopObserving('change');
                        var elId = $el.id;
                        $el.replace($el.outerHTML);
                        events.each(function(event) {
                            Event.observe($(elId), event.eventName, event.handler);
                        });
                    } else {
                        el.stopObserving('change', adminSystemConfig.onchangeSharedElement);
                        if (tagName == 'input' && el.getAttribute('type') == 'checkbox') {
                            if (el.checked != element.checked) {
                                $(el).click();
                            }
                        } else if (tagName == 'select') {
                            var $el = $(el);
                            $(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 ($(el).requiresObj) {
                            $(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($(inputElement), element, callback);
                });
            }
            callback(this);
        }
    };

    $$('.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),
            '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($(required), eventObj.element, eventObj.callback);
                    }.bind(this));
                }
            },
            keydownCheckRequirements: function() {
                window.setTimeout(eventObj.checkRequirements, 1);
            },
            bindCheckingObserver: function(element) {
                if (element.tagName.toLowerCase() == 'fieldset') {
                    $(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 = $(className.substr(9));
            if (typeof requiredElement != 'undefined') {
                eventObj.requires.push(requiredElement);
            }
        }, 'requires');
        $(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();
    });
//]]>
</script>
