var tid = null;
var utid = null;
var utype = null;
var dlg = null;
var deadlinechanged = false;
var timeid = null;
var taskname = "";
var autocomplete = false;
var hhid = null;
var ssid = null;
var reactionresolutionerrormessage = null;
var showImageTimeout = 0;
var redirectWithoutFormChange = false;
var positionStart = 0;
var positionEnd = 0;

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

var selectedCategories = null;
var selectedAssets = null;

var fixRequiredTaskFields = new Array();
var fixRequiredMainFields = new Array();

var autoDeadline = $('#deadline').val();

var oldBrowser = typeof (window.FileReader) == 'undefined';
var ctrlDown = false;

var commentEditTimeout = $('#CommentEditTimeout').val();

var taskLastChanged = $('#changed').val();

$(document).ready(function () {
    $('#tabs a')
        .removeClass('disabled')
        .click(function (e) {
            setTab($(this).data('target'));
        });
});

window.onbeforeunload = function () {
    setTimeout(function () {
        setTimeout(function () {
            hideLoader();
        }, 1);
    }, 1);
    if (!redirectWithoutFormChange) {
        if (formchanged) {
            return FormResources.FormChangedPartialMessage;
        }
    } else {
        redirectWithoutFormChange = false;
    }
};

//получить ОР блок по имени
//пример 
// getDefferedBlockByName('name')
//  .done(function (block) { /* блок найден */ })
//  .fail(function(){ /* блок не найден */ });
function getDefferedBlockByName(blockName) {
    var def = new $.Deferred();
    if (!GLOBAL_taskFormHubObserver) {
        def.reject();
    }
    else{
        var block = GLOBAL_taskFormHubObserver.getBlocks()[blockName];
        if (block) {
            def.resolve(block);
        }
        else {
            def.reject();
        }
    }
    return def.promise();
}

//основные поля, обязательность для перехода статуса
//у полей, у которых слоожная обработка обязательности (категории, активы), валидация работает не по required
function getMainFieldName(fieldid) {
    switch (fieldid) {
        case '2':
            // название поля, класс для обязательности
            return ["description", "required"];
        case '5':
            return ["deadline", "required"];
        case '6':
            return ["addcategory", "categoriesfield"];
        case '8':
            return ["addasset", "assetsfield"];
        case '18':
            return ["servicestageid", "required"];
    }
}

function checkChangedFields() {
    var changedFields = $("[changed='true']").not($("#changed")).not($("#privatecomment"));
    return changedFields.length > 0;
}

function SaveForm(returnAfter) {
    $('#returnaftersave').val(returnAfter);
    window.onbeforeunload = null;
}

function SaveInCoordination() {
    $('#isCoordinated').val('true');
   // $('#btncoordinate').attr('disabled', true);
    window.onbeforeunload = null;
    //$('form').submit();
}

