$(function () {

    var $formIsAlredySaved = $('#formIsAlredySaved');
    if ($formIsAlredySaved.length > 0) {
        setTimeout(function () {
            $formIsAlredySaved.fadeOut('slow');
        }, 5000);
    }

    if ($('#id').val() == '0') { $('#file16').attr('disabled', false); }
    //if ($('#newtasktype').val() == "True")
    //    $.post(base + "tasktype.ivp/removesession");

    //чтобы сообщение об ошибке было в нужном месте
    if ($('form').data('validator')) {
        var validator = $('form').data('validator');
        validator.settings = $.extend({}, validator.settings, {
            errorPlacement: function (error, element) {
                if (element.is('[name$="TemplateServiceId"]')) {
                    element.closest('[service-container]').find('[error-placement]').append(error);
                }
                else if (element.is('[name$="TemplateTaskTypeId"]')) {
                    element.closest('[tasktype-container]').find('[error-placement]').append(error);
                }
                else if (element.is('[name$="TemplateExecutorUserId"]') || element.is('[name$="TemplateExecutorGroupId"]')) {
                    element.closest('[executor-container]').find('[error-placement]').append(error);
                }
                else {
                    error.insertAfter(element);
                }
            }
        });
    }
    else {
        $("form").validate({
            errorPlacement: function (error, element) {
                if (element.is('[name$="TemplateServiceId"]')) {
                    element.closest('[service-container]').find('[error-placement]').append(error);
                }
                else if (element.is('[name$="TemplateTaskTypeId"]')) {
                    element.closest('[tasktype-container]').find('[error-placement]').append(error);
                }
                else if (element.is('[name$="TemplateExecutorUserId"]') || element.is('[name$="TemplateExecutorGroupId"]')) {
                    element.closest('[executor-container]').find('[error-placement]').append(error);
                }
                else {
                    error.insertAfter(element);
                }
            }
        });
    }

    if ($('#tab').val() == 'mainfields') loadMainFields(true);
    if ($('#tab').val() == 'fields') loadFields(true);
    if ($('#tab').val() == 'designer') updateDesigner();

    $('body').on('click', '#tab a', function () { return setTab($(this).attr('data-tabname')); });
    $('body').on('click', '.js-tasktypelanguage', function () {
        return selectTaskTypeLanguageDialog($(this).attr('data-field'));
    });
    $('body').on('click', '.js-filetrg', function() {
        $('#changefiletrg').hide();
        $('#changefile').show();
        $('#file16').attr('disabled', false);
        return false;
    });
    $('body').on('click', '.js-loadAdditionalFields', loadFields);
    $('body').on('click', '.js-loadMainFields', loadMainFields);
    $('body').on('click', '.js-openMainFieldView', function() {
        return openMainFieldViewDialog($(this).attr('data-id'));
    });
    $('body').on('click', '.js-loadDesigner', function () {
        return updateDesigner();
    });
    $('body').on('click', '.save', function() {
        $('#returnaftersave').val('');
    });
    $('body').on('click', '.saveandreturn', function () {
        $('#returnaftersave').val('true');
    });
    $('body').on('click', '.js-setTab', function() {
        return setTab($(this).attr('data-tabname'));
    });
    $('body').on('click', '.return', function () {
        document.location.href =$(this).attr('data-action');
        return;
    });
    $('body').on('click', '.js-setTaskSettingValue', openSettingDialog);//, function () {

    //  changeSettingValue($(this).attr('id'), $(this).val());
    //});
    $('body').on('click', '.js-resetSettings', setTypeSettingsToDefault);

    $('body').on('click', '.js-allTypesSettings', setAllTypeSettingsToDefault);

    $('body').on('click', '.js-showCopyDialog', showCopyDialog);

    $('.spanHint').tooltip({ position: { my: "left top+15", at: "left center" } });
});

