var tid = null;
var utid = null;
var utype = null;
var dlg = null;
var endstatus = false;
var deadlinechanged = false;
var timeid = null;
var taskname = "";
var autocomplete = false;
var hhid = null;
var ssid = null;
var reactionresolutionerrormessage = null;
var isdatepicker = false;
var showImageTimeout = 0;

var _columns = 1;
var _columnWidth = 0;
var _currentLevel = 1;

var selectedCategories = null;
var selectedAssets = null;

$(function () {
    //Костыль для ie и mvc биндера, так как долбаный ie сабмитит Content-Disposition: form-data; name="" и биндер определяет тип модели как simple а не complex
    $('button').each(function (index, input) {
        var $input = $(input);
        if (!$input.attr('name')) {
            $input.attr('name', 'noname');
        }
    });
    initEventHandlers();
    initAutocompleteRightMenu();
    removeExecutors();
    removeCategories();
    removeParticipants();

    if ($('#create').length > 0) { $('#name').focus(); loadPriorityDescription(); }
    else $('#priorityid').attr('title', $('#prioritydescription').val());
    setFieldFocus();

    checkParamsIfChangedWorkflow();

    $("#exportTemplate").click(function () {
        $('#actionholder').toggle();
    });




});

function initAutocompleteRightMenu() {
    $('#choosecreator').autocomplete(base + 'task.ivp/findcreators/' + $('#serviceid').val(), { minChars: 1 }).result(creatorSelected);
    $('#addexecutor').autocomplete(base + 'task.ivp/findexecutors/' + $('#serviceid').val(), { minChars: 1 }).result(userAdded);
    $('#addparticipant').autocomplete(base + 'task.ivp/findparticipants/' + $('#serviceid').val(), { minChars: 1 }).result(userAdded);
    $('#addexecutorgroup').autocomplete(base + 'task.ivp/findexecutorgroups/' + $('#serviceid').val(), { minChars: 1 }).result(groupAdded);
}

function initEventHandlers() {

    $('body').on('click', 'a.saveandreturnicon ', function () {
        var $self = $(this);
        if (!$self.attr('disabled')) {
            $('#returnaftersave').val('true');
            $('#taskform').submit();
        }
    });

    $('body').on('click', 'a.saveicon ', function () {
        var $self = $(this);
        if (!$self.attr('disabled')) {
            $('#returnaftersave').val('');
            $('#taskform').submit();
        }
    });

    if ($.fn.calendar) {
        $('body').on('hover focus', '#deadline', function () {
            var $self = $(this);
            if ($self.data('initialized') || !$.fn.calendar)
                return;
            $self.calendar({ selectHandler: selectDeadlineHandler });
            $self.data('initialized', true);
        });
    }

    if ($.browser.msie) {
        $('#attachscreenshotbutton').show();
    }
        //проверяем показывать ли функционал со скриншотами: только FF с 22 версии, Chrome  с 24 версии и Opera с 16 версии
    else if (($.browser.mozilla && $.browser.version > 21)
                ||
                ($.browser.chrome && $.browser.version > 23)
                ||
                ($.browser.opera && $.browser.version > 15)
                ) {
        $('#pastescreenbtn').show();
    }

    $('input').keydown(function (e) {
        if (e.keyCode == 13) {
            return false;
        }
    });

    if ($('#exphours') && $('#expminutes')) {
        $('#exphours,#expminutes').focus(function () {
            if ($(this).val() == '00') {
                $(this).val('');
            }
        }).blur(function () {
            if ($(this).val() == '') {
                $(this).val('00');
            }
        });
    }



    $('#actionholder').click(function () { $(this).hide(); });
    $('input, textarea, select').change(function () { $(this).attr('changed', true); });
    $('input.dateevent').change(checkDates);
    $('#recalculate').click(function (e) { recalculateDates(e, this); });

    //если пользователь на новой заявке пытается изменить сервис предупреждаем его о том что то что он уже ввел сохранено не будет
    //$('#NewTask').click(function () {
    //    return confirm(TaskResources.ChangeServiceForNewTaskWorning);
    //});

    $('.changestatus').click(chooseTaskStatus);
    $('.cancel').click(function () {
        if (confirm(TaskResources.Cancel + $(this).attr('statusname') + '"?'))
            changeTaskStatus($(this).attr('taskid'), $(this).attr('tostatusid'));
    });
    $('#expensesuserid').attr('disabled', true);
    //$('#expensesuserid').change(loadExpensesRate);

    $('form input').keydown(function (e) { if (e.keyCode == 13) { formchanged = true; return false; } });
    $('#statusid').change(onchangeStatus);

    $('#deadline').change(checkEndStatus);
    $('#deadline').change(function () { deadlinechanged = true; });

    $('.deadline').change(function () { var data = $(this).val(); $('.deadline').each(function (i, e) { $(e).val(data); }); });
    $('#priorityid').change(loadPriorityDescription);

    if ($('#notparentautodeadline').val().toLowerCase() == 'true' || ($('#notparentautodeadline').val().toLowerCase() == 'false' && $('#haschild').val().toLowerCase() == 'false'))
        $('#priorityid').change(function () {
            getWorkflowAndSLA(null, "Priority");
        });

    $('#expensesuserid').change(getExecutorRate);
    $('textarea.autogrow').elastic();
    $('#comment').blur(function () { if (!$('#comment').val()) $('#comment').css('height', 30); });
    $('#addexecutors input.cb').click(function () { if ($("#addexecutors input.cb:checked").length > 0) $('#addexecutorswarning').show(); else $('#addexecutorswarning').hide(); });
    $('#addparticipants input.cb').click(function () { if ($("#addparticipants input.cb:checked").length > 0) $('#addparticipantswarning').show(); else $('#addparticipantswarning').hide(); });

    $('#addasset').autocomplete(base + 'task.ivp/findassets/' + $('#serviceid').val(), { minChars: 1 }).result(assetAdded);
    $('#addcategory').autocomplete(base + 'task.ivp/findcategories/' + $('#serviceid').val(), { minChars: 1 }).result(categoryAdded);
    $('#typeid').change(loadAttributes);

    if ($('#isMultipleCombo').val() == 'True')
        $(document).on('change', '.typecombo', multipleComboSelection);

    $(document).on('change', '.expensesinput', function () {
        calculateExpensesMinutes(this);
        validateexpensesadditional(this);
    });
}



$(document).ready(function () {

    reinitHeader();
    $(window).bind("resize", function () {
        reinitHeader();
    });
});

function formAfterSubmit(form) {
    if (customValidate())
        form.submit();
}

function reinitHeader() {
    if ($('#tasktypespan').offset()) {
        var offsetlink = $('#tasktypespan').offset().left;
        if (offsetlink < 50)
            $('div.formheader:first').css('margin-bottom', '15px');
        else
            $('div.formheader:first').css('margin-bottom', '0px');
    }
}

function selectDeadlineHandler(dateObj, dateStr) {
    $.getJSON(base + 'task.ivp/checkDeadlineWithSchedule', { date: dateStr, serviceid: $('#serviceid').val() }, function (result) {
        if (result) {
            $('#deadline').val(result).trigger('change');
        }
        else $('#deadline').val(dateStr).trigger('change');
    });
}

//Загружает дополнительные атрибуты заявки при выборе типа заявки
function loadAttributes() {
    $('#attributes').load(base + 'task.ivp/getattributes/' + $('#typeid').val(), { timestamp: new Date().toString() }, function () {
        $('#attributes textarea.autogrow').elastic();
    });
}

function getExecutorRate() {
    $.get(base + 'task.ivp/getExecutorRate/', { exid: $('#expensesuserid').val(), taskid: $('#id').val() }, function (json) { $('#expensesrate').val(json); });
}

function customValidate() {
    if ($('form').validate().numberOfInvalids() == 0) {
        if (reactionresolutionerrormessage) { alert(reactionresolutionerrormessage); return false; }
        if ($('#reactiondate').val() != null && $('#reactiondate').val() != '' && $.parseDate($('#reactiondate').val()) < $.parseDate($('#created').val())) { alert(TaskResources.ReactionDateEarlierThanCreated); return false; }
        //if ($('#reactiondatefact').val() != null && $('#reactiondatefact').val() != '' && $.parseDate($('#reactiondatefact').val()) < $.parseDate($('#created').val())) { alert(TaskResources.ReactionDateFactEarlierThanCreated); return false; }
        if ($.trim($('#deadline').val()) && deadlinechanged) {
            var date = $.parseDate($('#deadline').val());

            var dateTimeNow;
            $.ajax({
                async: false,
                url: base + 'user.ivp/userdatetime/',
                dataType: 'json',
                data: { timestamp: new Date().toString() },
                success: function (data) {
                    dateTimeNow = $.parseDate(data);
                }
            });

            //Проверяем на истечение дедлайна только если дедлайн менялся
            if (deadlinechanged && date < dateTimeNow && !endstatus && !confirm(TaskResources.DeadlinePassed)) return false;

            //Проверяем сроки дочерних и родительских заявок
            if (deadlinechanged && $('#notparentautodeadline').val() == 'true') {
                var childsLatestDeadline = $.parseDate($('#childslatestdeadline').val());
                if (childsLatestDeadline != null && date < childsLatestDeadline && !endstatus && !confirm(TaskResources.ChildDeadlineLaterThanParent)) return false;

                var parentsEarliestDeadline = $.parseDate($('#parentsearliestdeadline').val());
                if (parentsEarliestDeadline != null && date > parentsEarliestDeadline && !endstatus && !confirm(TaskResources.ParentDeadlineEarlierThanChild)) return false;
            }
        }
        serializeChanges();
        $('.save,.saveandreturn').attr('disabled', true);
        return true;
    }
}

function checkEndStatus() { //Проверка, конечный ли статус. Если конечный, то дедлайн проверять не надо.
    $.getJSON(base + 'task.ivp/isstatusfinal/' + $('#statusid').val(), function (json) { endstatus = json; });
}

var categories = 0;

//#region actions on status change
function onchangeStatus() {
    if (!$("#create").val())
        updateTaskOnStatusChange();

    checkEndStatus();
}

function updateTaskOnStatusChange(statusId, callback) {
    if (!statusId)
        statusId = $('#statusid').val();


    GetUpdateTaskOnStatusChange(statusId, callback);
}