$(function () {

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

    var commentTimer = setInterval(function () {
        commentEditTimeout--;
        if (commentEditTimeout <= 0) {
            clearInterval(commentTimer);
            $("#editCommentButton").remove();
        }
    }, 1000);

    if (oldBrowser) {
        $("#dropzone").hide();
        $("#taskform").on('submit', function () {
            document.cookie = "oldBrowser=1;path=/";
        });
        //$("#taskform").on('beforesubmit', function () {
        //    $('#taskform').append('<input class="hidden" id="oldBrowser" name="oldBrowser" value="1">');
        //});
    } else {
        $("#buttonAddFile").remove();

        var taskId = $('#id').val();
        var serviceId = $('#serviceid').val();
        var typeId = $('#typeid').val();
        var statusId = $('#oldstatus').val() > 0 ? $('#oldstatus').val() : $('#currentStatusId').val();

        $('#dropzone').load("Task/GetFileDropZone", { taskId: taskId, serviceId: serviceId, typeId: typeId, statusId: statusId }, configDropZone);
    }
    //Костыль для 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();
    //assignUsersCategoryData();
    getDefferedBlockByName("executorgroupid").then(function (block) { block.UpdateGroupCallBack = UpdateGroupCallBack });
    if ($('#create').length > 0) { $('#name').focus(); loadPriorityDescription(); }
    else $('#priorityidselector').attr('title', $('#prioritydescription').val());
    setFieldFocus();
    //если клик по полю Файл, то пишем флаг чтобы не отработалособытие "Вы ушли со страницы"
    $('a.saveFile').click(function () {
        redirectWithoutFormChange = true;
    });
    checkParamsIfChangedWorkflow();

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

    $('body').on('click', '.js-href-button', function () {
        var $self = $(this);
        var href = $self.attr('data-href');
        if (href)
            window.location = href;
        return false;
    });


    $('body').on('click', '.js-changeStatus-by-button', function (event) {
        event.preventDefault();
        var $self = $(this);
        var $taskForm = $("#taskform");
        var $currentcomment = $('#currentcomment, label[for="CurrentComment"]');

        var statusId = $self.attr('data-statusid');

        var isConcurence = $self.attr('data-isconcurrence') === 'True';

        var isExternal = $self.attr('data-external') === 'True';
        var commentRequired = $self.attr('data-commentrequired') === 'True';

        if (commentRequired) {
            $currentcomment.addClass('required');
        } else {
            $currentcomment.removeClass('required');
        }
        if ($('#statusesRequiredField option[value="' + statusId + '"]').size() > 0) {
            fixRequiredTaskFields = [];
            var arrayOfFields = $('#statusesRequiredField option[value="' + statusId + '"]').text().split(',');
            $.each(arrayOfFields, function (i, elem) {
                var field = $('#field' + elem);
                if (field && !field.attr('disabled') && !field.hasClass('readonly') && !field.hasClass('hidden') && !field.hasClass('required')) {
                    field.addClass('required');
                    $('label[for="field' + elem + '"]').addClass('required');
                    fixRequiredTaskFields[fixRequiredTaskFields.length] = elem;
                }
            });
        }
        else if (fixRequiredTaskFields.length > 0) {
            $.each(fixRequiredTaskFields, function (i, elem) {
                $('#field' + elem).removeClass('required');
                $('label[for="field' + elem + '"]').removeClass('required');
            });
            fixRequiredTaskFields = [];
        }
        if ($('#statusesRequiredMainField option[value="' + statusId + '"]').size() > 0) {
            fixRequiredMainFields = [];
            var arrayOfMainFields = $('#statusesRequiredMainField option[value="' + statusId + '"]').text().split(',');
            $.each(arrayOfMainFields, function (i, elem) {
                var fieldname = getMainFieldName(elem);
                var field = $('#' + fieldname[0]);
                if (field && !field.attr('disabled') && !field.hasClass('readonly') && !field.hasClass('hidden') && !field.hasClass(fieldname[1])) {
                    field.addClass(fieldname[1]);
                    var label = (fieldname[1] == "required") ? $('label[for="' + fieldname[0] + '"]') : $('label.' + fieldname[0]);
                    label.addClass('required');
                    fixRequiredMainFields[fixRequiredMainFields.length] = elem;
                }
            });
        }
        else if (fixRequiredMainFields.length > 0) {
            $.each(fixRequiredMainFields, function (i, elem) {
                var fieldname = getMainFieldName(elem);
                $('#' + fieldname[0]).removeClass(fieldname[1]);
                var label = (fieldname[1] == "required") ? $('label[for="' + fieldname[0] + '"]') : $('label.' + fieldname[0]);
                label.removeClass('required');
            });
            fixRequiredMainFields = [];
        }

        changeStatusToConcurenceValidator = function () { return true; };
        changeStatusToExternalValidator = function () { return true; };

        if (customValidate()) {
            $('#returnaftersave').val('true');

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

            if ($taskForm.find('input#statusid').size() == 0) {
                $taskForm.append('<input type="hidden" value="' + statusId + '" name="statusid" id="statusid"/>');
            } else {
                $('input#statusid').val(statusId);
            }

            changeStatusToConcurenceValidator = function () {
                if ($('#oldstatus').val() !== statusId) {

                    if (isConcurence) {
                        var $coordinators = $('select.js-coordinators');

                        if ($coordinators.length) {
                            {
                                if (taskConcurrency.validate()) {
                                    return true;
                                } else {
                                    $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                                    return false;
                                }
                            }
                        } else {
                            if (!$('#assignCoordinationDialog').length) {
                                $('body').trigger('showCoordinationDialog');
                            }
                            $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                            return false;
                        }
                    }
                }
                return true;
            };

            changeStatusToExternalValidator = function () {
                if ($('#oldstatus').val() !== statusId) {

                    if (isExternal) {
                        var $emails = $('input[name="ExternalContractors.Emails"]');
                        var emails = $emails.val();

                        if (emails) {
                            if (taskExternalContractorsDialog.validate()) {
                                return true;
                            } else {
                                $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                                return false;
                            }
                        } else {
                            if (!$('#external-contractors-dialog').length) {
                                $('body').trigger('showExternalContractorsDialog');
                            }
                            $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                            return false;
                        }
                    }
                }
                return true;
            };

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

    $('body').on('closeExternalContractorsDialog', function () { changeStatusToExternalValidator = function () { return true; }; });

    $('span.titleHint').tooltip({ position: { my: "right top+15", at: "right center" } });

    $('#privatecomment').on('change', function () {
        if ($(this).prop('checked') == true) {
            $('.commentsHiddenFrom').show();
        } else {
            $('.commentsHiddenFrom').hide();
        }
    });
    if ($('#onecategoryonticket').val() == "True") {
        var options = $('#categoryids option');
        if (options.length > 1) {
            var id = options.first().val()
            var name = options.first().text();
            options.first().remove();
            categorySelected(id, name);
        }
    }
    if ($.browser.mozilla) {
        $('form').attr('autocomplete', "off");
    }
});

var changeStatusToConcurenceValidator = function () {
    var $status = $('#statusid');
    var $changeForced = $('#isChangeStatusForced');
    if ($('#oldstatus').val() !== $status.val() && $changeForced.val() != 'true') {
        var $option = $status.find('option:selected');
        if ($option.attr('data-isconcurrence') === 'True') {
            var $coordinators = $('select.js-coordinators');

            if ($coordinators.length) {
                {
                    if (taskConcurrency.validate()) {
                        return true;
                    } else {
                        $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                        return false;
                    }
                }
            } else {
                if (!$('#assignCoordinationDialog').length) {
                    $('body').trigger('showCoordinationDialog');
                }
                $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                return false;
            }
        }
    }
    return true;
};

var changeStatusToExternalValidator = function () {
    var $status = $('#statusid');
    if ($('#oldstatus').val() !== $status.val()) {
        var $option = $status.find('option:selected');
        if ($option.attr('data-external') === 'True') {
            var $emails = $('input[name="ExternalContractors.Emails"]');
            var emails = $emails.val();

            if (emails) {
                if (taskExternalContractorsDialog.validate()) {
                    return true;
                } else {
                    $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                    return false;
                }
            } else {
                if (!$('#external-contractors-dialog').length) {
                    $('body').trigger('showExternalContractorsDialog');
                }
                $('.save,.saveandreturn,.save-ext').attr('disabled', false);
                return false;
            }
        }
    }

    return true;
};

//function addUserOnServiceAndTask(suggestion, withRole) {
//    params = new Array();
//    params[params.length] = { name: 'serviceid', value: $('#serviceid').val() };
//    params[params.length] = { name: 'uids', value: suggestion.data.id };
//    if (withRole)
//        params[params.length] = { name: 'rids', value: $('#addUserWithRole').val() };
//    $.ajax({
//        url: base + 'serviceuser.ivp/AddUsers',
//        data: params,
//        type: 'POST',
//        success: function (response) {
//            if (response != null) {
//                var result = $.parseJSON(response)
//                if (result != null && result.IsOK != null) {
//                    if (result.IsOK) {
//                        //addExecutor($('#addexecutor'), suggestion);
//                        GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].addExecutor(suggestion);
//                        $('#addexecutor').autocomplete('clearCache');
//                    }
//                    else if (result.Description != null) {
//                        alertDialog(CommonResources.Error, result.Description);
//                    }
//                    else {
//                        return false;
//                    }
//                }
//            }
//        },
//        error: function (XMLHttpRequest, textStatus, errorThrown) {
//            alertDialog(CommonResources.Error, TaskResources.CantAddExecutor);
//        }
//    });
//}

function initAutocompleteRightMenu() {
    var serviceId = $('#serviceid').val();

    $('#choosecreator').devbridgeAutocomplete({
        serviceUrl: 'Task/FindCreators/' + serviceId,
        minChars: 1,
        autoClearInputOnSelect: true,
        onSelect: addCreator
    });
  
    //$('#addexecutor').devbridgeAutocomplete({
    //    serviceUrl: 'Task/FindExecutors/' + serviceId,
    //    autoQueryOnEmptyField: true,       
    //    minChars: 1,
    //    rightOrientation: true,
    //    containerClass: 'autocomplete-suggestions executorsearchContainer',
    //    width: '400',
    //    maxWidth:'400',
    //    widthImportant: true,
    //    params: {
    //        deadline: function () { return $('#deadline').val(); },
    //        executorgroupid: function () { return ($('#executorsfromexecutorgroup') && $('#executorsfromexecutorgroup').val() == 'True' && $('#executorgroupid')) ? $('#executorgroupid').val() : '' }
    //    },
    //    autoClearInputOnSelect: true,
    //    onSelect: addUser,
    //    formatDivClassResult: function (suggestion) {
    //        var classCss = 'executorSearch';
    //        if(suggestion.data.firstAdded) 
    //            classCss += ' topBorder';
    //        return classCss;
    //    },
    //    onSelect: function (suggestion) {
    //        if (suggestion.data.isAddToService) {                
    //            setTimeout(function () {
    //                if (suggestion.data.roleInService) {                        
    //                    alertDialog(TaskResources.UserNotOnService, TaskResources.AddUserOnService.replace('{0}', suggestion.data.systemRoleName), function () {
    //                        addUserOnServiceAndTask(suggestion);
    //                    });
    //                }
    //                else {
    //                    $.ajax({
    //                        url: base + 'task/GetServiceRoles',
    //                        data: { serviceid: $('#serviceid').val() },
    //                        type: 'POST',
    //                        success: function (response) {
    //                            if (response != null && response.roles != null && response.roles.length > 0) {
    //                                var roles = '<select id="addUserWithRole" class="px200">'
    //                                for (var i = 0; i < response.roles.length; i++) {
    //                                    var selected = i == 0 ? ' selected="true"' : '';
    //                                    roles += '<option value="' + response.roles[i].Id + '"' + selected + '>' + response.roles[i].Name + '</option>';
    //                                }
    //                                roles += '</select>';
    //                                alertDialog(TaskResources.UserNotOnService, TaskResources.AddUserOnService.replace('{0}', roles), function () {
    //                                    addUserOnServiceAndTask(suggestion, true);
    //                                });
    //                            }
    //                            else {
    //                                alertDialog(CommonResources.Error, TaskResources.ExecRolesOnServiceNotFound);
    //                            }
    //                        },
    //                        error: function (XMLHttpRequest, textStatus, errorThrown) {
    //                            alertDialog(CommonResources.Error, TaskResources.ErrorWhenGetRolesList);
    //                        }
    //                    });
                        
    //                }
    //            }, 0);
    //        }
    //        else {
    //            addExecutor($(this), suggestion);
    //            $(this).val('');
    //            //$('#addexecutor').val('');
    //        }
    //    },
    //    formatResult: function (suggestion, currentValue) {
    //        var pattern = '(' + currentValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ')';
    //        var isarchive = suggestion.data.isAddToService ? " archivecategory" : "";
    //        var createValue = suggestion.data.iscreatecategory ? ' "' + currentValue + '"' : "";
    //        var cValue = '<span class="ac-value' + isarchive + '">' + suggestion.value + createValue
    //            .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
    //            .replace(/&/g, '&amp;')
    //            .replace(/</g, '&lt;')
    //            .replace(/>/g, '&gt;')
    //            .replace(/"/g, '&quot;')
    //            .replace(/&lt;(\/?strong)&gt;/g, '<$1>') + '</span>';
    //        return cValue;
    //    }
    //});
    //$('#addparticipant').devbridgeAutocomplete({
    //    serviceUrl: 'Task/FindObservers/' + serviceId,
    //    minChars: 1,
    //    autoClearInputOnSelect: true,
    //    autoQueryOnEmptyField: true,      
    //    onSelect: addUser
    //});
    $('#addexecutorgroup').devbridgeAutocomplete({
        serviceUrl: 'Task/FindExecutorGroups/' + serviceId,
        minChars: 1,
        autoClearInputOnSelect: true,
        onSelect: addGroup
    });
    $('#addcoordinator').devbridgeAutocomplete({
        serviceUrl: 'Task/FindCoordinators/' + serviceId,
        autoQueryOnEmptyField: true,  
        minChars: 1,
        autoClearInputOnSelect: true,
        onSelect: addUser
    });
}

function initEventHandlers() {

    function formSubmit() {
       // $('a.saveicon, a.saveandreturnicon').attr('disabled', true);
        //setTimeout(function () {
        //    $('a.saveicon, a.saveandreturnicon').attr('disabled', false);
        //}, 2000);
        $('#taskform').submit();
    }

    $('body').on('click', 'a.saveandreturnicon ', function () {
        var $self = $(this);
        if (!$self.attr('disabled')) {
            SaveForm('true');
            formSubmit();
        }
    });

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

    //костыль с плановым сроком. При установке через календарь нужно устанавливать время на конец дня с учётом расписания
    if ($.fn.calendar) {
        $('body').on('hover focus', '#deadline.dateTime', function () {
            var $self = $(this);
            if ($self.data('initialized') || !$.fn.calendar)
                return;
            $self.calendar({ selectHandler: selectDeadlineHandler });
            $self.data('initialized', true);
        });
    }   
    if ($.browser.msie && $.browser.version < 11) {
        $('#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)
                ||
                $.browser.msie || $.browser.edge || $.browser.yandex
                ||
                $.browser.safari && $.browser.version >= 4
                ) {
        //показываем кнопку "Вставить скриншот"
        $('#pastescreenbtn').show();
        //добавляем события вставки для Комментария и Описания
        addPasteEvent();
    }

    $('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);
    //});

    $('.cancel').click(function () {
        if (confirm(TaskResources.Cancel + $(this).attr('statusname') + '"?'))
            changeTaskStatus($(this).attr('taskid'), $(this).attr('tostatusid'));
    });

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

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

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

    //$('#AddExpenses_UserId').change(function () {
    //    var $self = $(this);
    //    var $option = $self.find('option:selected');
    //    var $rate = $('#AddExpenses_Rate');

    //    $rate.val($option.attr('data-rate'));
    //});
    $('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').devbridgeAutocomplete({
        serviceUrl: 'Task/FindAssets/' + $('#serviceid').val(),
        formatWithTags: true,
        onSelect: addAsset,
        minChars: 1,
        autoClearInputOnSelect: true, //после выбора элемента очищаем инпут
        autoQueryOnEmptyField: true //отсылаем запрос при фокусе на пустое поле
    });
    $('#addcategory').devbridgeAutocomplete({
        serviceUrl: 'Task/FindCategories/' + $('#serviceid').val(),
        triggerSelectOnValidInput: false,
        //autoClearInputOnSelect: true, //после выбора элемента очищаем инпут
        autoQueryOnEmptyField: true,
        closeAfterOnEnter: true,
        minChars: 1,
        onSelect: function (suggestion) {
            if (suggestion.data.isonservice == "False") {
                setTimeout(function () {
                    if (!confirm(TaskResources.AddCategoryOnService)) {
                        setTimeout(function () { $('.autocomplete-suggestions').css("display", "none"); }, 10);
                        return false;
                    }
                    else {
                        setTimeout(function () { $('.autocomplete-suggestions').css("display", "none"); }, 10);
                        addCategoryFromTask(suggestion.data.cid, $('#serviceid').val(), suggestion.value);
                        return;
                    }
                    tagAdded(suggestion.data.cid, suggestion.value, suggestion.data.isarchive);
                }, 0);
            }
            else {
                if (suggestion.data.iscreatecategory && $('#cancreatecategory').size() > 0) {
                    var element = $('#addcategory');
                    var elementValue = element.val();
                    setTimeout(function () {
                        if (!confirm(TaskResources.WantCreateCategory.replace('{0}', elementValue)))
                            return false;
                        $(element).val('');
                        setTimeout(function () { $('.autocomplete-suggestions').css("display", "none"); }, 10);
                        addCategoryFromTask(0, $('#serviceid').val(), elementValue);
                    }, 0);
                }
                else {
                    tagAdded(suggestion.data.cid, suggestion.value, suggestion.data.isarchive);
                }
            }
            $('#addcategory').val('');
        },
        onEnter: ($('#cancreatecategory').size() > 0) ? function () {
            var elementValue = $(this).val();
            element = $(this);
            setTimeout(function () {
                if (!confirm(TaskResources.WantCreateCategory.replace('{0}', elementValue)))
                    return false;
                $(element).val('');
                setTimeout(function () { $('.autocomplete-suggestions').css("display", "none"); }, 10);
                addCategoryFromTask(0, $('#serviceid').val(), elementValue);
                $('#addcategory').val('');
            }, 0);
            return false;
        } : null,
        transformResult: function (response) {
            var result = typeof response === 'string' ? $.parseJSON(response) : response;
            if ($('#cancreatecategory').size() > 0 && $('#addcategory').val() != '') {
                result.suggestions.push({ value: CategoryResources.CreateCategory, data: { cid: 0, iscreatecategory: true } });
            }            
            return result;
        },
        formatDivClassResult: function (suggestion) {
            return suggestion.data.iscreatecategory ? 'topBorder' : '';
        },
        formatResult: function (suggestion, currentValue) {
            //if (!currentValue) {
            //    return suggestion.value;
            //}
            var pattern = '(' + currentValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ')';
            var isarchive = suggestion.data.isarchive ? " archivecategory" : "";
            var iscreate = suggestion.data.iscreatecategory ? " italictext" : "";
            var createValue = suggestion.data.iscreatecategory ? ' "'+ currentValue +'"' : "";
            var cValue = '<span class="ac-value' + isarchive + iscreate + '">' + suggestion.value + createValue
                .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/&lt;(\/?strong)&gt;/g, '<$1>') + '</span>';
            if (suggestion.data.isonservice == "False") {
                cValue += ' <span class="addToService">' + TaskResources.AddOnService + '</span>';
            }
            return cValue;
        }
    });    

    $('#addexpensesexecutor').devbridgeAutocomplete({
        serviceUrl: 'Task/FindExpensesExecutors/?taskId=' + $('#id').val() + '&serviceId=' + $('#serviceid').val(),
        triggerSelectOnValidInput: false,
        //autoClearInputOnSelect: true, //после выбора элемента очищаем инпут
        autoQueryOnEmptyField: true,
        minChars: 1,
        preserveInput: false,
        onSelect: function (suggestion) {
            $('#addexpensesexecutor').attr('disabled', true);
            $('#addexpensesexecutorclearebtn').show();
            $('#AddExpenses_Rate').val(suggestion.data.rate);
            $('#AddExpenses_UserId').val(suggestion.data.id);
            $('#addexpensesexecutor').valid();
        }
    });

    $('#addexpensesexecutorclearebtn').click(function (e) {
        e.preventDefault();
        $('#addexpensesexecutor').attr('disabled',false).val('');
        $(this).hide();
        $('#AddExpenses_Rate').val('');
        $('#AddExpenses_UserId').val('');
    })

    jQuery.validator.addMethod("addexpensesexecutor", function (value, element) {
        if ($('#AddExpenses_UserId').length) {
            return $('#AddExpenses_UserId').val() != '';
        }
        else {
            return true;
        }
    }, TaskResources.NoSelectExpensesExecutor);


    function addCategoryFromTask(categoryid, serviceid, categoryname) {
        $.ajax({
            url: base + 'Category/AddCategoryFromTask',
            data: { categoryId: categoryid, serviceId: serviceid, categoryName: categoryname },
            type: 'POST',
            success: function (result) {
                if (result != null && result.IsOK != null) {
                    if (result.IsOK) {
                        tagAdded(categoryid == 0 ? result.Result : categoryid, categoryname);
                    }
                    else if (result.Description != null) {
                        alert(result.Description);
                    }
                    else {
                        return false;
                    }
                }
            }
        });
        return false;
    }
    $(document).on('change', '.treetypecombo', multipleComboSelection);

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

$(document).ready(function () {

    reinitHeader();
    $(window).bind("resize", function () {
        reinitHeader();
    });
    var $comentNoty = $('.notyFullComment');
    if($comentNoty != null)
    {  
        $comentNoty.css('backgroundColor', '#c5ffbd');
            setTimeout(function () {              
                $comentNoty.css('backgroundColor', 'initial');
            }, 3000);        
    }
     
    $('body').on('click', '.modalOverlay ', function (e) {
        if (e.target != this)
            return true;
        e.preventDefault();
        closeModalOverlay();
    });
});

//кастомные функции перед сабмитом
var customFormAfterSubmitEx = [];
function customFormAfterSubmit() {
    for (var i = 0; i < customFormAfterSubmitEx.length; i++) {
        try{
            customFormAfterSubmitEx[i]();
        }
        catch(ex){}
    }
}

function formAfterSubmit(form) {
    customFormAfterSubmit();
    if (customValidate()) {

        //если не создание заявки, то дедлайн посылаем только если его изменили руками
        if ($("#create").size() <= 0) {
            //после того как прошла валидация 
            var $deadline = $('#deadline');

            if (!$deadline.attr('changed'))
                $deadline.attr('name', 'nosubmit');
            else {
                $deadline.attr('name', 'deadline');
            }
            if (managedInTime)
                $("#taskform").append('<input type="hidden" id="CommentEditedInTime" name="CommentEditedInTime" value="' + timeLeft + '"/>');
            if (autoDeadline != null) {
                $("#taskform").append('<input type="hidden" id="AutoDeadline" name="AutoDeadline" value="' + autoDeadline + '"/>')
            }
        }

        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) {

    $.ajax({
        contentType: 'application/json',
        url: 'Task/GetEndOfDayWithSchedule',
        data: JSON.stringify({ date: dateStr, serviceId: $('#serviceid').val() }),
        type: 'POST',
        success: function (result) {

            if (result && result.date)
                $('#deadline').val(result.date).trigger('change');
            else
                $('#deadline').val(dateStr).trigger('change');

        }
    });
}
//кастомные проверки перед сабмитом
//должны возвращать boolean
var customValidateEx = [];
customValidateEx.push(function () { return changeStatusToConcurenceValidator(); });
customValidateEx.push(function () { return changeStatusToExternalValidator(); });
function customValidate() {
    if ($("#taskform").valid()) {
        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);
                }
            });

            var isFinal = isFinalStatus();

            //#135054
            var sysdate = $.parseDate($('#deadlinesystem').val());
            if (sysdate != undefined && date != undefined && date.getTime() === sysdate.getTime() && $('#create').val() === 'True')
                deadlinechanged = false;

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

            //в условиях переноса настройки в тип - убираем, так как не до конца понятна эта фигня, так только лишние проверки. Если придумаем когда и как выводить сообщения(если надо) - то вернем
            //пока же в лес, так как в предыдущих версиях (4.32 и 4.31) это и не работало (так как в 4.32 в условии true было написано с маленькой буквы и условие никогда не выполнялось

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

            //    var parentsEarliestDeadline = $.parseDate($('#parentsearliestdeadline').val());
            //    if (parentsEarliestDeadline != null && date > parentsEarliestDeadline && !isFinal && !confirm(TaskResources.ParentDeadlineEarlierThanChild)) return false;
            //}
        }
        serializeChanges();
        $('.save,.saveandreturn,.save-ext').attr('disabled', true);
        setTimeout(function () {
            $('.save,.saveandreturn,.save-ext').attr('disabled', true); 
        }, 0);
        var result = true;
        for (i=0;i<customValidateEx.length;i++) {
            if (customValidateEx[i] !== 'undefined') {
                var r = customValidateEx[i]();
                if(!r){
                    result = false;
                    break;
                }
            }
        }
        //если кастомную проверку не прошли
        if (!result) {
            //через 2 секунды включить кнокпи
            setTimeout(function () {
                $('.save,.saveandreturn,.save-ext').attr('disabled', false);
            }, 2000);
        }
        return result;
    }
    setTimeout(function () {
        $('.save-ext').attr('disabled', false);
    }, 100);
    return false;
}

function isFinalStatus() {
    var $option = $('#statusid option:selected');
    if ($option.length) {
        return $option.attr('data-final') === 'True';
    }

    return false;
}

var categories = 0;
var taskStatusChanged = false;
//#region actions on status change
function onchangeStatus(st) {
    var $self = $(st);
    taskStatusChanged = true;
    var commentrequired = $self.find('option:selected').attr('data-commentrequired') === 'True';
    var $currentcomment = $('#currentcomment, label[for="CurrentComment"]');
    if (commentrequired) {
        $currentcomment.addClass('required');
    } else {
        $currentcomment.removeClass('required');
    }
    if (fixRequiredTaskFields.length > 0) {
        $.each(fixRequiredTaskFields, function (i, elem) {
            $('#field' + elem).removeClass('required');
            $('label[for="field' + elem + '"]').removeClass('required');
        });
        fixRequiredTaskFields = [];
    }
    if ($('#statusesRequiredField option[value="' + $self.val() + '"]').size() > 0) {
        var arrayOfFields = $('#statusesRequiredField option[value="' + $self.val() + '"]').text().split(',');
        $.each(arrayOfFields, function (i, elem) {
            var field = $('#field' + elem);
            if (field && !field.attr('disabled') && !field.hasClass('readonly') && !field.hasClass('hidden') && !field.hasClass('required')) {
                if (field.attr('type') && field.attr('type') == 'file') {
                    field.addClass('filerequired');
                }
                else {
                    field.addClass('required');
                }
                $('label[for="field' + elem + '"]').addClass('required');
                fixRequiredTaskFields[fixRequiredTaskFields.length] = elem;
            }
        });
    }
    if (fixRequiredMainFields.length > 0) {
        $.each(fixRequiredMainFields, function (i, elem) {
            var fieldname = getMainFieldName(elem);
            $('#' + fieldname[0]).removeClass(fieldname[1]);
            var label = (fieldname[1] == "required") ? $('label[for="' + fieldname[0] + '"]') : $('label.' + fieldname[0]);
            label.removeClass('required');
        });
        fixRequiredMainFields = [];
    }
    if ($('#statusesRequiredMainField option[value="' + $self.val() + '"]').size() > 0) {
        var arrayOfMainFields = $('#statusesRequiredMainField option[value="' + $self.val() + '"]').text().split(',');
        $.each(arrayOfMainFields, function (i, elem) {
            var fieldname = getMainFieldName(elem);
            var field = $('#' + fieldname[0]);
            if (field && !field.attr('disabled') && !field.hasClass('readonly') && !field.hasClass('hidden') && !field.hasClass(fieldname[1])) {
                field.addClass(fieldname[1]);
                var label = (fieldname[1] == "required") ? $('label[for="' + fieldname[0] + '"]') : $('label.' + fieldname[0]);
                label.addClass('required');
                fixRequiredMainFields[fixRequiredMainFields.length] = elem;
            }
        });
    }
    if ($('#isFinalStatus') && $('#isFinalStatus').val().toLowerCase() == 'true') {
        if (commentrequired) {
            $('#addcomments').show();

        } else {
            $('#addcomments textarea').val('');
            $('#addcomments').hide();
        }
    }

    if (($(st).find('option:selected').attr('data-isconcurrence') || '').toLowerCase() == 'true') {
        $('.saveandreturn').addClass('hidden');
        $('.save:first').html(CommonResources.Continue);

    } else {
        $('.saveandreturn').removeClass('hidden');
        $('.save:first').html(CommonResources.Save);
    }

    if (!$("#create").val())
        updateTaskOnStatusChange();
}

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

function GetUpdateTaskOnStatusChange(statusId, callback, async) {
    //'/' + statusId + '/' + $('#creatorid').val();
    var url = 'Task/GetUpdateTaskOnStatusChange?serviceId=' + $('#serviceid').val() + '&statusId=' + statusId + '&creatorId=' + $('#creatorid').val() + '&typeid=' + $('#typeid').val();
    if (async !== false)
        async = true;

    $.ajax({
        url: url,
        type: 'GET',
        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;
            var isExpendituresRequired = false;

            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;

                isExpendituresRequired = json.ExpendituresRequired;
            }

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

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

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

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

            if(isExpendituresRequired)
                $('#expensestaskrightsdisplaytype span:first').addClass("star");
            else
                $('#expensestaskrightsdisplaytype span:first').removeClass("star");
        }
    });
}

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,"", -1, -1);
            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, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + this.Id + "); return false;", -1, -1);
            else
                _checkUser(this.Id, "#participant");
        });
    } else {
        if ($("#create").val()) {
            removeAllObservers(false);
        }
    }

    if (callback)
        updateParticipantsCallback(callback);
}

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

    if (executorsGroup) {
        _executorGroupsSelected(executorsGroup.Id, executorsGroup.Name, canRemove, undefined, async);
    } 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").each(function (index, element) {
            $(element).removeAttr('selected');
        });
        $('#categoryids').trigger('change');

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

