var selectedIds = new Array();
var selectedPaths = new Array();
var selectedNames = new Array();

$(function() {
    if ($.browser.mobile) {
        $('li>.hover').css('visibility', 'visible');
    }

    if (typeof c2c != 'function') {
        window.c2c = function(selector) {
            if (selector === null || selector === undefined)
                selector = "#wrapper";

            $selector = $(selector);

            if ($selector.length === 0) //Мы пришли не из _Layout...
                return false;

            var taContent = [];
            var inputValues = [];
            $(selector + " textarea").each(function (idx, elem) {
                taContent.push($(elem).html());
                $(elem).html("");
            })

            $(selector + " input").each(function (idx, elem) {
                inputValues.push($(elem).val());
                $(elem).val("");
            })

            var regex = /(?:(?:\D8|^8|\+\d{1,3})\d{10})(?!.+\"|[@"'_\w])|(?:\bext\d+)(?![@"'_\w])/gmi
            var text = $selector.html();
            text = text.replace(regex,
                function (phone) {
                    if (phone === null || phone === undefined || phone === "" || phone.startsWith("ext"))
                        return phone;
                    if (!/(^(\D*8|\+\d{1,3})\d{10}$)/.test(phone))
                        return phone;
                    var regex = /(^(\D*8|\+\d{1,3})(\d{3})(\d{3})(\d{2})(\d{2})$)/gm;
                    return phone.replace(regex, '$2($3)$4-$5-$6');
                });
            $selector.html(text);

            $(selector + " textarea").each(function (idx, elem) {
                $(elem).html(taContent[idx]);
            })

            $(selector + " input").each(function (idx, elem) {
                $(elem).val(inputValues[idx]);
            })
            return false;
        }
        c2c();
    }
});

window.onresize = function (event) {
    loadingPosition();
};

//Common.js should be used only for functions that are available (and needed) code-wide.
//None of page-specific functions should be placed here.
/// <reference path="jquery.intellisense.js"/>
/// <reference path="jquery.keyboard.js"/>
$.ajaxSetup({ cache: false });

var base = '';
var showLoading = true;
var documentReady = false;
var sid = 0;
var hid = 0;
var showud = true;

function keyPressHandler(evt) {
    // Получаем объект event
    evt = evt || window.event;
    var key = evt.keyCode || evt.which;
    // Определяем нажатие Ctrl+S
    var escKey = key == 27;
    key = String.fromCharCode(key).toLowerCase() == "s";
    if (evt.ctrlKey && key || escKey) {
        // Блокируем появление диалога о сохранении
        if (evt.preventDefault) evt.preventDefault();
        evt.returnValue = false;
        // Возвращаем фокус в окно
        window.focus();
        return false;
    }
    else if (evt.keyCode == 13 && $("#savefilterholder").length > 0 && $("#savefilterholder").css('display') != 'none') {
        //Хотим сохранить фильтр по нажатию Enter
        Save();
        return false;
    }
    return true;
}