function GetUpdateTaskOnStatusChange(statusId, callback, async) {
    var url = base + 'task.ivp/GetUpdateTaskOnStatusChange/' + $('#serviceid').val() + '/' + statusId + '/' + $('#creatorid').val();
    if (async !== false)
        async = true;

    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        async: async,
        success: function (json) {

            var executorsData = undefined;
            var observersData = undefined;
            var executorsGroup = undefined;
            var canRemoveExecutor = undefined;
            var canRemoveObserver = undefined;
            var canRemoveExecutorGroup = undefined;
            var deleteExecutors = undefined;
            var deleteCategories = undefined;
            
            if (json) {

                executorsData = { DeleteExecutors: json.DeleteExecutors, Executors: json.Executors };

                observersData = { DeleteObservers: json.DeleteObservers, Observers: json.Observers };

                executorsGroup = json.ExecutorGroup;


                canRemoveExecutor = json.CanRemoveExecutors;

                canRemoveObserver = json.CanRemoveObservers;

                canRemoveExecutorGroup = json.CanRemoveExecutorGroup;

                deleteExecutors = json.DeleteExecutors;

                deleteCategories = json.DeleteCategories;
            }

            //Исполнители 
            updateExecutorsOnStatusChange(statusId, executorsData, callback, canRemoveExecutor);

            //Наблюдатели
            updateObserversOnStatusChange(statusId, observersData, callback, canRemoveObserver);

            //Категории
            deleteCategoriesOnStatusChange(deleteCategories);

            //Группы исполнителей
            updateExecutorsGroupOnStatusChange(statusId, executorsGroup, callback, canRemoveExecutorGroup, deleteExecutors);
        }
    });
}

function updateParticipantsCallback(callback) {
    categories++;

    if (categories == 3)
        callback();
}

function updateExecutorsOnStatusChange(statusId, data, callback, canRemove) {

    if (data) {

        if ($("#create").val() || data.DeleteExecutors) {

            if ($("#create").val() && statusId == $("#changestatuswhenassignexecutor").val())
                removeAllExecutorsButNotThis($('#userid').val(), false);
            else
                removeAllExecutors(false);
        }

        $.each(data.Executors, function () {
            if (!$("#fewExecutors").length)
                _addUserToList(this.Id, this.Name, this.Company.Name, "#executors", true, this.HashId, canRemove);
            else
                _checkUser(this.Id, "#executor");
        });

    } else {

        if ($("#create").val()) {
            if (statusId == $("#changestatuswhenassignexecutor").val())
                removeAllExecutorsButNotThis($('#userid').val(), false);
            else
                removeAllExecutors(false);
        }
    }

    if (callback) {
        updateParticipantsCallback(callback);
    }
}

function updateObserversOnStatusChange(statusId, data, callback, canRemove) {

    if (data) {
        if ($("#create").val() || data.DeleteObservers)
            removeAllObservers(false);

        $.each(data.Observers, function () {
            if (!$("#fewParticipants").length)
                _addUserToList(this.Id, this.Name, this.Company.Name, "#participants", true, this.HashId, canRemove);
            else
                _checkUser(this.Id, "#participant");
        });
    } else {
        if ($("#create").val()) {
            removeAllObservers(false);
        }
    }

    if (callback)
        updateParticipantsCallback(callback);
}


function updateExecutorsGroupOnStatusChange(statusId, executorsGroup, callback, canRemove, deleteExecutors) {

    if (executorsGroup) {
        _executorGroupsSelected(executorsGroup.Id, executorsGroup.Name, canRemove);
    } else {
        if (deleteExecutors)
            removeExecutorGroup(false);
    }

    if (callback)
        updateParticipantsCallback(callback);
}

function deleteCategoriesOnStatusChange(deleteCategories) {
    if (deleteCategories) {
        $('#categories').find('ul.items li').each(function(index,element) {
            element.addClass('archive changed');
        });
        $("#categoryids option").remove();

        getWorkflowAndSLA(null, "Category", function () {
            if ($("#create").val())
                onchangeCategories();
        });
    }
}
//#endregion


function userAdded(e, d) {
    var iid = '#' + e.target.id.substr(3) + 's';
    var name = d[0];
    var company = d[1];
    var id = d[2];

    $(e.target).val('');
    _addUserToList(id, name, company, iid);
}

function creatorSelected(e, d) {
    var id = d[2];
    var name = d[0];

    $(e.target).val('');
    _creatorSelected(id, name);
}

function _creatorSelected(id, name) {
    $.getJSON(base + 'user.ivp/getuserhash', { userid: id, date: new Date().toString() }, function (hashid) {

        //проверка на наличие действующего договора
        var serviceid = $("#serviceid").val();
        var tasktypeid = $("#typeid").val();
        $.getJSON(base + 'user.ivp/GetCreateTaskAccess', { userid: id, serviceid: serviceid, tasktypeid: tasktypeid != 0 ? tasktypeid : null }, function (result) {
            if (!result.IsCreateTaskAccess) {
                // $('#creator ul').append('<li style="color: red;">' + TaskResources.IsBlockCreate + '</li>');
                if (!confirm(result.Message)) {
                    return false;
                }
            }

            //добавление выбранного заявителя
            $('#creator ul li').remove();
            var html = '<li class="changed"><a href="user.ivp/viewhash/' + hashid + '" onclick="return userDetails(' + "'" + hashid + "'" + ');" class="nounderline">' + name + '</a></li>';
            $('#creator ul').append(html);
            $('#creatorid').attr('changed', true).val(id);

            $.getJSON(base + 'task.ivp/GetExecutorGroupByCreator', { creatorId: id, serviceId: $('#serviceid').val(), taskId: $('#id').val(), statusId: $('#statusid').val() }, function (result) {
                if (result.hasOwnProperty('Name') && result.hasOwnProperty('Id'))
                    _executorGroupsSelected(result.Id, result.Name);
            });

            getWorkflowAndSLA(null, "User");
            return false;
        });
    });
}

function _addUserToList(id, name, company, type, dontChangeStatusInProgress, hash, canRemove) {
    var wrapper = $(type);
    var ul = wrapper.find('ul:first');
    var select = wrapper.find('select:first');
    if ($('option[value="' + id + '"]:selected', select).length > 0)
        return;
    if (hash) {
        _addUserToListAction(hash, id, name, company, type, dontChangeStatusInProgress, ul, select, canRemove);
    } else {
        $.getJSON(base + 'user.ivp/getuserhash', { userid: id, date: new Date().toString() }, function (hashid) {
            _addUserToListAction(hashid, id, name, company, type, dontChangeStatusInProgress, ul, select, canRemove);
        });
    }
}

function _addUserToListAction(hashid, id, name, company, type, dontChangeStatusInProgress, ul, select, canRemove) {
    if ($('#oneexecutoronticket').val() == "True" && $('option', select).length >= 1 && type == "#executors") {
        select.find("option").remove();
        ul.find("li").addClass('archive changed');
        if (!$(".OnlyOneExecutor").length)
            $("#executors").prepend('<div class="warning OnlyOneExecutor">' + TaskResources.OnlyOneExecutor + '</div>');
    }

    if ($('option[value="' + id + '"]', select).length > 0)
        $('option[value="' + id + '"]', select).attr("selected", "selected");
    else
        select.append('<option selected value="' + id + '">' + name + '</option>');

    if (!ul.find('li[userid=' + id + ']').length) {

        var html = '<li userid="' + id + '" class="changed"><a href="user.ivp/viewhash/' + hashid + '" onclick="return userDetails(' + "'" + hashid + "'" + ');" class="nounderline">' + name + '</a>';

        if (canRemove) {
            if ((type === '#executors' && canRemove) || (type === '#participants' && canRemove)) {
                html += '<span class="hover"><a href="#" onClick="return removeUser(this,' + id + ');"><img src="img/trash.gif" /></a></span>';
            }

        } else {
            html += '<span class="hover"><a href="#" onClick="return removeUser(this,' + id + ');"><img src="img/trash.gif" /></a></span>';
        }

        html += '<div class="grey small">' + company + '</div></li>';
        ul.append(html);
        ul.find('.empty').hide();
    } else {
        removeUser(ul.find('li[userid=' + id + ']').find("a"), id);
    }

    if (!(dontChangeStatusInProgress) && type == "#executors" && $('#userid').val() == id) {
        changeStatusWhenAssignSelfExecutor();
    }
}

//#region Lifetime
function resizeTextarea(e) {
    var ta = $(this).get(0);
    if ($(ta).val().length == 0) return;
    if (e.keyCode == 13 || Math.abs(parseInt($(ta).height(), 10) - parseInt(ta.scrollHeight, 10)) > 5) $(ta).css('height', ta.scrollHeight + 16);
}

function switchLifetime() {
    if ($('#switchlifetime').html().indexOf(TaskResources.CommentsOnly) > 0)
        $('#switchlifetime').html('&darr; ' + TaskResources.ShowFull);
    else
        $('#switchlifetime').html('&uarr; ' + TaskResources.CommentsOnly);

    if (!$("#lifetimefull").children().length)
        $("#lifetimefull").load(base + "task.ivp/GetFullLifeTime/" + $("#id").val(), function () {
            $(".lifetime").toggle();
        });
    else {
        $(".lifetime").toggle();
    }

    return false;
}
//#endregion

//#region files, screenshots
function attachFile() {
    var n = $('#addfiles>div').length + 1;
    formchanged = true;
    $('#addfiles').append('<div class="changed padded5"><input size="50" type="file" id="file' + n + '" name="file' + n + '" /></div>');
    return false;
}