//#region add/remove users (executors, observers and other) handlers
//function selectExecutors() {
//    var url = 'taskuser.ivp/selectexecutors?tb_serviceid=' + $('#serviceid').val();
//    if ($('#deadline').val() != '') {
//        url += '&tb_deadline=' + $('#deadline').val();
//    }
//    if ($('#executorsfromexecutorgroup') && $('#executorsfromexecutorgroup').val() == 'True' && $('#executorgroupid') && $('#executorgroupid').val() != '') {
//        url += '&tb_executorgroupid=' + $('#executorgroupid').val();
//    }
//    utype = '#executors';
//    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
//    dlg.callback = taskUsersCallback;
//    return false;
//}

function taskUsersCallback(result) {
    var uids = result["selectedIds"];
    var names = result["selectedNames"];
    var companies = result["selectedCompanies"];
    addSelected(uids, names, companies);
}

function selectCoordinators() {
    var url = 'taskuser.ivp/selectcoordinators?tb_serviceid=' + $('#serviceid').val();
    utype = '#coordinators';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = taskUsersCallback;
    return false;
}
function selectPosibleCoordinators() {
    var url = 'taskuser.ivp/selectpossiblecoordinators?tb_serviceid=' + $('#serviceid').val();
    utype = '#coordinators';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = taskUsersCallback;
    return false;
}
//function selectParticipants() {
//    var url = 'taskuser.ivp/selectobservers?tb_serviceid=' + $('#serviceid').val();
//    utype = '#participants';
//    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
//    dlg.callback = taskUsersCallback;
//    return false;
//}
function selectCreator() {
    var url = 'taskuser.ivp/selectcreators?tb_serviceid=' + $('#serviceid').val();
    utype = '#creator';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = taskUsersCallback;
    return false;
}

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];
    var cn = d[1];

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

function addAsset(suggestion) {
    var name = suggestion.value;
    var id = "" + suggestion.data.id;
    autocomplete = true;
    var ids = [id];
    var names = new Array();
    names["id" + id] = name;
    assetSelected(ids, names);
    autocomplete = false;
    $('#addasset').valid();
}

function addCreator(suggestion) {
    var id = suggestion.data.id;
    var name = suggestion.value;
    var cn = suggestion.data.companyName;
    _creatorSelected(id, name, cn);
}

function addExecutor(that, suggestion) {
    var iid = '#' + $(that).attr('id').substr(3) + 's';
    var name = suggestion.value;
    var company = suggestion.data.companyName;
    var id = suggestion.data.id;
    _addUserToList(id, name, company, iid);
}
function addUser(suggestion) {
    var iid = '#' + this.id.substr(3) + 's';
    var name = suggestion.value;
    var company = suggestion.data.companyName;
    var id = suggestion.data.id;
    _addUserToList(id, name, company, iid);
}

function addGroup(suggestion) {
    var name = suggestion.value;
    var id = suggestion.data.id;
    _executorGroupsSelected(id, name);
}

function _creatorSelected(id, name, company) {
    var serviceid = $("#serviceid").val();
    var tasktypeid = $("#typeid").val();
    var hashid = '';
    return $.getJSON(base + 'user.ivp/getuserhash', { userid: id, date: new Date().toString() }).then(function (hid) {
        hashid = hid;
        return $.getJSON(base + 'user.ivp/GetCreateTaskAccess', { userid: id, serviceid: serviceid, tasktypeid: tasktypeid != 0 ? tasktypeid : null });
    }).then(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>';
        html += '<div class="grey small">' + company + '</div></li>';
        $('#creator ul').append(html);
        $('#creatorid').attr('changed', true).val(id).trigger('change');

        $.ajax({
            type: 'POST',
            url: 'Task/GetExecutorGroupByCreator',
            dataType: 'json',
            data: { creatorId: id, serviceId: $('#serviceid').val(), taskId: $('#id').val(), statusId: $('#statusid').val(), typeId: $('#typeId').val() },

            success: function (json) {
                if (json && json.Data) {

                    if (json.Data.hasOwnProperty('Name') && json.Data.hasOwnProperty('Id')) {
                        _executorGroupsSelected(json.Data.Id, json.Data.Name);

                        if (json.Data.Observers.length > 0) {
                            var observersData = { DeleteObservers: false, Observers: json.Data.Observers };
                            updateObserversOnStatusChange(undefined, observersData);
                        }
                    }
                }
            }
        });

        getWorkflowAndSLA(null, "User");
        return false;
    }).promise();
    /*
    $.getJSON(base + 'user.ivp/getuserhash', { userid: id, date: new Date().toString() }, function (hashid) {
        //проверка на наличие действующего договора
        
        $.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>';
            html += '<div class="grey small">' + company + '</div></li>';
            $('#creator ul').append(html);
            $('#creatorid').attr('changed', true).val(id).trigger('change');


            $.ajax({
                type: 'POST',
                url: 'Task/GetExecutorGroupByCreator',
                dataType: 'json',
                data: { creatorId: id, serviceId: $('#serviceid').val(), taskId: $('#id').val(), statusId: $('#statusid').val(), typeId: $('#typeId').val() },

                success: function (json) {
                    if (json && json.Data) {

                        if (json.Data.hasOwnProperty('Name') && json.Data.hasOwnProperty('Id')) {
                            _executorGroupsSelected(json.Data.Id, json.Data.Name);

                            if (json.Data.Observers.length > 0) {
                                var observersData = { DeleteObservers: false, Observers: json.Data.Observers };
                                updateObserversOnStatusChange(undefined, observersData);
                            }
                        }
                    }
                }
            });

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

    */

    //на будущее
    //recalcComplexOrderSlaOnCreate();
}

function _addUserToList(id, name, company, type, dontChangeStatusInProgress, hash, canRemove, onclickRemoveStr, categoryId, groupId) {
    var def = $.Deferred();
    var wrapper = $(type);
    var ul = wrapper.find('ul:first');
    var select = wrapper.find('select:first');
    if ($('option[value="' + id + '"]:selected', select).length > 0) {
        user = ul.find('li[userid=' + id + ']');
        if (categoryId !== undefined && categoryId != "")
            addTagData('categoryids', user, categoryId);
        if (groupId !== undefined && groupId != "")
            addTagData('groupids', user, groupId);
        return def.resolve('exists').promise();
    }
    if (hash) {
        _addUserToListAction(hash, id, name, company, type, dontChangeStatusInProgress, ul, select, canRemove, onclickRemoveStr, categoryId, groupId);
        def.resolve('added');
    } else {
        $.getJSON(base + 'user.ivp/getuserhash', { userid: id, date: new Date().toString() }, function (hashid) {
            _addUserToListAction(hashid, id, name, company, type, dontChangeStatusInProgress, ul, select, canRemove, onclickRemoveStr, categoryId, groupId);
            def.resolve('added');
        });
    }
    return def;
}

function _addUserToListAction(hashid, id, name, company, type, dontChangeStatusInProgress, ul, select, canRemove, onclickRemoveStr, categoryId, groupId) {
    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>');
    categoryId = categoryId === undefined ? "" : categoryId;
    groupId = groupId === undefined ? "" : groupId;
    if (!ul.find('li[userid=' + id + ']').length) {

        var html = '<li userid="' + id + '" class="changed" data-categoryids="' + categoryId + '" categoryids="' + categoryId + '" data-groupids="' + groupId + '" groupids="' + groupId + '"><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="' + (onclickRemoveStr || 'return removeUser(this,' + id + ');') + '"><img src="img/trash.gif" /></a></span>';
            }

        } else {
            html += '<span class="hover"><a href="#" onclick="' + (onclickRemoveStr || '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, categoryId, groupId);
    }

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

function _checkExecutors(userId, handler, userData, canRemove, onclickRemoveStr) {
    var user = $(handler + 's').find(handler + 'ids' + userId);
    if (!user.length) {
        var $executors = $('select#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.Name + '</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', (onclickRemoveStr || '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, onclickRemoveStr) {
    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.Name + '</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', (onclickRemoveStr || 'return removeUser(this,' + userData.Id + ');')));
                $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];
        var cn = companies['id' + id];
        if (cn.indexOf('/') >= 0)
        {
            var copmpanies = cn.split('/');
            cn = "&nbsp" + copmpanies[copmpanies.length - 1];
        }
        _creatorSelected(id, un, cn);
    }
    else {
        uids.forEach(function (id) {
            var un = names['id' + id];
            var cn = companies['id' + id];
            _addUserToList(id, un, cn, utype);
        });
    }
}

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

    var isExecutorAdded = a.closest('div').find('#executorids').length > 0;
    var user = a.closest('li')
    if (del) {
        a.closest('li').addClass('archive changed');
        if (categoryId !== undefined && categoryId != "")
            removeTagData('categoryids', user, categoryId);
        if (groupId !== undefined && groupId != "")
            removeTagData('groupids', user, groupId);
        if (isExecutorAdded && $('#oneexecutoronticket').val() == "True") {
            $("#executorids option").remove();
        }
    } else {
        a.closest('li').removeClass('archive changed');
        if (categoryId !== undefined && categoryId != "")
            addTagData('categoryids', user, categoryId);
        if (groupId !== undefined && groupId != "")
            addTagData('groupids', user, groupId);
        if (isExecutorAdded && $('#oneexecutoronticket').val() == "True") {
            a.closest('ul').find('li').not(a.closest('li')).addClass('archive changed');
            var users = a.closest('ul').find('li').not(a.closest('li'));
            users.each(function () {
                var user = $(this);
                if (categoryId !== undefined && categoryId != "")
                    removeTagData('categoryids', user, categoryId);
                if (groupId !== undefined && groupId != "")
                    removeTagData('groupids', user, groupId);
            })
            $("#executorids option").remove();
            $("#executorids").append('<option selected="selected" value="' + id + '">' + id + '</option>');
        }
    }

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

function assignSelfExecutor() {
    //$.getJSON('Task/GetCurrenUserData', { json: "json" }, function (data) {
    //    _addUserToList(data.Id, data.Name, data.CompanyName, "#executors", undefined, data.HashId);
    //});
    //return false;
}

//function assignSelfParticipant() {
//    var def = $.Deferred();
//    $.getJSON('Task/GetCurrenUserData', { json: "json" }, function (data) {
//        _addUserToList(data.Id, data.Name, data.CompanyName, "#participants", undefined, data.HashId)
//            .done(function (d1result) {
//                def.resolve(d1result);
//            });
        
//    });
//    return def.promise();
//}

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 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();

    //GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].removeAllExecutors(dontshowdeleted);
    getDefferedBlockByName('taskexecutors')
        .done(function (block) {
            block.removeAllExecutors(dontshowdeleted);
        });
}

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();

    //GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeAllObservers(dontshowdeleted);
    getDefferedBlockByName('taskparticipants')
        .done(function (block) {
            block.removeAllObservers(dontshowdeleted);
        });
}

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();

    //GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].removeAllExecutorsButNotThis(id, dontshowdeleted);
    getDefferedBlockByName('taskexecutors')
        .done(function (block) {
            block.removeAllExecutorsButNotThis(id, dontshowdeleted);
        });
}

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 selectPerson() {
    var serviceid = $('#serviceid').val();
    var url = 'user.ivp/select?tb_mode=serviceusers&tb_serviceid=' + serviceid;
    dlg = window.openDialog(url, 'selectpersons', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function usersCallback(result) {
    var uids = result["selectedIds"];
    addPerson(uids);
}

//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;

    //GLOBAL_taskFormHubObserver.getBlocks()['executorgroupid'].removeExecutorGroup(notext);
    getDefferedBlockByName('executorgroupid')
        .done(function (block) {
            block.removeExecutorGroup(notext);
        });
    return false;
}

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

    //GLOBAL_taskFormHubObserver.getBlocks()['executorgroupid'].selectExecutorGroups();
    getDefferedBlockByName('executorgroupid')
        .done(function (block) {
            block.selectExecutorGroups();
        });
    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, categoryId, async) {
    //removeExecutorGroup(true);   
    //$.ajax({
    //    url: 'ExecutorGroup/GetGroupExecutorHash/?id=' + id,
    //    success: function (hash) {
    //        $('#executorgroupid').val(id).attr('changed', true);
    //        var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', 'executorgroup/viewhash/' + hash).click(function () { return executorGroupDetailsByHash(hash); });
    //        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");

    //$.ajax({
    //    contentType: 'application/json',
    //    type: 'GET',
    //    url: 'ExecutorGroup/FindDefaultGroupObservers/?groupid=' + id,
    //    success: function (response) {

    //        $.each(response.Observers, function (i, el) {
    //            _addUserToList(el.Id, el.Name, el.Company, '#participants', false, undefined, true, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + el.Id + "); return false;");
    //        })
    //    }
    //});
   
    //GLOBAL_taskFormHubObserver.getBlocks()['executorgroupid']._executorGroupsSelected(id, name, canRemove);
    return getDefferedBlockByName('executorgroupid')
        .done(function (block) {
            block._executorGroupsSelected(id, name, canRemove, categoryId, async);
        });
}

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