$(function () {
    $('input[type="text"]:disabled, [readonly="true"]').addClass('readonly');

    function urldecode(str) {
        return decodeURIComponent((str + '').replace(/\+/g, '%20'));
    }

    $('body').on('click', 'a.post-href', function () {
        var p = $(this).attr('href').split('?');
        var action = p[0];
        var params = p[1].split('&');

        var form = $(document.createElement('form')).attr('action', action).attr('method', 'POST');
        $('body').append(form);

        $(form).submit(function () {
            window.open('', 'formpopup', 'width=1300,height=800,resizeable,scrollbars');
            this.target = 'formpopup';
        });

        for (var i = 0; i < params.length; i++) {
            var keyLastIndex = params[i].indexOf('=');

            if (keyLastIndex > 0) {
                var key = params[i].substring(0, keyLastIndex), value = params[i].substring(keyLastIndex + 1, params[i].length);
                $(document.createElement('input')).attr('type', 'hidden').attr('name', key).attr('value', urldecode(value)).appendTo(form);
            }
        }
        $(form).submit();
        return false;
    });

    $('#languageholder').hide();

    //#region Hot buttons
    //Отключим стандартные обработчики горячих клавиш
    $(document).bind("keypress", keyPressHandler).bind("keydown", keyPressHandler);

    //если обработчики уже привязаны - отключим их
    $.keyboard('Ctrl+s').keyboard('Ctrl+Shift+s').keyboard('Esc');
    $(document).keyboard('Ctrl+s').keyboard('Ctrl+Shift+s').keyboard('Esc');
    $('form input').keyboard('Ctrl+s').keyboard('Ctrl+Shift+s').keyboard('Esc');
    $('form textarea').keyboard('Ctrl+s').keyboard('Ctrl+Shift+s').keyboard('Esc').unbind("keydown").unbind("keypress");

    //подключим свои обработчики
    $.keyboard('Ctrl+s', save);
    $.keyboard('Ctrl+Shift+s', saveandreturn);
    $.keyboard('Esc', comeback);

    function save() {
        if ($('form:first').size() > 0 && $('form:first').valid() && !$('.save[disabled="true"]').length) {
            $('.save:first').focus().click();
        }
        return false;
    }

    function saveandreturn() {
        if ($('form:first').size() > 0 && $('form:first').valid() && !$('.save[disabled="true"]').length) {
            $('.saveandreturn[data-isstatusbutton!=1]').focus().click();
        }
        return false;
    }

    function comeback() {
        $('.return').focus().click();
        return false;
    }
    //#endregion

    $('#togglelanguage').click(function () {
        var elem = $('#languageholder')[0];
        if (elem.style.display == 'none') {
            $('#contexticon').attr('src', 'img/context/contextmenu2.gif');
            $('#languageholder').show();
        }
        else {
            $('#contexticon').attr('src', 'img/context/contextmenu.gif');
            $('#languageholder').hide();
        }
        return false;
    });

    $('#morelink').click(function () {
        $('#configurationmenu li.additionalSetting').toggle();
        $("#morelink").toggleClass("additionalShowed");

        if ($("#morelink").hasClass("additionalShowed")) {
            $(this).text(CommonResources.HideAdditionalSettings);
            $(this).closest("li").switchClass("toshow", "tohide");
        }
        else {
            $(this).text(CommonResources.AdditionalSettings);
            $(this).closest("li").switchClass("tohide", "toshow");
        }
        return false;
    });

    documentReady = true;
    base = $('base').attr('href');
    //Create datepickers
    if ($.fn.calendar) {
        $('body').on('hover focus', 'input.datePicker', function () {
            var $self = $(this);

            if ($self.data('initialized') || !$.fn.calendar)
                return;

            if ($self.hasClass('date'))
                $self.calendar({ usedatetime: false });
            else
                $self.calendar();

            $self.data('initialized', true);
        });
    }
    $('body').click(function () {
        $('#contexticon').attr('src', 'img/context/contextmenu.gif');
        $('#languageholder').hide();
    });
    $('body').append('<div id="Error"></div>').append('<div id="Loading"><img src="img/ajax-loader.gif" hspace="5" align="absmiddle"/></div>');
    $('body').ajaxError(function (e, r, s) { if (r.status == 403) { alert(CommonResources.SessionFinished); top.location.href = base + 'login'; } });

    var enabledSubmitButtons;
    var enableSubmitLinks;

    loadingPosition();
    $('#Loading').ajaxStart(function () {
        showLoading = true;
        var loadingTop = $(window).height() / 2 - 60;//window.outerHeight / 2 - 60;
        var loadingLeft = $(window).width() / 2 - 60;//window.innerWidth / 2 - 60;
        $("#Loading").css({ top: loadingTop, left: loadingLeft });
        setTimeout('if(showLoading) { $("#Loading").show(); }', 300);
        //блокируем кнопки сохранения пока идет загрузка
        enabledSubmitButtons = $("button[type='submit']:enabled");
        enableSubmitLinks = $('a.saveandreturnicon, a.saveicon').not('[disabled]');
        if (enableSubmitLinks)
            enableSubmitLinks.attr("disabled", "disabled");
        if (enabledSubmitButtons)
            enabledSubmitButtons.attr("disabled", "disabled");
    }).ajaxStop(function () {
        $(this).hide(); showLoading = false;
        if ($('#returnaftersave').val() !== 'true' && $('#returnaftersave').val() !== 'True') {
            if (enabledSubmitButtons)
                enabledSubmitButtons.removeAttr("disabled");
            if (enableSubmitLinks)
                enableSubmitLinks.removeAttr("disabled");
        }
    });
    $('#userdata span.currentLogin').mouseover(showUserDescription).mouseout(function () { showud = false; clearTimeout(sid); hid = setTimeout('hideUserDescription()', 400); }).click(function () { showud = false; });
    ReInitCheckboxes();
});