//добавляем скриншот из редактора(только хром, фф и опера)
function attachPasteScreenshot(imageValue, name) {
    var n = parseInt(Math.random() * 1000);
    formchanged = true;
    $('#addscreenshots').append('<li class="screenshot changed padded5"><input type="hidden" id="attachscreenshots' + n
        + '" name="attachscreenshots' + n + '" value="' + imageValue + '"/><input id="nameattachscreenshots' + n +
        '" name="nameattachscreenshots' + n + '" type="hidden" value="' + name.replace(/\"/g, "\'") + '"><span>' + name + '.png</span>' +
        '<a class="noul" href="#" onclick="return removePasteScreen($(this));"><img src="img/trash.gif" title="' + CommonResources.Remove + '"/></a>' +
        '</li>');
    return false;
}

function removePasteScreen(link) {
    $(link).parent('li.screenshot').remove();
    return false;
}

//Удаление стандартных файлов
function removeFile(id) {
    if (!$('#file' + id + ' a:first').hasClass("selectdeletedfile")) {
        $('#file' + id + ' a:first').removeClass("noul").addClass("selectdeletedfile");
        deleteFile(id);
    } else {
        $('#file' + id + ' a:first').removeClass("selectdeletedfile").addClass("noul");
        restoreFile(id);
    }
    return false;
}

//Удаление файлов доп. полей
function removeAdditionalFile(fieldid) {
    var fileid = $('a[fieldid=' + fieldid + ']').attr("fileid");
    $("#filefield" + fieldid).remove();
    deleteFile(fileid);
    var input = $('#field' + fieldid);
    input.attr('disabled', false).closest('.changed').show();
    return false;
}

//установка флага на удаление
function deleteFile(id) {
    if ($('#taskform INPUT#deletedfiles').length == 0) {
        $('#taskform').prepend('<input id="deletedfiles" type="hidden" name="deletedfiles" value="">');
    }
    var elems = $('#deletedfiles').val() != '' ? ($('#deletedfiles').val()).split('|') : [];
    elems.push(id);
    $('#deletedfiles').val(elems.join('|'));
}

//снятие флага на удаление для файла
function restoreFile(id) {
    if ($('#taskform INPUT#deletedfiles').length == 0) {
        $('#taskform').prepend('<input id="deletedfiles" type="hidden" name="deletedfiles" value="">');
    }
    var elems = ($('#deletedfiles').val()).split('|');
    var newelems = [];
    for (var i = 0; i <= elems.length - 1; i++) {
        if (elems[i] != id) newelems.push(elems[i]);
    }
    $('#deletedfiles').val(newelems.join('|'));
}

function attachScreenshot() {
    var str = "cеnter=1;scroll=1;dialogWidth=" + (screen.availWidth - 100) + "px;" + "dialogHeight=" + (screen.availHeight - 100) + 'px;';
    var result = window.showModalDialog(base + 'screenshot.ivp/create/', '', str);
    if (result && parseInt(result[0], 10) > 0) {
        formchanged = true;
        $('#screenshotsids').val($('#screenshotsids').val().length > 0 ? $('#screenshotsids').val() + ',' + result[0] : result[0]);
        $('#screenshotsnames').val($('#screenshotsnames').val().length > 0 ? $('#screenshotsnames').val() + ',.' + result[1] : result[1]);
        var screenshots = new Array();
        screenshots = $('#screenshotsids').val().split(',');
        screenshotsnames = $('#screenshotsnames').val().split(',.');
        var html = '<ul class="items">';
        for (var i = 0; i < screenshots.length; i++) {
            html += '<li class="file" id="screenshot' + screenshots[i] + '">';
            html += '<img class="icon16" src="img/mime/jpg_16.gif" />';
            html += '<a class="noul" href="screenshot.ivp/view/' + screenshots[i] + '"> ' + screenshotsnames[i] + ' </a>';
            html += '<a href="#" onclick="return removeScreenshot(' + screenshots[i] + ');"><img src="img/trash.gif" /></a>';
            html += '</li>';
        }
        html += '</ul>';
        $('#screenshots').html(html);
    }
    return false;
}
function removeScreenshot(id) {
    if (!confirm(TaskResources.SureDeleteScreenshot)) return false;
    $.getJSON('screenshot.ivp/remove/' + id, { date: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true) {
            $('#screenshot' + result.Id).fadeOut('fast').remove();

            //Удаляем идентификатор и имя скриншота из скрытых полей
            var ids = new Array();
            var names = new Array();
            ids = $('#screenshotsids').val().split(',');
            names = $('#screenshotsnames').val().split(',.');
            for (var i = 0; i < ids.length; i++)
                if (id == ids[i]) {
                    ids.splice(i, 1);
                    names.splice(i, 1);
                }
            $('#screenshotsids').val('');
            $('#screenshotsnames').val('');
            for (var i = 0; i < ids.length; i++) {
                $('#screenshotsids').val($('#screenshotsids').val().length > 0 ? $('#screenshotsids').val() + ',' + ids[i] : ids[i]);
                $('#screenshotsnames').val($('#screenshotsnames').val().length > 0 ? $('#screenshotsnames').val() + ',.' + names[i] : names[i]);
            }
        }
        else
            alert(result.Description);
    });
    return false;
}
//#endregion

//#region assets
function assetSelectedTree(id, count, name) {
    var wrapper = $('#assets');
    var ul = wrapper.find('ul:first');
    var select = wrapper.find('select:first');
    formchanged = true;
    if ($('option[value="' + id + '"]', select).length > 0) return;

    select.append('<option selected value="' + id + '">' + name + '</option>');
    var html = '<li class="changed">' + name;
    var sid = select.attr('id');
    html += '<span class="hover"><a href="#"><img src="img/trash.gif" /></a></span></li>';
    ul.append(html).show();
    ul.find('.empty').hide();
    $('li:last span.hover a', ul).click(function () {
        var a = $(this);
        a.parents('li.changed').remove();
        if (ul.children().length == 0)
            $('#tal').addClass('middle');
        $('option[value="' + id + '"]', select).remove();
        return false;
    });
    $('#tal').removeClass('middle');
}
function initSelectedAssets() {
    if (selectedAssets == null)
        selectedAssets = $("#assetids").val();
}

var Task = {
    selectAssets: function selectAssets() {
        dlg = openDialog('assettable.ivp/select?cbmode=Task&tb_select_mode=task&tb_task_id=' + $('#id').val() + '&tb_service_id=' + $('#serviceid').val());//+ '&parentid='+$('#possibleassets').val());
        dlg.callback = Task.assetsCallback;
        return false;
    },
    assetsCallback: function assetsCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        assetSelected(ids, names);
    }
}

function assetSelected(ids, names) {
    var wrapper = $('#assets');
    var ul = wrapper.find('ul:first');
    var select = wrapper.find('select:first');
    formchanged = true;

    ids.forEach(function (id) {
        if ($('option[value="' + id + '"]', select).length > 0) return;

        select.append('<option selected value="' + id + '">' + names['id' + id] + '</option>');
        var html;        
        html = '<li class="changed">' + names['id' + id];        
        html += '<span class="hover"><a href="#"><img src="img/trash.gif" /></a></span></li>';
        ul.append(html).show();
        ul.find('.empty').hide();

        $('li:last span.hover a', ul).click(function () {
            var a = $(this);
            a.parents('li.changed').remove();
            if (ul.children().length == 0)
                $('#tal').addClass('middle');
            $('option[value="' + id + '"]', select).remove();

            getWorkflowAndSLA(null, 'AssetType');

            return false;
        });
    });

    getWorkflowAndSLA(null, 'AssetType');

    $('#tal').removeClass('middle');

}
function assetAdded(e, d) {
    var name = d[0];
    var id = d[1];
    $(e.target).val('');
    autocomplete = true;

    assetSelected(id, name);
    autocomplete = false;
}
function removeAsset(link, id) {
    var a = $(link);
    var del = !a.parents('li:first').hasClass('archive');
    formchanged = true;
    $('select option[value="' + id + '"]', a.parents('#assets')).attr('selected', !del);
    if (del) a.parents('li:first').addClass('archive changed'); else a.parents('li:first').removeClass('archive changed');

    getWorkflowAndSLA(null, 'AssetType');

    return false;
}
function assetDetails(id) {
    openDialog('assettable.ivp/view/' + id + '?popup=true&read=true', 'asset' + id);
    return false;
}
//#endregion

//#region Caregories
function initSelectedCategories() {
    selectedCategories = $("#categoryids").val();
}
function selectCategory() {
    dlg = openDialog('category.ivp/select?tb_serviceid=' + $('#serviceid').val());
    return false;
}
function categorySelected(id, name) {
    var wrapper = $('#categories');
    var ul = wrapper.find('ul:first');
    var select = wrapper.find('select:first');
    formchanged = true;
    if ($('option[value="' + id + '"]', select).length > 0) return;

    if ($('#onecategoryonticket').val() == "True" && $('option', select).length >= 1) {
        select.find("option").remove();
        ul.find("li").addClass('archive changed');
        if (!$(".OnlyOneCategory").length)
            $("#categories").closest("table").before('<div class="warning OnlyOneCategory">' + TaskResources.OnlyOneCategory + '</div>');
        /*alert(TaskResources.OnlyOneCategory);
        return;*/
    }

    select.append('<option selected value="' + id + '">' + name + '</option>');

    if (!ul.find('li[data-id=' + id + ']').length) {
        var html = '<li class="changed" data-id=' + id + '>' + name;
        html += '<span class="hover"><a href="#" onclick="return removeCategory(this,' + id + ');"><img src="img/trash.gif" /></a></span></li>';
        ul.append(html).show();
        ul.find('.empty').hide();
    } else {
        removeCategory(ul.find('li[data-id=' + id + ']').find("a"), id);
    }
    $('#tcl').removeClass('middle');

}
function addSelectedCategories(cids) {

    $(cids.toString().split(',')).each(function (i, id) {
        var lb = $.trim(dlg.categoryNames['lb' + id]);
        categorySelected(id, lb);
    });

    getWorkflowAndSLA(null, 'Category', function () {
        if ($("#create").val())
            onchangeCategories();
    });
}

function categoryAdded(e, d) {
    var name = d[0];
    var id = d[1];
    $(e.target).val('');
    categorySelected(id, name);

    getWorkflowAndSLA(null, "Category", function () {
        if ($("#create").val())
            onchangeCategories();
    });
}
function removeCategory(a, id) {
    a = $(a);
    var del = !a.parents('li:first').hasClass('archive');
    formchanged = true;
    var arrayId = [id];
    var serviceId = $('#serviceid').val();
    removeAutoAssignsUsersOnCategoryChange(serviceId, arrayId);

    if (del) {
        a.closest('li').addClass('archive changed');
        if ($('#onecategoryonticket').val() == "True") {
            $("#categoryids option").remove();
        }
    } else {
        a.closest('li').removeClass('archive changed');
        if ($('#onecategoryonticket').val() == "True") {
            a.closest('ul').find('li').not(a.closest('li')).addClass('archive changed');
            $("#categoryids option").remove();
            $("#categoryids").append('<option selected="selected">' + id + '</option>');
        }
    }

    $('select option[value="' + id + '"]', a.closest('#categories')).attr('selected', !del);
    selectedCategories = $("#categoryids").val();

    getWorkflowAndSLA(null, "Category", function () {
        if ($("#create").val())
            onchangeCategories();
    });

    return false;
}

function removeAutoAssignsUsersOnCategoryChange(serviceId, categoryIds) {
    $.ajax({
        type: 'POST',
        url: base + 'task.ivp/GetAutoAssignsUsersOnCategoryChange/' + serviceId,
        dataType: 'json',
        data: { categories: categoryIds }
    }).done(function(result) {
        if (result && result.Data) {
            //исполнители
            $.each(result.Data.Executors, function () {
                    $("#executors .users li[userid=" + this.Id + "]").find("span.hover a").click();
                });

            //наблюдатели
            $.each(result.Data.Observers, function () {
                    $("#participants .users li[userid=" + this.Id + "]").find("span.hover a").click();
                });

            //группы исполнителей
            if (result.Data.ExecutorGroup) {
                $("#egroupholder a").last().click();
            }
        }
    });
}