function executorGroupDetailsByHash(hash) {
    openDialog('executorgroup/viewhash/?popup=true&hashcode=' + hash);
            return false;
}
function groupAdded(e, d) {
    var name = d[0];
    var id = d[1];
    $(e.target).val('');
    _executorGroupsSelected(id, name);
}

//#endregion

//#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("Task/GetTaskLifeTimeFull/" + $("#id").val(), function () {
            $(".lifetime").toggle();
        });
    else {
        $(".lifetime").toggle();
    }  

    return false;
}
//#endregion

//#region files, screenshots
function attachFile() {
    if (oldBrowser) {
        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="' + encodeHTML(name).replace(/\"/g, "\'") + '"><span>' + encodeHTML(name) + '.png</span>' +
        '<a class="noul" href="#" onclick="return removePasteScreen($(this));"><img src="img/trash.gif" title="' + CommonResources.Remove + '"/></a>' +
        '</li>');
    $('#inputDropFileAndScreenshot').valid();
    //if (GLOBAL_taskFormHubObserver && GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist']) {
    //    GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist'].attachPasteScreenshot(n);
    //}
    getDefferedBlockByName('mainfilelist')
        .done(function (block) {
            block.attachPasteScreenshot(n);
        });
    return false;
}

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

function removePasteScreen(link) {
    var $li = $(link).parent('li.screenshot');
    var n = $li.find('input[name^="attachscreenshots"]').attr('name').replace('attachscreenshots', '');
    $li.remove();
    $('#inputDropFileAndScreenshot').valid();
    //if (GLOBAL_taskFormHubObserver && GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist']) {
    //    GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist'].removePasteScreen(n);
    //}
    getDefferedBlockByName('mainfilelist')
        .done(function (block) {
            block.removePasteScreen(n);
        });
    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);
    }
    $('#file' + id + '').toggleClass('deletefile');
    $('#inputDropFileAndScreenshot').valid();
    //if (GLOBAL_taskFormHubObserver && GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist']) {
    //    GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist'].removeMainFile(id);
    //}
    getDefferedBlockByName('mainfilelist')
        .done(function (block) {
            block.removeMainFile(id);
        });
    return false;
}

//Удаление файлов доп. полей
function removeAdditionalFile(fileid) {
    if (!$('#filefield' + fileid + ' a:first').hasClass("selectdeletedfile")) {
        $('#filefield' + fileid + ' a:first').removeClass("noul").addClass("selectdeletedfile");
        deleteFile(fileid);
    } else {
        $('#filefield' + fileid + ' a:first').removeClass("selectdeletedfile").addClass("noul");
        restoreFile(fileid);
    }
    return false;
}

function removeDroppedFile(fileId) {
    $.post('Task/DeleteFileAjax', { fileId: fileId, taskToken: $('#taskToken').val() }, function (data) {
        if (data.hasOwnProperty('IsOk') && data.IsOk == true) {
            $("li#newfile" + fileId).remove();
            $('#inputDropFileAndScreenshot').valid();
            //if (GLOBAL_taskFormHubObserver && GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist']) {
            //    GLOBAL_taskFormHubObserver.getBlocks()['mainfilelist'].removeDroppedFile(fileId);
            //}
            getDefferedBlockByName('mainfilelist')
                .done(function (block) {
                    block.removeDroppedFile(fileId);
                });
        }
    });

    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('|'));
    $('#inputDropFileAndScreenshot').valid();
}

//снятие флага на удаление для файла
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 = '';
        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>';
        }
        $('#addscreenshots').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();
        $('#addasset').valid();
        return false;
    });    
    $('#tal').removeClass('middle');    
}
function initSelectedAssets() {
    if (selectedAssets == null)
        selectedAssets = $("#assetids").val();
}

var Task = {
    selectAssets: function selectAssets() {
        dlg = openDialog('assettable.ivp/select?callback=assetSelected&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);
        $('#addasset').valid();
    }
}

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 data-id="'+id+'" 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');
            $('#addasset').valid();
            $('#assetids').trigger('change');
            return false;
        });
    });

    getWorkflowAndSLA(null, 'AssetType');

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

    $('#assetids').trigger('change');

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

    var ids = [id];
    var names = new Array();
    names["id" + id] = name;

    assetSelected(ids, names);
    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');
    $('#addasset').valid();
    $('#assetids').trigger('change');
    return false;
}
function assetDetails(id) {
    openDialog('assettable.ivp/view/' + id + '?popup=true&read=true', 'asset' + id);
    return false;
}
//#endregion

//#region categories
function initSelectedCategories(ids) {
    selectedCategories = ids != null? ids : $("#categoryids").val();
}
function selectCategory() {
    dlg = openDialog('category/select?reset=true&tb_serviceid=' + $('#serviceid').val(), 'category', { width: 990, height: 660 });
    dlg.callback = categoriesCallback;
    return false;
}

function categoriesCallback(result) {
    var ids = result["selectedIds"];
    var names = result["selectedNames"];
    addSelectedCategories(ids, names);
   $('#addcategory').valid();
}

function categorySelected(id, name, isarchive) {
    var wrapper = $('#categories');
    var ul = wrapper.find('ul:first');
    var select = wrapper.find('select:first');
    formchanged = true;
    if ($('option[value="' + id + '"]', select).length > 0)
    {
        $('option[value="' + id + '"]', select).attr('selected', 'selected');
        ul.find('li[data-id=' + id + ']').removeClass('archive');
        return
    };

    if ($('#onecategoryonticket').val() == "True" && $('option', select).length >= 1) {
        select.find("option").remove();
        var notArhiveCategory = ul.find('li').not('.archive');
        var notArhiveCategoryIds = notArhiveCategory.map(function () {
            return $(this).data('id');
        }).get();
        removeExecutorsAndObserversByCategory(notArhiveCategoryIds);
        notArhiveCategory.addClass('archive changed');
        //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 archiveclass = isarchive ? "archivecolor" : "";
        var html = '<li class="changed ' + archiveclass + '" 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');
    return select.trigger('change');
}
function addSelectedCategories(cids, names) {
    var ieCids = new Array();
    $.each(cids, function (id, el) {
        ieCids.push(el);
    });
    Promise.all(ieCids.map(function (id) {
        var lb = $.trim(names['id' + id]);
        return categorySelected(id, lb);
    })).then(function () {

        getWorkflowAndSLA(null, 'Category', function () {
            if ($("#create").val() === 'True' || $('#isInitialStatus').val() === 'True')
                onchangeCategories(ieCids);
        });
    });
}

function tagAdded(id, name, isarchive) {
    categorySelected(id, name, isarchive);
    if ($('#isFinalStatus').size() > 0 && $('#isFinalStatus').val() == "True")
        return;
    var ids = new Array();
    ids.push(id);
    getWorkflowAndSLA(null, "Category", function () {
        if ($("#create").val() === 'True' || $('#isInitialStatus').val() === 'True')
            onchangeCategories(ids);
    });   
    $('#addcategory').valid();
}

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() === 'True' || $('#isInitialStatus').val() === 'True')
            onchangeCategories();
    });
}
function removeCategory(a, id) {
    a = $(a);
    var del = !a.parents('li:first').hasClass('archive');
    formchanged = true;

    var arrayId = [id];
    var serviceId = $('#serviceid').val();
    getWorkflowAndSLA(null, "Category", function () {
        if ($("#create").val() === 'True' || $('#isInitialStatus').val() === 'True')
            removeAutoAssignsUsersOnCategoryChange(serviceId, arrayId, del);
    });
    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") {
            var notArhiveCategory = a.closest('ul').find('li').not(a.closest('li')).not('.archive');
            var notArhiveCategoryIds = notArhiveCategory.map(function () {
                    return $(this).data('id');
            }).get();
            removeExecutorsAndObserversByCategory(notArhiveCategoryIds);
            notArhiveCategory.addClass('archive changed');
            //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() === 'True' || $('#isInitialStatus').val() === 'True')
         //   onchangeCategories();
    //});
    $('#addcategory').valid();
    $('#categoryids').trigger('change');
    return false;
}
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'); });
        $('#categoryids').trigger('change');
    }
}

function removeExecutorsAndObserversByCategory(categoryIds)
{
    if ($("#create").val() !== 'True' && $('#isInitialStatus').val() !== 'True')
        return;
    var executors = $("#executors .users li").not('.empty');
    var observers = $("#participants .users li").not('.empty');
    $(categoryIds).each(function (i, c) {
        executors.each(function (j, e) {
            var executor = $(e);
            if (removeTagData('categoryids', executor, c)) {
                //executor.addClass('archive changed');
                //$("#executors select option[value=" + executor.attr("userid") + "]").removeAttr("selected");
            }
        });
        observers.each(function (j, e) {
            var observer = $(e);
            if (removeTagData('categoryids', observer, c)) {
                //observer.addClass('archive changed');
                //$("#participants select option[value=" + observer.attr("userid") + "]").removeAttr("selected");
            }
        });

        if (removeGroupCategoryData($('#egroupholder').attr('group-id'), c))
        {
            $('#executorgroupid').attr('changed', true);
            $('#egroupholder').addClass('removed changed');
            $('#executorgroupid').attr('changed', true).val('');
            UpdateGroupCallBack($('#egroupholder').attr('group-id'), true);
        }
    });
}

function addTagData(tag, user, categoryId)
{
    strCaterory = user.data(tag);
    if (strCaterory != null && strCaterory != '') {
        caterories = strCaterory.toString().split(';');
        var ind = caterories.indexOf(categoryId ? categoryId.toString() : "");
        if (categoryId && ind === -1)
            caterories.push(categoryId.toString());
        user.data(tag, caterories.join(';'))
    }
    else
    {
        user.data(tag, categoryId)
    }
}

function addGroupCategoryData(groupId, categoryId) {
    if ($('#egroupholder').attr('group-id') == groupId) {
        strCaterory = $('#egroupholder').data('categoryids');
        if (strCaterory != null && strCaterory != '') {
            caterories = strCaterory.toString().split(';');
            var ind = caterories.indexOf(categoryId ? categoryId.toString() : "");
            if (categoryId && ind === -1)
                caterories.push(categoryId.toString());
            $('#egroupholder').data('categoryids', caterories.join(';'))
        }
        else {
            $('#egroupholder').data('categoryids', categoryId.toString())
        }
    }
}

function removeTagData(tag, user, categoryId)
{
    caterories = []
    strCaterory = user.data(tag);
    if (strCaterory != null && strCaterory != '') {
        caterories = strCaterory.toString().split(';');
        var ind = caterories.indexOf(categoryId ? categoryId.toString() : "");
        if (ind !== -1)
            caterories.remove(ind);
        user.data(tag, caterories.join(';'))
    }
    return (strCaterory === undefined) || caterories.length === 0;
}



function removeGroupCategoryData(groupId, categoryId)
{
    if ($('#egroupholder').attr('group-id') == groupId)
    {
        caterories = []
        strCaterory = $('#egroupholder').data('categoryids');
        if (strCaterory != null && strCaterory != '') {
            caterories = strCaterory.toString().split(';');
            var ind = caterories.indexOf(categoryId ? categoryId.toString() : "");
            if (ind !== -1)
                caterories.remove(ind);
            $('#egroupholder').data('categoryids', caterories.join(';'))
        }
        return (strCaterory === undefined) || caterories.length === 0;
    }
}

//function assignUsersCategoryData()
//{
//    var activeCaterories = $('#categories').find('li').not('.archive').map(function () {
//        return $(this).data('id');
//    }).get();
//    var serviceId = $('#serviceid').val();
//    if ($('#name').val() == '') //костыль на автоназначения в новой заявке присвоить всем авто -1
//    {
//        $("#executors .users li").filter(function () { return $(this).data('categoryids') == undefined }).data('categoryids', -1);
//        $("#participants .users li").filter(function () { return $(this).data('categoryids') == undefined }).data('categoryids', -1);
//    }

//    Promise.all([removeAutoAssignsUsersOnCategoryChange(serviceId, activeCaterories, false)]).then(function () {
//        $("#executors .users li").filter(function () { return $(this).data('categoryids') == undefined }).data('categoryids', -1);
//        $("#participants .users li").filter(function () { return $(this).data('categoryids') == undefined }).data('categoryids', -1);
//    });
//}

function removeAutoAssignsUsersOnCategoryChange(serviceId, categoryIds, del) {
    return $.ajax({
        contentType: 'application/json',
        url: 'Task/GetAutoAssignsUsersOnCategoryChange',
        data: JSON.stringify({
            serviceId: serviceId,
            categoryIds: categoryIds
        }),
        type: 'POST'
    }).done(function(result) {
        if (result && result.Data) {
            var activeCaterories = $('#categories').find('li').not('.archive').map(function () {
                return $(this).data('id');
            }).get();
            //исполнители
            $.each(result.Data.Executors, function () {
                if (categoryIds && categoryIds.indexOf(this.CategoryId) == -1)
                    return;
                var executor = $("#executors .users li[userid=" + this.Id + "]")
                if (del)
                    removeTagData('categoryids', executor, this.CategoryId)
                        //$("#executors .users li[userid=" + this.Id + "]").addClass('archive changed');
                        //$("#executors select option[value=" + this.Id + "]").removeAttr("selected");
                else {
                    if ($('#oneexecutoronticket').val() == "True") {
                        var categoryId = this.CategoryId;
                        $("#executors .users li")
                            .each(function (j, e) {
                                var executor = $(e);
                                removeTagData('categoryids', executor, categoryId)
                            });
                    }
                    addTagData('categoryids', executor, this.CategoryId)
                    $("#executors .users li[userid=" + this.Id + "]").removeClass('archive');
                    $("#executors select option[value=" + this.Id + "]").attr('selected', 'selected');
                }
                GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].BlockChange();
            });

            //наблюдатели
            $.each(result.Data.Observers, function () {
                if (categoryIds && categoryIds.indexOf(this.CategoryId) == -1)
                    return;
                var observer = $("#participants .users li[userid=" + this.Id + "]")
                if (del) {
                    if (removeTagData('categoryids', observer, this.CategoryId)) {
                        //$("#participants .users li[userid=" + this.Id + "]").addClass('archive changed');
                        //$("#participants select option[value=" + this.Id + "]").removeAttr("selected");
                    }
                }
                else {
                    addTagData('categoryids', observer, this.CategoryId)
                    $("#participants .users li[userid=" + this.Id + "]").removeClass('archive');
                    $("#participants select option[value=" + this.Id + "]").attr('selected', 'selected');
                }
                GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].BlockChange();
            });

            var def = new $.Deferred();
            //группы исполнителей
            if (result.Data.ExecutorGroup && result.Data.ExecutorGroup.length > 0) {
                if (result.Data.ExecutorGroup[0].CategoryId !== undefined && result.Data.ExecutorGroup[0].Id == $('#egroupholder').attr('group-id')) {
                    if (!del) {
                        addGroupCategoryData(result.Data.ExecutorGroup[0].Id, result.Data.ExecutorGroup[0].CategoryId)
                        $('#egroupholder').removeClass('removed changed');
                        $('#executorgroupid').attr('changed', true).val($('#egroupholder').attr('group-id'));
                        addObserversByGroup(result.Data.ExecutorGroup[0].Id)
                            .then(function () { def.resolve(); })
                    }
                    else
                    {
                        if (removeGroupCategoryData(result.Data.ExecutorGroup[0].Id, result.Data.ExecutorGroup[0].CategoryId)) {
                            //$("#egroupholder a").last().click();
                            $('#executorgroupid').attr('changed', true);
                            $('#egroupholder').addClass('removed changed');
                            $('#executorgroupid').attr('changed', true).val('');
                            UpdateGroupCallBack($('#egroupholder').attr('group-id'), true);
                            def.resolve();
                        } else {
                            UpdateGroupCallBack($('#egroupholder').attr('group-id'), true);
                            def.resolve();
                        }
                    }
                } else {
                    if ($('#egroupholder').find("div#noexecutorgroup").length === 0) {
                        strCaterory = $('#egroupholder').attr('categoryids');
                        if (strCaterory === undefined || strCaterory === '' || strCaterory == -1) {
                            $("#egroupholder a").last().click();
                        }
                    }
                    def.resolve();
                }
            } else
                def.resolve();

            def.done(function () {
                if (activeCaterories.length === 0)
                    addUserWithoutCategory();
                else {
                    clearUserWithoutCategory();
                }
                updateTask();
                //$("#executors .users li").filter(function () { return $(this).data('categoryids') == undefined }).data('categoryids', 0);
                //$("#participants .users li").filter(function () { return $(this).data('categoryids') == undefined }).data('categoryids', 0);
            });
        }
    });
}

