inkinru.HtmlPage.prototype.setAdminLayout = function (b)
{
    var that = this;
    var i;

    if (b)
    {
        this.loadCssFile('/css/admin/jquery-ui.css');
        this.loadCssFile('/javascript/dhtmlx/dhtmlxcombo.css');

        this.ensureStringHashLoaded(function (sh) {

            that.ensureLayoutLoaded();

            $('.inkinru-section')
                    .addClass('inkinru-section-adminLayout');

            var files = [
                    'jquery-ui.js',
                    'InputSourceSwitchControl.js',
                    'PageModulePickControl.js',
                    'jquery.ui.nestedSortable.js',
                    'ContentItemTreeControl.js',
                    'multilingual_controls.js',
                    'dhtmlx/dhtmlxcommon.js',
                    'dhtmlx/dhtmlxcombo.js',
                    'dhtmlx/ext/dhtmlxcombo_whp.js',
                    'Dhtmlx_inkinru.js'
                ];

            that.loadJavaScriptFiles(files, function () {

                    $('.inkinru-section')
                            .sortable({
                                'connectWith':  '.inkinru-section',
                                update:         function (event, ui) {that.onModuleOrderChange(event, ui);}
                            });

                    if (mapLength(that.dialogs))
                    {
                        that.ensureDialogIconsVisible();

                        for (i in that.dialogs)
                            that.dialogs[i].ensureIconExists(that.dialogIconsElement);
                    }
            });
        });
    }

    this.adminLayout = b;
}

inkinru.HtmlPage.prototype.onModuleOrderChange = function (event, ui)
{
    //  Fires twice if moved between containers.
    //  Use only one of them, the one with sender unset.

    if (!ui.sender)
    {
        var moduleDivId = ui.item[0].id;
        var moduleId = /^mdl(.+)$/.exec(moduleDivId)[1];
        var arrNewModuleOrder = $(ui.item[0].parentNode).sortable('toArray');

        //var arrAction = {'action': 'reorder', 'id': /^pageModule(\d+)$/.exec(strModuleDivId)[1] - 0};
        var command = {command: 'reorder', id: moduleId};
        var nNewIndex;

        for (var i in arrNewModuleOrder)
        {
            if (arrNewModuleOrder[i] == moduleDivId)
            {
                nNewIndex = i - 0;
                break;
            }
        }

        if (nNewIndex)
            command.after = /^mdl(.+)$/.exec(arrNewModuleOrder[nNewIndex - 1])[1];
            //arrAction['after'] = /^pageModule(\d+)$/.exec(arrNewModuleOrder[nNewIndex - 1])[1] - 0;

        if (nNewIndex < arrNewModuleOrder.length - 1)
            command.before = /^mdl(.+)$/.exec(arrNewModuleOrder[nNewIndex + 1])[1];
            //arrAction['before'] = /^pageModule(\d+)$/.exec(arrNewModuleOrder[nNewIndex + 1])[1] - 0;

        command.section = /^section(.+)$/.exec(ui.item[0].parentNode.id)[1];
        //arrAction['section'] = /^section(.+)$/.exec(ui.item[0].parentNode.id)[1];
        //console.log(arrAction);
        //console.log(command);
        this.layoutChangesDataSaver.addCommand(command);
        this.previewLayoutChanges();
    }
}

inkinru.HtmlPage.prototype.setModuleAdminLayout = function (module)
{
    var that = this;
    var moduleSelector = $(module.getElement());

    moduleSelector
            .addClass('inkinru-module-adminLayout');

    if (!moduleSelector.children('.inkinru-module-adminHeader').length)
    {
        var sh = this.getStringHash();
        var adminHeaderElement = document.createElement('div');

        $(adminHeaderElement)
                .addClass('inkinru-module-adminHeader')
                .css({'z-index': 1, position: 'relative'})
                .prependTo(moduleSelector);

        adminHeaderElement.innerHTML =
                '<div class="inkinru-module-adminHeader-buttons">' +
                    '<a href="javascript:;" class="inkinru-module-adminHeader-buttons-properties" title="' + sh.get('HtmlPage_moduleProperties') + '"></a>' +
                '</div>' +
                '<div class="inkinru-module-adminHeader-delete">' +
                    '<a href="javascript:;" title="' + sh.get('HtmlPage_removeModule') + '"></a>' +
                '</div>' +
                '<div class="inkinru-module-adminHeader-text">' +
                    module.info.displayClassName + ' | ID: ' + module.id +
                '</div>';

        $(adminHeaderElement).children('.inkinru-module-adminHeader-delete').children('a')
                .click(function () {that.removeModule(module);});

        $(adminHeaderElement).children('.inkinru-module-adminHeader-buttons').children('.inkinru-module-adminHeader-buttons-properties')
                .click(function () {that.showModuleProperties(module);});
    }
}

inkinru.HtmlPage.prototype.ensureLayoutLoaded = function ()
{
    if (!this.sections)
        this.initLayout();
}