function openSettingDialog() {
    var setting = $(this);
    $.ajax({
        url: $('#settingViewDialogAction').val(),
        data: { id: $("#id").val(), settingKey: setting.attr('settingKey') },
        success: function (data, textStatus, jqXHR) {
            var dialog = $('<div id="settingViewDialog"></div>').dialog({
                autoOpen: false,
                open: function () {
                    $('body').on('click', '.js-closeSettingViewDialog', function () {
                        $('#settingViewDialog').dialog('close');
                        return false;
                    });
                },
                width: '570px',
                maxWidth: screen.width - 25,
                //minHeight: 0,
                modal: true,
                // position: { my: "right bottom" },
                //resizable: false,
                close: function () {
                    $(this).dialog("destroy");
                    $(this).remove();
                }
            });
            //$(".ui-dialog .ui-dialog-title").html(FormatString(TaskTypeResources.CopyTypeDialogTitle));
            dialog.append(data);
            dialog.dialog('open');
            dialog.dialog("option", "title", $('#settingViewName').val());
        }
    });
    return false;
}

function showCopyDialog() {
    $.ajax({
        url: base+'TaskType/ShowCopyDialog/',
        data: { typeId: $('#id').val() },
        success: function(data, textStatus, jqXHR) {
            var dialog = $('<div id="copyLocalDialog"></div>').dialog({
                autoOpen: false,
                open: function() {
                    $('body').on('click', '.js-closeShowCopyDialog', function() {
                        $('#copyLocalDialog').dialog('close');
                        return false;
                    });
                    $('#copyform').validate();
                    $.keyboard('Ctrl+s', function () {
                        $('.js-copyTypeBtn:first').focus().click();
                    });
                   
                  },
                width: 'auto',
                maxWidth: screen.width - 25,
                //minHeight: 0,
                modal: true,
               // position: { my: "right bottom" },
                //resizable: false,
                close: function () {
                    $(this).dialog("destroy");
                    $(this).remove();
                }
            });
            $(".ui-dialog .ui-dialog-title").html(FormatString(TaskTypeResources.CopyTypeDialogTitle));
            dialog.append(data);
            dialog.dialog('open');
        }
    });
    return false;
}

function openMainFieldViewDialog(fieldId) {
    var href = $('#mainfieldViewUrl').val() +'/'+ fieldId;
    $.ajax({
        url: href,
        data: { typeid:$('#id').val() },
        success: function (data, textStatus, jqXHR) {
            var dialog = $('<div id="mainfielddialog" class="hidden"></div>').dialog({
                autoOpen: false,
                open: function () {
                    if ($('#fieldPermissions').height() >320) {
                        $('#fieldPermissions').css("max-height", 320).css('overflow-y','scroll');
                    }
                    $(this).removeClass('hidden');
                    $('body').on('click', '.js-closeDialog', function() {
                        $('#mainfielddialog').dialog('close');
                    });
                    $('body').on('click', '.js-tasktypemainfieldlanguage', function () {
                        return selectTaskTypeMainFieldLanguageDialog($(this).attr('data-field'), $(this).attr('data-fieldid'));
                    });

                    $('.js-hiddenForAll').change(function() {
                        if ($(this).is(':checked')) {
                            $('#fieldPermissions table.data').addClass('tableGray');
                            $('.js-selectAllPermissions[data-name="canEditNull"]').attr('checked', 'checked');
                            $('.js-selectAllPermissions[data-name!="canEditNull"]').removeAttr('checked');
                            $('.js-selectAllPermissions').attr('disabled', 'disabled');
                            $('#fieldPermissions input.canCreate').removeAttr('checked').attr('disabled', 'disabled');
                            $('#fieldPermissions input.isRequired').attr('disabled', 'disabled');
                             
                            $('#fieldPermissions input.canEditNull').attr('checked', 'checked');
                            $('#fieldPermissions input.canEditFalse,#fieldPermissions input.canEditTrue').attr('disabled', 'disabled');

                        } else {
                            $('#fieldPermissions table.data').removeClass('tableGray');
                            $('#fieldPermissions input.canCreate, #fieldPermissions input.isRequired').removeAttr('disabled');
                            $('#fieldPermissions input.canEditFalse,#fieldPermissions input.canEditTrue').removeAttr('disabled');
                            $('.js-selectAllPermissions').removeAttr('disabled');
                        }
                    });

                    $.keyboard('Ctrl+Shift+s', function() {
                        $('.js-saveMainField:first').focus().click();
                    });
                   
                    var form = $('#mainFieldForm');
                    form.ajaxForm(function(json) {
                        if (json.IsOk) {
                            $('#mainfielddialog').dialog('close');
                            loadMainFields(true);
                        } else {
                            alert(json.Description);
                        }
                        return false;
                    });
                    $('.js-selectAllPermissions').change(function () {
                        var elementClass ='.'+ $(this).attr('data-name');
                        var checkboxes = $(elementClass); 
                        if ($(this).is(':checked')) {
                            checkboxes.attr('checked', 'checked');
                        } else {
                            checkboxes.removeAttr('checked');
                        }
                    });
                },
                width: 'auto',
                maxWidth: screen.width - 25,
                //minHeight: 0,
               modal: true,
               // position: { my: "right bottom" },
               // resizable: false,
                close: function () {
                    $(this).dialog("destroy");
                    $(this).remove();
                }
            });
            //ужасный костыль для ie8, так как при wrapAll не срабатывают навешанные события, использующие что-то для диалога(т.е. например, по нажатию на отмена не работает dialog('close'))
            if ($.browser.msie && $.browser.version < 8) {
                dialog.append(data);
            } else {
                //а в нормальных браузерах append тормозит при большом количестве ролей в системе.
                dialog.wrapAll(data);
            }
            dialog.dialog('open');
            dialog.dialog("option", "title", $('#mainfieldTitle').val());
            dialog.dialog("option", "position", { my: "center", at: "center", of: window });
        }
    });
    return false;
}