function loadingPosition() {
    var loadingTop = $(window).height() / 2 - 60;//window.outerHeight / 2 - 60;
    var loadingLeft = $(window).width() / 2 - 60;//window.innerWidth / 2 - 60;
    $("#Loading").css({ top: loadingTop, left: loadingLeft });
}

function ReInitCheckboxes() {
    if ($('#disablenotclick').val() != "true") {
        var a = $("tr").has("input[disabled]");
        a.click(function () { return false; });
    }
    return false;
}

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
        if (m == "{{") { return "{"; }
        if (m == "}}") { return "}"; }
        return args[n];
    });
};

Array.prototype.remove = function (from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

Array.prototype.removeItems = function (itemsToRemove) {

    if (!/Array/.test(itemsToRemove.constructor)) {
        itemsToRemove = [itemsToRemove];
    }

    var j;
    for (var i = 0; i < itemsToRemove.length; i++) {
        j = 0;
        while (j < this.length) {
            if (this[j] == itemsToRemove[i]) {
                this.splice(j, 1);
            } else {
                j++;
            }
        }
    }
};
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fun /*, thisp*/) {
        var len = this.length;
        if (typeof fun != "function")
            throw new TypeError();

        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this)
                fun.call(thisp, this[i], i, this);
        }
    };
}

String.prototype.startsWith = function (str) {
    return (this.indexOf(str) === 0);
};

function getId(id) {
    ///<summary>
    ///Returns numeric value from id string like 'SomeText_id'
    ///</summary>
    if (!id) return null;
    id = id.toString();
    if (id.indexOf('_') < 0) return id;
    return id.substr(id.lastIndexOf('_') + 1);
}

function getPrefix(id) {
    ///<summary>
    ///Returns prefix from id string like 'SomeText_id'
    ///</summary>
    if (!id) return;
    id = id.toString();
    if (id.indexOf('_') < 0) return id;
    return id.substr(0, id.indexOf('_'));
}

function getControllerByUrl(url) {
    ///<summary>
    ///Allows to get controller by url like 'controller/action/params?other_params'
    ///</summary>
    url = url.toString();
    if (url.indexOf('/') < 0) return url;
    return url.substr(0, url.indexOf('/'));
}

function fillFormat(format, obj) {
    ///<summary>
    ///Returns string specified in format with wildcards like %id replaced with properties of specified object.
    ///</summary>
    var re = /(\%[\w}]+)/g;
    var matches = format.match(re);
    $(matches).each(function (i, m) { var val = obj[m.substr(1)]; if (!val) val = ''; format = format.replace(m, val); });
    return format;
}

function Logout() {
    var href = "login/logout";
    $.removeCookie('user_list');
    $.removeCookie('wid');
    $.removeCookie('wftab');
    $.removeCookie('task_list');
    location.href = href;
}

function deleteCookie(name) {
    setCookie(name, "", {
        'max-age': -1
    });
}