function getAutoAssignsUsersOnCategoryChange(serviceId, categoryIds) {

    var isFewExecutors = $("#fewExecutors").length > 0;

    $.ajax({
        type: 'POST',
        url: base + 'task.ivp/GetAutoAssignsUsersOnCategoryChange/' + serviceId,
        dataType: 'json',
        data: { categories: categoryIds },

        success: function (json) {
            if (json) {

                //исполнители
                $.each(json.Executors, function () {

                    if (!isFewExecutors)
                        _addUserToList(this.Id, this.Name, this.Company.Name, "#executors", true, this.HashId, json.CanRemoveExecutors);
                    else
                        _checkExecutors(this.Id, "#executor", this, json.CanRemoveExecutors);
                });

                //наблюдатели
                $.each(json.Observers, function () {

                    if (!isFewExecutors)
                        _addUserToList(this.Id, this.Name, this.Company.Name, "#participants", true, this.HashId, json.CanRemoveObservers);
                    else
                        _checkObservers(this.Id, "#participant", this, json.CanRemoveObservers);
                });

                //группы исполнителей
                if (json.ExecutorGroup)
                    _executorGroupsSelected(json.ExecutorGroup.Id, json.ExecutorGroup.Name, json.CanRemoveExecutorGroup);
            }
        }
    });
}
function onchangeCategories() {
    console.log(23);
    var serviceId = $('#serviceid').val();

    initSelectedCategories();

    getAutoAssignsUsersOnCategoryChange(serviceId, selectedCategories);

}
//#endregion

function taskCoordinationFormPrint(coordinationListId, taskid, taskHistoryId) {
    openDialog('taskcoordinationprint.ivp/view/' + coordinationListId + '?popup=true&taskid=' + taskid + '&taskHistoryId=' + taskHistoryId);
    return false;
}
function taskHistory() {
    openDialog('taskhistory.ivp/list/' + $('#id').val() + "?reset=true", 'History');
    return false;
}
function addExpenses() {
    $('input,select', $('#addexpenses')).attr('disabled', false);
    $('#addexpenses').show('fast'); $('#btnaddexpenses').hide();
    return false;
}
function cancelAddExpenses() {
    $('input,select', $('#addexpenses')).attr('disabled', true);
    $('#addexpenses').hide('fast', function () { $('#btnaddexpenses').show() });
    return false;
}
function removeExpenses(id) {
    $.getJSON('task.ivp/removeexpenses/' + id, { date: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true)
            $('#expenses' + result.Id).fadeOut('fast').remove();
        else
            alert(result.Description);
    });
    return false;
}
function selectExecutors() {
    var url = 'user.ivp/select?reset=true&tb_mode=executors&tb_serviceid=' + $('#serviceid').val();
    utype = '#executors';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function usersCallback(result) {
    var cbmode = result["callbackMode"];
    switch (cbmode) {
        case "person": {
            var uids = result["selectedIds"];
            addPerson(uids);
            break;
        }
        default: {
            var uids = result["selectedIds"];
            var names = result["selectedNames"];
            var companies = result["selectedCompanies"];
            addSelected(uids, names, companies);
        }
    }    
}

function selectCoordinators() {
    var url = 'user.ivp/select?reset=true&tb_mode=coordinators&tb_serviceid=' + $('#serviceid').val();
    utype = '#coordinators';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}
function selectPosibleCoordinators() {
    var url = 'user.ivp/select?reset=true&tb_mode=COORDINATORSFILTER&tb_serviceid=' + $('#serviceid').val();
    utype = '#coordinators';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}
function selectParticipants() {
    var url = 'user.ivp/select?reset=true&tb_mode=participants&tb_serviceid=' + $('#serviceid').val();
    utype = '#participants';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}
function selectCreator() {
    var url = 'user.ivp/select?reset=true&tb_mode=creators&tb_serviceid=' + $('#serviceid').val();
    utype = '#creator';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function getWorkflowAndSLA(action, entityName, callback) {

    var $workflow = $("#workflowid");

    var priorityId = $('#priorityid').val();
    var serviceId = $('#serviceid').val();
    var taskId = $('#id').val();
    var catIds = $("#categoryids").val();
    var assetIds = $("#assetids").val();
    var creatorId = $('#creatorid').val();
    var tasktypeId = $('#typeid').val();
    var statusId = $('#statusid').val();
    var workflowId = $workflow.val();

    initSelectedCategories();
    initSelectedAssets();

    var $serviceLevelName = $('#servicelevelname');

    var taskForm = $("#taskform");

    $.ajax({
        type: 'POST',
        url: base + 'task.ivp/GetWorkflowAndSLA/',
        dataType: 'json',
        data: {
            priorityid: priorityId,
            serviceid: serviceId,
            taskid: taskId,
            tasktypeId: tasktypeId,
            creatorId: creatorId,
            assetIds: assetIds,
            catIds: catIds,
            statusId: statusId,
            workflowId: workflowId,
            field: entityName,
            date: new Date().toString()
        },

        success: function (json) {
            if (json) {

                //Если в ответе пришли данные по бизнес-процессу
                if (json.CalculateWorkflowData && json.WorkflowData) {
                    var $status = $('#statusid');
                    var optionsHtml = '<option value=""></option>';

                    $.each(json.WorkflowData.Statuses, function (index, option) {
                        optionsHtml += '<option value="' + option.Id + '">' + option.Name + '</option>';
                    });

                    $status.html(optionsHtml).val(json.WorkflowData.SelectedStatusId).attr("selected", "selected");

                    $workflow.val(json.WorkflowData.WorkflowId);

                    $('#workflowName').text(json.WorkflowData.WorkflowName);
                }

                //Если в ответе пришел SLA
                if (json.SLAData) {
                    setSLA(json.SLAData.ResolutionTime, json.SLAData.ReactionTime, json.SLAData.ServiceLevelName);
                } else {
                    if (json.CalculateSLAData)
                        $serviceLevelName.hide().prev().hide();
                }
            }

            if (action) {
                taskForm.attr("action", action);
                taskForm.unbind('submit').submit();
                return;
            }

            if (callback)
                callback();
        }
    });

}

function _checkExecutors(userId, handler, userData, canRemove) {
    var user = $(handler + 's').find(handler + 'ids' + userId);
    if (!user.length) {
        var $executors = $('#executorids');
        var $ul = $('#executors ul.users');

        if (!$ul.find('li[data-user-key="' + userId + '"]').length) {
            $ul.find('li.empty').hide();
            var $li = $('<li class="changed"></li>');
            $li.attr('data-user-key', userId);
            var $a = $('<a class="nounderline fewparticipants">' + userData.Id + '</a>');
            $a.attr('onclick', 'return userDetails("' + userData.HashId + '")');
            $a.attr('href', 'user.ivp/viewhash/' + userData.HashId);
            var $div = $('<div class="grey small" title="' + userData.Company.Name + '">' + userData.Company.Name + '</div>');
            $li.append($a);

            if (canRemove) {
                var $span = $('<span class="hover"></span>');
                $span.append($('<a href="#"><img src="img/trash.gif"/></a>').attr('onclick', 'return removeUser(this,' + userId + ');'));
                $li.append($span);
            }

            $li.append($div);
            $ul.append($li);
        }

        var $option = $executors.find('option[value="' + userId + '"]');
        if ($option.length > 0) {
            $option.attr('selected', 'selected');
        } else {
            $option = $('<option></option>');
            $option.attr('value', userId);
            $option.attr('selected', 'selected');
            $executors.append($option);
        }

    } else {
        user.attr("checked", "True");
    }
}
//Выбор чекбокса пользователя 
function _checkObservers(userId, handler, userData, canRemove) {
    var user = $(handler + 's').find(handler + 'ids' + userId);
    if (!user.length) {
        var $participants = $('#participantids');
        var $ul = $('#participants ul.users');
        if (!$ul.find('li[data-user-key="' + userId + '"]').length) {
            $ul.find('li.empty').hide();
            var $li = $('<li class="changed"></li>');
            $li.attr('data-user-key', userId);
            var $a = $('<a class="nounderline fewparticipants">' + userData.Id + '</a>');
            $a.attr('onclick', 'return userDetails("' + userData.HashId + '")');
            $a.attr('href', 'user.ivp/viewhash/' + userData.HashId);

            var $div = $('<div class="grey small" title="' + userData.Company.Name + '">' + userData.Company.Name + '</div>');
            $li.append($a);
            if (canRemove) {
                var $span = $('<span class="hover"></span>');
                $span.append($('<a href="#"><img src="img/trash.gif"/></a>').attr('onclick', 'return removeUser(this,' + userId + ');'));
                $li.append($span);
            }
            $li.append($div);
            $ul.append($li);
        }

        var $option = $participants.find('option[value="' + userId + '"]');
        if ($option.length > 0) {
            $option.attr('selected', 'selected');
        } else {
            $option = $('<option></option>');
            $option.attr('value', userId);
            $option.attr('selected', 'selected');
            $participants.append($option);
        }

    } else {
        user.attr("checked", "True");
    }
}
//Выбор чекбокса пользователя 
function _checkUser(userId, handler) {

    var user = $(handler + 's').find(handler + 'ids' + userId);

    if (user)
        user.attr("checked", "True");
}

function getEntityIds(id) {

    var options = $("#" + id + " option[selected]");
    var ids = "";
    var isFirst = true;
    if (options.length) {
        options.each(function () {
            if (!isFirst)
                ids = ids + ",";
            ids = ids + $(this).val();
            isFirst = false;
        });
    }

    return ids;
}

function addSelected(uids, names, companies) {

    if (utype == '#creator') {
        var id = uids[0];
        var un = names['id' + id];
        _creatorSelected(id, un);
    }
    else if (utype == '#coordinators') {
        // добавление согласующих на форме согласования
        addCoordinatorsToDb(uids);
    }
    else {
        uids.forEach(function (id) {
            var un = names['id' + id];
            var cn = names['id' + id];
            _addUserToList(id, un, cn, utype);
        });
    }
}

function removeUser(a, id) {
    a = $(a);
    var del = !a.parents('li:first').hasClass('archive');

    var isExecutorAdded = (a.closest("div").attr("id") == "executors");

    if (del) {
        a.closest('li').addClass('archive changed');
        if (isExecutorAdded && $('#oneexecutoronticket').val() == "True") {
            $("#executorids option").remove();
        }
    } else {
        a.closest('li').removeClass('archive changed');

        if (isExecutorAdded && $('#oneexecutoronticket').val() == "True") {
            a.closest('ul').find('li').not(a.closest('li')).addClass('archive changed');
            $("#executorids option").remove();
            $("#executorids").append('<option selected="selected">' + id + '</option>');
        }
    }

    $('select option[value="' + id + '"]', a.closest('div')).attr('selected', !del);
    return false;
}

function assignSelfExecutor() {
    $.getJSON(base + 'task.ivp/getuserelement', { json: "json" }, function (data) {
        _addUserToList(data.id, data.name, data.company, "#executors");
    });
    return false;
}

function assignSelfParticipant() {
    $.getJSON(base + 'task.ivp/getuserelement', { json: "json" }, function (data) {
        _addUserToList(data.id, data.name, data.company, "#participants");
    });
    return false;
}

function addUserElement(data, usertype) {
    //Много пользователей - список
    if ($('#' + usertype + 'ids').length > 0) {
        if ($('#' + usertype + 'ids option[value="' + data.id + '"]').length > 0) {
            if ($('#' + usertype + 'ids option[value="' + data.id + '"]:selected').length > 0) {
                switch (usertype) {
                    case "executor":
                        alert(TaskResources.AlreadyExecutor);
                        break;
                    case "participant":
                        alert(TaskResources.AlreadyParticipant);
                        break;
                }
            }
            else {
                $('#' + usertype + 'ids option[value="' + data.id + '"]').attr('selected', true);
                $('#' + usertype + 's > ul.users >li.details').remove();
                $('#' + usertype + 's > ul.users').append(data.userelement);

                if (usertype == "executor")
                    changeStatusWhenAssignSelfExecutor();
            }
        }
        else {
            $('#' + usertype + 'ids').append('<option value="' + data.id + '" selected="selected">New executor</option>'); //Это необязательно переводить
            $('#' + usertype + 's > ul.users >li.details').remove();
            $('#' + usertype + 's > ul.users').append(data.userelement);

            if (usertype == "executor")
                changeStatusWhenAssignSelfExecutor();
        }
        $('#assignself' + usertype).hide();
    }
    return false;
}

function isAnyExecutorOnTask(id) {
    if ($('#oneexecutoronticket').val() == "True" && $('input[name = executorids]:checked').length > 1) {
        alert(TaskResources.OnlyOneExecutor);
        $('#executorids' + id).removeAttr("checked");
        return;
    }
}
function checkSelfExecutor(checked, value) {
    var userId = $('#userid').val();
    if (checked && userId == value) {
        changeStatusWhenAssignSelfExecutor();
    }
    return false;
}
function changeStatusWhenAssignSelfExecutor() {
    var changeStatusId = $('#changestatuswhenassignexecutor').val();

    if ($('#statusid option[value="' + changeStatusId + '"]').length > 0) {
        if ($('#statusid option[value="' + changeStatusId + '"]:selected').length > 0)
            return false;

        $('#statusid option[value="' + changeStatusId + '"]').attr('selected', true);

        onchangeStatus();
    }
    return false;
}
function assignSelfCoordinator(id) {
    //Много согласующих - список
    if ($('#coordinatorids').length > 0) {
        if ($('#coordinatorids option[value="' + id + '"]').length > 0) {
            if ($('#coordinatorids option[value="' + id + '"]:selected').length > 0) alert(TaskResources.AlreadyParticipant);
            else {
                $('#coordinatorids option[value="' + id + '"]').attr('selected', true);
                $('#coordinators > ul.users >li.details').remove();
                $('#coordinators > ul.users').append('<li class="changed">' + TaskResources.YouAreAssignedAsParticipant + '</li>');
            }
        }
        else {
            $('#coordinatorids').append('<option value="' + id + '" selected="selected">New Coordinator</option>');//Это необязательно переводить
            $('#coordinators > ul.users >li.details').remove();
            $('#coordinators > ul.users').append('<li class="changed">' + TaskResources.YouAreAssignedAsParticipant + '</li>');
        }
        $('#assignselfcoordinator').hide();
    }
    return false;
}

//Назначить себя и снять других
function reassignExecutors(userid, few) {
    removeAllExecutorsButNotThis(userid);
    if ($('li[userid=' + userid + ']').length)
        $('#executorids option[value="' + userid + '"]').attr('selected', true);
    else
        assignSelfExecutor(few);

    return false;
}

//Показать окно для ручной эскалации заявки
function showEscalationDialog() {
    $('.formbottom').append('<div id="escalation" class="popup"></div>');
    $('#escalation').load(base + 'task.ivp/showescalationdialog/' + $('#serviceid').val(), null, function () { $('#escalation').show(); });
    return false;
}

function showBindTicketDialog() {
    $('#content').append('<div id="childparent" class="popup"></div>');
    $('#childparent').load(base + 'task.ivp/showbindticketdialog', null, function () { $('#childparent').show(); $('#parentnumber').focus(); $('#parentnumber').keyboard('enter', { preventDefault: true }, function () { }); });
    return false;
}



function checkTicketExistense(event, parentTicketNumber) {

    if (event.keyCode == 13) {
        if (parentTicketNumber != '') {
            $('ul.parentexist').empty();
            $('#parenttasklist').addClass('hidden');
            return checkTicketExistenseTimer(parentTicketNumber, false);

        }
        return false;
    }
}

function checkTicketExistenseTimer(ticketNumber, again) {
    var taskid = $('#id').val();

    if ($('#searchFullLink').hasClass('hidden')) {
        $('#searchFullLink').removeClass('hidden');
    }
    $('ul.parentexist').empty();

    $.getJSON(base + 'task.ivp/ParentExists', { parenttasksearch: ticketNumber, childtaskid: taskid, isAgainSearch: again }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            $('ul.parentexist').append('<li class="ticketnumber">' + result.Description + '</li>');
            if (result.hasOwnProperty('IsNotFountNumber') && result.IsNotFountNumber) {



                $('#searchFullLink').attr('onclick', 'return checkTicketExistenseTimer("' + ticketNumber + '",true);return false;');

            }
            else {
                $('#searchFullLink').attr('onclick', 'return fullSearchParent();return false;');
            }
            if (result.hasOwnProperty('IsAfterQuick') && result.IsAfterQuick) {
                $('#searchFullLink').addClass('hidden');
            }
            return;
        }

        if (result.hasOwnProperty('IsNotFountNumber') && result.IsNotFountNumber) {
            $('#searchFullLink').attr('onclick', 'return checkTicketExistenseTimer("' + ticketNumber + '",true);return false;');
        } else {
            $('#searchFullLink').attr('onclick', 'return fullSearchParent();return false;');
        }
        $('#searchFullLink').removeClass('hidden');
        jQuery.each(result.TaskResult, function () {
            $('ul.parentexist').append('<li class="ticketnumber ticketlabel">#<a href="#" onclick=" bindToParent2(' +
         this.Key + ');return false;" title="Выбрать заявку" ><span id="taskname_' +
          this.Key + '" class="ticketshow" onmouseover="showDescription(this);" onmouseout="hideDescription(this)">' +
           this.Key + '</span></a> </li>');
            $('ul.parentexist').append('<li class="ticketname">' + this.Value + '</li>');
        });

        $('ul.parentexist').highlight(ticketNumber);
    });

    $('#parenttasklist').removeClass('hidden');


    return false;
}