function clearUserWithoutCategory()
{
    var executors = $("#executors .users li").not('.empty');
    var observers = $("#participants .users li").not('.empty');
    executors.each(function () {
        var executor = $(this);
        var categoryids = executor.attr('categoryids') || '';
        var groupids = executor.attr('groupids') || '';
        if (!((categoryids === '' || categoryids === '-1') && (groupids === '' || groupids === '-1')))
            return;
        executor.data('categoryids', '').data('groupids', '');
    });
    observers.each(function () {
        var observer = $(this);
        var categoryids = observer.attr('categoryids') || '';
        var groupids = observer.attr('groupids') || '';
        if (!((categoryids === '' || categoryids === '-1') && (groupids === '' || groupids === '-1')))
            return;
        observer.data('categoryids', '').data('groupids', '');
    });
    //Удалить группу исполнителей
    if ($('#egroupholder').find("div#noexecutorgroup").length === 0) {
        var activeCategories = $('#categories').find('li').not('.archive').map(function () {
            return $(this).data('id');
        }).get();
        strCaterory = $('#egroupholder').attr('categoryids');
        if (strCaterory === undefined || strCaterory === '' || strCaterory == -1 || !intersectCategoryes(strCaterory, activeCategories)) {
            $('#egroupholder').addClass('removed changed');
            $('#executorgroupid').attr('changed', true).val(undefined);
            UpdateGroupCallBack($('#egroupholder').attr('group-id'), true);
        }
    }
}

function intersectCategoryes(strCaterory, activeCategories)
{
    var currentCategories = strCaterory.split(';').map(function (f) {
        return parseInt(f);
    });
    const itersect = currentCategories.filter(value => activeCategories.includes(value));
    return itersect.length > 0;
}

function addObserversByGroup(groupId)
{
    return $.ajax({
        contentType: 'application/json',
        type: 'GET',
        url: 'ExecutorGroup/FindDefaultGroupObservers/?groupid=' + groupId,
        success: function (response) {
            var promises = [];
            $.each(response.Observers, function (i, el) {
                promises.push(_addUserToList(el.Id, el.Name, el.Company, '#participants', false, undefined, true,
                    "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + el.Id + "); return false;", undefined, groupId).promise());
            });
        }
    })
}

function UpdateGroupCallBack(groupId, del) {
    var executors = $("#executors .users li").not('.empty');
    var observers = $("#participants .users li").not('.empty');
    if (del) {
        executors.each(function (j, e) {
            var executor = $(e);
            removeTagData('groupids', executor, groupId)
        });
        observers.each(function (j, e) {
            var observer = $(e);
            removeTagData('groupids', observer, groupId)
        });
    }
    else
    {
        executors.each(function (j, e) {
            var executor = $(e);
            if(hasGroup(executor, groupId))
                addTagData('groupids', executor, groupId)
        });
        observers.each(function (j, e) {
            var observer = $(e);
            if (hasGroup(observer, groupId))
                addTagData('groupids', observer, groupId)
        });
    }
    updateTask();
}

function hasGroup(user, groupId)
{
    var attr = user.attr('groupids')
    if (attr === undefined || attr == '')
        return false;
    var groups = attr.split(';');
    var ind = groups.indexOf(groupId ? groupId.toString() : "");
    return ind !== -1;
}

function updateTask()
{
    var executors = $("#executors .users li").not('.empty');
    var observers = $("#participants .users li").not('.empty');
    var activeCaterories = $('#categories').find('li').not('.archive').map(function () {
        var id = $(this).data('id')
        return id ? id.toString() : '';
    }).get();
    var hasCategory = activeCaterories.length > 0;
    if ($('#oneexecutoronticket').val() == "True" && executors.length > 1) {
        executors.addClass('archive changed');
        $("#executors select option").removeAttr("selected");
        var cand = executors.toArray().filter(function (f) {
            var e = $(f)
            return (e.data('categoryids') !== undefined && e.data('categoryids') !== '')
            || (e.data('groupids') !== undefined && e.data('groupids') !== '')
        });
        if (cand.length > 0) {
            $(cand[cand.length - 1]).removeClass('archive');
            $("#executors select option[value=" + $(cand[cand.length - 1]).attr('userid') + "]").attr('selected', 'selected');
        }
    }
    else {
        if (!taskStatusChanged)
            executors.each(function (j, e) {
                var executor = $(e);
                if (canRemove(executor, false)) {
                    executor.addClass('archive changed');
                    $("#executors select option[value=" + executor.attr("userid") + "]").removeAttr("selected");
                }
                else {
                    executor.removeClass('archive');
                    $("#executors select option[value=" + executor.attr("userid") + "]").attr("selected", "selected");
                }
            });
    }
    observers.each(function (j, e) {
        var observer = $(e);
        if (!taskStatusChanged)
            if (canRemove(observer, true)) {
                observer.addClass('archive changed');
                $("#participants select option[value=" + observer.attr("userid") + "]").removeAttr("selected");
            }
            else
            {
                observer.removeClass('archive');
                $("#participants select option[value=" + observer.attr("userid") + "]").attr("selected", "selected");
            }
    });
    function canRemove(user, isObserver)
    {
        if ((user.data('categoryids') === undefined || user.data('categoryids') == "") &&
            (user.data('groupids') === undefined || user.data('groupids') == ""))
        {
            var groupids = user.attr('groupids') || '';
            var strcategoryids = user.attr('categoryids') || '';
            var categoryids = strcategoryids.split(';')
            if ($("input#id").val() != '0') {
                if ($('#isInitialStatus').val() !== 'True')
                {
                    return false;
                }
                if ((groupids === '' || groupids === '-1') && (categoryids.length === 0 || categoryids.indexOf('-1') != -1))
                    return false;
            }
            else
            {
                if (hasCategory) {
                    return activeCaterories.findIndex(function (f) { categoryids.indexOf(f) >= 0 }) < 0;
                }
                return categoryids.indexOf('-1') === -1;
            }
            return true;
        }
        return false;
    }
}



function addUserWithoutCategory()
{
    var executors = $("#executors .users li").not('.empty');
    var observers = $("#participants .users li").not('.empty');
    executors.each(function () {
        var executor = $(this);
        var categoryids = executor.attr('categoryids') || '';
        var groupids = executor.attr('groupids') || '';
        if ((categoryids !== '' && categoryids !== '-1') || (groupids !== '' && groupids !== '-1'))
            return;
        executor.data('categoryids', '').data('groupids', '-1');
    });
    observers.each(function () {
        var observer = $(this);
        var categoryids = observer.attr('categoryids') || '';
        var groupids = observer.attr('groupids') || '';
        if ((categoryids !== '' && categoryids !== '-1') || (groupids !== '' && groupids !== '-1'))
            return;
        observer.data('categoryids', '').data('groupids', '-1');
    });
    //Вернуть группу исполнителей
    //todo получить группу исполнителей по умолчанию с бека
    if ($('#egroupholder').find("div#noexecutorgroup").length === 0) {
        strCaterory = $('#egroupholder').attr('categoryids');
        if (strCaterory === undefined || strCaterory === '' || strCaterory == -1) {
            $('#egroupholder').removeClass('removed changed');
            $('#executorgroupid').attr('changed', true).val($('#egroupholder').attr('group-id'));
            UpdateGroupCallBack($('#egroupholder').attr('group-id'), false);
        }
    }
}

function checkCategory()
{
    var activeCaterories = $('#categories').find('li').not('.archive').map(function () {
        var id = $(this).data('id')
        return id ? id.toString() : '';
    }).get();
    var executors = $("#executors .users li");
    executors.each(function (i, e) {
        var executor = $(e);
        var categoryStrIds = executor.data('categoryids');
        var categoryIds = categoryStrIds != null ? categoryStrIds.toString().split(";") : [];
        executor.data('categoryids', activeCaterories.filter(function (item) { return categoryIds.indexOf(item) > -1 }).join(';'));
    });
    var observers = $("#participants .users li");
    observers.each(function (i, e) {
        var observer = $(e);
        var categoryStrIds = observer.data('categoryids');
        var categoryIds = categoryStrIds != null ? categoryStrIds.toString().split(";") : [];
        observer.data('categoryids', activeCaterories.filter(function (item) { return categoryIds.indexOf(item) > -1 }).join(';'));
    });
}

function excludeUser()
{
    var arhiveCaterories = $('#categories').find('li.archive').map(function () {
        return $(this).data('id');
    }).get();
    removeExecutorsAndObserversByCategory(arhiveCaterories);
}

function getAutoAssignsUsersOnCategoryChange(serviceId, categoryIds) {
    var isFewExecutors = $("#fewExecutors").length > 0;


    $.ajax({
        contentType: 'application/json',
        url: 'Task/GetAutoAssignsUsersOnCategoryChange',
        data: JSON.stringify({
            serviceId: serviceId,
            categoryIds: categoryIds
        }),
        type: 'POST',
        success: function (json) {
            if (json && json.Data) {
                //clearUserWithoutCategory();
                //исполнители
                $.each(json.Data.Executors, function () {

                    if (!isFewExecutors) {
                        _addUserToList(this.Id, this.Name, this.Company.Name, "#executors", true, this.HashId, json.Data.CanRemoveExecutors, "GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].removeUser(this," + this.Id + "); return false;", this.CategoryId);
                        GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].BlockChange();
                    }
                    else
                        _checkExecutors(this.Id, "#executor", this, json.Data.CanRemoveExecutors, "GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].removeUser(this," + this.Id + "); return false;");
                    
                });

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

                    if (!isFewExecutors) {
                        _addUserToList(this.Id, this.Name, this.Company.Name, "#participants", true, this.HashId, json.Data.CanRemoveObservers, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + this.Id + "); return false;", this.CategoryId);
                        GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].BlockChange();
                    }
                    else
                        _checkObservers(this.Id, "#participant", this, json.Data.CanRemoveObservers, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + this.Id + "); return false;");
                });
                //группы исполнителей
                var def = new $.Deferred();
                if (json.Data.ExecutorGroup && json.Data.ExecutorGroup.length > 0) {
                    _executorGroupsSelected(json.Data.ExecutorGroup[0].Id, json.Data.ExecutorGroup[0].Name, json.CanRemoveExecutorGroup, json.Data.ExecutorGroup[0].CategoryId)
                        .then(function () { def.resolve(); });
                }
                else
                    def.resolve();
                def.done(function () {
                    clearUserWithoutCategory();
                    updateTask();
                });
            }
        }
    });
}
function onchangeCategories(ids) {

    var serviceId = $('#serviceid').val();

    initSelectedCategories(ids);

    getAutoAssignsUsersOnCategoryChange(serviceId, selectedCategories);

}
//#endregion

function taskCoordinationFormPrint(coordinationListId, taskid, taskLifeTimeId) {
    openDialog('Task/PrintCoordinationList/' + coordinationListId + '?popup=true&taskId=' + taskid + '&taskLifeTimeId=' + taskLifeTimeId);
    return false;
}
function taskCoordinationsFormPrint(taskId) {
    openDialog('Task/PrintCoordinationsList/' + taskId + '?popup=true');
    return false;
}
function taskHistory() {
    openDialog('taskhistory.ivp/list/' + $('#id').val() + "?reset=true", 'History');
    return false;
}
function addExpenses() {
    $('input:not("#addexpensesexecutor"),select', $('#addexpenses')).attr('disabled', false).removeClass('readonly');
    if ($('#addexpensesexecutor').val() == '') {
        $('#addexpensesexecutor').attr('disabled', false);
    }
    $('#addexpenses').show('fast', function () {
        $('html, body').animate({
            scrollTop: $("#addexpenses").offset().top
        }, 600);
    });

    var h = $("#addexpenses #exphours").val();
    var m = $("#addexpenses #expminutes").val();
    //#113360
    if (h != '00' || m != '00') {
        var minutes = parseInt(h, 10) * 60 + parseInt(m, 10);
        $("#addexpenses #exphours").val(h);
        $("#addexpenses #expminutes").val(m);
        $('#AddExpenses_Minutes').val(minutes);
    }
    $('#btnaddexpenses').hide();
    
    return false;
}
function cancelAddExpenses() {
    $('input,select', $('#addexpenses')).attr('disabled', true);
    $('#addexpenses').hide('fast', function () {
        $('#btnaddexpenses').show();
        //$('#btncanceladdexpenses').hide();
    });
    return false;
}
function removeExpenses(id) {
    var def = $.Deferred();
    if (!confirm(TaskResources.ConfirmDeleteExpense))
        return def.resolve(false).promise();

    var rows = $("#expenses" + id).closest('table').find('tr:not(.total)').length - 1;
    $.ajax({
        dataType: "json",
        url: 'Task/RemoveExpenses/',
        data: { id: id, changed: taskLastChanged },
        type: 'POST'
    }).done(function (result) {
        if (result.hasOwnProperty('IsOk') && result.IsOk === true) {
            if (rows == 1) {
                $('#expenses table[serverdata]').remove();
                $('#expenses').prepend('<div class="details indent10">' + TaskResources.NoExpenses + '</div>');
            }
            else {
                //Обновляем Итого
                if (result.TotalMinutes)
                    $("#totalminutes").text(result.TotalMinutes);
                if (result.TotalPrice)
                    $("#totalprice").text(result.TotalPrice);

                $('#expenses' + id).fadeOut('fast').remove();
            }
            if (result && result.Data) {
                $('#changed').val(result.Data);
                taskLastChanged = result.Data;
            }
            def.resolve(true);
        }
        else {
            alert(result.Description);
            def.resolve(false);
        }
    }).fail(function () {
        def.resolve(false);
    });

    return def.promise();
}

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({
        contentType: 'application/json',
        url: 'Task/GetWorkflowAndSla',
        data: JSON.stringify({
            taskId: taskId,
            serviceId: serviceId,
            field: entityName,
            priorityId: priorityId,
            creatorId: creatorId,
            workflowId: workflowId,
            statusId: statusId,
            taskTypeId: tasktypeId,
            assetIds: assetIds,
            categoryIds: catIds
        }),
        type: 'POST',
        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) {
                        var isFinal = 'True';
                        var isConcurrence = 'False';
                        if (option.IsFinal)
                            isFinal = 'False';
                        if (option.hasOwnProperty('IsConcurrence') && option.IsConcurrence) {
                            isConcurrence = 'True';
                        }


                        optionsHtml += '<option value="' + option.Id + '" data-final="' + isFinal + '" data-isconcurrence="' + isConcurrence + '">' + option.Name + '</option>';
                    });
                    
                    $status.html(optionsHtml).val(json.WorkflowData.SelectedStatusId).attr("selected", "selected");
                    if(json.WorkflowData.Statuses.length > 1)
                    $status.removeAttr('disabled');

                    $('[name="statusid"]').val(json.WorkflowData.SelectedStatusId);
                    $workflow.val(json.WorkflowData.WorkflowId);

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

                    onchangeStatus($status);
                }

                //Если в ответе пришел SLA
                if (json.SLAData) {
                    setSLA(json.SLAData.ResolutionTime, json.SLAData.ResolutionTimeLeft, 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 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($('#statusid'));
    }
    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 ($('#executors li[userid=' + userid + ']').length)
    //    $('#executorids option[value="' + userid + '"]').attr('selected', true);
    //else
    //    GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].assignSelfExecutor(few);

    //GLOBAL_taskFormHubObserver.getBlocks()['taskexecutors'].reassignExecutors(userid, few);
    getDefferedBlockByName('taskexecutors')
       .done(function (block) {
           block.reassignExecutors(userid, few);
       });

    return false;
}