inkinru.HtmlPage.prototype.initLayout = function ()
{
    var that = this;
    this.sections = {};

    $('.inkinru-section').each(function () {
        var name = /^section(.*)$/.exec(this.id)[1];
        that.sections[name] = this;
    });

    this.dialogIconsDiv = document.createElement('div');

    $(this.dialogIconsDiv)
        .addClass('inkinru-dialogIconsDiv')
        .hide()
        .appendTo('body');

    this.dialogIconsElement = document.createElement('ul');

    $(this.dialogIconsElement)
        .addClass('inkinru-IconList')
        .appendTo(this.dialogIconsDiv);

    this.loadAdminLayoutModuleInfo();

    for (var id in this.modules)
        this.modules[id].updateContentsHash();

    this.layoutChangesDataSaver = new inkinru.CommandDataSaver();
    this.layoutChangesDataSaver.addListener({onSaveSuccess: function () {window.location.reload(true);}});
    this.layoutChangesDataSaver.saveCallback = function (commands, c, e) {that.saveLayoutChanges(commands, c, e);};
    this.addDataSaver(null, this.layoutChangesDataSaver);
}

inkinru.HtmlPage.prototype.getSectionNames = function ()
{
    var result = [];

    for (var name in this.sections)
        if (name.substring(0, 7) != 'dialog:')
            result.push(name);

    return result;
}

inkinru.HtmlPage.prototype.getSectionNameBySectionId = function (id)
{
    //  id == 'section' + 'name'
    return id.substring(7);
}

inkinru.HtmlPage.prototype.getDialogBySectionName = function (name)
{
    if (name.substring(0, 7) == 'dialog:')
    {
        var dialogId = name.substring(7);
        return this.dialogs[dialogId];
    }

    return null;
}

inkinru.HtmlPage.prototype.getLayoutChangesDataSaver = function ()
{
    this.ensureLayoutLoaded();
    return this.layoutChangesDataSaver;
}

inkinru.HtmlPage.prototype.saveLayoutChanges = function (commands, c, e)
{
    this.callServerMethod(
            'Core',
            'saveLayoutChanges',
            {c: serialize(commands)},
            c, e);
}

inkinru.HtmlPage.prototype.addModule = function (className, section)
{
    var moduleId = 'new' + this.nextModuleId++;

    this.ensureLayoutLoaded();

    var sectionElement = document.getElementById('section' + section);
    var element = document.createElement('div');
    element.setAttribute('id', 'mdl' + moduleId);
    $(element).addClass('inkinru-module');
    sectionElement.appendChild(element);
    $(sectionElement).sortable('refresh');

    var command = {
        command:    'addModule',
        className:  className,
        section:    section,
        id:         moduleId,
        pageId:     this.id
    };

    this.layoutChangesDataSaver.addCommand(command);
    this.previewLayoutChanges();
}

inkinru.HtmlPage.prototype.addDialog = function ()
{
    var dialogId = ++this.nextDialogId;
    var dialogStringId = 'new' + dialogId;
    var name_m = {};

    this.ensureLayoutLoaded();

    name_m[this.language] = this.stringHash.getAndSubstitute('HtmlPageDialog_nameTemplate', {n: dialogId});

    var command = {
        command:    'addDialog',
        id:         dialogStringId,
        pageId:     this.id,
        name_m:     name_m
    }

    this.layoutChangesDataSaver.addCommand(command);
    this.previewLayoutChanges();
}

inkinru.HtmlPage.prototype.ensureDialogIconsVisible = function ()
{
    $(this.dialogIconsDiv).css({display: 'block'});
}

inkinru.HtmlPage.prototype.loadAdminLayoutModuleInfo = function ()
{
    var that = this;
    var url = addParamToUrl(window.location.href, 'inkinru-modules', 1);

    $.post(url, {getContents: 0}, function (data) {that.onAdminLayoutModuleInfoLoad(data);});
}

inkinru.HtmlPage.prototype.onAdminLayoutModuleInfoLoad = function (result)
{
    if (!this.checkAjaxResult(result))
        return;

    this.siteTemplate   = result.data.siteTemplate;
    this.pageTemplate   = result.data.pageTemplate;

    for (var dialogId in result.data.dialogs)
        this.dialogs[dialogId].setInfo(result.data.dialogs[dialogId]);

    for (var moduleId in result.data.modules)
    {
        var moduleInfo = result.data.modules[moduleId];

        if (!(moduleId in this.modules))
        {
            var module = eval('new inkinru.' + moduleInfo.javaScriptClassName + '()');
            module.id = moduleId;
            this.addModuleJavaScript(module, moduleInfo.section);
            module.variables = parseJson(moduleInfo.variables);
            module.initBase();
        }

        this.modules[moduleId].info = moduleInfo;
        this.modulesByName[moduleInfo.name] = this.modules[moduleId];

        if (this.isAdminLayout())
            this.setModuleAdminLayout(this.modules[moduleId]);
    }

    this.eventSet.fire('onAdminLayoutModuleInfoLoad');
}