function fullSearchParent() {
    var str = '';
    if ($('#parentnumber')) str = $('#parentnumber').val();
    $('#searchFullLink').addClass('hidden');
    if (str != '') {
        var taskid = $('#id').val();
        $('ul.parentexist').empty();
        $.getJSON(base + 'task.ivp/FullSearchParent', { parenttasksearch: str, childtaskid: taskid }, function (result) {
            if (result.hasOwnProperty('IsOK') && !result.IsOK) {
                $('ul.parentexist').append('<li class="ticketnumber">' + result.Description + '</li>');
                return;
            }
            jQuery.each(result.TaskResult, function () {
                //$('ul.parentexist').append('<li class="ticketnumber ticketlabel">#<a href="#" onclick=" bindToParent2(' + this.Key + ');return false;" title="Выбрать заявку" class="ticketshow"><span id="taskname_' + this.Key + '">' + this.Key + '</span></a> </li>');
                $('ul.parentexist').append('<li class="ticketnumber ticketlabel">#<a href="#" onclick=" bindToParent2(' +
             this.Key + ');return false;" title="Выбрать заявку" ><span id="taskname_' +
              this.Key + '" class="ticketshow" onmouseover="showDescription(this);" onmouseout="hideDescription(this)">' +
               this.Key + '</span></a> </li>');
                $('ul.parentexist').append('<li class="ticketname">' + this.Value + '</li>');
            });
            $('ul.parentexist').highlight($('#parentnumber').val());
        });

        $('#parenttasklist').removeClass('hidden');
    }
    else {
        alert('Введите строку поиска!');
    }

    return false;
}


function bindToParent2(id) {
    $('#taskform').attr('action', 'task.ivp/bindtoparent/' + id);
    $('#taskform').submit();

}

function bindToParent() {

    //$('#taskform').attr('action', 'task.ivp/bindtoparent/' + $('#parentnumber').val());
    $('#taskform').attr('action', 'task.ivp/bindtoparent/' + $('#taskParentResult').text());
}
function escalate() {
    $('#taskform').attr('action', 'task.ivp/escalate');
}

function loadPriorityDescription() {
    var $priorityId = $('#priorityid');
    var priorityId = $priorityId.val();
    if (priorityId) {
        $.get(base + 'task.ivp/getprioritydescription/' + priorityId, function (description) {
            $priorityId.attr('title', description);
        });
    } else {
        $priorityId.removeAttr('title');
    }
}

function unbindChildFromParent() {
    $('#taskform').attr('action', 'task.ivp/UnbindChildTaskFromParent/' + $('#id').val());

}

// При изменении приоритета заявки изменяем дедлайн, если для сервиса задан класс обслуживания и время разрешения отлично от нуля
function updateDeadline() {

    var priorityId = $('#priorityid').val();
    var serviceId = $('#serviceid').val();
    var taskId = $('#id').val();
    var catIds = $("#categoryids").val();
    var assetIds = $("#assetids").val();
    var creatorId = $('#creatorid').val();
    var tasktypeId = $('#typeid').val();

    if (parseInt(priorityId, 10) > 0 && parseInt(serviceId, 10) > 0) {

        $.getJSON('task.ivp/getreactionandresolutiondates',
            {
                priorityid: priorityId,
                serviceid: serviceId,
                taskid: taskId,
                tasktypeId: tasktypeId,
                creatorId: creatorId,
                assetIds: assetIds,
                catIds: catIds,
                date: new Date().toString()
            },
            function (result) {

                if (result.hasOwnProperty('IsOK') && result.IsOK == true) {

                    //Установим SLA
                    setSLA(result.ResolutionTime, result.ReactionTime, result.ServiceLevelName);

                } else {
                    $('#servicelevelname').hide();
                    $('#servicelevelname').prev().hide();
                }
            });
    }
}

