<?php
// Copyright 1999-2015. Parallels IP Holdings GmbH. All Rights Reserved.
?>
var localeKeys = <?php echo Zend_Json::encode(Zend_Registry::get('translate')->getSection('admin.controllers.customer-service-plan._shared')); ?>;

function optionConflictWarning(element, defaultValue, resetHandler) {
    Jsw.messageBox.show({
        'type': Jsw.messageBox.TYPE_YESNO,
        'subtype': 'confirm',
        'text': localeKeys['sureToApplyConflictOptionTitle'],
        'description': localeKeys['sureToApplyConflictOptionDescription'],
        'onNoClick': function() {
            if ('undefined' != typeof resetHandler) {
                resetHandler();
            } else {
                if ('input' == element.tagName.toLowerCase() && 'checkbox' == element.type) {
                    // set inverted value and simulate the selection by click to fire event observers
                    element.checked = !defaultValue;
                    element.click();
                } else if ('select' == element.tagName.toLowerCase()) {
                    element.value = defaultValue;
                }
            }
        },
        'buttonTitles': {
            'yes': localeKeys['buttonConflictYes'],
            'no': localeKeys['buttonConflictNo']
        }
    });
}

function checkShellOptionConflict(option, element, callback) {
    var shellEnabledElement = $(optionsElementsPrefix + 'shellEnabled');
    var shellEnabled = shellEnabledElement && shellEnabledElement.checked || !shellEnabledElement;

    if (shellEnabled && element.value != '/bin/false' && element.value != 'Login Disabled') {
        defaultValue = optionsDefaults[option];
        callback(element, defaultValue, function() {
            if ('off' == defaultValue || '' == defaultValue) {
                if (shellEnabledElement) {
                    shellEnabledElement.checked = false;
                    $(optionsElementsPrefix + 'shell').disable();
                } else {
                    // first value is "disable shell", so it's ok
                    defaultValue = element.options.first().value;
                    element.value = defaultValue;
                }
            } else {
                element.value = defaultValue;
            }
        });
    }
}

function checkOptionConflict(element, callback) {
    var option = element.id.split('-').last().underscore();

    if ('input' == element.tagName.toLowerCase() && 'checkbox' == element.type) {
        if (!element.checked && ('1' == optionsDefaults[option] || 'on' == optionsDefaults[option])) {
            callback(element, true);
        } else if (element.checked && ('' == optionsDefaults[option] || 'off' == optionsDefaults[option])) {
            callback(element, false);
        }
    } else if ('select' == element.tagName.toLowerCase()) {
        if (option.startsWith('php_handler_id')) {
            option = 'php_handler_id';
        }
        if ('any' != optionsDefaults[option] && element.value != optionsDefaults[option]) {
            if (option == 'shell') {
                checkShellOptionConflict(option, element, callback);
            } else if ('php_handler' == option) {
                defaultValue = optionsDefaults[option];
                callback(element, defaultValue, function() {
                    element.value = defaultValue;
                    if ('undefined' != typeof onAfterPhpHandlerChange) {
                        onAfterPhpHandlerChange();
                    }
                });
            } else {
                callback(element, optionsDefaults[option]);
            }
        }
    }
}

var optionsElements = [];

optionsNames.each(function(option) {
    var element = $(optionsElementsPrefix + option.dasherize().camelize());

    if (!element) {
        if ('ssl' == option) {
            element = $('sslSettings-ssl');
        } else if ('write_modify' == option) {
            element = $(optionsElementsPrefix + 'write_modify');
        } else if ('iis_app_pool' == option) {
            element = $('tabs-performanceTab-performanceSubForm-iis_app_pool');
        } else if ('php_handler' == option) {
            element = $('tabs-phpSettingsTab-phpSettings-phpHandler');
        } else if ('php_handler_id' == option) {
            var handlerHash = optionsDefaults['php_handler']
            element = $(optionsElementsPrefix + 'phpHandlerId' + handlerHash);
            if (!element) {
                element = $('tabs-phpSettingsTab-phpSettings-phpHandlerId' + handlerHash);
            }
        } else if ('php_safe_mode' == option) {
            element = $('tabs-phpTab-php-general-safe_mode_predefined');
            if (!element) { // hosting panel
                element = $('tabs-phpSettingsTab-phpsection-general-safe_mode_predefined');
            }
            optionsDefaults['safe_mode_predefined'] = optionsDefaults[option];
        }
    }

    if (!element) {
        return ;
    }

    optionsElements.push(element);
});