inkinru.HtmlPage.prototype.previewLayoutChanges = function ()
{
    var that = this;
    var url = addParamToUrl(window.location.href, 'inkinru-modules', 1);
    var modulesHash = {};

    for (var id in this.modules)
    {
        //modulesHash[id] = this.modules[id].getContentsHash();
        modulesHash[id] = this.modules[id].info.hash;
    }

    var data = {
        commands:       serialize(this.layoutChangesDataSaver.getCommands()),
        modulesHash:    serialize(modulesHash),
        getContents:    1
    };

    $.post(
            url,
            data,
            function (data) {that.onLayoutChangesLoad(data);});
}

inkinru.HtmlPage.prototype.onLayoutChangesLoad = function (result)
{
    var that = this;

    if (!inkinru.page.checkAjaxResult(result))
        return;

    this.loadJavaScriptFiles(
            result.data.javaScriptFiles,
            function () {that.onLayoutChangesLoad_continue(result.data);});
}

inkinru.HtmlPage.prototype.onLayoutChangesLoad_continue = function (data)
{
    for (var i in data.cssFiles)
        if (!this.isCssFileLoaded(data.cssFiles[i]))
            this.loadCssFile(data.cssFiles[i]);

    for (var dialogId in data.dialogs)
    {
        if ((dialogId in this.dialogs))
            this.dialogs[dialogId].setInfo(data.dialogs[dialogId]);
        else
        {
            var dialog = new inkinru.HtmlPageDialog();

            dialog.id = dialogId;
            this.addDialogJavaScript(dialog);
            dialog.create(data.dialogs[dialogId]);
            //this.ensureDialogIconsVisible();
        }
    }

    for (var moduleId in data.modules)
    {
        var created = true;
        var moduleInfo = data.modules[moduleId];

        document.getElementById('mdl' + moduleId).innerHTML = moduleInfo.contents;

        if (moduleId in this.modules)
        {
            this.removeModuleJavaScript(this.modules[moduleId]);
            created = false;
        }

        var module = eval('new inkinru.' + moduleInfo.javaScriptClassName + '()');
        module.id = moduleId;
        this.addModuleJavaScript(module, moduleInfo.section);
        module.variables = parseJson(moduleInfo.variables);
        module.initBase();
        module.info = moduleInfo;

        if (created)
            module.blinkCreated(true);
        else
            module.blinkUpdated(true);

        if (this.isAdminLayout())
            this.setModuleAdminLayout(module);
    }
}

inkinru.HtmlPage.prototype.removeModule = function (module)
{
    var command = {
        command:    'removeModule',
        id:         module.id
    };

    this.layoutChangesDataSaver.addCommand(command);
    module.blinkDeleted();
    this.removeModuleJavaScript(module);
}

inkinru.HtmlPage.prototype.removeDialog = function (dialog)
{
    var command = {
        command:    'removeDialog',
        id:         dialog.id
    };

    this.layoutChangesDataSaver.addCommand(command);
    dialog.blinkDeleted();
    this.removeDialogJavaScript(dialog);
}

inkinru.HtmlPage.prototype.removeDialogJavaScript = function (dialog)
{
    delete this.dialogs[dialog.id];
}