function setSLA(resolutionTime, reactionTime, serviceLevelName) {

    if (resolutionTime != '' && resolutionTime != $('#deadline').val()) {
        $('#deadline').attr('changed', true);
        $('#deadline').val(resolutionTime);
        blinkbg($('#deadline'));
    }

    if (reactionTime != '' && reactionTime != $('#reactiondate').val()) {
        $('#reactiondate').attr('changed', true);
        $('#reactiondate').val(reactionTime);
    }

    if ($('#servicelevelname').length) {
        var currentServicelevelname = $('#servicelevelname').text();
        if (currentServicelevelname != serviceLevelName) {
            $('#servicelevelname').text(serviceLevelName);
        }

        $('#servicelevelname').show();
        $('#servicelevelname').prev().show();
    }
}

function loadExpensesRate() {
    $.get(base + 'user.ivp/getexpensesrate/' + this.value, function (rate) { $('#expensesrate').val(rate); });
}

function submitReadOnlyForm(type) {
    switch (type) {
        case "concurrent":
            $('#coordinate').attr('disabled', true);
            $('#addcomment').attr('disabled', true);
            $('.navigate').attr('disabled', true);
            $('.changestatus').attr('disabled', true);
            $('form').attr('action', 'task.ivp/coordinate').submit();
            break;
        case "addcomment":
            $('#addcomment').attr('disabled', true);
            $('#coordinate').attr('disabled', true);
            $('.navigate').attr('disabled', true);
            $('.changestatus').attr('disabled', true);

            if ($('#comment').val() == "" && $('input[type=file]').length <= 0) {
                alert(TaskResources.NoFileOrComment);
                $('#addcomment').removeAttr('disabled');
                $('#coordinate').removeAttr('disabled');
                $('.navigate').removeAttr('disabled');
                $('.changestatus').removeAttr('disabled');
                return false;
            }
            $('form').attr('action', 'task.ivp/addcomment').submit();
            break;
    }
    return false;
}

//Изменить статус
function chooseTaskStatus() {
    var button;
    if (this.tagName == "BUTTON" && this.className == "changestatus") button = $(this);

    var taskid = button.attr('taskid');
    var statusid = button.attr('statusid');

    if ($('#choosestatus').length == 0) $('body').append('<div id="choosestatus" class="popupwrapperdown"></div>');
    $('#choosestatus').load(base + 'task.ivp/getpossiblestatuses', { taskid: taskid, statusid: statusid, timestamp: new Date().toDateString(), taskform: true }, function () {
        var offset = button.offset();
        $('#choosestatus').css('top', offset.top - $('#choosestatus').height() - 10).css('left', offset.left).show();
    });
}

function changeTaskStatus(taskid, statusid) {
    $('#choosestatus').hide();

    var ids = taskid;
    $.getJSON(base + 'task.ivp/changestatus', { taskids: ids, statusid: statusid, comment: $('#currentcomment').val(), timestamp: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else {
            if (result.Action == null) {
                document.location = base + "task.ivp/view/" + taskid;
            }
            var curl = base + "task.ivp/" + result.Action + "/";
            if (result.Action != null && result.Action != "list") {
                curl += result.StatusId + "/" + result.Id
            }
            if (result.Action != null)
                document.location = curl;
        }
    });
    return false;
}

function changeTask(id, n) {
    $('.navigate').attr('disabled', true);
    $('#addcomment').attr('disabled', true);
    $('#coordinate').attr('disabled', true);
    $('.changestatus').attr('disabled', true);
    window.location = base + 'task.ivp/taskinconcurrense/' + id + '?next=' + n;
    return false;
}

function removeExecutors(dontshowdeleted) {
    if ($('#removeexecutors').val() == "True") {
        removeAllExecutors(dontshowdeleted);
    }
}

function removeAllExecutors(dontshowdeleted) {
    $('#executors input[type="checkbox"]').each(function (i, e) { $(e).removeAttr('checked'); });
    $('#executors #executorids option').each(function (i, e) { $(e).removeAttr('selected'); });
    if (dontshowdeleted)
        $('#executors ul').empty();
    else
        $('#executors ul.many li').each(function (i, e) { if (!$(e).hasClass('empty')) $(e).addClass('archive changed'); });

    $('input#hexecutorids').remove();
}

function removeAllObservers(dontshowdeleted) {
    $('#participants input[type="checkbox"]').each(function (i, e) { $(e).removeAttr('checked'); });
    $('#participants #participantids option').each(function (i, e) { $(e).removeAttr('selected'); });
    if (dontshowdeleted)
        $('#participants ul').empty();
    else
        $('#participants ul.many li').each(function (i, e) { if (!$(e).hasClass('empty')) $(e).addClass('archive changed'); });

    $('input#hparticipantids').remove();
}

function removeAllExecutorsButNotThis(id, dontshowdeleted) {
    $('#executors input[type="checkbox"]').each(function (i, e) { $(e).removeAttr('checked'); });
    $('#executors #executorids option').each(function (i, e) { $(e).removeAttr('selected'); });
    $('#executors ul.many li').each(function (i, e) {
        if ($(e).attr("userid") == id)
            $(e).removeClass('archive');
        else {
            if (dontshowdeleted)
                $(e).remove();
            else if (!$(e).hasClass('empty')) {
                $(e).addClass('archive changed');
            }
        }
    });
    $('input#hexecutorids').remove();
}

function removeParticipants() {
    if ($('#removeparticipants').val() == "True") {
        $('#participants input[type="checkbox"]').each(function (i, e) { $(e).removeAttr('checked'); });
        $('#participants #participantids option').each(function (i, e) { $(e).removeAttr('selected'); });
        $('#participants ul.many li').each(function (i, e) { if (!$(e).hasClass('empty')) $(e).addClass('archive changed'); });
        $('input#hparticipantids').remove();
    }
}

function removeCategories() {
    if ($('#removecategories').val() == "True") {
        $('td#categories #categoryids option').each(function (i, e) { $(e).removeAttr('selected'); });
        $('td#categories ul.items li').each(function (i, e) { $(e).addClass('archive changed'); });
    }
}

function enableSystemFields() {
    //Включим дату
    $('#systemfields .readonlydate').each(function (i, e) {
        $(e).removeAttr('readOnly').removeClass('disabled').removeClass('readonlydate').addClass('datePicker').addClass('dateTime');
    });
    //Включим select
    $('#systemfields select').each(function (i, e) { $(e).removeAttr('disabled'); $(e).parent().find('input[type="hidden"]').remove(); });
    $('#systemfields #recalculate').removeClass('disabledlink').addClass('link');

}

function setFieldFocus() {
    switch ($('#focus').val()) {
        case "comment":
            $('#comment').focus();
            break;
    }

    var nameType = $("#name").attr("type");
    if (nameType != undefined && nameType == "hidden") {
        setTimeout(function () {
            $('textarea#description').focus();
        }, 0);
    }

    return false;
}

function checkDates() {
    reactionresolutionerrormessage = null;
    if (!$(this).hasClass('readonlydate')) {
        if (($(this).attr('oldvalue') == null && $(this).val() != '') || ($(this).attr('oldvalue') != $(this).val() && $(this).attr('oldvalue') != null)) {

            var changedField = this;
            if ($(this).val() == '' || $(this).val() == null) {
                $.getJSON(base + 'task.ivp/getstatusinjson', { statusid: $('#statusid').val() }, function (result) {
                    if ($(changedField).attr('id') == 'reactiondatefact' && result.IsInitial == false) {
                        alert(TaskResources.FactReactionDateWarning);
                        if ($(changedField).attr('oldvalue') == null)
                            $(changedField).val('');
                        else
                            $(changedField).val($(changedField).attr('oldvalue'));
                        return;
                    }
                    else if ($(changedField).attr('id') == 'resolutiondatefact' && result.IsFixed == true) {
                        alert(TaskResources.FactResolutionWarning);
                        if ($(changedField).attr('oldvalue') == null)
                            $(changedField).val('');
                        else
                            $(changedField).val($(changedField).attr('oldvalue'));
                        return;
                    }
                    else {
                        changeDates(changedField);
                    }
                });
            }
            else
                changeDates(changedField);
        }
    }
    return false;
}

function changeDates(changedField) {
    var deadline = $('#deadline').val();
    if ($(changedField).attr('id') == 'deadlinesystem')
        deadline = $(changedField).val();



    $.getJSON(base + 'task.ivp/checkreactionresolutiondates', { reactionplan: $('#reactiondate').val(), reactionfact: $('#reactiondatefact').val(), deadline: deadline, deadlinefact: $('#resolutiondatefact').val(), changed: $(changedField).attr('id'), taskid: $('#id').val(), serviceid: $('#serviceid').val() }, function (result) {
        reactionresolutionerrormessage = null;
        if (result != null) {
            if (result.hasOwnProperty('IsOK') && !result.IsOK) {
                //костыль #30140: при открытом календаре проверку не выполняем, также не выполняем проверку если мы выбрали дату из календаря и у нас отрабатывает метод, получающий время конца дня
                if ($('.calendar.calpopup').is(":visible") || isdatepicker) {
                    return;
                }
                reactionresolutionerrormessage = result.Description;
                alert(result.Description);
                if ($(changedField).attr('id') == 'deadlinesystem')
                    $('#deadline').val($(changedField).val());
                if ($(changedField).attr('id') == 'deadline')
                    $('#deadlinesystem').val($(changedField).val());
            }
            else {
                $(changedField).attr('oldvalue', $(changedField).val());
                $(changedField).attr('changed', true);
                if ($(changedField).attr('id') == 'deadlinesystem') {
                    $('#deadline').attr('changed', true);
                    $('#deadline').attr('oldvalue', $(changedField).val());
                }
                if ($(changedField).attr('id') == 'deadline')
                    $('#deadlinesystem').attr('oldvalue', $(changedField).val());

                if (result.ReactionChanged == true) {
                    if (result.ReactionOverdue == null) $('#reactionoverduetext').hide();
                    if (result.ReactionOverdue == false) $('#reactionoverduetext').removeClass('notoverdue overdue').addClass('notoverdue').show();
                    if (result.ReactionOverdue == true) $('#reactionoverduetext').removeClass('notoverdue overdue').addClass('overdue').show();
                    $('#reactionoverduetext').empty().append(result.ReactionText);
                    $('#reactionplanspan').empty().append(result.PlanReactionTime);
                    $('#reactionfactspan').empty().append(result.FactReactionTime);
                }

                if (result.ResolutionChanged == true) {
                    if (result.ResolutionOverdue == null) $('#resolutionoverduetext').hide();
                    if (result.ResolutionOverdue == false) $('#resolutionoverduetext').removeClass('notoverdue overdue').addClass('notoverdue').show();
                    if (result.ResolutionOverdue == true) $('#resolutionoverduetext').removeClass('notoverdue overdue').addClass('overdue').show();
                    $('#resolutionoverduetext').empty().append(result.ResolutionText);
                    $('#resolutionplanspan').empty().append(result.PlanResolutionTime);
                    $('#resolutionfactspan').empty().append(result.FactResolutionTime);
                }
            }
        }
    });
}