function setCookie(name, value, options) {
    if (options.expires instanceof Date) {
        options.expires = options.expires.toUTCString();
    }

    var updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);

    for (let optionKey in options) {
        updatedCookie += "; " + optionKey;
        var optionValue = options[optionKey];
        if (optionValue !== true) {
            updatedCookie += "=" + optionValue;
        }
    }
    document.cookie = updatedCookie;
}

function reloadUL(ul, objects) {
    ///Reloads UL with list of objects
    $(ul).html('');
    var format = ($(ul).attr('itemformat')) ? $(ul).attr('itemformat') : '<li>%Name</li>';
    var html = '';
    for (var i = 0; i < objects.length; i++)
        html += fillFormat(format, objects[i]);
    $(ul).html(html);
}

function addCheckListWarning(cls, id) {
    ///Shows warning if one or more of checkboxes with specified class are not checked
    $('.' + cls).click(function () { var show = false; $('.' + cls).each(function (i, el) { if (!el.checked) show = true; }); if (show) $('#' + id).show(); else $('#' + id).hide(); });
}

function openDialog(url, name, params) {
    ///Opens window with the specified url, name and params, but without radio, toolbar etc.
    if (!url) return;
    var width = (params && params.width) ? params.width : 860;
    var height = (params && params.height) ? params.height : 600;
    var features = 'width=' + width + ',height=' + height + ',location=0,radio=0,toolbar=0,status=0,resizable=1,scrollbars=1';
    var wnd = window.open(base + url, name, features, false);
    if (wnd)
        wnd.focus();
    return wnd;
}

function toggle(link, id, showText, hideText) {
    ///Toggles element with specified id and changed link text
    var text;
    if ($(id).is(':visible')) {
        text = (showText == null) ? CommonResources.Show : showText;
        $(link).html('&darr; ' + text);
    }
    else {
        text = (hideText == null) ? CommonResources.Hide : hideText;
        $(link).html('&uarr; ' + text);
    }
    // fix. for IE8
    $(id).toggleClass('hidden'); // it work	
    return false;
}

function setTab(id) {
    if (!id) return;
    if (!documentReady) return;

    $('#tab').val(id);
    $('.tab').hide();
    $('#' + id).show();
    $('#tabs>ul>li>a').removeClass('selected');
    $('#tabs>ul>li>a#a' + id).addClass('selected');

    return false;
}

function prettyprinttree(select) {
    var re = /(\s\/\s)/g;
    $('option', select).each(function (i, el) {
        var m = el.text.match(re);
        if (m) {
            var orig = el.text;
            var cc = el.text.split(re);
            var level = (cc.length / 2) - 1;
            el.text = cc[cc.length - 1];
            for (var i = 0; i < level; i++)
                el.text = String.fromCharCode(8212) + el.text;
            $(el).data('original-text', orig).data('level', cc.length);
        }
    });
}

function unprettyprinttree(select) {
    $('option', select).each(function (i, el) {
        if ($(el).data('original-text')) el.text = $(el).data('original-text');
    });
}

function leadZero(number, len) {
    while (number.length < len)
        number = '0' + number;
    return number;
}

Number.prototype.decline = function (word) {
    var n = this + " ", p = word.split(/-|,/g);
    var pn = n.match(/([^1]|^)1 /) ? 1 : (n.match(/([^1]|^)[234] /) ? 2 : 3);
    return n + p[0] + p[pn];
};