inkinru.HtmlPage.prototype.showModuleProperties = function (module)
{
    var that = this;
    var param;
    var name;
    var i, j;

    if (!this.modulePropertiesDialogs)
        this.modulePropertiesDialogs = {};

    if (!(module.id in this.modulePropertiesDialogs))
        this.modulePropertiesDialogs[module.id] = this.createModulePropertiesDialog(module);

    var dialog = this.modulePropertiesDialogs[module.id];


    $(dialog.sectionSelect).html('');
    var sectionNames = this.getSectionNames();

    for (i in sectionNames)
    {
        name = sectionNames[i];

        dialog.sectionSelect.options[dialog.sectionSelect.options.length] = new Option(
                name, name, false, false);
    }

    for (var dialogId in this.dialogs)
    {
        name = this.dialogs[dialogId].getName();

        dialog.sectionSelect.options[dialog.sectionSelect.options.length] = new Option(
                this.stringHash.getAndSubstitute('HtmlPage_moduleProperties_sectionDialog', {name: name}),
                'dialog:' + dialogId,
                false,
                false);
    }

    dialog.sectionSelect.value = module.info.section;

    dialog.titleInput.setValue(module.info.title);

    if (in_array(module.info.height, ['auto', '100%']))
    {
        dialog.heightSelect.value = module.info.height;
        dialog.heightInput.value = '';
    }
    else
    {
        dialog.heightSelect.value = 'set';
        dialog.heightInput.value = module.info.height;
    }

    dialog.nameInput.value          = module.info.name;
    dialog.onErrorSelect.value      = module.info.onError;

    $(dialog.frameTemplateSelect).html('');

    this.callServerMethod(
            'Core',
            'getModuleFrameTemplates',
            {siteTemplate: this.siteTemplate, pageTemplate: this.pageTemplate/*, section: module.info.section*/},
            function (result) {
                if (!that.checkAjaxResult(result))
                    return;

                dialog.frameTemplateSelect.options[0] = new Option(that.stringHash.get('HtmlPage_moduleProperties_none'), '-', true, true);

                for (var i in result.data)
                {
                    var title       = result.data[i];
                    var selected    = (title == module.info.frameTemplate);
                    dialog.frameTemplateSelect.options[dialog.frameTemplateSelect.options.length] = new Option(title, title, selected, selected);
                }
            });

    $(dialog.contentTemplateSelect).html('');

    this.callServerMethod(
            'Core',
            'getModuleContentTemplates',
            {siteTemplate: this.siteTemplate, pageTemplate: this.pageTemplate, className: module.info.className},
            function (result) {
                if (!that.checkAjaxResult(result))
                    return;

                dialog.contentTemplateSelect.options[0] = new Option(that.stringHash.get('HtmlPage_moduleProperties_none'), '-', true, true);

                for (var i in result.data)
                {
                    var title       = result.data[i];
                    var selected    = (title == module.info.contentTemplate);
                    dialog.contentTemplateSelect.options[dialog.contentTemplateSelect.options.length] = new Option(title, title, selected, selected);
                }
            });

    dialog.heightSelect.onchange();

    $(dialog.paramsDiv).children().remove();
    dialog.paramInputs = {};

    var row, cell;
    var table = document.createElement("table");
    var thead = document.createElement("thead");
    var tbody = document.createElement("tbody");
    var tfoot = document.createElement("tfoot");
    table.appendChild(thead);
    table.appendChild(tbody);
    table.appendChild(tfoot);
    dialog.paramsDiv.appendChild(table);

    for (i in module.info.params)
    {
        param = module.info.params[i];
        var div = document.createElement('div');
        var divId = 'properties-mdl' + module.id + '-param-' + param.name;

        row = document.createElement('tr');
        cell = document.createElement('td');
        $(cell).css({'vertical-align': 'top', width: '160px'});

        if (!param.displayName)
            cell.innerHTML = param.name + ':';
        else
            cell.innerHTML = '<div title="' + param.name + '">' + param.displayName + ':</div>';

        row.appendChild(cell);

        cell = document.createElement('td');
        $(div).attr('id', divId);
        cell.appendChild(div);
        row.appendChild(cell);
        tbody.appendChild(row);

        var paramInput = new inkinru.InputSourceSwitchControl(divId);
        paramInput.getModuleById    = function (id) {return that.getModuleById(id);};
        paramInput.getRegExp        = function () {return that.getRegExp();};

        paramInput.create(
                param.name,
                param.instance,
                param.type,
                param.instance.sources,
                this.getPageModuleProvider(),
                this.language,
                this.languages,
                600,
                this.getInputSourceStringHash());

        dialog.paramInputs[param.name] = paramInput;
    }

    for (i in module.info.params)
    {
        param = module.info.params[i];
        var matches = param.type.match(/\{@[^}]+\}/);

        if (matches)
        {
            for (j = 0; j < matches.length; j++)
            {
                var referenceParamName = matches[j].substring(2, matches[j].length - 1);

                dialog.paramInputs[referenceParamName].addDependent(dialog.paramInputs[param.name]);
            }
        }
    }

    $(dialog).dialog('open');
}

inkinru.HtmlPage.prototype.onModulePropertiesOk = function (module)
{
    var dialog = this.modulePropertiesDialogs[module.id];
    var i;

    if (dialog.sectionSelect.value != module.info.section)
    {
        var newSectionName  = dialog.sectionSelect.value;
        var newSection      = this.sections[newSectionName];

        var arrNewSectionModuleIds = $(newSection).sortable('toArray');

        var moduleNode = this.sections[module.info.section].removeChild(this.modules[module.id].getElement());
        newSection.appendChild(moduleNode);

        $([this.sections[module.info.section], newSection]).sortable('refresh');
        module.info.section = newSectionName;

        var targetDialog = this.getDialogBySectionName(newSectionName);

        if (targetDialog)
        {
            module.info.pageId      = targetDialog.info.pageId;
            module.info.moduleSetId = targetDialog.info.moduleSetId;
        }

        var reorderCommand = {
            command:    'reorder',
            id:         module.id,
            section:    newSectionName
        };

        if (arrNewSectionModuleIds.length)
            reorderCommand.after = /^mdl(.+)$/.exec(arrNewSectionModuleIds[arrNewSectionModuleIds.length - 1])[1];

        this.layoutChangesDataSaver.addCommand(reorderCommand);
        console.log(reorderCommand);
    }

    //  TODO: See if changed.
    module.info.title       = dialog.titleInput.getValue();
    module.info.height      = in_array(dialog.heightSelect.value, ['auto', '100%']) ? dialog.heightSelect.value : dialog.heightInput.value;
    module.info.name        = dialog.nameInput.value;
    module.info.frameTemplate = dialog.frameTemplateSelect.value == '-' ? '' : dialog.frameTemplateSelect.value;
    module.info.contentTemplate = dialog.contentTemplateSelect.value == '-' ? '' : dialog.contentTemplateSelect.value;
    module.info.onError     = dialog.onErrorSelect.value;
//    module.info.advancedParameters  = module.advancedParameters;

    if (dialog.advancedParameters)
        module.info.advancedParameters = dialog.advancedParameters;

    for (i in module.info.params)
    {
        var param   = module.info.params[i];
        var input   = dialog.paramInputs[param.name];

        module.info.params[i].instance = input.getValue();
        input.clear();
    }

    $(dialog).dialog('close');

    switch (module.info.height)
    {
        case 'auto':
        case '100%':
            $(module.getElement()).css({height: null});
            break;
        default:
            $(module.getElement()).css({height: module.info.height + 'px'});
    }

    if (!in_array(module.id, this.fullHeightModuleIds) && module.info.height == '100%')
    {
        this.fullHeightModuleIds.push(module.id);
        this.setFullHeightModules(this.fullHeightModuleIds);
    }
    else if (in_array(module.id, this.fullHeightModuleIds) && module.info.height != '100%')
    {
        for (i = this.fullHeightModuleIds.length; --i >= 0; )
        {
            if (this.fullHeightModuleIds[i] == module.id)
            {
                this.fullHeightModuleIds.splice(i, 1);
                break;
            }
        }

        this.setFullHeightModules(this.fullHeightModuleIds);
    }

    var command = {
            command:    'editModuleProperties',
            id:         module.id,
            properties: module.info
    }

    this.layoutChangesDataSaver.addCommand(command);
    this.previewLayoutChanges();
}