function recalculateDates(event, control) {
    event.preventDefault();
    if (!$(control).hasClass('disabledlink')) {
        $.getJSON(base + 'task.ivp/recalculatereactionresolution', { recalculatedate: $('#recalculatedate').val(), taskid: $('#id').val(), reactionfact: $('#reactiondatefact').val(), deadlinefact: $('#resolutiondatefact').val() }, function (result) {
            if (result.hasOwnProperty('IsOK') && !result.IsOK) {
                alert(result.Description);
            }
            else {
                $('#created').val($('#recalculatedate').val());

                if (result.ReactionOverdue == null) $('#reactionoverduetext').hide();
                if (result.ReactionOverdue == false) $('#reactionoverduetext').removeClass('notoverdue overdue').addClass('notoverdue').show();
                if (result.ReactionOverdue == true) $('#reactionoverduetext').removeClass('notoverdue overdue').addClass('overdue').show();
                $('#reactionoverduetext').empty().append(result.ReactionText);
                $('#reactionplanspan').empty().append(result.PlanReactionTime);
                $('#reactionfactspan').empty().append(result.FactReactionTime);
                $('#reactiondate').val(result.ReactionDate);
                $('#reactiondate').attr('changed', true);

                if (result.ResolutionOverdue == null) $('#resolutionoverduetext').hide();
                if (result.ResolutionOverdue == false) $('#resolutionoverduetext').removeClass('notoverdue overdue').addClass('notoverdue').show();
                if (result.ResolutionOverdue == true) $('#resolutionoverduetext').removeClass('notoverdue overdue').addClass('overdue').show();
                $('#resolutionoverduetext').empty().append(result.ResolutionText);
                $('#resolutionplanspan').empty().append(result.PlanResolutionTime);
                $('#resolutionfactspan').empty().append(result.FactResolutionTime);
                $('#deadline').val(result.Deadline);
                $('#deadline').attr('changed', true);
                $('#deadlinesystem').val(result.Deadline);

                $('#reactionAndResolutionChanged').val(true);
            }
        });
    }
    return false;
}

function serializeChanges() {
    var serialize = $('#taskchangedfields').val();
    if (serialize == null) return false;
    $('[changed=true]').each(function (i, e) {
        if (serialize.length > 0)
            serialize += ',';
        serialize += $(e).attr('name');
    });
    $('#taskchangedfields').val(serialize);
    return false;
}

// formReadOnly + coordinators
// получаем данные по согласующим
function getTableOfCoordinators(taskId) {
    $.getJSON(base + 'task.ivp/gettableofcoordinators', { taskId: taskId }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            alert(result.Description);
        }
        else {
            var str = "";
            for (var i = 0; i < result.length; i++) {
                str += '<tr><td>' + result[i].Key + '</td><td>' + result[i].Value + '</td></tr>'
                //alert(result[i].Key+" "+result[i].Value);
            }
            //удаляем старые данные и заполняем таблицу новыми.
            $('table.data td').remove();
            $('table.data tr.top').after(str);
        }
    });
}
function removeCoordinators(link, userId, taskId) {
    $(link).remove();
    $.getJSON(base + 'task.ivp/removecoordinator', { taskid: taskId, userid: userId }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            alert(result.Description);
        }
        else { getTableOfCoordinators(taskId); getListOfCoordinators(taskId); }
    });
    return false;
}

function loadNotifications() {
    $('#notificationholder').html("");
    $('#notificationholder').load(base + 'task.ivp/LoadNotifications', { taskid: $('#id').val() });
    return false;
}

function showActionPopup() {
    $('#actionholder').toggle();
    return false;
}