function updateDesigner() {
    $('#designer').load(base + 'tasktypedesignerfield.ivp/list .designerfield', { reset: true, typeid: $('#id').val() }, function () {
        initDesigner();
        setTab('designer');
    });
    return false;
}

function setTab(id) {
    if (!documentReady) return;
    $('#tab').val(id);
    $('.tab').each(function (i, el) { if (el.id == id) $(el).show(); else $(el).hide(); });
    $('#tabid').val(id);
    $('#tabs>ul>li>a').each(function (i, el) { if (el.id == 'a' + id) $(el).addClass('selected'); else $(el).removeClass('selected'); });
    if (id != 'general' && id != 'complexorder') {
        $('.save').attr('disabled', true);
        $('.saveandreturn').attr('disabled', true);
    }
    else {
        $('.save').attr('disabled', false);
        $('.saveandreturn').attr('disabled', false);
    }
    if (id == 'settings') {
        $('#resetSettings').removeClass('hidden');
    } else {
        $('#resetSettings').addClass('hidden');
    }
    return false;
}

function reloadSettingList() {
    $('#settings').load($('#getTypeSettingsListViewAction').val(), { id: $('#id').val() }, null);
    return false;
}

function saveAndCloseMainFieldForm() {
    $('#mainFieldForm').submit();
}

function setTypeSettingsToDefault() {

    $.ajax({
        url: 'TaskType/ResetSettingsToDefault',
        type: 'PUT',
        data: { id: $('#id').val() },
        dataType: 'json',
        success: function(result) {
            if (result.hasOwnProperty('IsOk') && !result.IsOk)
                alert(result.Description);
            else {
                reloadSettingList();
                return false;
            }
        }
    });
    return false;
}

function setAllTypeSettingsToDefault()
{
    jConfirm('Вы действительно хотите сбросить к стандартным значениям бизнес-правила для всех типов заявок?', '', function (confirmed) {
        if (!confirmed) {
            return false;
        } else {
            $.ajax({
                url: 'TaskType/SetAllTypeSettingsToDefault',
                type: 'PUT',
                dataType: 'json',
                success: function (result) {
                    if (result.hasOwnProperty('IsOk') && !result.IsOk)
                        alert(result.Description);
                    else {
                        jAlert('Настройки типов успешно приведены к стандартным', 'Сообщение');

                        return false;
                    }
                }
            });
            return false;
        }
    });
    return false;
}

function changeSettingValue() {
    var key = '';
    var value = '';
    var settingIdContainer = $('#SettingId');
    if (settingIdContainer.length > 0) {
        key = settingIdContainer.attr('SettingKey');
        value = $('#SettingId').val();

        if (!value || value == '') {
            alert('Значение поля обязательно!');
            return false;
        }
    }
    else {
        var customContainer = $('#settingViewFormCustom');
        key = customContainer.attr('SettingKey');
        value = customContainer.find(':input').serialize();
    }
 
    $.ajax({
        url: $('#changeSettingValueAction').val(),
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ typeid: $('#id').val(), settingKey: key, settingValue: value }),
        dataType: 'json',
        async: false,
        success: function (result) {
            if (result.hasOwnProperty('IsOk') && !result.IsOk)
                alert(result.Description);
            else {
                $('#settings').load($('#getTypeSettingsListViewAction').val(), { id: $('#id').val() }, function () {
                    $('#settingViewDialog').dialog('close');
                });

                return false;
            }
            return false;
        }
    });
}