inkinru.HtmlPage.prototype.createModulePropertiesDialog = function (module)
{
    var that = this;
    var sh = this.getStringHash();
    var dialog = document.createElement('div');

    var title = sh.getAndSubstitute('HtmlPage_moduleProperties_dialogTitle', {
            className:  module.info.displayClassName,
            id:         module.id
    });

    $(dialog).dialog({
            bgiframe:   true,
            modal:      true,
            autoOpen:   false,
            width:      865,
            title:      title,
            buttons:    {OK: function () {that.onModulePropertiesOk(module);}}
    });

    var tabsDiv = document.createElement('div');
    dialog.appendChild(tabsDiv);

    $(tabsDiv).attr('id', 'properties-mdl' + module.id + '-tabs');

    var ul      = document.createElement('ul');
    var li      = document.createElement('li');
    var a       = document.createElement('a');

    a.innerHTML = sh.get('HtmlPage_moduleProperties_tab_general');
    $(a).attr('href', '#properties-mdl' + module.id + '-tab-general');
    li.appendChild(a);
    ul.appendChild(li);

    a = document.createElement('a');
    li = document.createElement('li');
    a.innerHTML = sh.get('HtmlPage_moduleProperties_tab_parameters');
    $(a).attr('href', '#properties-mdl' + module.id + '-tab-parameters');
    li.appendChild(a);
    ul.appendChild(li);
    tabsDiv.appendChild(ul);

    var tabDiv = document.createElement('div');
    $(tabDiv).attr('id', 'properties-mdl' + module.id + '-tab-general');
    tabsDiv.appendChild(tabDiv);

    var row, cell, div;
    var table = document.createElement("table");
    var thead = document.createElement("thead");
    var tbody = document.createElement("tbody");
    var tfoot = document.createElement("tfoot");
    table.appendChild(thead);
    table.appendChild(tbody);
    table.appendChild(tfoot);
    tabDiv.appendChild(table);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_section') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    dialog.sectionSelect = document.createElement('select');
    $(dialog.sectionSelect).css({width: '400px'});
    cell.appendChild(dialog.sectionSelect);
    row.appendChild(cell);
    tbody.appendChild(row);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_title') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    div = document.createElement('div');
    $(div).attr('id', 'properties-mdl' + module.id + '-title');
    cell.appendChild(div);
    row.appendChild(cell);
    tbody.appendChild(row);
    dialog.titleInput = new inkinru.InputSourceSwitchControl('properties-mdl' + module.id + '-title');
    dialog.titleInput.getModuleById = function (id) {return that.getModuleById(id);};
    dialog.titleInput.getRegExp     = function () {return that.getRegExp();};

    dialog.titleInput.create(
            null,                                                       //  name
            null,                                                       //  value
            'String',
            module.info.title.sources,
            //['none', 'default', 'multilingual_input', 'page_module'],
            this.getPageModuleProvider(),
            this.language,
            this.languages,
            400,                                                        //  width
            this.getInputSourceStringHash());

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_height') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    row.appendChild(cell);

    dialog.heightSelect = document.createElement('select');
    $(dialog.heightSelect).css({width: '170px'});
    dialog.heightSelect.options[0] = new Option(sh.get('HtmlPage_moduleProperties_height_auto'), 'auto', true, true);
    dialog.heightSelect.options[1] = new Option(sh.get('HtmlPage_moduleProperties_height_full'), '100%', false, false);
    dialog.heightSelect.options[2] = new Option(sh.get('HtmlPage_moduleProperties_height_set'), 'set', false, false);
    dialog.heightSelect.onchange = function () {
            $(dialog.heightDiv).css({display: in_array(dialog.heightSelect.value, ['auto', '100%']) ? 'none' : 'inline-block'});
    };

    dialog.heightInput = document.createElement('input');
    $(dialog.heightInput).css({width: '70px', 'text-align': 'right'});

    dialog.heightDiv = document.createElement('div');

    $(dialog.heightDiv)
        .append('<span> </span>')
        .append(dialog.heightInput)
        .append('<span> px</span>');

    $(cell)
        .append(dialog.heightSelect)
        .append(dialog.heightDiv);
//        cell.appendChild(dialog.heightSelect);
//        cell.appendChild(dialog.heightInput);
    tbody.appendChild(row);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_name') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    dialog.nameInput = document.createElement('input');
    $(dialog.nameInput).css({width: '400px'});
    cell.appendChild(dialog.nameInput);
    row.appendChild(cell);
    tbody.appendChild(row);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_frameTemplate') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    dialog.frameTemplateSelect = document.createElement('select');
    $(dialog.frameTemplateSelect).css({width: '400px'});
    cell.appendChild(dialog.frameTemplateSelect);
    row.appendChild(cell);
    tbody.appendChild(row);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_contentTemplate') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    dialog.contentTemplateSelect = document.createElement('select');
    $(dialog.contentTemplateSelect).css({width: '400px'});
    cell.appendChild(dialog.contentTemplateSelect);
    row.appendChild(cell);
    tbody.appendChild(row);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_onError') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    dialog.onErrorSelect = document.createElement('select');
    dialog.onErrorSelect.options[0] = new Option(sh.get('HtmlPage_moduleProperties_onError_display'), 'display', false, false);
    dialog.onErrorSelect.options[1] = new Option(sh.get('HtmlPage_moduleProperties_onError_ignore'), 'ignore', false, false);
    dialog.onErrorSelect.options[2] = new Option(sh.get('HtmlPage_moduleProperties_onError_skip'), 'skip', false, false);
    dialog.onErrorSelect.options[3] = new Option(sh.get('HtmlPage_moduleProperties_onError_403'), '403', false, false);
    dialog.onErrorSelect.options[4] = new Option(sh.get('HtmlPage_moduleProperties_onError_404'), '404', false, false);
    dialog.onErrorSelect.options[5] = new Option(sh.get('HtmlPage_moduleProperties_onError_500'), '500', false, false);
    $(dialog.onErrorSelect).css({width: '400px'});
    cell.appendChild(dialog.onErrorSelect);
    row.appendChild(cell);
    tbody.appendChild(row);
    tabDiv = document.createElement('div');

    $(tabDiv).attr('id', 'properties-mdl' + module.id + '-tab-parameters');
    dialog.paramsDiv = document.createElement('div');
    tabDiv.appendChild(dialog.paramsDiv);

    if (module.showAdvancedParametersDialog)
    {
        div = document.createElement('div');
        $(div).css({textAlign: 'right'});

        var button = document.createElement('button');

        button.setAttribute('type', 'button');
        button.innerHTML = sh.get('HtmlPage_moduleProperties_advanced');
        button.onclick = function () { that.showModuleAdvancedParametersDialog(module) };
        div.appendChild(button);
        tabDiv.appendChild(div);
        $(button).button();
    }

    tabsDiv.appendChild(tabDiv);

    $(tabsDiv).tabs();

    return dialog;
}