function loadPriorityDescription() {
    var $priorityId = $('#priorityidselector');
    var priorityId = $priorityId.val();
    if (priorityId) {
        var description = $priorityId.find('option:selected').data('description');
        $priorityId.attr('title', description);
    } else {
        $priorityId.removeAttr('title');
    }
}

function unbindChildFromParent() {
    var taskId = $('#id').val();
    $.ajax({
        contentType: 'application/json',
        url: 'Task/UnbindTaskFromParent',
        data: JSON.stringify({
            id: taskId, changed: taskLastChanged
        }),
        type: 'POST',
        success: function (result) {
            if (result && result.Data) {
                $('#changed').val(result.Data);
                taskLastChanged = result.Data;
            }
                
            $('#taskchildrenplaceholder').load('Task/GetTaskChildren?id=' + taskId, function () {
                $('#dialog').empty();
                $('#dialog').append('<div class="warning padded5">' + TaskResources.ParentRemoved.format(taskId) + '</div><div class="spacer10"></div>');
                $('#parentchildholder').empty();
                $('#parentchildholder').load('Task/GetParentChild?id=' + taskId, function () {
                    $('.menu_vert').liMenuVert();
                });
            });
        }
    });
}

function ShowSiblings() {
    $('#taskchildrenplaceholder').load('Task/GetTaskChildren?id=' + $('#id').val() + '&showsiblings=true');
    return false;
}