function selectPerson() {
    var serviceid = $('#serviceid').val();
    var url = 'user.ivp/select?cbmode=person&tb_mode=serviceusers&tb_serviceid=' + serviceid;
    dlg = window.openDialog(url, 'selectpersons', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function removeExecutorsStroke() {
    if (!$('#egroupholder').hasClass('removed')) {
        $('#executorgroupid').attr('changed', true);
        $('#egroupholder').addClass('removed changed');
        $('#executorgroupid').attr('changed', true).val('');
    }
    else {
        $('#egroupholder').removeClass('removed changed');
        $('#executorgroupid').attr('changed', true).val($('#egroupholder').attr('group-id'));
    }
    return false;
}

function removeExecutorGroup(notext) {
    $('#executorgroupid').attr('changed', true).val('');
    $('#egroupholder').empty();
    if (notext == false) {
        var $nogroup = $('<div/>').addClass('details').attr('id', 'noexecutorgroup').text(TaskResources.ExecutorGroupNotAssigned);
        $('#egroupholder').append($nogroup);
    }
    return false;
}

function selectExecutorGroups() {
    var serviceid = $('#serviceid').val();
    dlg = openDialog('executorgroup/select?tb_mode=SERVICEGROUPS&tb_serviceid=' + serviceid);
    dlg.callback = executorGroupsCallback;
    return false;
}

function executorGroupsCallback(result) {
    var ids = result["selectedIds"];
    var names = result["selectedNames"];
    executorGroupsSelected(ids, names);
}

function executorGroupsSelected(ids, names) {
    var id = ids[0];
    var gn = names['id' + id];
    _executorGroupsSelected(id, gn);
}

function _executorGroupsSelected(id, name, canRemove) {
    removeExecutorGroup(true);
    $('#executorgroupid').val(id).attr('changed', true);
    var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', 'executorgroup/view/' + id).click(function () { return executorGroupDetails(id); });
    var $ar = $('<a href="#"/>').click(function () { return removeExecutorGroup(false); });
    $ar.append($('<img/>').attr('src', 'img/trash.gif').attr('title', CommonResources.Remove));
    $('#egroupholder').append(TaskResources.Group + ': ').append($ag);

    if (canRemove) {
        $('#egroupholder').append($ar);
    }

    if (canRemove === undefined)
        $('#egroupholder').append($ar);


    $('#egroupholder').removeClass("removed");
}

function executorGroupDetails(id) {
    openDialog('executorgroup/view/' + id + '?popup=true', 'executorgroup' + id);
    return false;
}

function groupAdded(e, d) {
    var name = d[0];
    var id = d[1];
    $(e.target).val('');
    _executorGroupsSelected(id, name);
}

function submitByButton(statusid) {

    $('#returnaftersave').val('true');
    changeaddress($('#taskform'), 'action', 'statusid', statusid);

    //Помечаем аттрибутом disabled, что бы поле не сабмитилось.
    $('#statusid').attr('disabled', 'disabled');

    GetUpdateTaskOnStatusChange(statusid, function () {
        $('#statusid').removeClass('required');
        $('#statusid option:selected').each(function () {
            this.selected = false;
        });

        if (!$.browser.msie)
            $("#taskform").submit();
    }, false);
}




function changeServiceAjax(isnewtask) {
    //if (isnewtask && !confirm(TaskResources.ChangeServiceForNewTaskWorning)) return false;
    $("body").append('<div id="bodyoverlay"></div><div id="changeservicedialog" style="width:100%; height:90%;z-index:9999; position:absolute; top:120px; left:20px"></div>');
    var oldtypeid = $("#typeid").val();
    var oldserviceid = $("#serviceid").val();
    $("#changeservicedialog").load(base + 'task.ivp/selectservice?nolayout=true',
        { serviceid: null, taskid: $("#id").val(), oldserviceid: $("#serviceid").val(), oldtypeid: $("#typeid").val() },
        function () {
            $("#servicecontainer").height($("#changeservicedialog").height() - 100);
            $("a#back").remove();
            $("#changeservicedialog form").prepend('<a style="float:right;" class="noul" id="back" href="#" onclick="return false;"><img src="img/close.gif"/></a>');
            $('#serviceholder ul').first().css('z-index', 30).show();
            $('#changeservicedialog li[data-service-id=' + oldserviceid + '][data-type-id=' + oldtypeid + ']').remove();

            $('a#back').attr("href", "#").click(function () {
                $("#changeservicedialog").remove();
                $("#bodyoverlay").remove();
                return false;
            });
            $('#btnback').click(_backOneLevel);
            $('#serviceholder li').click(_selectServiceAjax);

            _columnWidth = $("#serviceholder ul").first().width() + 1;
            $(window).resize(_resizeContainer);
            _resizeContainer();

            _restorePosition();
        });

    return false;
}

function _restorePosition() {
    if ($('#serviceid').val()) {
        var $li = $('li.service[data-service-id="' + $('#serviceid').val() + '"]');
        $($li.parents('li').get().reverse()).trigger('click');
        if (!$li.hasClass('endpoint'))
            $li.trigger('click');
    }
}

function _selectServiceAjax(event) {
    var $li = $(this);
    var $ul = $li.find('ul:first');

    event.stopPropagation();
    $li.siblings().removeClass('selected').find('h3').removeClass('selected');
    $li.children().removeClass('selected').find('h3').removeClass('selected');

    $('ul:visible', $li.siblings()).hide();
    $('ul:visible', $li.children()).hide();
    $li.addClass('selected').find('h3:first').addClass('selected');


    //Если мы на последнем уровне - отпавляем запрос на создание заявки
    if (!$li.find('ul').size()) {

        $('#serviceid').val($li.attr('data-service-id'));
        $('#typeid').val($li.attr('data-type-id'));
        if ($('#typeid').val() != '' && $('#tariff').val() != 'SaaSPlus' && $('#tariff').val() != 'Enterprise') {
            alert(TaskResources.DisabledInThisTariff);
            return;
        }

        if ((!$('#taskid').val() || $('#taskid').val() == '0') && $('#oldtypeid').val() != '1001' && $('#oldserviceid').val() != 0 && $li.attr('data-type-id') == '1001') {
            alert(TaskResources.NoChangeToMeetingRoom);
            $('#typeid').val('');
            return;
        }

        var $taskForm = $("#taskform");
        $taskForm.find("#serviceid").val($li.data("service-id"));
        $taskForm.find("#typeid").val($li.data("type-id"));

        var form = $li.closest("form");
        var action = form.attr("action");

        $taskForm.attr("action", action);
        $taskForm.unbind('submit').submit();
        //getWorkflowAndSLA(action, "Service");

        return;
    }

    _currentLevel = $li.parents('ul').length + 1;
    _currentLI = $li;
    $('#btnback').attr('disabled', _currentLevel <= _columns);
    if ((_currentLevel <= _columns) == true) $('#btnback').hide();
    else $('#btnback').show();

    var scrolled = _scrollContainer();

    _setRolloutUlPosition($ul, $li);
    _setHeight();

    if (!scrolled)
        $ul.animate({ 'left': _columnWidth }, 'fast');
    else
        $ul.css('left', _columnWidth);
}

function _scrollContainer() {
    if (_currentLevel > _columns) {
        var offset = (_columns - _currentLevel) * _columnWidth;
        $('#serviceholder').animate({ left: offset }, 'fast');
        return true;
    }
    else if (_currentLevel == _columns) {
        $('#serviceholder').animate({ left: 0 }, 'fast');
    }
    return false;
}

function _resizeContainer() {
    _columns = Math.round(($('#servicecontainer').width() - 70) / _columnWidth);
    _scrollContainer();
}

function _setRolloutUlPosition($ul, $li) {
    $ul.css('left', 0);
    var windowHeight = $(window).height();
    var liTop = $li.offset().top - $(window).scrollTop();
    var windowScrollTop = $(window).scrollTop();
    var freeTop = $li.offset().top - windowScrollTop - (windowScrollTop < $('#serviceholder').offset().top ? $('#serviceholder').offset().top - windowScrollTop : 0);
    var freeBottom = $(window).height() - freeTop;

    if ($ul.height() <= freeBottom) {
        $ul.css('top', $li.position().top).show();
    }
    else if ($ul.height() <= freeTop) {
        $ul.css('top', $li.position().top + $li.height() - $ul.height() + 2).show();
    }
    else {
        $ul.css('top', windowScrollTop).show();
    }
}

function _setHeight() {
    var height = 0;
    $('#serviceholder ul:visible').each(function (i, el) { var $el = $(el); if ($el.height() + $el.position().top > height) height = $el.position().top + $el.height(); });
    $('#serviceholder').height(height);
}

function _backOneLevel() {
    var $parent = _currentLI.parents('li:first');
    if ($parent.length > 0) {
        $parent.trigger('click');
    }
    else {
        _currentLevel = 1;
        $('#serviceholder ul:first li h3').removeClass('selected');
        $('#serviceholder ul:first li ul').hide();
        _scrollContainer();
    }
}

function formAfterSubmit(form) {
    if (customValidate())
        form.submit();
}

function checkForm() {
    if (formchanged == true && !confirm(FormResources.LeaveChangedForm)) return false;
    return true;
}

//show description

function showDescription(el) {

    var id = el.id;


    ssid = setTimeout(function () { _showDescription1(id) }, 400);
    clearTimeout(hhid);
}

function hideDescription() {
    clearTimeout(ssid);
    hhid = setTimeout(function () { $('.taskdescription').hide(); }, 400);

    //   $('.taskdescription').hide();


}
function _showDescription1(tid) {
    var id = getId(tid);
    if ($('#taskname_' + id).length == 0) return;

    var tdkey = '#taskdescription_' + id;
    $('.taskdescription').hide();

    var offset = $('#taskname_' + id).offset();
    var h = $('#taskname_' + id).height();
    var w = $(window).width() - 300;
    if (w < 400) w = 400;
    if (w > 900) w = 900;

    if ($(tdkey).length > 0) {
        $(tdkey).css('top', offset.top + h + 5).css('left', offset.left + 50).css('width', w);
        $(tdkey).fadeIn('fast');
    }
    else {
        $('body').append('<div id="taskdescription_' + id + '" class="taskdescription popupwrapper"><div class="popup"></div></div>');
        $(tdkey).css('top', offset.top + h + 5).css('left', offset.left + 40).css('width', w);
        $(tdkey).mouseover(function () { clearTimeout(hhid); }).mouseout(function () { hhid = setTimeout('hideTaskDescription()', 500); });
        $('.popup', $(tdkey)).load(base + 'task.ivp/taskdetails/' + id, { withoutmark: true, date: new Date().toString() }, function () { if (!showtd) return; $('.popup', $(tdkey)).bgiframe(); $(tdkey).show(); $('#taskname_' + id).parents('tr:first').removeClass('newtask').find('.imgnc').hide(); $(tdkey).highlight($('#parentnumber').val()); });

    }


}

function multipleComboSelection() {
    var fid = parseInt($(this).attr('data-fieldid'));
    var currentLevel = parseInt($(this).attr('data-level'));

    var sel = $(this).find('option:selected').val();
    if (sel == '' && $(this).attr('data-level') != 0)
        sel = $('[data-fieldid="' + fid + '"][data-level="' + (currentLevel - 1) + '"] option:selected').val();
    $('#field' + fid).val(sel);

    var selectedId = parseInt($(this).find('option:selected').val());
    $('.typecombo').filter(function () { return $(this).attr('data-level') > currentLevel && $(this).attr('data-fieldid') == fid && $(this).attr('data-parentId') != selectedId; }).remove();
    if ($(this).find('option:selected').attr('data-islast') != undefined && $(this).find('option:selected').attr('data-islast') == 'true') {
        return false;
    }
    if ($(this).val() == '') return false;
    var classes = $('[data-level=0][data-fieldid="' + fid + '"]').attr('class');
    var $select = $('<select/>').attr('class', classes.replace('error', '').replace('required', '')).attr('data-level', currentLevel + 1).attr('data-fieldid', fid).attr('data-parentId', selectedId).attr('id', $(this).attr('id')).attr('name', $(this).attr('name'));
    $select.append($('<option/>').val('').text(''));
    $.getJSON(base + 'tasktypefield.ivp/getchildcombo', { fieldId: fid, parentId: selectedId }, function (result) {
        $(result).each(function () {
            var $option = $('<option/>').val(this.Id).text(this.Name);
            if (this.IsLast)
                $option.attr('data-islast', true);
            if ($.trim($option.html()).length == 0)
                return false;
            $select.append($option);
        });
        if ($.trim($select.html()).length > 0)
            $('#mfield' + fid).closest('#typecomboholder').append($select);
    });
}

function multipleComboSelection() {
    var fid = parseInt($(this).attr('data-fieldid'));
    var currentLevel = parseInt($(this).attr('data-level'));

    var sel = $(this).find('option:selected').val();
    if (sel == '' && $(this).attr('data-level') != 0)
        sel = $('[data-fieldid="' + fid + '"][data-level="' + (currentLevel - 1) + '"] option:selected').val();
    $('#field' + fid).val(sel);

    var selectedId = parseInt($(this).find('option:selected').val());
    $('.typecombo').filter(function () { return $(this).attr('data-level') > currentLevel && $(this).attr('data-fieldid') == fid && $(this).attr('data-parentId') != selectedId; }).remove();
    if ($(this).find('option:selected').attr('data-islast') != undefined && $(this).find('option:selected').attr('data-islast') == 'true') {
        return false;
    }
    if ($(this).val() == '') return false;
    var classes = $('[data-level=0][data-fieldid="' + fid + '"]').attr('class');
    var $select = $('<select/>').attr('class', classes.replace('error', '').replace('required', '')).attr('data-level', currentLevel + 1).attr('data-fieldid', fid).attr('data-parentId', selectedId).attr('id', $(this).attr('id')).attr('name', $(this).attr('name'));
    $select.append($('<option/>').val('').text(''));
    $.getJSON(base + 'tasktypefield.ivp/getchildcombo', { fieldId: fid, parentId: selectedId }, function (result) {
        $(result).each(function () {
            var $option = $('<option/>').val(this.Id).text(this.Name);
            if (this.IsLast)
                $option.attr('data-islast', true);
            if ($.trim($option.html()).length == 0)
                return false;
            $select.append($option);
        });
        if ($.trim($select.html()).length > 0)
            $('#mfield' + fid).closest('#typecomboholder').append($select);
    });
}

function checkParamsIfChangedWorkflow() {
    if (window.location.href != null) {
        var hr = window.location.href;
        if (hr.indexOf("changedworkflow=true") != -1) {
            $("#categoryids option").each(function (i, e) { $(e).attr("selected", "true"); });
            $("#assetids option").each(function (i, e) { $(e).attr("selected", "true"); });
        }
    }
}
//прикрепляем скриншот
function pasteScreenshot() {
    $.ajax({
        url: base + 'task.ivp/selectscreenshot/' + $('#id').val(),
        //async: false,
        success: function (data, textStatus, jqXHR) {
            var dialog = $('<div id="screenshotdialog"></div>').dialog({
                autoOpen: false,
                open: function () {
                    setParametersForScreenFrom();
                },
                width: 'auto',
                maxWidth: screen.width - 25,
                modal: true,
                position: { my: "center" },
                resizable: false,
                close: function () {
                    window.removeEventListener("paste", pasteHandler);
                    $(this).dialog("destroy");
                    $('#drawingMenu').addClass('hidden');
                    $(this).remove();
                }
            });
            $(".ui-dialog .ui-dialog-title").html(FormatString(ScreenshotResources.PasteScreenshot));
            dialog.append(data);
            dialog.dialog('open');
        }
    });

    return false;
}
function calculateExpensesMinutes(source) {
    var sourceid = $(source).attr('id');
    var hours, minutes, result;
    if (sourceid.indexOf('_') > 0) {
        hours = parseInt($('#exphours_' + getId(sourceid)).val(), 10);
        minutes = parseInt($('#expminutes_' + getId(sourceid)).val(), 10);
        result = $('#exptotalminutes_' + getId(sourceid));
    } else {
        hours = parseInt($('#exphours').val(), 10);
        minutes = parseInt($('#expminutes').val(), 10);
        result = $('#exptotalminutes');
    }
    result.val(hours * 60 + minutes);
}

//#region кастомная валидация трудозатрат. (одна валидация для двух полей). Костыль((
function validateexpensesadditional(source) {
    var $validateinput, $inputhh, $inputmm;
    var $source = $(source);
    var sourceid = $source.attr('id');
    if (sourceid.indexOf('_') > 0) {
        $validateinput = $('#expvalid_' + getId(sourceid));
        $inputhh = $('#exphours_' + getId(sourceid));
        $inputmm = $('#expminutes_' + getId(sourceid));
    } else {
        $validateinput = $('#expvalid');
        $inputhh = $('#exphours');
        $inputmm = $('#expminutes');
    }
    return customvalidateinput($validateinput, $inputhh.attr("customclasses").split(' '), $inputhh.val())
        && customvalidateinput($validateinput, $inputmm.attr("customclasses").split(' '), $inputmm.val());
}

function customvalidateinput(validateinput, classes, value) {
    validateinput.removeClass();
    $.each(classes, function (classindex, classname) {
        validateinput.addClass(classname);
    });
    validateinput.val(value);
    return validateinput.valid();
}
//#endregion