function getURLParameter(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

//показать сведения о текущем пользователе
function showUserDescription() {
    var id = this.id;
    showud = true;
    sid = setTimeout('_showUserDescription("' + id + '")', 500);
    clearTimeout(hid);
}
function hideUserDescription() {
    $('.userdescription').hide();
}

function _showUserDescription(tid) {
    if (!showud) return;
    var id = getId(tid);

    var tdkey = '#userdescription_' + id;
    $('.userdescription').hide();

    var offset = $('span.currentLogin').offset();
    var offset2 = $('#currentLoginExit').offset();
    var h = $('span.currentLogin').height();
    var w = $(window).width() - offset.left + 75;
    if (w < 100) w = 100;
    if (w > 203) w = 203;

    if ($(tdkey).length > 0) {
        $(tdkey).css('top', offset.top + h + 5).css('left', offset2.left - 90).css('width', w);
        $(tdkey).fadeIn('fast');

    }
    else {
        $('body').append('<div id="userdescription_' + id + '" class="userdescription popupwrapper2"><div class="popup"></div></div>');
        $(tdkey).css('top', offset.top + h + 5).css('left', offset2.left - 90).css('width', w);
        $(tdkey).mouseover(function () { clearTimeout(hid); }).mouseout(function () { hid = setTimeout('hideUserDescription()', 500); });
        $('.popup', $(tdkey)).load(base + 'user.ivp/userdescriptions/', { date: new Date().toString() }, function () { if (!showud) return; $('.popup', $(tdkey)).bgiframe(); $(tdkey).show(); }); //$('#taskname_' + id).parents('tr:first').removeClass('newtask').find('.imgnc').hide(); });
    }
}

//Метод, возвращающий хеш на основе Id пользователя
function getuserhash(id) {
    var result;
    $.ajax({
        async: false,
        dataType: "json",
        url: base + 'user.ivp/getuserhash',
        data: { userid: id, date: new Date().toString() },
        success: function (hashid) {
            result = $.trim(hashid);
        }
    });

    return result;
}

function userDetails(hashid) {
    openDialog('user.ivp/viewhash/' + hashid + '?popup=true', 'viewuserhash');
    return false;
}

function companyDetailsHash(hashid) {
    //Для светлого будущего
    /*   var href = 'company.ivp/viewhash/' + hashid + '?popup=true';
       $.ajax({
           url: base + href,
           success: function (data) {
               var dialog = $('<div id="companyDetailsDialog"></div>').dialog({
                   width: 700,
                   minHeight: 100,
                   autoOpen: false,
                   resizable: false,
                   close: function () {
                       $(this).dialog("destroy");
                       $(this).remove();
                   }
               });
               dialog.append(data);
               dialog.dialog('open');
               $('.autogrow').elastic();
               $('a').css("outline", "none");
               $('#content.popup').css("width", "auto");
           },
       });
       return false;*/

    openDialog('company.ivp/viewhash/' + hashid + '?popup=true', 'companyDetailsDialog');
    return false;
}

function companyDetails(id) {
    openDialog('company.ivp/view/' + id + '?popup=true', 'companyDetailsDialog');
    return false;
}

function serviceDetails(id) {
    openDialog('service.ivp/view/' + id + '?popup=true', 'viewService');
    return false;
}

function taskTypeDetails(id) {
    openDialog('TaskType/View/' + id + '?popup=true', 'viewTaskType');
    return false;
}

// Аналог String.Format из шарпа
function FormatString(sText, oArgArr) {
    var sResult = new String();
    var nTmpIndex = 0;
    var nCounter = 0;

    sResult = sText;
    do {
        nTmpIndex = sResult.indexOf("{%}");
        if (nTmpIndex > -1) {
            sResult = sResult.substring(0, nTmpIndex) + oArgArr[nCounter] + sResult.substring(nTmpIndex + 3, sResult.length);
            nCounter++;
        }
    } while (nTmpIndex > -1)

    return sResult;
}

//exact extension of :contains
$.expr[":"].econtains = function (obj, index, meta, stack) {
    return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}

String.prototype.endsWith = function (suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

Array.prototype.contains = function (_value) {
    for (var i = 0, l = this.length; i < l; i++) if (this[i] == _value) return true;
    return undefined;
};

function DisableSaveButtons() {
    $('.save').attr('disabled', true);
    $('.saveandreturn').attr('disabled', true);
}

//замечательная функция для добавления к адресу в атрибуте элемента параметров(помогает избежать задваивания параметров)
//
// element - элемент в атрибуте которого меняет адрес
//attribute - атрибут элемента element, где меняем
//param - имя параметра для добавления или замены его значения
//value - значение параметра
//пример использования: changeaddress($('#taskform'), 'action', 'statusid', statusid);
function changeaddress(element, attribute, param, value) {
    var address = element.attr(attribute);
    var first = address.indexOf('?' + param + '=') > -1;
    var nofirst = address.indexOf('&' + param + '=') > -1;
    if (nofirst || first) {
        var params = address.split('?')[1].split('&');
        var oldvalue;
        for (var p in params) {
            if (params[p].substring(0, param.length + 1) == param + '=') {
                oldvalue = params[p];
                break;
            }
        }
        if (value == '') {
            if (first)
                if (address.indexOf('&') > -1)
                    element.attr(attribute, address.replace(oldvalue, ''));
                else
                    element.attr(attribute, address.replace('?' + oldvalue, ''));
            if (nofirst)
                element.attr(attribute, address.replace('&' + oldvalue, ''));
        }
        else
            element.attr(attribute, address.replace(oldvalue, param + '=' + value));
    }
    else if (value != '')
        if (address.indexOf('?') > -1)
            element.attr(attribute, address + '&' + param + '=' + value);
        else
            element.attr(attribute, address + '?' + param + '=' + value);
}

function blinkbg($input) {
    var oldBg = $input.css("background");
    $input.css("background-color", "#f9f8e0");
    if ($.browser.msie) {
        setTimeout(function () { $input.css("background-color", "#ffffff"); }, 1000);
    } else {
        setTimeout(function () { $input.css("background", oldBg); }, 1000);
    }
}

function createModalDialog(title, body, action, initialization, settingsEx) {
    /// <summary>Функция для создания и открытия модального диалогового окна на основе jquery.dialog.js</summary>
    /// <param name="title" type="String">Заголовок</param>
    /// <param name="body" type="String">HTML-разметка тела диалога</param>
    /// <param name="action" type="function">функция, выполняющаяся при нажатии на кнопку "сохранить и закрыть"</param>
    if ($('#dialog').length == 0) $('body').append('<div id="dialog"></div>');

    settingsEx = settingsEx || {};
    var dialogSettings = {
        modal: true,
        title: title,
        autoOpen: false,
        width: 'auto',
        height: 'auto',
        minWidth: '600px'
    };

    dialogSettings = $.extend({}, dialogSettings, settingsEx);

    var d = $('#dialog').dialog(dialogSettings);

    //чистка
    d.empty();
    d.off('click', '.close-dialog-button');
    d.off('click', '.saveAndClose-dialog-button');

    var hasAction = typeof (action) != 'undefined';

    //html
    d.append('<div class="formbody">' + body + '</div>');
    var formBottom = '<div class="formbottom">';
    if (hasAction)
        formBottom += '<button style="margin-right: 3px;" type="submit" class="saveAndClose-dialog-button">' + CommonResources.SaveAndClose + '</button>';
    formBottom += '<button type="button" class="close-dialog-button">' + (hasAction ? CommonResources.Cancel : CommonResources.Close) + '</button></div>';

    d.append(formBottom);

    //js
    d.on('click', '.close-dialog-button', function () { d.dialog('destroy'); });
    if (hasAction)
        d.on('click', '.saveAndClose-dialog-button', function () {
            var result = action();
            if (result === undefined || result == true)
                d.dialog('destroy');
        });

    if (typeof (initialization) != 'undefined') initialization();
    d.dialog('open');

    if (hasAction)
        $('.saveAndClose-dialog-button').focus()
    else
        $('.close-dialog-button').focus();

    //Устанавливаем автоматически выбранные размеры окна минимальными + края
    var dialogForm = $('#dialog').closest('div[role="dialog"]');
    d.dialog({
        minWidth: dialogForm.width() + 14,
        minHeight: dialogForm.height() + 14
    });
}

function alertDialog(title, body, okBtnAction, okBtnName) {
    /// <summary>Функция для создания и открытия модального диалогового окна на основе jquery.dialog.js</summary>
    /// <param name="title" type="String">Заголовок</param>
    /// <param name="body" type="String">HTML-разметка тела диалога</param>
    if ($('#alertDialog').length == 0) $('body').append('<div id="alertDialog"></div>');
    var d = $('#alertDialog').dialog({
        modal: true,
        title: title,
        autoOpen: false,
        width: 'auto',
        maxWidth: screen.width - 25,
        position: { my: "center" },
        resizable: false,
        close: function () {
            $(this).dialog("destroy");
            $(this).remove();
        }
    });
    //чистка
    d.empty();
    d.off('click', '.close-dialog-button');

    //html
    d.append('<div class="formbody">' + body + '</div>');
    var formBottom = '<div class="formbottom">';
    if (okBtnAction) {
        var name = (okBtnName) ? okBtnName : CommonResources.OK;
        formBottom += '<button type="button" class="ok-dialog-button">' + name + '</button>&nbsp;';
    }
    formBottom += '<button type="button" class="close-dialog-button">' + CommonResources.Cancel + '</button>';
    formBottom += '</div>';
    d.append(formBottom);
    //js
    d.on('click', '.close-dialog-button', function () { d.dialog('close'); });
    if (okBtnAction) {
        d.on('click', '.ok-dialog-button', function () {
            var result = okBtnAction();
            if (result === undefined || result == true) {
                d.dialog('close');
                return true;
            }

        });
    }
    d.dialog('open');
    $('.close-dialog-button').focus();
    //Устанавливаем автоматически выбранные размеры окна минимальными + края
    var dialogForm = $('#alertDialog').closest('div[role="dialog"]');
    d.dialog({
        minWidth: dialogForm.width() + 14,
        minHeight: dialogForm.height() + 14
    });
}


//------------------ autoselect stuff -----------------------------
function addSelectedValues(values, labels, paths, msName) {
    if (!jQuery || !jQuery.multipleSelects) return;
    var ms = jQuery.multipleSelects[msName];
    values.forEach(function (value) {
        var label = labels['id' + value];
        if ($('option[value="' + value + '"]', ms.select).length > 0) return;
        window.test = ms;
        ms.select.append('<option selected value="' + value + '">' + label + '</option>');
        ms.addOption(value, label, true);
        ms.optionsToString();
        ms.select.trigger('change');
    });
}

function addSelectedValues(result, msName) {
    if (!jQuery || !jQuery.multipleSelects) return;
    var ms = jQuery.multipleSelects[msName];
    var values = result["selectedIds"];
    var labels = result["selectedNames"];
    values.forEach(function (value) {
        var label = labels['id' + value];
        if ($('option[value="' + value + '"]', ms.select).length > 0) return;
        window.test = ms;
        ms.select.append('<option selected value="' + value + '">' + label + '</option>');
        ms.addOption(value, label, true);
        ms.optionsToString();
        ms.select.trigger('change');
    });
}

function addSelectedPaths(result, msName) {
    if (!jQuery || !jQuery.multipleSelects) return;
    var ms = jQuery.multipleSelects[msName];
    var values = result["selectedIds"];
    var labels = result["selectedNames"];
    var paths = result["selectedPaths"];
    values.forEach(function (value) {
        var label = labels['id' + value];
        var path = paths['id' + value];
        if ($('option[value="' + path + '"]', ms.select).length > 0) return;
        window.test = ms;
        ms.select.append('<option selected value="' + path + '">' + label + '</option>');
        ms.addOption(path, label, true);
        ms.optionsToString();
        ms.select.trigger('change');
    });
}

function addSelectedSingleValue(result, msName) {
    if (!jQuery || !jQuery.multipleSelects) return;
    var ms = jQuery.multipleSelects[msName];
    ms.uncheckAll();
    var values = result["selectedIds"];
    var labels = result["selectedNames"];
    window.test = ms;
    var value = $(values).last()[0];
    var label = labels['id' + value];
    var alreadyInList = $('option[value="' + value + '"]', ms.select);
    if (alreadyInList.length > 0) {
        alreadyInList.each(function (id, e) {
            $(e).attr("selected", true);
        });

    } else {
        ms.select.append('<option selected value="' + value + '">' + label + '</option>');
    }
    ms.addOption(value, label, true);
    ms.optionsToString();
    ms.select.trigger('change');
}

function addSelectedSinglePath(result, msName) {
    if (!jQuery || !jQuery.multipleSelects) return;
    var ms = jQuery.multipleSelects[msName];
    ms.uncheckAll();
    var values = result["selectedIds"];
    var labels = result["selectedNames"];
    var paths = result["selectedPaths"];
    window.test = ms;
    var value = $(values).last()[0];
    var path = paths['id' + value];
    var label = labels['id' + value];
    var alreadyInList = $('option[value="' + path + '"]', ms.select);
    if (alreadyInList.length > 0) {
        alreadyInList.each(function (id, e) {
            $(e).attr("selected", true);
        });

    } else {
        ms.select.append('<option selected value="' + path + '">' + label + '</option>');
    }
    ms.addOption(path, label, true);
    ms.optionsToString();
    ms.select.trigger('change');
}

function rowChecked(id, check) {
    if ($('#id' + id).length > 0) {
        selectedNames['id' + id] = $('#id' + id).attr('fullname');
        selectedPaths["id" + id] = $("#id" + id).attr('path');
    }
}

//autocomplete
function selectAC(url, msName) {
    dlg = openDialog(url);
    dlg.callback = function (result) {
        addSelectedValues(result, msName);
    }
    return false;
}

function selectACSingle(url, msName) {
    dlg = openDialog(url);
    dlg.callback = function (result) {
        addSelectedSingleValue(result, msName);
    }
    return false;
}

function shortenComplexName(inputName) {
    var nameParts = inputName.split(' / ');
    var lastNamePart = nameParts.pop();
    var shortenName = "";
    $.each(nameParts, function (id, e) {
        shortenName += e.substring(0, 7) + '...';
        shortenName += ' / ';
    });

    shortenName += lastNamePart;

    return shortenName;
}

function getTaskServiceFilterAcParams() {
    var fltVal = $('#fttService_Path').val();
    if (fltVal == '1') {
        return {
            'EqualOrChild': 1
        };
    }
    else {
        return {};
    }
}

function getTaskServiceFilterChildCond() {
    var fltVal = $('#fttService_Path').val();
    return fltVal != '1';
}

function afterAjaxMessage(element, messagetype, text) {
    var colorclass = ''
    switch (messagetype) {
        case 'success': colorclass = 'message-success'; break;
        case 'error': colorclass = 'message-error'; break;
        case 'warning': colorclass = 'message-warning'; break;
        case 'info': colorclass = 'message-info'; break;
    }
    $(element).text(text);
    $(element).addClass(colorclass);
    $(element).fadeIn(500, function () {
        $(element).fadeOut(4500, function () {
            $(this).text('');
            $(this).removeClass(colorclass);
        })
    });
}

function userData2LoadPopup(that) {
    var $that = $(that);
    var $userData2Popup = $that.closest('tr').find('.userData2Popup');

    function _showHide(show) {
        if (show) {
            $('#userData2Overlay').fadeIn(500);
            $userData2Popup.fadeIn(500);
        }
        else {
            $('#userData2Overlay').fadeOut(500);
            $userData2Popup.fadeOut(500);
        }
    };

    if ($userData2Popup.data('loaded')) {
        _showHide(!$userData2Popup.is(':visible'))
    }
    else {
        $userData2Popup.load('Layout/GetUserInfoShort', function () {
            if (!$('#userData2Overlay').length) {
                $('body').append('<div id="userData2Overlay" style="position: fixed;width: 100%;height: 100%;top: 0px;left: 0px; background: rgba(0,0,0,.4)"></div>');
            }
            $userData2Popup.data('loaded', true);
            _showHide(true);
            $('#userData2Overlay').click(function (e) {
                e.preventDefault();
                _showHide(false);
            });
        });
    }
}