inkinru.HtmlPage.prototype.showModuleAdvancedParametersDialog = function (module)
{
    var that = this;
    var dialog;

    if (!this.moduleAdvancedParametersDialogs)
        this.moduleAdvancedParametersDialogs = {};

    if (module.id in this.moduleAdvancedParametersDialogs)
        dialog = this.moduleAdvancedParametersDialogs[module.id];
    else
    {
        if (module.createAdvancedParametersDialog)
            dialog = module.createAdvancedParametersDialog();
        else
        {
            var sh = this.getStringHash();

            var title = sh.getAndSubstitute('HtmlPage_moduleProperties_advanced_title', {
                    className:  module.info.displayClassName,
                    id:         module.id
            });

            dialog = document.createElement('div');

            $(dialog).dialog({
                    bgiframe:   true,
                    modal:      true,
                    autoOpen:   false,
                    width:      665,
                    title:      title,
                    buttons:    {OK: function () {that.onModuleAdvancedParametersOk(module, dialog);}}
            });
        }

        this.moduleAdvancedParametersDialogs[module.id] = dialog;
    }

    module.showAdvancedParametersDialog(dialog);
    $(dialog).dialog('open');
}

inkinru.HtmlPage.prototype.onModuleAdvancedParametersOk = function (module, dialog)
{
    //module.advancedParameters = module.getAdvancedParametersFromDialog(dialog);
    this.modulePropertiesDialogs[module.id].advancedParameters = module.getAdvancedParametersFromDialog(dialog);
    console.log(module.advancedParameters);
    $(dialog).dialog('close');
}