function setSLA(resolutionTime, resolutionTimeLeft, reactionTime, serviceLevelName) {

    if (resolutionTimeLeft != '' && resolutionTimeLeft != $('#timeleft').val()) {
        $('#timeleft').attr('changed', true);
        $('#timeleft').val(resolutionTimeLeft).trigger('change');
        blinkbg($('#timeleft'));
    }

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

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

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

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

function showEstimatedDeadline() {
    var taskId = $('#id').val();
    //if ($('#timeleft').attr('changed') == "true" && (autoDeadline || $('#timeleft').attr('data-deadline'))) {
    //    $('#EstimatedDeadline').val(autoDeadline);
    //    //alertDialog('IntraService',TaskResources.EstimatedDeadline +(autoDeadline || $('#timeleft').attr('data-deadline')));
    //}
    //else {
        $.ajax({
            contentType: 'application/json',
            url: 'Task/GetEstimatedDeadline',
            data: JSON.stringify({
                taskId: taskId
            }),
            type: 'POST',
            success: function (json) {
                if (json) {
                    $('#EstimatedDeadline').val(json.Deadline);
                    //alertDialog('IntraService', json.Deadline);
                }
            }
        });
    //}
    return false;
}

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



function enableSystemFields() {
    //Включим дату
    $('#systemfields .readonlydate').each(function (i, e) {
        $(e).removeAttr('readOnly').removeClass('disabled').removeClass('readonlydate').removeClass('readonly').removeAttr('readonly').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();

            //если фокус попадает на скрытый элемент, то переводим его на ближайшее доступное поле
            if ($(".readonly:focus, .hidden:focus").length) {
                $('input:not(.readonly, .hidden, [type=hidden]), select:not(.readonly, .hidden), textarea:not(.readonly, .hidden)').first().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) {
                var $statusOption = $('#statusid option:selected');
                var isInitial = $statusOption.attr('data-isinitial') === 'True';
                var isFixed = $statusOption.attr('data-isfixed') === 'True';

                if ($(changedField).attr('id') == 'reactiondatefact' && !isInitial) {
                    alert(TaskResources.FactReactionDateWarning);
                    if ($(changedField).attr('oldvalue') == null)
                        $(changedField).val('');
                    else
                        $(changedField).val($(changedField).attr('oldvalue'));
                }
                else if ($(changedField).attr('id') == 'resolutiondatefact' && isFixed) {
                    alert(TaskResources.FactResolutionWarning);
                    if ($(changedField).attr('oldvalue') == null)
                        $(changedField).val('');
                    else
                        $(changedField).val($(changedField).attr('oldvalue'));
                }
                else if ($(changedField).val() != '') {
                    changeDates(changedField);
                }

            }
            else
                changeDates(changedField);
        }
    }
    return false;
}

function changeDates(changedField) {
    var $deadline = $('#deadline');
    var deadline = $deadline.val();
    var $changedField = $(changedField);
    var field = $changedField.attr('id');
    var taskId = parseInt($('#id').val());
    var serviceId = $('#serviceid').val();
    var date = $changedField.val();
    var $deadlinesystem = $('#deadlinesystem');

    if (field === 'deadlinesystem')
        deadline = date;


    $.ajax({
        contentType: 'application/json',
        url: 'Task/ValidateTaskTimeField',
        data: JSON.stringify({ taskId: taskId, serviceId: serviceId, date: date, field: field }),
        type: 'POST',
        success: function (validationResult) {
            if (validationResult && validationResult.ErrorMessage) {

                if (field == 'deadlinesystem')
                    $deadline.val(date);

                if (field === 'deadline')
                    $deadlinesystem.val(date);

                alert(validationResult.ErrorMessage);

            } else {
                $changedField.attr('oldvalue', date).attr('changed', true);

                if (field === 'deadlinesystem')
                    $deadline.attr('changed', true).attr('oldvalue', date);

                if (field === 'deadline')
                    $deadlinesystem.attr('oldvalue', date);

                if (taskId > 0) {

                    var statusId = $('#statusid').val();
                    var reactionPlan = $('#reactiondate').val();
                    var reactionFact = $('#reactiondatefact').val();
                    var deadlineFact = $('#resolutiondatefact').val();


                    $.ajax({
                        contentType: 'application/json',
                        url: 'Task/GetTaskTimeInfo',
                        data: JSON.stringify({
                            taskId: taskId,
                            serviceId: serviceId,
                            statusId: statusId,
                            reactionPlan: reactionPlan,
                            reactionFact: reactionFact,
                            deadline: deadline,
                            deadlineFact: deadlineFact
                        }),
                        type: 'POST',
                        success: function (taskTimeInfo) {

                            if (taskTimeInfo) {

                                if (taskTimeInfo.ReactionChanged) {

                                    var $reactionOverdueText = $('#reactionoverduetext');

                                    if (taskTimeInfo.ReactionOverdue == null)
                                        $reactionOverdueText.hide();

                                    if (taskTimeInfo.ReactionOverdue == false)
                                        $reactionOverdueText.removeClass('notoverdue overdue').addClass('notoverdue').show();

                                    if (taskTimeInfo.ReactionOverdue == true)
                                        $reactionOverdueText.removeClass('notoverdue overdue').addClass('overdue').show();

                                    $reactionOverdueText.empty().append(taskTimeInfo.ReactionMessage);

                                    $('#reactionplanspan').empty().append(taskTimeInfo.PlanReactionTime);

                                    $('#reactionfactspan').empty().append(taskTimeInfo.FactReactionTime);
                                }

                                if (taskTimeInfo.ResolutionChanged) {

                                    var $resolutionOverdueText = $('#resolutionoverduetext');

                                    if (taskTimeInfo.ResolutionOverdue == null)
                                        $resolutionOverdueText.hide();

                                    if (taskTimeInfo.ResolutionOverdue == false)
                                        $resolutionOverdueText.removeClass('notoverdue overdue').addClass('notoverdue').show();

                                    if (taskTimeInfo.ResolutionOverdue == true)
                                        $resolutionOverdueText.removeClass('notoverdue overdue').addClass('overdue').show();

                                    $resolutionOverdueText.empty().append(taskTimeInfo.ResolutionMessage);

                                    $('#resolutionplanspan').empty().append(taskTimeInfo.PlanResolutionTime);
                                    $('#resolutionfactspan').empty().append(taskTimeInfo.CleanAndTotalTime);
                                }

                            }
                        }
                    });
                }
            }
        }
    });
}

function recalculateDates(event, control) {
    event.preventDefault();
    var taskId = parseInt($('#id').val());
    if (!$(control).hasClass('disabledlink') && taskId > 0) {

        var serviceId = $('#serviceid').val();
        var statusId = $('#statusid').val();
        var recalculateDate = $('#recalculatedate').val();
        var reactionFact = $('#reactiondatefact').val();
        var deadlineFact = $('#resolutiondatefact').val();
        var taskId = parseInt($('#id').val());
    
                    $.ajax({
                        contentType: 'application/json',
                        url: 'Task/RecalculateReactionResolution',
                        data: JSON.stringify({
                            taskId: taskId,
                            serviceId: serviceId,
                            statusId: statusId,

                            recalculateDate: recalculateDate,
                            reactionFact: reactionFact,
                            deadlineFact: deadlineFact
                        }),
                        type: 'POST',
                        success: function (jsonMessage) {

                            if (jsonMessage.hasOwnProperty('IsOk') && !jsonMessage.IsOk) {
                                alert(jsonMessage.Description);
                            } else {

                                var taskTimeInfo = jsonMessage.Data;

                                if (taskTimeInfo) {
                                    $('#created').val(recalculateDate).trigger('change');

                                    var $reactionOverdueText = $('#reactionoverduetext');
                                    var $resolutionOverdueText = $('#resolutionoverduetext');

                                    if (taskTimeInfo.ReactionOverdue == null)
                                        $reactionOverdueText.hide();

                                    if (taskTimeInfo.ReactionOverdue == false)
                                        $reactionOverdueText.removeClass('notoverdue overdue').addClass('notoverdue').show();

                                    if (taskTimeInfo.ReactionOverdue == true)
                                        $reactionOverdueText.removeClass('notoverdue overdue').addClass('overdue').show();


                                    $reactionOverdueText.empty().append(taskTimeInfo.ReactionMessage);
                                    $('#reactionplanspan').empty().append(taskTimeInfo.PlanReactionTime);
                                    $('#reactionfactspan').empty().append(taskTimeInfo.FactReactionTime);

                                    $('#reactiondate').val(taskTimeInfo.ReactionDate).attr('changed', true).trigger('change');

                                    if (taskTimeInfo.ResolutionOverdue == null)
                                        $resolutionOverdueText.hide();

                                    if (taskTimeInfo.ResolutionOverdue == false)
                                        $resolutionOverdueText.removeClass('notoverdue overdue').addClass('notoverdue').show();

                                    if (taskTimeInfo.ResolutionOverdue == true)
                                        $resolutionOverdueText.removeClass('notoverdue overdue').addClass('overdue').show();

                                    $resolutionOverdueText.empty().append(taskTimeInfo.ResolutionMessage);

                                    $('#resolutionplanspan').empty().append(taskTimeInfo.PlanResolutionTime);
                                    $('#resolutionfactspan').empty().append(taskTimeInfo.CleanAndTotalTime); 

                                    $('#deadline').attr('changed', true).val(taskTimeInfo.Deadline).trigger('change');

                                    $('#deadlinesystem').val(taskTimeInfo.Deadline).trigger('change');

                                    $('#reactionAndResolutionChanged').val(true).trigger('change');
                                }
                            }
                        }
                    });
                }       
    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;
}


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

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

function showEvaluationPopup() {
    $('#evaluationholder').toggle();
    return false;
}

//#region Смена сервиса 

function changeServiceAjax() {
    $("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();

    $.get('Task/SelectService', { oldServiceId: $("#serviceid").val(), oldTypeId: $("#typeid").val() },
        function (data) {
            $("#changeservicedialog").html(data);
            $("#servicecontainer").height($("#changeservicedialog").height() - 100);

            $("#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();
        }
    );
    $('input,select', $('#addexpenses')).attr('disabled', true);
    $('#addexpenses').hide('fast', function () { $('#btnaddexpenses').show(); });

    return false;
}

function _restorePosition() {
    if ($('#serviceid').val()) {
        var $li = $('li.service[data-service-id="' + $('#serviceid').val() + '"]');
        if ($li.length > 0) {
            var $parent = $li.parents('li:first');
            if ($parent.length === 0)
                $parent = $li;
            var scroll = $parent.position().top - $('#servicecontainer').height() / 2;
            if (scroll < 0)
                scroll = 0;

            $('#servicecontainer').scrollTop(scroll);
        }

        $($li.parents('li').get().reverse()).trigger('click');
        if (!$li.hasClass('endpoint'))
            $li.trigger('click');
    }
}

function _selectServiceAjax(event) {
    var tariff = $('#tariff').val().toUpperCase();
    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()) {
        var oldServiceId = $('#serviceid').val();
        var oldTypeId = $('#typeid').val();
        $('#serviceid').val($li.attr('data-service-id'));

        if (Number($("#id").val()) > 0) {
            var proced = true;

            $.ajax({
                url: 'Task/UsersNotOnService',
                data: { taskId: $("#id").val(), newServiceId: $("#serviceid").val() },
                async: false,
                type: "GET"
            }).done(function (data) {

                if (data.hasOwnProperty("IsOk") && !data.IsOk) {
                    alert(data.Description);
                    proced = false;
                } else {

                    if (data.Data.Executors.length > 0 || data.Data.Observers.length > 0 || data.Data.Coordinators.length > 0 || data.Data.Creator != null) {
                        var notAssignUsers = "";
                        if (data.Data.Creator != null)
                            notAssignUsers = notAssignUsers.concat(TaskResources.Creator, data.Data.Creator, "; ");
                        if (data.Data.Executors.length > 0) {
                            notAssignUsers = notAssignUsers.concat(TaskResources.Executors, data.Data.Executors.join(', '), "; ");

                        }
                        if (data.Data.Observers.length > 0) {
                            notAssignUsers = notAssignUsers.concat(TaskResources.Observers, data.Data.Observers.join(', '), "; ");
                        }
                        if (data.Data.Coordinators.length > 0) {
                            notAssignUsers = notAssignUsers.concat(TaskResources.Coordinators, data.Data.Coordinators.join(', '), "; ");
                        }
                        var message = TaskResources.NotAllUsersOnNewServiceWarning.replace('{0}', notAssignUsers);
                        proced = confirm(message);

                    }
                }
            });
            if (!proced) {
                $("#changeservicedialog").remove();
                $("#bodyoverlay").remove();
                $('#serviceid').val(oldServiceId);
                $('#typeid').val(oldTypeId);
                return;
            }
        }

        $('#typeid').val($li.attr('data-type-id'));
        //if ($('#typeid').val() != '' && tariff != 'SAASPLUS' && tariff != '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");

        var taskTypeAction = $li.attr('data-url');

        if (typeof taskTypeAction !== 'undefined' && taskTypeAction !== false) {
            action = taskTypeAction;
        }

        window.onbeforeunload = null;

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

        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 windowScrollTop = $('#servicecontainer').scrollTop();
    var freeTop = $li.offset().top - windowScrollTop - (windowScrollTop < $('#serviceholder').offset().top ? $('#serviceholder').offset().top - windowScrollTop : 0);
    var freeBottom = $('#servicecontainer').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();
    }
}

//#endregion

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 checkForm() {
    if (formchanged == true && !confirm(FormResources.LeaveChangedForm)) return false;
    cancelUpload();
    return true;
}

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();

    var selectedId = parseInt($(this).find('option:selected').val());
    $('.treetypecombo').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') {
        $('#field' + fid).val(sel).trigger('change');
        return false;
    }
    else if ($('#field' + fid).hasClass("required"))
        $('#field' + fid).val("").trigger('change');
    else
        $('#field' + fid).val(sel).trigger('change');


    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)
            $select.insertAfter('[name=mfield' + fid + ']:last');
    });
}
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"); });
            $('#categoryids').trigger('change');
            $('#assetids').trigger('change');
        }
    }
}
//прикрепляем скриншот
function pasteScreenshot(url, imagesource) {
    $.ajax({
        url: url ? url : 'Task/PasteScreenShotDialog',
        data: { taskId: $('#id').val() },
        //async: false,
        success: function (data, textStatus, jqXHR) {
            var dialog = $('<div id="screenshotdialog"></div>').dialog({
                autoOpen: false,
                open: function () {
                    setParametersForScreenFrom(imagesource);
                    if($.browser.msie && $.browser.version > 10)
                        $('#screenshotarea').focus();
                },
                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 $source = $(source);
    var targetId = $source.attr('data-target');
    var $target = $('#' + targetId);
    var expensesId = $source.attr('id');
    var hours, minutes;
    if (expensesId.indexOf('_') > 0) {
        var id = getId(expensesId);

        hours = parseInt($('#exphours_' + id).val(), 10);
        minutes = parseInt($('#expminutes_' + id).val(), 10);
    } else {
        hours = parseInt($('#exphours').val(), 10);
        minutes = parseInt($('#expminutes').val(), 10);
    }

    $target.val(hours * 60 + minutes);
}

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


function closeTaskForm(self) {
    var $self = $(self);
    document.location.href = $self.attr('data-action');
    return;
}

//Поставить признак массовый инцидент из действий
function ChangeMassIncidentsProperty(taskId) {
    $.post("Task/ChangeMassIncidentsProperty", { taskId: taskId })
        .done(function (result) {
            if (result.IsOk) {
                var incidentAttr = 'data-' + !result.Data;
                var linkText = $('a.massIncident').attr(incidentAttr);
                $('a.massIncident').text(linkText);
                $('#Massincidents').val(capitaliseFirstLetter(result.Data.toString()));
            } else {
                alert(result.Description);
            }
        });
    return false;
}

function setEvaluation(ev) {
    ///<summary>выставить оценку заявке с карточки</summary>>
    ///<param name="ev" type="Element"></param>
    var iscommentRequired = $(ev).attr('data-commentrequired');
    var evaluationId = $(ev).attr('data-id');
    var isCommentRequired = iscommentRequired == 'True';
    if (isCommentRequired) {
        createModalDialog(TaskResources.CommentForEvaluationDialogTitle, '<textarea id="commentForEvaluation" rows="8" class="width98 autogrow required" style="height: 98%; min-width: 600px;"/>', function () {
            var comment = $('#commentForEvaluation').val();
            if (comment != '') {
                evaluateTask(evaluationId, true, comment);
            } else {
                jAlert(TaskResources.EnterComment, TaskResources.EvaluationCommentRequired);
                return false;
            }
        });
    } else {
        evaluateTask(evaluationId, false, '');
    }
    return false;
}

function evaluateTask(evaluationId, isCommentRequired, evalComment) {
    $.ajax({
        contentType: 'application/json',
        url: 'Task/EvaluateTask',
        data: JSON.stringify({ evaluateId: evaluationId, id: $('#id').val(), comment: evalComment, changed: taskLastChanged }),
        type: 'POST',
        success: function (result) {
            if (result && !result.IsOk) {
                alert('что-то пошло не так');
            } else if (result.IsOk && result.Data) {
                $('#changed').val(result.Data);
                taskLastChanged = result.Data;
                evaluteSuccess(evaluationId);
                if (isCommentRequired)
                    $('#lifetimeshort').load('Task/GetTaskLifetimeShort', { id: $('#id').val(), serviceId: $('#serviceid').val() }, function () {
                        if ($('#lifetimefull').attr('style') == 'display: block;')
                            switchLifetime();
                        $('#lifetimefull').empty();
                    });
            }
        }
    });
}
function evaluteSuccess(evaluateId) {
    if ($('#evaluationid'))
        $('#evaluationid').val(evaluateId);
    $('a.taskevaluatebtn ').remove();
    $('#taskevaluationmenuholder').remove();
    jAlert(TaskResources.TaskWasAssessed, TaskResources.TaskEvaluation);
    return false;
}

//Сделать первую букву в строке заглавной
function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

///добавляем обработчики события вставки в поля textarea Комментарий и Описание
function addPasteEvent() {
    var commentTextarea = $('textarea#currentcomment');
    var descriptionTextarea = $('textarea#description');
    if ($('#pastescreenbtn').length > 0 && (commentTextarea.size() > 0 || descriptionTextarea.size() > 0)) {
        //если это фаерфокс, то он не поддерживает возможность лазить по clipBoard, поэтому костыль: заменяем textarea элементы, на которые надо навешивать отслуживание paste на div с contenteditable
        if ($.browser.mozilla && $.browser.version < 50 || $.browser.msie) {
            $(document).keydown(function (e) {
                if (e.keyCode == 17) ctrlDown = true;
            }).keyup(function (e) {
                if (e.keyCode == 17) ctrlDown = false;
            });
            // заменяем для поля Комментарий            
            //проверим есть ли такое поле вообще (может быть убрано через настройки)
            if (commentTextarea.size() > 0 && !commentTextarea.hasClass('hidden')) {
                commentTextarea.keydown(function (e) {
                    //если прожали ctrl+v, то вставляем в див
                    if (ctrlDown && e.keyCode == 86) { positionStart = this.selectionStart; positionEnd = this.selectionEnd; $('#currentcommentdiv').focus(); }//return false;
                });
                $('body').append('<div id="currentcommentdiv" contenteditable="true"></div>');
                //$('<div id="currentcommentdiv" contenteditable="true"></div>').insertBefore(commentTextarea);
                var commentDiv = document.getElementById("currentcommentdiv");
                commentDiv.addEventListener("paste", function (e) { pasteScreenToFields(e, 'currentcomment', positionStart, positionEnd) });
            }

            //заменяем для поля Описание           
            //проверим есть ли textarea для описания: когда нет возможности редактировать - на форме есть только скрытый инпут.
            if (descriptionTextarea.size() > 0) {
                descriptionTextarea.keydown(function (e) {
                    //если прожали ctrl+v, то вставляем в див
                    if (ctrlDown && e.keyCode == 86) { positionStart = this.selectionStart; positionEnd = this.selectionEnd; $('#descriptiondiv').focus(); }
                });
                $('body').append('<div id="descriptiondiv" contenteditable="true"></div>');
                //$('<div id="descriptiondiv" contenteditable="true"></div>').insertBefore(descriptionTextarea);
                var descriptionDiv = document.getElementById("descriptiondiv");
                descriptionDiv.addEventListener("paste", function (e) { pasteScreenToFields(e, 'description', positionStart, positionEnd) });
            }
        }//chrome и хромоподобные, edge - позволяют лазить в clipBoard поэтому тут проще
        else {
            if (commentTextarea.size() > 0) {
                var comment = document.getElementById("currentcomment");
                comment.addEventListener("paste", function (e) { pasteScreenToFields(e, null, null, null); });
            }
            if (descriptionTextarea.size() > 0) {
                var description = document.getElementById("description");
                description.addEventListener("paste", function (e) { pasteScreenToFields(e, null, null, null); });
            }
        }
    }
}
//вставка текста из буфера обмена
function setSelectionRange(myValue, fieldId, selectionStart, selectionEnd) {
    var myField = $('#' + fieldId);
    myField.focus();
    if (selectionStart || selectionStart == '0') {
        var partOne = myField.val().substring(0, selectionStart);
        var partTwo = myField.val().substring(selectionEnd, myField.val().length);
        var result = partOne + myValue + partTwo;
        myField.val(result);
        setSelectionRange1(fieldId, selectionStart + myValue.length, selectionStart + myValue.length);
    } else {
        myField.val(myField.val() + myValue);
    }
}

function setSelectionRange1(inputId, selectionStart, selectionEnd) {
    var input = document.getElementById(inputId);
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

//#region EditComennt
var commentBeforeEdit;
var managedInTime = false;
var timeLeft = 0;
function editComment(e) {
    if (commentEditTimeout > 0) {
        managedInTime = true;
        timeLeft = commentEditTimeout;
        //Прячем существуеющий комментарий
        $(e).parent().hide();
        //Определяем с какого предстваления жизненного цикла вызавана функция
        var onFullLifeTime = $('#lifetimefull').is(':visible');
        var $currentlifetime = onFullLifeTime ? $('#lifetimefull') : $('#lifetimeshort');
        var $anotherlifetime = onFullLifeTime ? $('#lifetimeshort') : $('#lifetimefull');
        //Находим поле ввода комментария и сохраняем его значение до редактирования
        var $textarea = $currentlifetime.find('#editedcomment');
        if (commentBeforeEdit === undefined) commentBeforeEdit = $textarea.val();
        //Показываем блок редактирования
        $currentlifetime.find('div[name="EditCommentContainer"]').show();
        $textarea.removeAttr("disabled");
        $textarea.on('input', function () {
            //Синхронизируем поля редактирования комментариев на всех представлениях жизненного цикла
            $anotherlifetime.find('#editedcomment').val($textarea.val());
            //Не позволяем сохранить пустой комментарий
            var $applyButton = $('[name="ApplyEditComment"]');
            if ($textarea.val().trim() == '') {
                $applyButton.addClass("grey-filter");
                $applyButton.removeAttr('onclick');
                $applyButton.removeAttr('href');
            } else {
                $applyButton.removeClass("grey-filter");
                $applyButton.attr('href', '#');
                $applyButton.attr('onclick', 'applyEditComment(true); return false;');
            }
        }).off('change').elastic();//Отключаем предупреждение о изменениях на форме для этого поля и включаем эластик 
    }
} 
function applyEditComment() {
    var taskId = $("#id").val();

    if(GLOBAL_taskFormHubObserver){
        GLOBAL_taskFormHubObserver.CheckCanSubmitTaskForm();
    }

    $.post(base + 'Task/EditComment', {
        id: taskId,
        comment: $('#editedcomment').val(),
        changed: taskLastChanged,
        version: $('#version').val(),
        //пока что криво работает определение своего изменения
        //taskFormConnectionId: $('[name="taskFormConnectionId"]').val(),
        managedInTime: managedInTime
    }, function(result) {
        if (!result.IsOk) {
            alert(result.Description);
        } else if (result.IsOk) {
            $('#lifetimefull').load(base + 'Task/GetTaskLifeTimeFull/' + taskId);
            $('#lifetimeshort').load(base + 'Task/GetTaskLifetimeShort/', { id: taskId, serviceId: $('#serviceid').val() });
        }
    });
}

function cancelEditComment() {
    //Отменяем изменения на всех жизненных циклах
    $('textarea[name="EditedComment"]').val(commentBeforeEdit).trigger('input');

    var onFullLifeTime = $('#lifetimefull').is(':visible');
    var $currentlifetime = onFullLifeTime ? $('#lifetimefull') : $('#lifetimeshort');
    var $editcommentcontainer = $currentlifetime.find('div[name="EditCommentContainer"]');
    $editcommentcontainer.hide();
    var $textarea = $editcommentcontainer.find('#editedcomment');
    $textarea.attr("disabled", "disabled");
    $editcommentcontainer.parent().find('.comment').show();
}
//#endregion

//#region Наряды

$(document).ready(function () {

    jQuery.validator.addMethod("complexOrderTaskTypeValidator", function (value, element) {
        var $selectTaskType = $(element);
        var $tr = $selectTaskType.closest('tr');
        var $selectService = $tr.find('[name$=".TemplateServiceId"]');
        var result = false;
        $.ajax({
            url: 'ComplexOrderCommon/ValidateComplexOrderTaskTypeEx',
            type: "post",
            data:
            {
                taskTypeId: function () {
                    return $selectTaskType.val();
                },
                serviceId: function () {
                    return $selectService.val();
                }
            },
            async: false,
            success: function (data) {
                if (data) {
                    if (data.success) {
                        $selectTaskType.removeAttr('my-error-message');
                        result = true;
                    }
                    else {
                        $selectTaskType.attr('my-error-message', data.message);
                        result = false;
                    }
                }
                //result = data.toLowerCase() === 'true';
            }
        });
        return result;
    }, //'Данный тип заявки не назначен на сервис');
    function (error, element) {
        if (error) {
            return $(element).attr('my-error-message');
        }
        return '';
    });

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

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


    jQuery.validator.addMethod("required-span", function (value, element) {         
        var count_screenshots = $("#addscreenshots").children().length;
        var f = $("#files").find("li.changed").length;
        var count_file = $("#files").find("li").length - $("#files").find(".deletefile").length + $("#files").find("li.changed").length;
        if (count_file > 0 || count_screenshots > 0)
            return true;
        else
            return false;     
    }, TaskResources.DropFileValid);

    $('#complexOrderTemplatesTable').TableForm({
        removeConfirmMessage: ComplexOrderResources.SureDeleteOrder,
        removeIndirectlyServerEntity: false,
        onBeforeInitRow: function ($tr, alredyInit, entityType) {
            if (entityType == 'dynamic') {
                var $resolutionDate = $tr.find('[name$=".ResolutionDate"]');
                $resolutionDate.attr('disabled', 'disabled');
            }
        },
        onInitRow: function ($tr, entityType) {

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

            //, chooseMessage: '<span title="123">Автоматически</span>'

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

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

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

            if (!$selectExecutorUser.is('[multipleselect-off]')) {
                $selectExecutorUser.multipleSelect({ maxwidth: '300px', init: true, single: true, chooseMessage: $selectExecutorUser.attr('choose-message') });
            }

            if (!$selectExecutorGroup.is('[multipleselect-off]')) {
                $selectExecutorGroup.multipleSelect({ maxwidth: '300px', init: true, single: true, chooseMessage: $selectExecutorGroup.attr('choose-message') });
            }

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

                $selectService.valid();
                $selectTaskType.valid();
                if ($selectExecutorUser.length) {
                    $selectExecutorUser.valid();
                }
                if ($selectExecutorGroup.length) {
                    $selectExecutorGroup.valid();
                }
            });

            $selectTaskType.change(function (e) {
                if ($(this).is('select')) {
                    checkComplexOrderPermissions($tr);
                    recalcComplexOrderSlaOnCreate($tr);
                    getComplexOrderAutoAssignExecutors($tr);
                    //checkTaskTypeRequiredFields($tr);
                }

                $selectTaskType.valid();
            });

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

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

            $selectService.trigger('change');

        },

        onAfterInitRow: function ($tr) {
            setTimeout(function () {
                $tr.find('textarea').elastic();
            }, 1500);
        },
        onReindexElement: function ($tr, $element, index, oldName, newName) {
            if (oldName != newName && jQuery.multipleSelects != undefined && jQuery.multipleSelects[oldName] != undefined) {
                jQuery.multipleSelects[newName] = jQuery.multipleSelects[oldName];
            }
        },
        onAfterAddRow: function ($tr) {
            //этот метод вызовется в любов случае в событии onInitRow - $selectService.change
            //recalcComplexOrderSlaOnCreate($tr);
        }
    });
});

function showHideTaskParentDetails(that) {
    var $this = $(that);
    var $divTaskId = $this.closest('[taskid]');
    var taskId = $divTaskId.attr('taskid');
    var $divTaskDetails = $divTaskId.find('#taskdetails_' + taskId);
    if ($this.data('detailsIsShow')) {
        $this.data('detailsIsShow', false);
        $this.text(TaskResources.ShowDetails);
        $divTaskDetails.hide();
    }
    else {
        //TODO loc
        $this.text(TaskResources.HideDetails);
        $this.data('detailsIsShow', true);
        if ($divTaskDetails.data('taskIsLoaded')) {
            $divTaskDetails.show();
        }
        else {
            $divTaskDetails.find('.popup').load('Task/GetTaskDetailsTopFive/' + taskId, function () {
                $divTaskDetails.show();
                $divTaskDetails.data('taskIsLoaded', true);
            });
        }
    }
    return false;
}

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

    if ($selectExecutorUser.val() > 0 && $selectExecutorGroup > 0)
        return;

    var dataToServer = {
        serviceId: $selectService.val(),
        taskTypeId: $selectTaskType.val(),
        executorUserId: $selectExecutorUser.val(),
        executorGroupId: $selectExecutorGroup.val(),
        index: $tr.attr('index')
    };

    var req = $.post('ComplexOrderCommon/GetAutoAssignExecutors', dataToServer);
    req.done(function (data) {
        if (data) {
            var msUser = jQuery.multipleSelects[$selectExecutorUser.attr('name')];
            var $userNotEditContainer = $tr.find('td[executor-container="user"] > div[not-edit-container]');
            //if (msUser) {
                if (data.eus && data.eus.eid != 0) {
                    if (data.eus.ecount > 1) {
                        //автоматически
                        if (msUser) {
                            msUser.options.chooseMessage = "<span title='Правила назначения исполнителей определены на сервисе'> Автоматически </span>";
                        }
                        else if ($userNotEditContainer.length > 0) {
                            $userNotEditContainer.html("<span title='Правила назначения исполнителей определены на сервисе'> Автоматически </span>");
                        }
                        else {
                            //bad
                        }
                    }
                    else {
                        //добавить исполнителя
                        if (msUser) {
                            msUser.addSelectedValue(data.eus.eid, data.eus.ename);
                        }
                        else if ($userNotEditContainer.length > 0) {
                            $userNotEditContainer.text(data.eus.ename);
                        }
                        else {
                            //bad
                        }
                    }
                }
                else {
                    if (msUser) {
                        msUser.options.chooseMessage = MultipleSelectResources.Choose;
                    }
                    else if ($userNotEditContainer.length > 0) {
                        $userNotEditContainer.html('Не заданы');
                    }
                }
                if (msUser) {
                    msUser.optionsToString();
                }
            //}

                var msGroup = jQuery.multipleSelects[$selectExecutorGroup.attr('name')];
                var $groupNotEditContainer = $tr.find('td[executor-container="group"] > div[not-edit-container]');
            //if (msGroup) {
                if (data.egs && data.egs.eid != 0) {
                    if (data.egs.ecount > 1) {
                        //автоматически
                        if(msGroup){
                            msGroup.options.chooseMessage = "<span title='Правила назначения исполнителей определены на сервисе'> Автоматически </span>";
                        }
                        else if ($groupNotEditContainer.length > 0) {
                            $groupNotEditContainer.html("<span title='Правила назначения исполнителей определены на сервисе'> Автоматически </span>");
                        }
                        else {
                            //bad
                        }
                    }
                    else {
                        //добавить группу
                        if (msGroup) {
                            msGroup.addSelectedValue(data.egs.eid, data.egs.ename);
                        }
                        else if ($groupNotEditContainer.length > 0) {
                            $groupNotEditContainer.text(data.egs.ename);
                        }
                        else {
                            //bad
                        }
                    }
                }
                else {
                    //выбор
                    if (msGroup) {
                        msGroup.options.chooseMessage = MultipleSelectResources.Choose;
                    }
                    else if ($groupNotEditContainer.length > 0) {
                        $groupNotEditContainer.html('Не задана');
                    }
                }
                if (msGroup) {
                    msGroup.optionsToString();
                }
            }
    });
}

function checkComplexOrderPermissions($tr) {
    setTimeout(function () {
        var $selectTaskType = $tr.find('[name$=".TemplateTaskTypeId"]');
        var $selectService = $tr.find('[name$=".TemplateServiceId"]');
        var $resolutionDate = $tr.find('[name$=".ResolutionDate"]');
        var req = $.post('ComplexOrderCommon/CheckComplexOrderPermissions', { taskTypeId: $selectTaskType.val(), serviceId: $selectService.val() });
        req.done(function (result) {
            if (result) {
                if (result.CanEditResolutionDate) {
                    $resolutionDate.removeAttr('disabled');
                }
                else {
                    $resolutionDate.attr('disabled', 'disabled');
                }
            }
        });
    }, 0);
}

function checkTaskTypeRequiredFields($tr) {
    setTimeout(function () {
        var $selectTaskType = $tr.find('[name$=".TemplateTaskTypeId"]');
        var $requiredFieldsPlacement = $selectTaskType.closest('td').find('[required-fields-placement]');
        var req = $.post('ComplexOrderCommon/CheckTaskTypeRequiredFields', { taskTypeId: $selectTaskType.val() });
        req.done(function (result) {
            if (result && result.MainFieldsValid && result.AddFieldsValid) {
                    $requiredFieldsPlacement.hide();            
            }
            else {
                $requiredFieldsPlacement.show();
            }
        });
    }, 0);
}

//если есть tr - то считаем сроки только на этой строке
function recalcComplexOrderSlaOnCreate($tr) {
    //если в настройках отключено
    if (!($('#complexOrderTemplatesContainer').data('calculateoncreate'))) {
        return;
    }

    setTimeout(function () {
        var creatorId = $('#creatorid').val();

        //одним запросом пересчитываем сразу все сроки
        var dataToServer = { creatorId: creatorId };
        if ($tr && $tr.length > 0) {
            dataToServer['[0].RowIndex'] = $tr.attr('index');
            dataToServer['[0].TemplateServiceId'] = $tr.find('[name$=".TemplateServiceId"]').val();
            dataToServer['[0].TemplateTaskTypeId'] = $tr.find('[name$=".TemplateTaskTypeId"]').val();
        }
        else {
            var $trs = $('#complexOrderTemplatesTable').TableForm('getRows');
            $.each($trs, function (i, v) {
                var massBase = '[' + i + ']';
                var $v = $(v);
                var $selectService = $v.find('[name$=".TemplateServiceId"]');
                var $selectTaskType = $v.find('[name$=".TemplateTaskTypeId"]');
                dataToServer[massBase + '.RowIndex'] = $v.attr('index');
                dataToServer[massBase + '.TemplateServiceId'] = $selectService.val();
                dataToServer[massBase + '.TemplateTaskTypeId'] = $selectTaskType.val();
            });
        }

        var req = $.post('ComplexOrderCommon/GetTaskTableSlaOnCreate', dataToServer);
        req.done(function (data) {
            if (data && data.length > 0) {
                $.each(data, function (i, v) {
                    //if (v.ResolutionDate || v.ReactionDate) {
                        var $row = $('#complexOrderTemplatesTable').TableForm('getRowByIndex', v.RowIndex);
                        if ($row) {
                            var $resolutionDate = $row.find('[name$=".ResolutionDate"]');

                            if (v.ReactionDate) {
                                $row.find('[name$=".ReactionDate"]').val(v.ReactionDate);
                            }
                            if (v.ResolutionDate) {                           
                                $resolutionDate.val(v.ResolutionDate);
                                //подсветка инпута
                                $resolutionDate.css('background-color', '#fff7a8'); //.effect('highlight', { color: '#ffff99' }, 2500);
                                //сообщение которое удалится через N времени
                                var $resolutionDateWaring = $('<div>Обновлено</div>').css({ color: '#2e33fd' })
                                $resolutionDateWaring.insertAfter($resolutionDate);
                                setTimeout(function () {
                                    $resolutionDate.css('background-color', '#ffffff');
                                    $resolutionDateWaring.remove();
                                }, 2500);
                            }
                        }
                    //}
                });
            }
        }).fail(function (jqxhr, textStatus, error) {

        });
    }, 1000);
}

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

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


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

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

     url += ('msName=' + serviceName);
     url += '&reset=true';

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

    return false;
}

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

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

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

    url += '&tb_serviceid=' + serviceId;
    url += '&reset=true';

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

    return false;
}

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

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

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

    url += '&serviceid=' + serviceId;
    url += '&reset=true';

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

    return false;
}

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

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

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

    url += '&serviceid=' + serviceId;
    url += '&reset=true';

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

    return false;
}

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