optionsElements.each(function(element) {
    var eventType = ('select' == element.tagName.toLowerCase()) ? 'change' : 'click';
    element.observe(eventType, function(event) {
        if (insecureHostingOptionsElement && insecureHostingOptionsElement.checked) {
            return ;
        }

        checkOptionConflict(element, optionConflictWarning);
    });
});

var shellEnabledElement = $(optionsElementsPrefix + 'shellEnabled');
var shellElement = $(optionsElementsPrefix + 'shell');
if (shellEnabledElement) {
    shellEnabledElement.observe('click', function(event) {
        if (insecureHostingOptionsElement && insecureHostingOptionsElement.checked) {
            return;
        }

        if (shellEnabledElement.checked && ('' == optionsDefaults['shell'] || 'off' == optionsDefaults['shell'])) {
            optionConflictWarning(shellEnabledElement, false, function() {
                shellEnabledElement.checked = false;
                shellElement.disable();
            });
        }
    });
}

var formElement = $$('button[name="send"]').first().up('form');
var origSubmitHandler = formElement.submit;

formElement.submit = function() {
    if ((insecureHostingOptionsElement && insecureHostingOptionsElement.checked)
        || ($(optionsElementsPrefix + 'hostingEnabled') && !$(optionsElementsPrefix + 'hostingEnabled').checked)
    ) {
        return origSubmitHandler();
    }

    var conflictsFound = false;
    var conflictOptionsHtml = '<ul class="ul">';

    optionsElements.each(function(element) {
        checkOptionConflict(element, function() {
            var option = element.id.split('-').last().underscore();
            if (option.startsWith('php_handler_id')) {
                option = 'php_handler_id';
            }
            conflictOptionsHtml += '<li>' + localeKeys['option_' + option] + '</li>';
            conflictsFound = true;
        });
    });

    conflictOptionsHtml += '</ul>';

    if (!conflictsFound) {
        return origSubmitHandler();
    }

    Jsw.messageBox.show({
        'type': Jsw.messageBox.TYPE_YESNO,
        'subtype': 'confirm',
        'text': localeKeys['foundConflictOptionsTitle'],
        'description': localeKeys['foundConflictOptionsDescription'] + conflictOptionsHtml,
        'descriptionWrapperTag': 'div',
        'onYesClick': function() {
            origSubmitHandler();
        },
        'buttonTitles': {
            'yes': localeKeys['buttonConflictYes'],
            'no': localeKeys['buttonConflictNo']
        }
    });

    return false;
}

function applySecureSettings(event) {
    if (event) {
        event.preventDefault();
    }
    optionsElements.each(function(element) {
        var option = element.id.split('-').last().underscore();

        if ('shell' == option && ('' == optionsDefaults[option] || 'off' == optionsDefaults[option])) {
            if ($(optionsElementsPrefix + 'shellEnabled')) {
                $(optionsElementsPrefix + 'shellEnabled').checked = false;
                $(optionsElementsPrefix + 'shell').disable();
            }
        } else if ('php_handler' == option && 'any' != optionsDefaults[option]) {
            element.value = optionsDefaults[option];
            if ('undefined' != typeof onAfterPhpHandlerChange) {
                onAfterPhpHandlerChange();
            }
        } else if (option.startsWith("php_handler_id") && 'any' != optionsDefaults[option]) {
            element.value = optionsDefaults['php_handler_id'];
        } else if ('input' == element.tagName.toLowerCase() && 'checkbox' == element.type) {
            if ('1' == optionsDefaults[option] || 'on' == optionsDefaults[option]) {
                element.checked = true;
            } else if ('' == optionsDefaults[option] || 'off' == optionsDefaults[option]) {
                element.checked = false;
            }

            // invert the value and simulate the selection by click to fire event observers
            element.checked = !element.checked;
            element.click();
        } else if ('select' == element.tagName.toLowerCase()) {
            if ('any' != optionsDefaults[option]) {
                element.value = optionsDefaults[option];
            }
        }
    });
}