inkinru.HtmlPage.prototype.showDialogProperties = function (dialog)
{
    this.currentDialog = dialog;

    if (!this.dialogPropertiesDialog)
        this.dialogPropertiesDialog = this.createDialogPropertiesDialog(dialog.info.titleProperty.sources);

    var propertiesDialog = this.dialogPropertiesDialog;

    propertiesDialog.nameInput.setValues(dialog.info.name_m);
    propertiesDialog.intNameInput.value = dialog.info.intName;
    propertiesDialog.titleInput.setValue(dialog.info.titleProperty);
    propertiesDialog.hideInput.value = dialog.info.hide;


    if (in_array(dialog.info.width, ['auto']))
    {
        propertiesDialog.widthSelect.value = dialog.info.width;
        propertiesDialog.widthInput.value = '';
    }
    else
    {
        propertiesDialog.widthSelect.value = 'set';
        propertiesDialog.widthInput.value = dialog.info.width;
    }

    propertiesDialog.widthSelect.onchange();

    if (in_array(dialog.info.height, ['auto']))
    {
        propertiesDialog.heightSelect.value = dialog.info.height;
        propertiesDialog.heightInput.value = '';
    }
    else
    {
        propertiesDialog.heightSelect.value = 'set';
        propertiesDialog.heightInput.value = dialog.info.height;
    }

    propertiesDialog.heightSelect.onchange();

    $(propertiesDialog).dialog('open');
}

inkinru.HtmlPage.prototype.createDialogPropertiesDialog = function (titleSources)
{
    var that = this;
    var sh = this.getStringHash();
    var dialog = document.createElement('div');

    var title = sh.get('HtmlPage_dialogProperties_dialogTitle');

    $(dialog).dialog({
            bgiframe:   true,
            modal:      true,
            autoOpen:   false,
            width:      865,
            title:      title,
            buttons:    {OK: function () {that.onDialogPropertiesOk();}}
    });

    var tabsDiv = document.createElement('div');
    dialog.appendChild(tabsDiv);

    $(tabsDiv).attr('id', 'properties-dialog-tabs');

    var ul      = document.createElement('ul');
    var li      = document.createElement('li');
    var a       = document.createElement('a');
    var div;

    a.innerHTML = sh.get('HtmlPage_dialogProperties_tab_general');
    $(a).attr('href', '#properties-dialog-tab-general');
    li.appendChild(a);
    ul.appendChild(li);

    tabsDiv.appendChild(ul);

    var tabDiv = document.createElement('div');
    $(tabDiv).attr('id', 'properties-dialog-tab-general');
    tabsDiv.appendChild(tabDiv);

    var row, cell;
    var table = document.createElement("table");
    var thead = document.createElement("thead");
    var tbody = document.createElement("tbody");
    var tfoot = document.createElement("tfoot");
    table.appendChild(thead);
    table.appendChild(tbody);
    table.appendChild(tfoot);
    tabDiv.appendChild(table);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_dialogProperties_name') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    row.appendChild(cell);
    tbody.appendChild(row);
    div = document.createElement('div');
    $(div).attr({id: 'properties-dialog-nameInput'})
    cell.appendChild(div);
    dialog.nameInput = new MultilingualInput('properties-dialog-nameInput');
    dialog.nameInput.create('', '400', [], this.languages, this.language);

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_dialogProperties_title') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    div = document.createElement('div');
    $(div).attr('id', 'properties-dialog-title');
    cell.appendChild(div);
    row.appendChild(cell);
    tbody.appendChild(row);
    dialog.titleInput = new inkinru.InputSourceSwitchControl('properties-dialog-title');
    dialog.titleInput.getModuleById = function (id) {return that.getModuleById(id);};
    dialog.titleInput.getRegExp     = function () {return that.getRegExp();};

    dialog.titleInput.create(
            null,                                                       //  name
            null,                                                       //  value
            'String',
            titleSources,
            this.getPageModuleProvider(),
            this.language,
            this.languages,
            400,                                                        //  width
            this.getInputSourceStringHash());

    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_dialogProperties_intName') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    dialog.intNameInput = document.createElement('input');
    $(dialog.intNameInput).css({width: '400px'});
    cell.appendChild(dialog.intNameInput);
    row.appendChild(cell);
    tbody.appendChild(row);


    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_dialogProperties_width') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    row.appendChild(cell);

    dialog.widthSelect = document.createElement('select');
    $(dialog.widthSelect).css({width: '170px'});
    dialog.widthSelect.options[0] = new Option(sh.get('HtmlPage_moduleProperties_height_auto'), 'auto', true, true);
    dialog.widthSelect.options[1] = new Option(sh.get('HtmlPage_moduleProperties_height_set'), 'set', false, false);
    dialog.widthSelect.onchange = function () {
            $(dialog.widthDiv).css({display: in_array(dialog.widthSelect.value, ['auto']) ? 'none' : 'inline-block'});
    };

    dialog.widthInput = document.createElement('input');
    $(dialog.widthInput).css({width: '70px', 'text-align': 'right'});

    dialog.widthDiv = document.createElement('div');

    $(dialog.widthDiv)
        .append('<span> </span>')
        .append(dialog.widthInput)
        .append('<span> px</span>');

    $(cell)
        .append(dialog.widthSelect)
        .append(dialog.widthDiv);

    tbody.appendChild(row);


    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_moduleProperties_height') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    row.appendChild(cell);

    dialog.heightSelect = document.createElement('select');
    $(dialog.heightSelect).css({width: '170px'});
    dialog.heightSelect.options[0] = new Option(sh.get('HtmlPage_moduleProperties_height_auto'), 'auto', true, true);
    dialog.heightSelect.options[1] = new Option(sh.get('HtmlPage_moduleProperties_height_set'), 'set', false, false);
    dialog.heightSelect.onchange = function () {
            $(dialog.heightDiv).css({display: in_array(dialog.heightSelect.value, ['auto']) ? 'none' : 'inline-block'});
    };

    dialog.heightInput = document.createElement('input');
    $(dialog.heightInput).css({width: '70px', 'text-align': 'right'});

    dialog.heightDiv = document.createElement('div');

    $(dialog.heightDiv)
        .append('<span> </span>')
        .append(dialog.heightInput)
        .append('<span> px</span>');

    $(cell)
        .append(dialog.heightSelect)
        .append(dialog.heightDiv);

    tbody.appendChild(row);


    row = document.createElement('tr');
    cell = document.createElement('td');
    cell.innerHTML = sh.get('HtmlPage_dialogProperties_hide') + ':';
    row.appendChild(cell);

    cell = document.createElement('td');
    dialog.hideInput = document.createElement('input');
    $(dialog.hideInput).css({width: '400px'});
    cell.appendChild(dialog.hideInput);
    row.appendChild(cell);
    tbody.appendChild(row);

    $(tabsDiv).tabs();

    return dialog;
}

