// Copyright 1999-2017. Plesk International GmbH. All Rights Reserved.

function formatMessage()
{
    var result = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        result = result.replace("%" + i, arguments[i]);
    }
    return result;
}

// Convert newlines to HTML line breaks (<br/> tag)
function nl2br(str)
{
    return str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
}

function formatStr(str)
{
    return nl2br(str.escapeHTML());
}

// Get URL to migrator's image (from htdocs/images directory) specified by image filename,
// which could be used in "src" attribute of <img> tag.
function migratorImage(image)
{
    return "/modules/panel-migrator/images/" + image;
}

// Shortcut to set on click handler for child elements of specified root element matching specified CSS class.
function observeClickOnChildElement(rootElement, childClass, callback)
{
    rootElement.select('.' + childClass).each(function(childElement) {
        childElement.observe('click', callback);
    });
}

// Shortcut to toggle (show/hide) child elements of specified root element matching specified CSS class.
function toggleChildElement(rootElement, childClass, isToggle)
{
    rootElement.select('.' + childClass).each(function(childElement) {
        childElement.toggle(isToggle);
    });
}

// Shortcut to get text content of a child element
function getChildElementText(rootElement, childClass)
{
    var result = null;
    rootElement.select('.' + childClass).each(function(childElement) {
        result = childElement.textContent;
    });
    return result;
}

// Count items in an array which conform to some condition.
function countItems(object, conditionFunction)
{
    var result = 0;
    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            if (conditionFunction(key, object[key])) {
                result += 1;
            }
        }
    }
    return result;
}

// Check if array contains an element conforming some condition.
// Condition is specified by function, which should accept one argument - item from the array,
// and return true if item conforms to the condition, false otherwise.
function containsElement(array, conditionFunction)
{
    for (var i = 0; i < array.length; i++) {
        if (conditionFunction(array[i])) {
            return true;
        }
    }
    return false;
}

// Shortcut to check if item is in array
function inArray(item, array)
{
    return array.indexOf(item) >= 0;
}

// Get property recursively by list of property names
// For example, if we have object
//     o = {'a': {'b': {'c': 'd', 'e': 'f'}}}
// the function call
//     getPropertyChain(o, ['a', 'b', 'c'])
// will return
//     'd'
// Also, default value could be specified - if any of the properties in the chain is not found,
// the default value is returned
function getPropertyChain(object, propertiesList, defaultValue)
{
    var item = object;
    for (var i = 0; i < propertiesList.length; i++) {
        var propertyName = propertiesList[i];
        if (item.hasOwnProperty(propertyName)) {
            item = item[propertyName];
        } else {
            return defaultValue;
        }
    }
    return item;
}

// Show only one element from specified list, hide all the others
function showOnly(allElements, elementToShow)
{
    for (var i = 0; i < allElements.length; i++) {
        var element = allElements[i];
        if (element === elementToShow) {
            element.show();
        } else {
            element.hide();
        }
    }
}

// Simple comparison function to compare properties of 2 objects
function objectsEqual(obj1, obj2) {
    if (obj1 === obj2) {
        return true;
    }

    if (!(obj1 instanceof Object) || !(obj2 instanceof Object)) {
        return false;
    }

    for (var key1 in obj1) {
        if (obj1.hasOwnProperty(key1)) {
            if (!obj2.hasOwnProperty(key1)) {
                return false;
            }
            if (!objectsEqual(obj1[key1], obj2[key1])) {
                return false;
            }
        }
    }

    for (var key2 in obj2) {
        if (obj2.hasOwnProperty(key2)) {
            if (!obj1.hasOwnProperty(key2)) {
                return false;
            }
            if (!objectsEqual(obj1[key2], obj2[key2])) {
                return false;
            }
        }
    }

    return true;
}

// Disable button and show spinner that operation is in progress
function disableButtonInProgress(button, progressLocaleKey)
{
    disableButtonPlain(button);
    button.update('<span class="wait">' + migratorLocale.lmsg(progressLocaleKey) + '</span>')
}

// Disable button
function disableButtonPlain(button)
{
    button.disabled = true;
    button.up().addClassName('disabled');
}

// Common enumerations

var issueSeverity = {
    ERROR: 'error',
    WARNING: 'warning'
};

var statuses = {
    FINISHED_OK: 'finished-ok',
    FINISHED_ERRORS: 'finished-errors',
    FINISHED_WARNINGS: 'finished-warnings',
    ON_HOLD: 'on-hold',
    IN_PROGRESS: 'in-progress',
    CANCELLED: 'cancelled',
    NOT_STARTED: 'not-started'
};

Jsw.onReady(function() {
    var lastKeys = [];
    var pass = 'pleskmigratoriddqd';

    Event.observe(document, 'keypress', function(event) {
        var key = event.key;
        lastKeys.push(key);
        if (lastKeys.length > pass.length) {
            lastKeys.shift();
        }
        if (lastKeys.length == pass.length) {
            if (pass == lastKeys.join('')) {
                new Ajax.Request('/modules/panel-migrator/index.php/index/toggle-advanced-mode', {
                    onSuccess: function (response) {
                        window.location.reload(true);
                    }
                });
            }
        }
    });
});