//#endregion
//копировать ссылку на комент 
$('body').on('click', '.js-linklcopybtn', function (e) {
    e.preventDefault();

    var $this = $(this);
    var href = $this.attr('data-href');
    var $conteiner = $this.closest('.itemcomments');
    var $notySpan = $conteiner.find('.notyLink');

    function success() {
        $notySpan.text(TaskResources.LinkCopy)
        $notySpan.fadeIn("slow");
          $notySpan.css('backgroundColor', '#a8ffa1');
        setTimeout(function () {
            $notySpan.fadeOut("slow");
            $notySpan.css('backgroundColor', 'initial');
        }, 2000);
    }

    function error() {
        $notySpan.text(CommonResources.Error)
        $notySpan.fadeIn("slow");
      
          $notySpan.css('backgroundColor', '#ff5f5f');
        setTimeout(function () {
            $notySpan.fadeOut("slow");
            $notySpan.css('backgroundColor', 'initial');
        }, 2000);
    }

 
    if (window.clipboardData && window.clipboardData.setData) {     
        clipboardData.setData("Text", href);
        success();

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = href;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            document.execCommand("copy");  // Security exception may be thrown by some browsers.
            success();
        } catch (ex) {
            error();
        } finally {
            document.body.removeChild(textarea);
        }
    }

    return false;
})
// end копировать ссылку на комент 

$(document).on('change', '#SendDateRemind', function () {
    if($(this).val() == '' )
        $('#RemindTime').addClass('hidden');
    else {
        if ($('#RemindTime').hasClass('hidden'))
            $('#RemindTime').removeClass('hidden');
    }
})


function remindOnTask() {    
    var action = $('.actions').first();
    if ($('#remindpopup').length == 0) $('body').append('<div id="remindpopup" class="popupwrapperdownfixed"></div>');
    $.get('Task/RemindOnTask', { taskId: $('#id').val() }, function (data) {
        $('#remindpopup').remove();
        openModalOverlay('<div id="remindpopup" class="popupwrapperfixed">' + data + '</div>');
        positionPopup($('#remindpopup'), action);  
        $('#RemindTime').timepicker({
            timeFormat: 'HH:mm',
            interval: 30,
            minTime: '0',
            maxTime: '23',
            defaultTime: '8',
            startTime: '8:00',
            dynamic: false,
            dropdown: true,
            scrollbar: false
        });
        if (!$('#RemindTime').hasClass('hidden'))
            $('#RemindTime').timepicker().setTime($('#strTimeRemind').val())
    });
}

function removeRemind() {
    $.post('Task/RemoveRemindOnTask', { remindId: $('#RemindId').val() }, function (data) {
        if (data.success) {
            closeModalOverlay();
            $('#remindpopup').remove();
         
            showAlertRemind(TaskResources.DeleteRemind);
            $('#remindontask').empty().append(TaskResources.Remind);            
        }
    });
    return false;
}

function saveRemindOnTask() {  
    $('#remindpopup').find('#remindForm').validate({
        submitHandler: function (form) {
            $.post('Task/SaveRemindOnTask', { taskId: $('#id').val(), subject: $('#SubjectRemind').val(), message: $('#messageRemind').val(), planDate: $('#SendDateRemind').val(), remindTime: $('#RemindTime').val(), remindId: $('#RemindId').val() }, function (data) {
                if (data.success) {
                    closeModalOverlay();
                    $('#remindpopup').remove();
                 
                    showAlertRemind(TaskResources.SaveRemind);
                    $('#remindontask').empty().append(TaskResources.ActiveRemind);
                    return false;
                }
            });
        }
    });
    
}

function closeModalOverlay() {
    $('#RemindTime').timepicker().close();
    var $modalOverlay = $('.modalOverlay');
    if ($modalOverlay.length) {
        $modalOverlay.remove();
        $('body').css("overflow", "visible");
    }
    if ($('html').hasClass('noScrol'))
        $('html').removeClass('noScrol')
    return false;
}

function openModalOverlay(data) {

    var $modalOverlay = $('.modalOverlay');
    if (!$modalOverlay.length) {
        $modalOverlay = $('<div class="modalOverlay">');
        $('body').append($modalOverlay).css("overflow", "hidden");
    }
    if (!$('html').hasClass('noScrol'))
        $('html').addClass('noScrol')
    $modalOverlay.html(data);   
}

function showAlertRemind(textNoty) {
    var $notySpan = $('#notyRemind');
    
        $notySpan.text(textNoty)
        $notySpan.fadeIn("slow");
        $notySpan.css('backgroundColor', '#a8ffa1');
        setTimeout(function () {
            $notySpan.css('backgroundColor', 'initial');
            $notySpan.fadeOut("slow");           
        }, 3000)
    
}


function positionPopup($element, action) {
    var padding = 40;
    var paddingArrow = 16;
    var offsetWindow = action[0].getBoundingClientRect();
    var positionElTop = offsetWindow.top;
    var positionElLeft = offsetWindow.left;
 
   
    var innerH = $('body').height();
    var innerW = $('body').width();

    var w = innerW - positionElLeft + 250 - padding
    $element.css('width', w);
  

    var h = $element.height() ;
        $element.find('.popup').css('height', h)
        .css('overflow', 'auto');
    $element.removeClass("popupwrapperfixed").addClass("popupwrapperremind").css('left', positionElLeft - 250)
           .css('top', positionElTop - h - paddingArrow)
   
    $element.show();
}


$('body').on('click', '.js-linkcreatetaskbtn', function(e) {
        e.preventDefault();
        var parent = $(this).closest(".itemcomments")
        var description = $(parent).find(".comment pre").html();
        var $this = $(this);
        var userId = $this.data('user-id');
        if (description != null && description != undefined)
            AddNewTaskFromComment(userId, description);
        return false;
    });

function AddNewTaskFromComment(userId, description) {
    var typeId = $("#typeid").val();
    var serviceId = $("#serviceid").val();
    window.open(base + 'Task/Create?serviceid=' + serviceId + '&typeid=' + typeId + "&creatorId=" + userId + '&description=' + encodeURIComponent(description));
    return false;
}