function selectTaskTypeLanguageDialog(fieldname) {
    var url = 'fieldlanguage.ivp/load?textarea=true&table=TaskTypes&field=' + fieldname + 'Xml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function selectTaskTypeMainFieldLanguageDialog(fieldname,mainfieldid) {
    var url = 'fieldlanguage.ivp/load?textarea=true&needJsonReply=true&table=TaskTypeMainFields&field=' + fieldname + 'Xml&id=' + mainfieldid;
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function getCurrentLanguageValue(fieldCallback, languageValue) {
    if (fieldCallback == '') return false;
    $('#mainFieldForm #' + fieldCallback).val(languageValue);
    return false;
}

function afterInitTable() {
    $('table[tasktypefieldstable]').treegrid({
        treeColumn: 2
    });
}

function rowChecked(val, check) {
    var $checkbox = $('#id' + val);

    if ($checkbox.attr('field-type') == 'ElementGroup') {
        var $trs = $('input.rowid[field-path^="' + $checkbox.attr('field-path') + '"]').closest('tr');
        if (check) {
            alert('Будут удалены все элементы выбранной группы');
            $trs.addClass('selected');
        }
        else {
            $trs.removeClass('selected');
        }
    }
}

function loadFields(reload) {
    DisableSaveButtons();
    if (reload || !$.trim($('#fields').html())) {
        $('#fields').load(base + 'tasktypefield.ivp/list', { tb_tasktypeid: $('#id').val(),  reset: true,  timestamp: new Date().toString() }, function () { setTab('fields'); initTable(); });
    }
    else setTab('fields');
    return false;
}

function loadMainFields(reload) {
    DisableSaveButtons();
    if (reload || !$.trim($('#mainfields').html())) {
        $('#mainfields').load('tasktypemainfield/list', { tasktypeid: $('#id').val() }, function() {
            setTab('mainfields');
           // initTable();
        });
    }
    else setTab('mainfields');
    return false;
}

function editField(id) {
    var url = id ? 'tasktypefield.ivp/view/' + id : 'tasktypefield.ivp/create/' + $('#id').val();
    openDialog(url, 'field', { width: 800, height: 490 });
    return false;
}



// костыль пока  tasktypefield не на мвц5
function del(options) {
    if (selectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(TableResources.SureDeleteRecords)) return false;

    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toString() };
    if (options != null) $.extend(params, options);
   
    var url = base + 'tasktypefield.ivp/Delete';
    selectedIds.length = 0;
    $(tableRootDiv).load(url, params, initTable);
    return false;
}