inkinru.HtmlPage.prototype.onDialogPropertiesOk = function ()
{
    var dialog = this.currentDialog;
    var propertiesDialog = this.dialogPropertiesDialog;

    dialog.info.name_m          = propertiesDialog.nameInput.getValues();
    dialog.info.name            = dialog.info.name_m[this.language];
    dialog.info.intName         = propertiesDialog.intNameInput.value;
    dialog.info.titleProperty   = propertiesDialog.titleInput.getValue();
    dialog.info.width           = in_array(propertiesDialog.widthSelect.value, ['auto']) ? propertiesDialog.widthSelect.value : propertiesDialog.widthInput.value;
    dialog.info.height          = in_array(propertiesDialog.heightSelect.value, ['auto']) ? propertiesDialog.heightSelect.value : propertiesDialog.heightInput.value;
    dialog.info.hide            = propertiesDialog.hideInput.value;

    var command = {
        command:    'editDialogInfo',
        id:         dialog.id,
        info:       dialog.info
    };

    $(propertiesDialog).dialog('close');
    dialog.updateIcon();
    this.layoutChangesDataSaver.addCommand(command);
    this.previewLayoutChanges();
}


inkinru.HtmlPageDialog.prototype.ensureIconExists = function (iconsElement)
{
    if (this.iconElement)
        return;

    this.iconElement = document.createElement('li');

    $(this.iconElement)
        .addClass('inkinru-dialogIcon');

    //this.iconElement.innerHTML = this.info.name;
    iconsElement.appendChild(this.iconElement);
    sh = inkinru.page.getStringHash();

    var that = this;

    this.iconElement.innerHTML =
            '<div class="inkinru-module-adminHeader-buttons">' +
                '<a href="javascript:;" class="inkinru-module-adminHeader-buttons-properties" title="' + sh.get('HtmlPageDialog_properties') + '"></a>' +
                '<a href="javascript:;" class="inkinru-dialog-adminHeader-buttons-test" title="' + sh.get('HtmlPageDialog_test') + '"></a>' +
            '</div>' +
            '<div class="inkinru-module-adminHeader-delete">' +
                '<a href="javascript:;" title="' + sh.get('HtmlPageDialog_remove') + '"></a>' +
            '</div>' +
            '<div class="inkinru-module-adminHeader-text">' +
                this.info.name +
            '</div>';

    $(this.iconElement).children('.inkinru-module-adminHeader-delete').children('a')
            .click(function () { that.page.removeDialog(that); });

    $(this.iconElement).children('.inkinru-module-adminHeader-buttons').children('.inkinru-module-adminHeader-buttons-properties')
            .click(function () { that.page.showDialogProperties(that); });

    $(this.iconElement).children('.inkinru-module-adminHeader-buttons').children('.inkinru-dialog-adminHeader-buttons-test')
            .click(function () { that.open(); });
}

inkinru.HtmlPageDialog.prototype.updateIcon = function ()
{
    $(this.iconElement).find('.inkinru-module-adminHeader-text').html(this.info.name);
}

inkinru.HtmlPageDialog.prototype.setInfo = function (info)
{
    this.info = info;

    var options = {
        title:      info.title,
        height:     info.height == 'auto' ? info.height : info.height - 0,
        hide:       inkinru.page.stringToJQueryEffect(info.hide)};

    if (info.width != 'auto')
        options.width = info.width - 0;

    $(this.element).dialog('option', options);
}

inkinru.HtmlPageDialog.prototype.blinkDeleted = function ()
{
    var div = document.createElement('div');

    $(div)
        .css({
            position:           'absolute',
            width:              '100%',
            height:             '100%',
            top:                0,
            left:               0,
            'background-color': '#ff0000'
        })
        .fadeTo(0, 0.4)
        .prependTo(this.iconElement);

    $(this.iconElement)
        .fadeOut(700, function () {$(this).remove();});
}