// Наряды
$(document).ready(function () {

    $('input[name="UseComplexOrder"]').click(function () {        
        disableComplexOrderTemplatesContainer();
    });

    function disableComplexOrderTemplatesContainer() {
        var isUseComplexOrder = $('input[name="UseComplexOrder"]:checked').val().toLowerCase() === 'true';
        if (isUseComplexOrder) {
            $('#complexOrderTemplatesContainer').show();
            $('#complexOrderTemplatesContainer :input').removeAttr('disabled');
        }
        else {
            $('#complexOrderTemplatesContainer').hide();
            $('#complexOrderTemplatesContainer :input').attr('disabled', true);
        }
    }

    disableComplexOrderTemplatesContainer();

    jQuery.validator.addMethod("complexOrderTaskTypeValidator", function (value, element) {
        var $selectTaskType = $(element);
        var $tr = $selectTaskType.closest('tr');
        var $selectService = $tr.find('[name$=".TemplateServiceId"]');
        var result = false;
        $.ajax({
            url: 'ComplexOrderCommon/ValidateComplexOrderTaskTypeEx',
            type: "post",
            data:
            {
                taskTypeId: function () {
                    return $selectTaskType.val();
                },
                serviceId: function () {
                    return $selectService.val();
                }
            },
            async: false,
            success: function (data) {
                if (data) {
                    if (data.success) {
                        $selectTaskType.removeAttr('my-error-message');
                        result = true;
                    }
                    else {
                        $selectTaskType.attr('my-error-message', data.message);
                        result = false;
                    }
                }
            }
        });
        return result;
    }, 
    function (error, element) {
        if (error) {
            return $(element).attr('my-error-message');
        }
        return '';
    });

    jQuery.validator.addMethod("complexOrderExecutorValidator", function (value, element) {
        //этот селект не обязателен
        if (!value)
            return true;

        var $selectExecutor = $(element);
        var $tr = $selectExecutor.closest('tr');
        var $selectService = $tr.find('[name$=".TemplateServiceId"]');
        var result = false;
        $.ajax({
            url: 'ComplexOrderCommon/ValidateComplexOrderExecutor',
            type: "post",
            data:
            {
                executorIdStr: function () {
                    return $selectExecutor.val();
                },
                serviceId: function () {
                    return $selectService.val();
                },
                etype: function () {
                    return $selectExecutor.attr('etype');
                }
            },
            async: false,
            success: function (data) {
                result = data.toLowerCase() === 'true';
            }
        });
        return result;
    }, 'Данный Исполнитель/Группа не назначены на сервис');

    $('#complexOrderTemplatesTable').TableForm({
        removeConfirmMessage: ComplexOrderResources.SureDeleteOrder,

        removeIndirectlyServerEntity: false,

        rowSelector: 'div[myrow]',

        onInitRow: function ($tr) {

            //$.multipleSelect.initByClassName($tr.find('.complexordermultipleselect'), { maxwidth: '300px', init: true, single: true, autoQueryOnEmptyField:true });

            var $selectService = $tr.find('[name$=".TemplateServiceId"]');
            var $selectTaskType = $tr.find('[name$=".TemplateTaskTypeId"]');
            var $selectExecutorUser = $tr.find('[name$=".TemplateExecutorUserId"]');
            var $selectExecutorGroup = $tr.find('[name$=".TemplateExecutorGroupId"]');

            if ($selectService.hasClass('complexordermultipleselect')) {
                $selectService.multipleSelect({ maxwidth: '300px', init: true, single: true });
            }

            if ($selectTaskType.hasClass('complexordermultipleselect')) {
                $selectTaskType.multipleSelect({ maxwidth: '300px', init: true, single: true, autoQueryOnEmptyField: true });
            }

            if ($selectExecutorUser.hasClass('complexordermultipleselect')) {
                $selectExecutorUser.multipleSelect({ maxwidth: '300px', init: true, single: true });
            }

            if ($selectExecutorGroup.hasClass('complexordermultipleselect')) {
                $selectExecutorGroup.multipleSelect({ maxwidth: '300px', init: true, single: true});
            }

            $selectService.change(function (e) {
                //TODO
                var $this = $(this);
                if ($this.val() > 0) {
                    $tr.find('div.service-is-set').show();
                    $tr.find('div.service-is-unset').hide();
                }
                else {
                    $tr.find('div.service-is-set').hide();
                    $tr.find('div.service-is-unset').show();
                }

                $selectService.valid();
                $selectTaskType.trigger('change');
                $selectExecutorUser.trigger('change');
                $selectExecutorGroup.trigger('change');

                //автоподстановка типа заявки
                setTimeout(function () {
                    if ($selectService.val() < 1 || $selectTaskType.val() > 0)
                        return;

                    $.ajax({
                        url: 'ComplexOrderCommon/GetTaskTypeByService',
                        type: "post",
                        data:
                        {
                            serviceId: function () {
                                return $selectService.val();
                            }
                        },
                        success: function (data) {
                            if (data) {
                                var msTaskType = jQuery.multipleSelects[$selectTaskType.attr('name')];
                                msTaskType.addSelectedValue(data.id, data.name);
                            }
                        }
                    });
                });

            });

            $selectTaskType.change(function (e) {
                $selectTaskType.valid();
            });

            $selectExecutorUser.change(function (e) {
                $selectExecutorUser.valid();
            });

            $selectExecutorGroup.change(function (e) {
                $selectExecutorGroup.valid();
            });

            $selectService.trigger('change');

            var $textareaDesc = $tr.find('[name$=".TemplateDescription"]');
            //fix проблемы в ie, там placeholder вставлялся как значение
            $textareaDesc.attr('placeholder', $textareaDesc.attr('text-placeholder'));
            $textareaDesc.focus(function () {
                $textareaDesc.attr('placeholder', '');
            });
            $textareaDesc.blur(function () {
                $textareaDesc.attr('placeholder', $textareaDesc.attr('text-placeholder'));
            });
            
        },
        onAfterInitRow: function ($tr) {
            setTimeout(function () {
                $tr.find('textarea').elastic();
            },2500);
        },
        onReindexElement: function ($tr, $element, index, oldName, newName) {
            if (oldName != newName && jQuery.multipleSelects != undefined && jQuery.multipleSelects[oldName] != undefined) {
                jQuery.multipleSelects[newName] = jQuery.multipleSelects[oldName];
            }
        },
        onAfterAddRow: function ($tr) {
            var $inputName = $tr.find('[name$=".TemplateName"]');
            $inputName.focus();
            $(document).scrollTop($inputName.offset().top + 50);
        }
    });
})

function getComplexOrderTaskTypeParams($select) {
    var $tr = $select.closest('tr');
    var serviceId = $tr.find('[name$=".TemplateServiceId"]').val();
    return {
        serviceId: serviceId,
        etype: $select.attr('etype')
    };
}

function getComplexOrderExecutorParams($select) {
    var $tr = $select.closest('tr');
    var serviceId = $tr.find('[name$=".TemplateServiceId"]').val();
    return {
        tb_serviceid: serviceId,
        etype: $select.attr('etype')
    };
}

function complexOrderServiceDialog(url, name, that) {
     if (url.indexOf('?') > -1) {
        url += "&";
    } else {
        url += "?";
     }

     var $link = $(that);
     var serviceName = $link.closest('[service-container]').find('[name$=".TemplateServiceId"]').attr('name');

    url += ('msName=' + serviceName);

    dlg = openDialog(url, 'selectservice', { width: 900, height: 650 });
    dlg.callback = complexOrderDialogCallback;

    return false;
}

function complexOrderExecutorDialog(url, name, that) {
    if (url.indexOf('?') > -1) {
        url += "&";
    } else {
        url += "?";
    }

    var $link = $(that);
    var $tr = $link.closest('tr');
    var eName = $tr.find('[name$=".TemplateExecutorUserId"]').attr('name');
    var serviceId = $tr.find('[name$=".TemplateServiceId"]').val();

    url += ('msName=' + eName);

    url += '&tb_serviceid=' + serviceId;

    dlg = openDialog(url, 'selectexecutor', { width: 900, height: 650 });
    dlg.callback = complexOrderDialogCallback;

    return false;
}

function complexOrderExecutorGroupDialog(url, name, that) {
    if (url.indexOf('?') > -1) {
        url += "&";
    } else {
        url += "?";
    }

    var $link = $(that);
    var $tr = $link.closest('tr');
    var eName = $tr.find('[name$=".TemplateExecutorGroupId"]').attr('name');
    var serviceId = $tr.find('[name$=".TemplateServiceId"]').val();

    url += ('msName=' + eName);

    url += '&serviceid=' + serviceId;

    dlg = openDialog(url, 'selectexecutorgroup', { width: 900, height: 650 });
    dlg.callback = complexOrderDialogCallback;

    return false;
}

function complexOrderTaskTypeDialog(url, name, that) {
    if (url.indexOf('?') > -1) {
        url += "&";
    } else {
        url += "?";
    }

    var $link = $(that);
    var $tr = $link.closest('tr');
    var eName = $tr.find('[name$=".TemplateTaskTypeId"]').attr('name');
    var serviceId = $tr.find('[name$=".TemplateServiceId"]').val();

    url += ('msName=' + eName);

    url += '&serviceid=' + serviceId;

    dlg = openDialog(url, 'tasktype', { width: 900, height: 650 });
    dlg.callback = complexOrderDialogCallback;

    return false;
}

function complexOrderDialogCallback(result) {
    var msName = result['msName'];
    addSelectedSingleValue(result, msName);
}