/// <reference path="jquery.intellisense.js"/>
/// <reference path="common.js" />
/// <reference path="~/js/resizablegrid/resizable-grid.js" />

var dlg = null;




window.onresize = function () {
    if ($('.chosen-container').size() > 0) {
        if (window.innerWidth < 1395) {
            $('.chosen-container').css('width', '350px');
        }
        else {
            $('.chosen-container').css('width', '510px');
        }
    }
    if ($('span.pagingCurrent').size() > 0) {
        if (window.innerWidth < 1105) {
            $('span.pagingCurrent').hide();
        }
        else {
            $('span.pagingCurrent').show();
        }
    }
}

function setTaskAttributes() {
    var $tableholder = $('#tableholder');
    var $service = $('#serviceid');
    var ids = [];
    var serviceId = $service.val();
    $tableholder.find(':checkbox[name="id"]').each(function (index, item) {
        var val = $(item).val();
        if (val)
            ids.push(val);
    });
    if (ids.length > 0) {
        $.ajax({
            contentType: 'application/json',
            url: 'Task/GetTaskAttributes',
            data: JSON.stringify({ serviceId: serviceId, taskIds: ids }),
            type: 'POST',
            success: function (data) {
                if (data) {
                    //TODO:Добавить титл у картинки с учетом ресурсов.
                    var newCommentImg = '<img src="img/newcomment.png" class="imgnc" />';
                    $.each(data, function (index, attribute) {
                        if (attribute) {
                            if (attribute.NewTask)
                                $('#id' + attribute.TaskId).parents('tr:first').addClass('newtask');

                            if (attribute.NewComment) {
                                var $td = $('#id' + attribute.TaskId).parents('tr:first').find('td.taskname');
                                if ($td.length > 0) {
                                    $td.find('a.openlink').append(newCommentImg);
                                    $('#taskdescription_' + attribute.TaskId).remove();
                                }
                            }
                        }
                    });
                }
            }
        });
    }
}

//фильтр и табличное представление не применены - да\нет
function isFilterOrColumnNotActive() {
    return ($('#showfilter img') && $('#showfilter img').attr('src') && $('#showfilter img').attr('src').indexOf('_active') < 0 &&
        $('#showcolumns img') && $('#showcolumns img').attr('src') && $('#showcolumns img').attr('src').indexOf('_active') < 0);
}


function isFilterAndServiceNotApply() {
    return ($('#serviceid').val() == "0" && $('#showfilter img') && $('#showfilter img').attr('src') && $('#showfilter img').attr('src').indexOf('_active') < 0);
}

function toggleSearchWithoutFilter(isShow) {
    if (isShow) {
        $('.searchWithoutFilterActiveLink').removeClass('hidden');
        $('.searchWithoutFilterDisabledLink').addClass('hidden');
    } else {
        $('.searchWithoutFilterActiveLink').addClass('hidden');
        $('.searchWithoutFilterDisabledLink').removeClass('hidden');
    }
}


function searchWithoutFilter(link) {
    if (isFilterAndServiceNotApply()) {
        return false;
    }
    $('#tb_issearchwithoutfilter').val('True');
    //$(link).addClass('hidden');
    toggleSearchWithoutFilter(false);
    _taskSearch();
    return false;
}

$(function () {   
    if ($.browser.msie && parseInt($.browser.version, 10) <= 6) $("#filter-sticker").hide();
    initNotificationHolder();
    //Подключим плагин автозаполнения выпадающего списка только для Desktop-платформ
    if (!$.browser.mobile && !($.browser.msie && parseInt($.browser.version, 10) <= 7)) {
        $("select[id='serviceid']").chosen({ search_contains: true, is_last_element: $('#chosenIsLastElement').val(), no_results_text: TaskResources.ServiceNotFound, onsetstar: fsaveElectedState, onsavestatusorder: fsaveElectedOrder });
    }
    else {
        $("select[id='serviceid']").removeClass('visibilityhidden');
    }

    $('#serviceid').change(function () {
        //Уберем фильтр чтобы сбросить его состояние, ведь список статусов может измениться
        $('#filterholder').remove();
        selectedIds.length = 0;
        hideTaskDescription();
        $.get('Task/List', { tb_serviceid: $('#serviceid').val(), tb_page: 1 }, function (data) {
            $(tableRootDiv).html(data);

            if (initTable)
                initTable();

            initNotificationHolder();
            if (!isFilterAndServiceNotApply()) {
                toggleSearchWithoutFilter(true);
            } else {
                toggleSearchWithoutFilter(false);
            }
            changeResetButton();     
            
        });
    });

    if ($("#selectedservice").length > 0) {
        $("#serviceid").val($("#selectedservice").val());
        $("#serviceid").trigger("chosen:updated");
    }
    changeResetButton();
    $("#resetservice").removeClass("hiddenImportant");

    if (!isFilterAndServiceNotApply()) {
        toggleSearchWithoutFilter(true);
    } else {
        toggleSearchWithoutFilter(false);
    }
    //если на списке присутствует форма подсказки по поиску, навесим событие обработки клика по области вне этой подсказки - она должна скрываться
    if ($("#searchSettingsForm")) {
        $(document).mouseup(function (e) {
            var container = $("#searchSettingsForm");
            //если это не клик по кнопке "показать настройки поиска", подсказка видна и мы кликаем не в ее области - то скрываем ее
            if (container.is(":visible") && container.has(e.target).length === 0) {
                toggleSearchSetting($('.btnSearchSetting'), false);
            }
        });
    }

});

function fsaveElectedState(event) {
    var star_parent = $(event.srcElement || this).parent().parent();
    var isElected = star_parent.attr("data-elect") == "False";
    var mvalue = star_parent.attr("id").substring("service_chosen".length);
    $.post(base + 'serviceuser.ivp/changestate', { serviceid: mvalue, date: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else {
            result = JSON.parse(result);
            if (result.hasOwnProperty('IsOK') && result.IsOK == false) 
                alert(result.Description);
            else {
                $("#serviceid").saveElectedState(result.Name, result.Value, result.Path, isElected);
            }    
        }
    });
    return false;
}

function fsaveElectedOrder(event) {
    $("#serviceid").saveElectedOrder(event.srcElement || event.originalEvent.target);
    event.stopPropagation();
    var ids = new Array;
    var sortableitems = $('ul.sortable li[data-elect=True]');
    sortableitems.each(function () {
        ids.push($(this).attr("id").substring("service_chosen".length));
    });
    $.getJSON(base + 'serviceuser.ivp/SaveOrder', { ids: ids });
}

function changeResetButton() {
    if ($('#resetservice').length) {
        if ($('#serviceid').val() > 0) {
            $("#resetservice").removeClass("disabled");
            $('#resetservice img').attr('src', $('#resetservice img').attr('src').replace('_gray', ''));
        }
        else {
            $("#resetservice").addClass("disabled");
            $('#resetservice img').attr('src', $('#resetservice img').attr('src').replace('_gray', '').replace('.gif', '_gray.gif'));

        }
    }
}
function toDefaultService() {
        if ($('#resetservice').hasClass('disabled')) return false;
        $("#serviceid").val("0");
         $("#serviceid").trigger("chosen:updated");
        $('#serviceid').change();
        changeResetButton();
        return false;
}

function dotasksearch(evt) {
    var e = ($.browser.msie) ? event : evt;
    var keycode = ($.browser.msie) ? e.keyCode : e.which;
    if (keycode == 13)
        return _taskSearch(false);
    else {
        enableOrDisableClear();
        return true;
    }
}

// появление окна настроек поиска
function toggleSearchSetting(link, isShowSetting) {
   // var img = $(link).find('img');
    if (!isShowSetting) {//&& $(img).attr('src').indexOf('_active') >= 0) {
        $("#searchSettingsForm").hide();
        $(link).removeClass('active');
        //$(img).attr('src', $(img).attr('src').replace('setting23_active.png', 'setting23.png'));
    } else {
        //$(img).attr('src', $(img).attr('src').replace('setting23.png', 'setting23_active.png'));
        $(link).addClass('active');
        $("#searchSettingsForm").show();
    }
    return false;
}

function toggleBtnSearchSetting(btn) {
    if ($(btn).hasClass('active')){//find('img').attr('src').indexOf('_active') >= 0) {
        toggleSearchSetting(btn, false);
    } else {
        toggleSearchSetting(btn, true);
    }
    return false;
}

window.overrideParamLoadState = function (params) {
    params[params.length] = { name: 'tb_tasksearchfilter', value: '' };
    $('div#newsearchul div').remove();
    $('#btnClearSearch').addClass('hiddenClearSearch');
}


window.saveStateParams = function (params) {
    var stringValue = '';
    $.each($('div#newsearchul div.bit-box'), function (i, elem) {
        stringValue += ($(elem).attr('categoryDetails') != null) ? $(elem).attr('rel') + $(elem).attr('categoryDetails') + '|' : $(elem).attr('rel') + '|';
    });
    params[params.length] = { name: 'tb_tasksearchfilter', value: stringValue };
}


window.afterSearch = function (json) {
    if (json.hasOwnProperty('IsOK'))
        //redirect to ticket
        window.location = base + 'task/view/' + json.Id;
};
window.afterApplyFilter = function () {
    if ($("#selectedservice").length > 0) {
        $("#serviceid").val($("#selectedservice").val());
        $("#serviceid").trigger("chosen:updated");
    }
    $.ajax({
        url: base + 'Task/GetSearchPartView',
        success: function (data) {
            $('#newsearch').parent('div').remove();
            $('#rightmenucontent').prepend(data);
            changeResetButton();
            toggleSearchWithoutFilter(true);
            newsearchAutocomplete();
        }
    });    
};
window.afterSearchAndInitTable = function () { 
    isSearchMore();
    if ($('#tableholder table td.taskid').size() < 5) {//$('#tableholder table td.taskid').size() != 1 &&
        toggleSearchSetting($('.btnSearchSetting'), true);
    }
    handleFilterToolbarState();
    $('ul.filterlist li.selected').removeClass('selected');
};
window.afterFilterAndInitTable = function () {
    if (!isFilterAndServiceNotApply()) {
        toggleSearchWithoutFilter(true);
    } else {
        toggleSearchWithoutFilter(false);
    }

    if ($("#selectedservice").length > 0) {
        $("#serviceid").val($("#selectedservice").val());
        $("#serviceid").trigger("chosen:updated");
    }
    changeResetButton();
};


window.afterClearFilter = function () {
    if (!isFilterAndServiceNotApply()) {
        toggleSearchWithoutFilter(true);
    } else {
        toggleSearchWithoutFilter(false);
    }
    $('div#newsearchul div').remove();
    $('#newsearch').val('');
    $('#btnClearSearch').addClass('hiddenClearSearch');
    $('.searchMore').addClass('hidden');
    $('.searchMoreDisabled ').removeClass('hidden');
    if ($("#selectedservice").length > 0) {
        $("#serviceid").val($("#selectedservice").val());
        $("#serviceid").trigger("chosen:updated");
    }
    changeResetButton();
};

window.beforeApplyColumns = function () {
    if (!$('#columns form').validate().element('#tb_pagesize')) {
        return false;
    }
    return true;
};


window.afterInitTable = function () {
    if (!isFilterAndServiceNotApply()) {
        toggleSearchWithoutFilter(true);
    } else {
        toggleSearchWithoutFilter(false);
    }
    if ($('span.pagingCurrent').size() > 0) {
        if (window.innerWidth < 1105) {
            $('span.pagingCurrent').hide();
        }
        else {
            $('span.pagingCurrent').show();
        }
    }
    $('.table-action-buttons').empty().append($('.tableholder-top').remove().children());
    $('.table-pagination').empty().append($('#pagination'));

    setTaskAttributes();
    $('.taskname span').mouseover(showTaskDescription).mouseout(function () {
        showtd = false;
        clearTimeout(sid);
        hid = setTimeout('hideTaskDescription()', 400);
    }).click(function () { showtd = false; });

    $('.showTreeView').mouseover(function () {
        showtd = true;
        var elem = $(this);
        sid = setTimeout(function () { showTreeDescription(elem); }, 700);
        clearTimeout(hid);
    }).mouseout(function () {
        showtd = false;
        clearTimeout(sid);
        hid = setTimeout('hideTreeDescription()', 400);
    }).click(function () { showtd = false; });

    $('.statusicon').click(chooseStatus);
    $('.priorityicon').click(choosePriority);
    $('.mirowid').click(function () { selectRow(this.value, this.checked); });

    InitResizableGrid('table.resizable-grid', window.getHeightTableHolder(95));
    setFooterTop();

    //на странице запоминает проставленные чекбоксы, например при постраничной навигации, и из-за этого был баг с опцией
    setActionsSelectedTasksCount($('.rowid:checked').length);
};

function rowChecked(val, check) {
    var $actions = $('#actions');
    var count = $actions.data('selectedTasksOnPage') || 0;
    if (check) {
        count++;
    }
    else {
        count = count > 0 ? (count - 1) : 0;
    }
    setActionsSelectedTasksCount(count);
    return true;
};

function setActionsSelectedTasksCount(count) {
    var $actions = $('#actions');
    var $option = $actions.find('option[copytask]')
    if (count != 1) {
        $option.attr('disabled', '');
    }
    else {
        $.ajax({
            url: 'Task/CheckIsExecutor',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ Id: selectedIds[0] }),
            success: function (data) {
                if (data && data.isOk) {
                    $option.removeAttr('disabled');
                }
            }
        });
        
    }
    $actions.data('selectedTasksOnPage', count);
}


function setFooterTop() {
    if ($("#content").height() > $("#rightmenu").height() && !$("#rightmenucontent").hasClass("hidden")) {
        var heightCont = $("#content").height() + $("#header").height();
        var heightRight = $("#rightmenucontent").height() + $("#header").height();

        $("#footer").css("top", heightCont - heightRight);
    }
}

function initNotificationHolder() {
    var $selectedOption = $('#serviceid option:selected');
    var serviceId = $selectedOption.attr('value');
    var hasChild = $selectedOption.attr('data-haschild');

    var $notificationHolder = $('#notificationholder');
    if ($notificationHolder.length < 1) return false;

    if (serviceId && parseInt(serviceId) > 0 && hasChild === 'False' && $('#tableaction').length) {
        $notificationHolder.empty();
        $notificationHolder.show();
        var $link = $('<a/>').attr('href', '#').click(function () {
            return window.editRule({ serviceId: serviceId, fromTaskList: true }, this);
        }).addClass('link').text(TaskResources.NotificationRules);
        $notificationHolder.append($link);
    } else {
        $notificationHolder.hide();
    }

    return false;
}

function addStatusNoIcon(checkbox) {
    var parent = $(checkbox).parent();
    if (checkbox.checked) {
        var scbhtml = '';
        scbhtml = initStatus($(checkbox).val(), parent.text(), true);
        $('.selectedstatuses').append(scbhtml);
        $('.statusapply').click(applyStatusTemplates);
    }
    else {
        var delId = "#delstatus_" + $(checkbox).val();
        removeSelectedStatus($(delId), $(checkbox).val());
    }
}

function hideTreeDescription() {
    $('.treeView').hide();
}

function showTreeDescription(elem) {
    if (!showtd) return;

    var id = $(elem).data('taskid');
    var mode = $(elem).data('parentmode');
    var tdkey = '#treeView' + mode + '_' + id;
    $('.treeView').hide();

    var offset = $(elem).offset();
    var h = $(elem).height();
    var w = $(window).width();
    // if (w < 400) w = 400;
    // if (w > 900) w = 900;

    if ($(tdkey).length > 0) {
        $(tdkey).css('top', offset.top + h).css('left', offset.left).css('width', w - offset.left);
        $(tdkey).fadeIn('fast');
    }
    else {
        $('body').append('<div id="treeView' + mode + '_' + id + '" class="treeView popupwrapper"><div class="popup"></div></div>');
        $(tdkey).css('top', offset.top + h).css('left', offset.left).css('width', w - offset.left);
        $(tdkey).mouseover(function () { clearTimeout(hid); }).mouseout(function () { hid = setTimeout('hideTreeDescription()', 500); });
        $('.popup', $(tdkey)).load('Task/GetTaskTreeView/' + id + '?isParentMode=' + mode, function () {
            if (!showtd) return;
            $('.popup', $(tdkey)).bgiframe();
            $(tdkey).show();
        });
    }
}

//Показать/скрыть описание заявки
function showTaskDescription() {
    var id = this.id;
    var that = this;
    showtd = true;
    //sid = setTimeout('_showTaskDescription("' + id + '")', 500);
    sid = setTimeout(function () {
        _showTaskDescription(id, that);
    }, 500);
    clearTimeout(hid);
}
function hideTaskDescription() {
    $('.taskdescription').hide();
}
function _showTaskDescription(tid, that) {
    if (!showtd) return;
    var id = getId(tid);
    if ($('#taskname_' + id).length == 0) return;

    var tdkey = '#taskdescription_' + id;
    $('.taskdescription').hide();
    var el = that == undefined ? $('#taskname_' + id) : $(that);
    var offset = that == undefined ? $('#taskname_' + id).offset() : $(that).offset();
    var h = that == undefined ? $('#taskname_' + id).height() : $(that).height();
    var w = $(window).width() - 300;
    if (w < 400) w = 400;
    if (w > 900) w = 900;

    if ($(tdkey).length > 0) {
        positionPopup($(tdkey), el,w)     
    }
    else {
     
        $('body').append('<div id="taskdescription_' + id + '" class="taskdescription popupwrapperfixed"><div class="popup"></div></div>');      
        $(tdkey).mouseover(function () { clearTimeout(hid); }).mouseout(function () { hid = setTimeout('hideTaskDescription()', 500); });
        $('.popup', $(tdkey)).load('Task/GetTaskDetails/' + id, function () {
            if (!showtd) return;
            $('.popup', $(tdkey)).bgiframe();
            positionPopup($(tdkey), el, w)
            $(tdkey).show();
            $('#taskname_' + id).parents('tr:first').removeClass('newtask').addClass('hidetaskmi').find('.imgnc').hide();
        });
    }
}

function setMode(mode) {
    $('#fltmode').val(mode);
    reloadTable();
    return false;
}


//Групповые операции
function triggerAction() {
    var action = $('#actions').val();
    $('#actions').val('');
    eval(action);
}
//Пометить заявки как прочитанные
function markAsRead() {
    if (selectedIds.length == 0) {
        alert(TaskResources.CheckTasksToMarkAsRead);
        return false;
    }
    $.ajax({
        url: 'Task/MarkTasksAsRead',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({ taskIds: selectedIds }),
        success: function () { $(tableRootDiv).load(tableUrl(), initTable); }
    });

    return false;
}
//Изменить статус
function chooseStatus() {
    var mass = $("#tableholder table.data td:first-child input:checked").length > 0;
    var img;

    if (this.tagName == 'IMG') img = $(this);
    else img = $($('tr.selected .statusicon').get(0));

    if (!img.attr('taskid')) {
        alert(TaskResources.CheckTasksToChangeStatus);
        return;
    }

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

    if ($('#id' + taskid).length == 0) return;  
    if ($('#choosestatus').length == 0) $('body').append('<div id="choosestatus" class="popupwrapperfixed"></div>');

    $.get('Task/GetPossibleStatuses', { taskId: taskid, statusId: statusid, isMass: mass }, function (data) {     
        $('#choosestatus').remove();
        openModalOverlay('<div id="choosestatus" class="popupwrapperfixed">' + data + '</div>');
        positionPopup($('#choosestatus'), img);
    });
}



function addCommentView() { 
    var img;

    if (this.tagName == 'IMG') img = $(this);
    else img = $($('tr.selected .statusicon').get(0));

    if (!img.attr('taskid')) {
        alert(TaskResources.WantAddComment);
        return;
    }

    var taskid = img.attr('taskid');   
    var Ids = selectedIds.length === 1 ? null : selectedIds;
    if ($('#id' + taskid).length == 0) return;
    if ($('#addcommentcontains').length == 0) $('body').append('<div id="addcommentview" class="popupwrapperfixed"></div>');

    $.ajax({
        url: 'Task/GetViewAddComment',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({ taskId: taskid, taskIds: Ids }),
        dataType: 'html',
        success: function (data) {
            $('#addcommentview').remove();
            openModalOverlay('<div id="addcommentview" class="popupwrapperfixed">' + data + '</div>');
                positionPopup($('#addcommentview'), img);
        }
    });
}

function AddComent(taskid) {
    $('#addcommentcontains').hide();
    var Ids = selectedIds.length === 1 ? null : selectedIds;
        $.ajax({
            url: 'Task/AddComentTaskList',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({ taskId: taskid, taskIds: Ids, comment: $('#commentChangetStatus').val() }),
            dataType: 'json',
            success: function (result) {
                if (result.hasOwnProperty('IsOk') && !result.IsOk)
                    alert(result.Description);
                else {
                    var curl = base + "task/" + result.Data.Action + "/";
                    $(tableRootDiv).load(tableUrl(), initTable);                    
                }
            }
        });
    closeModalOverlay();
    return false;
}

function changeStatus(taskid, statusid) {

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

    if (selectedIds.length === 0) {

        $.ajax({
            url: 'Task/ChangeTaskStatus',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({ taskId: taskid, statusId: statusid, comment: $('#commentChangetStatus').val() }),
            dataType: 'json',
            success: function (result) {
                if (result.hasOwnProperty('IsOk') && !result.IsOk)
                    alert(result.Description);
                else {
                    var curl = base + "task/" + result.Data.Action + "/";

                    if (result.Data.Action != "List") {
                        curl += result.Data.Id;
                        document.location = curl + "?tostatus=" + result.Data.StatusId;
                    }
                    else {
                        $(tableRootDiv).load(tableUrl(), initTable);
                    }
                }
            }
        });

    } else {

        $.ajax({
            url: 'Task/ChangeTasksStatuses',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({ taskIds: selectedIds, statusId: statusid,comment: $('#commentChangetStatus').val() }),
            dataType: 'json',
            success: function (result) {
                if (result.hasOwnProperty('IsOk') && !result.IsOk)
                    alert(result.Description);
                else {
                    if (result.Description && result.Description != "")
                        alert(result.Description);
                    selectedIds.length = 0;
                    $(tableRootDiv).load(tableUrl(), initTable);

                }
            }
        });

    }
    closeModalOverlay();
    return false;
}

//назначение исполнителей со списка заявок
function chooseExecutors() {
    if (this.tagName == 'IMG') img = $(this);
    else img = $($('tr.selected .statusicon').get(0));

    var serviceid = $('#serviceid option:selected').val();
    if (serviceid == '0') {
        alert(window.TaskResources.ChooseService);
        return;
    }

    if (!img.attr('taskid')) {
        alert(window.TaskResources.CheckTasksToChooseExecutors);
        return;
    }

    var url;
    if ($('#assignselfexecutor').length > 0 && $('#assignselfexecutor').val().toLowerCase() == 'true') {
        url = 'user.ivp/select?cbmode=TaskList&tb_mode=self&tb_serviceid=' + serviceid;
    } else {
        if ($('#assignotherexecutors').length > 0 && $('#assignotherexecutors').val().toLowerCase() == 'true')
            url = 'user.ivp/select?cbmode=TaskList&tb_mode=executors&tb_serviceid=' + serviceid;
        else {

            alert(window.TaskResources.DescriptionErrorAssignExecutors);
            $(window.tableRootDiv).load(window.tableUrl(), { nolayout: true, timestamp: new Date().toString() }, window.initTable);
            window.selectedIds.length = 0;
            return;
        }
    }
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = TaskList.usersCallback;
}

//назначение группы исполнителей со списка заявок
function chooseExecutorGroup() {
 
    var serviceid = $('#serviceid option:selected').val();

    if (serviceid == '0') {
        alert(window.TaskResources.ChooseService);
        return;
    }

    dlg = openDialog('executorgroup/select?targetBlock=ExecutorGroupItemData&tb_mode=SERVICEGROUPS&tb_serviceid=' + serviceid);
    dlg.callback = TaskList.selectExecutorGroupsCallback;
}

var TaskList = {
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        addusersselect(uids);
    },
    selectExecutorGroupsCallback: function selectExecutorGroupsCallback(result) {
        var ids = result["selectedIds"];
        addExecutorGroupSelect(ids[0]);
    }
}

function addExecutorGroupSelect(id) {
    $.ajax({
        url: 'Task/SaveExecutorGroupToManyTask',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({ executorGroupId: id, taskIds: selectedIds, serviceId: $('#serviceid option:selected').val() }),
        dataType: 'json'
    }).done(function (result) {
        if (result.hasOwnProperty('IsOk') && !result.IsOk) {
            alert(result.Description);
            $(tableRootDiv).load(tableUrl(), initTable);
        }
        else {
            selectedIds.length = 0;
            if (result.Description != null && result.Description != '')
                alert(result.Description);
            $(tableRootDiv).load(tableUrl(), initTable);
        }
    });
}

function addusersselect(executorIds) {
    //костыль для ie которое не умеет в массивы
    var ieExecutorIds = new Array();
    $.each(executorIds, function (id, el) {
        ieExecutorIds.push(el);
    });
    var ids = selectedIds;
    $.ajax({
        url: 'Task/SaveExecutorsToManyTask',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({ executorIds: ieExecutorIds, taskIds: ids, serviceId: $('#serviceid option:selected').val() }),
        dataType: 'json',
        success: function (result) {
            if (result.hasOwnProperty('IsOk') && !result.IsOk) {
                alert(result.Description);
                $(tableRootDiv).load(tableUrl(), initTable);
            }
            else {
                selectedIds.length = 0;
                if (result.Description != null && result.Description != '')
                    alert(result.Description);
                $(tableRootDiv).load(tableUrl(), initTable);
            }
        }
    });
}




//Изменить приоритет
function choosePriority() {
    var img;
    if (this.tagName == 'IMG') img = $(this);
    else img = $($('tr.selected .priorityicon').get(0));

    if (!img.attr('taskid')) {
        alert(TaskResources.CheckTasksToChangePriority);
        return;
    }

    var taskid = img.attr('taskid');

    if ($('#id' + taskid).length == 0) return;
    if ($('#choosepriority').length == 0) $('body').append('<div id="choosepriority" class="popupwrapperfixed"></div>');

    $.get('Task/GetPossiblePriorities', { taskId: taskid }, function (data) {      
        $('#choosepriority').remove();
        openModalOverlay('<div id="choosepriority" class="popupwrapperfixed">' + data + '</div>');
        positionPopup($('#choosepriority'), img)
    });
}


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


function changePriority(taskid, priorityid) {
    $('#choosepriority').hide();
    if ($('#servicelevelid').val() && $('#isinitialstatus_' + taskid).val() == 'true') {
        if (!confirm(TaskResources.SureChangePriority)) return false;
    }
    var ids = selectedIds;
    if (ids.length == 0)
        ids = [taskid];


    $.ajax({
        url: 'Task/ChangePriority',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({ taskIds: ids, priorityId: priorityid }),
        dataType: 'json',
        success: function (result) {
            if (result.hasOwnProperty('IsOk') && !result.IsOk)
                alert(result.Description);
            else {
                if (result.Description && result.Description != "")
                    alert(result.Description);
                selectedIds.length = 0;
                $(tableRootDiv).load(tableUrl(), initTable);
            }
            closeModalOverlay();
        }
    });

    return false;
}

function changeMassIncidentPage(page) {
    $('#massincidentsholder').load(base + 'task.ivp/changepage', { page: page, timestamp: new Date().toString() });
    return false;
}

function changeUserNotificationRules() {

}

function toggleMassIncidents(isChange) {
    var currentSetting = $("#HideAllMassIncidents").val();

    if (isChange) {
        var newVal = currentSetting == "False" ? "True" : "False";
        $.cookie("tb_hideallmassincidents", newVal);
        currentSetting = newVal;
    }

    if (currentSetting == "True") {
        $(".hidetaskmi").hide();
        var countTr = $("#tablemassincidents tr").size();
        var countTrhide = $("#tablemassincidents tr.hidetaskmi").size();
        if (countTr - countTrhide == 1) {
            $("#tablemassincidents").hide();
        }

        $("#amass-incidents").html(window.TaskResources.ShowMassIncidents);


    } else {
        $("#tablemassincidents").show();
        $(".hidetaskmi").show();
        $("#amass-incidents").html(window.TaskResources.HideMassIncidents);
        $("#tabletablemassincidents").show();
    }

    $("#HideAllMassIncidents").val(currentSetting);

    //  window.location = window.base + 'task.ivp/list/';

    //var height = $(window).height() - $('div.k-grid').position().top - window.getHeightTableHolder(95);
    var height = $(window).height() - $('div.k-grid').position().top - window.getHeightTableHolder(95);
    if (height < 200)
        height = 200;

    $(".k-grid-content").css("height", height - 25);
    $(".k-grid").css("height", height);
    $(".k-grid").parent().css("height", height);
    //alert(height);
}

function mergeTasks() {
    if (selectedIds.length <= 1) { alert(TableResources.NoMergeRecordsSelected); return false; }
    this.$content = $('#content');

    $.get('Task/MergeTicketDialog', function (html) {
        $content.append(html);
        $('#serchfields').hide();
        $('#searchFullLink').hide();
        $('#parenttasklist').show();
        var $parentexist = $('ul.parentexist');

        $.ajax({
            contentType: 'application/json',
            url: 'Task/GetTicketsByIds',
            data: JSON.stringify({
                ids: selectedIds
            }),
            type: 'POST',
            success: function (message) {
                if (message) {
                    if (!message.IsOk) {
                        $('#parenttasklist').hide();
                        $('#mergetask .desc').text(message.Description).show();
                    } else {
                        if (message.Description) {
                            $('#mergetask .desc').text(message.Description).show(); //Если выдано сообщение
                        }

                        if (message.Data) {
                            $('#parenttasklist').show();

                            $.each(message.Data, function (index, task) {
                                var element = createElement(task);
                                $parentexist.append(element);
                            });
                        }
                    }
                }
            }
        });

        $('html').scrollTop(0);
    });

    var createElement = function (task) {
        var result = [];

        var $li = $('<li class="ticketnumber ticketlabel">#</li>');
        var $span = $('<span class="ticketshow"></span>').text(task.Id);
        var $a = $('<a class="js-mergeToParent pointer" title="Выбрать заявку"></a>').attr('data-taskId', task.Id).append($span);

        result[0] = $li.append($a);
        result[1] = $('<li class="ticketname"></li>').text(task.Name);
        return result;
    };

    return false;
}

function mergeToParent(el) {
    var parentId = el.getAttribute('data-taskId');
    $.ajax({
        contentType: 'application/json',
        url: 'Task/Merge',
        data: JSON.stringify({ ids: selectedIds, parentId: parentId }),
        type: 'POST',
        success: function (result) {

            if (result) {
                if (!result.IsOk)
                    alert(result.Description);
            }

            $('#mergetask').remove();
            $.get('Task/List', function (data) {               
                $(tableRootDiv).html(data);
                if (initTable)
                    initTable();
                $("input:checkbox:checked").map(function (i, el) {
                    $(el).prop('checked', false);
                });
                selectedIds = [];
            });
        }
    });
};

function chooseParent() {
    if (selectedIds.length < 1) { alert(TableResources.NoMergeRecordsSelected); return false; }
    this.$content = $('#content');

    $.get('Task/ChooseParentDialog', function (html) {
        $content.append(html);
        $('#searchFullLink').hide();
        $('#parenttasklist').show();

        $('#childparent').find('a.fullsearch').bind("click.search", function () {
            showSearchContiner(this);
            searchParentTask(true, true);
            return false;
        });

        $('#parentnumber').keypress(function (e) {
            if (e.keyCode === 13) {
                showSearchContiner(this);
                searchParentTask(true, true);
                return false;
            }
        });

        $('#childparent').find('#columns').multipleSelect({});

        $('html').scrollTop(0);

        $('#parentnumber').focus();
    });

    return false;
}

function setAsParent(el) {
    var parentId = el.getAttribute('data-taskId');
    $.ajax({
        contentType: 'application/json',
        url: 'Task/SetParent',
        data: JSON.stringify({ ids: selectedIds, parentId: parentId }),
        type: 'POST',
        success: function (result) {

            if (result) {
                if (!result.IsOk)
                    alert(result.Description);
            }

            $('#childparent').remove();
            $.get('Task/List', function (data) {
                $(tableRootDiv).html(data);
                if (initTable)
                    initTable();
                $("input:checkbox:checked").each(function (i, el) {
                    $(el).prop('checked', false);
                });
                selectedIds.length = 0;
            });
        }
    });
}

function showSearchContiner(sender) {
    $(sender).find('#searchFullLink').hide();
    $(sender).find('#parenttasklist').show();
}

function searchParentTask(fullTextSearch, searchById) {
    var searchString = $("#childparent").find('#parentnumber').val().trim();
    var $parentexist = $('ul.parentexist');
    var $parentTaskList = $('#parenttasklist');
    var $searchParentWrap = $("#childparent").find('#childparent');
    var $errorBox = $searchParentWrap.find('.description');
    var $searchFullLink = $("#childparent").find('#searchFullLink');
    $errorBox.empty().hide();
    $parentexist.empty();

    var columns = $("#childparent").find('#columns').val();//Выбранные колонки по которым будет осуществяться поиск

    var success = function (message) {
        if (message) {
            if (!message.IsOk) {
                $parentTaskList.hide();
                $errorBox.text(message.Description).show();
            } else {

                if (message.Data.IsNumber)//Если найдена или не найдена заявка по Id                        
                    $searchFullLink.unbind("click.search").bind("click.search",// (
                        function () {
                            searchParentTask(true, false); return false;
                        }).show();
                else {

                    if (message.Data.IsFullTextSearch)//Если использовался полнотекстовый поиск
                        $searchFullLink.unbind("click.search").bind("click.search", //(
                            function () {
                                searchParentTask(false, false); return false;
                            }
                            ).show();
                    else
                        $searchFullLink.hide();
                }

                if (message.Description) {
                    $errorBox.text(message.Description).show();//Если выдано сообщение
                }

                if (message.Data.TaskResult) {
                    $parentTaskList.show();

                    $.each(message.Data.TaskResult, function (index, task) {
                        var element = createElement(task);
                        $parentexist.append(element);
                    });

                    $parentexist.highlight(searchString);
                }
            }
        }
    };

    $.ajax({
        contentType: 'application/json',
        url: 'Task/SearchParentTask',
        data: JSON.stringify({
            search: searchString,
            taskId: 0,
            isFullTextSearch: fullTextSearch,
            searchById: searchById,
            columns: columns
        }),
        type: 'POST',
        success: success
    });

    return false;
}

function createElement(task) {
    var result = [];

    var $li = $('<li class="ticketnumber ticketlabel">#</li>');
    var $span = $('<span class="ticketshow"></span>').text(task.Id);

    var $a = $('<a class="js-setAsParent pointer" title="Выбрать заявку"></a>').attr('data-taskId', task.Id).append($span);

    $span.on('mouseover', showDescription(task)).on('mouseout', hideDescription());

    result[0] = $li.append($a);
    result[1] = $('<li class="ticketname"></li>').text(task.Name);
    return result;
}

function showDescription(el) {
    showtd = true;
    var $span = $(el.target);
    if ($span.hasClass('highlight'))
        $span = $span.parent('span:first');
    var $a = $span.parent('a:first');
    var taskId = $a.attr('data-taskId');

    var showDescriptionInner = function () {
        if (!showtd) return;
        var tdkey = '#taskdescription_' + taskId;
        var $taskDetails = $(tdkey);
        $('.taskdescription').hide();

        var offset = $span.offset();
        var h = $span.height();
        var w = $(window).width() - 300;
        if (w < 400) w = 400;
        if (w > 900) w = 900;

        if ($taskDetails.length > 0) {
            $taskDetails.css('top', offset.top + h + 5).css('left', offset.left + 50).css('width', w).fadeIn('fast');
        } else {
            $taskDetails = $('<div id="taskdescription_' + taskId + '" class="taskdescription popupwrapperfixed"><div class="popup"></div></div>');
            $('body').append($taskDetails);

            $taskDetails.css('top', offset.top + h + 5).css('left', offset.left + 40).css('width', w);

            $taskDetails.mouseover(function () { clearTimeout(hideTimeoutId); }).mouseout(function () {
                setTimeout(hideDescription(), 500);
            }
            );

            $.get('Task/GetTaskDetails/' + taskId, { withoutmark: true }, function (data) {
                if (!showtd) return;

                var $target = $('.popup', $taskDetails);
                $target.html(data);
                $taskDetails.highlight($('#parentnumber').val()).show();
            });
        }
    };

    setTimeout(showDescriptionInner, 400);
}

function hideDescription() {
    setTimeout(function () { $('.taskdescription').hide(); }, 400);
}

$(document).ready(function () {
    $('body').on('click', '.js-mergeToParent', function (e) {
        e.preventDefault();
        mergeToParent(this);
    });
    $('body').on('click', '.modalOverlay ', function (e) {
        if (e.target != this)
            return true;
        e.preventDefault();
        closeModalOverlay();
    });
    $('body').on('click', '.js-close-mergeTaskDialog', function (e) {
        e.preventDefault();
        $('#mergetask').remove();
    });
    $('body').on('click', '.js-setAsParent', function (e) {
        e.preventDefault();
        setAsParent(this);
    });
    $('body').on('click', '.js-close-bindTaskDialog', function (e) {
        e.preventDefault();
        $('#childparent').remove();
    });
});


function copyTask(that) {
    var count = $('#actions').data('selectedTasksOnPage');;
    if (count != 1) {
        alert('Выберите одну заявку для копирования!');
        return false;
    }
    var taskId = $('.rowid:checked').val();
    var win = window.open('Task/Copy/' + taskId, '_blank');
    win.focus();
}

function chooseSetCategories() {
    if (selectedIds.length <= 0) { alert(CommonResources.NoOneSelected); return false; }

    $.ajax({
        contentType: 'application/json',
        url: 'Task/TasksSetCategoriesDialog',
        data: JSON.stringify({
            taskIds: selectedIds
        }),
        type: 'post',
        success: function (result1) {
            
            openModalOverlay(result1);

            var $setTaskCategoriesDialog = $('#setTaskCategoriesDialog');
            $setTaskCategoriesDialog.find('form')
                .submit(function (e) {
                    e.preventDefault();

                    $.ajax({
                        url: 'Task/TasksSetCategories',
                        data: $(this).serialize(),
                        type: 'post',
                        success: function (result2) {
                            openModalOverlay(result2);
                            $('input.rowid.cb:checked').each(function (i, el) { selectRow(el.value, !el.checked && !el.disabled); });
                            $(tableRootDiv).load(tableUrl(), initTable);
                        }
                    })

                    return false;
                });

            var $table = $setTaskCategoriesDialog.find('#setTaskCategoriesDialogTable');

            var $buttonSubmit = $setTaskCategoriesDialog.find('button[type="submit"]');

            if ($buttonSubmit.attr('task-count') == 0) {
                $setTaskCategoriesDialog.find('#setTaskCategorySearch').attr('disabled', true);
            }
            else{
                $setTaskCategoriesDialog.find('#setTaskCategorySearch').devbridgeAutocomplete({
                    serviceUrl: 'Task/TasksSetCategoriesFind/?serviceId='+ $('#serviceid').val(),
                    triggerSelectOnValidInput: false,
                    autoClearInputOnSelect: true, //после выбора элемента очищаем инпут
                    autoQueryOnEmptyField: true,
                    showNoSuggestionNotice: true,
                    noSuggestionNotice:TaskResources.ListSetCategoriesFindNoResult,
                    closeAfterOnEnter: true,
                    minChars: 1,
                    onSelect: function (suggestion) {                   
                        if (!$table.find('input[value="' + suggestion.data.cid + '"]').length) {
                            var $label = $('<label>' + suggestion.value + '</label>');
                            var $input = $('<input type="checkbox" name="cids" value="' + suggestion.data.cid + '" checked/>');
                            $label.prepend($input);
                            var $td = $('<td></td>');
                            $td.append($label);
                            var $tr = $('<tr></tr>');
                            $tr.append($td);
                            $table.append($tr);
                            //$table.append('<tr><td><label>' + suggestion.value + '</label></td></tr>');
                            $buttonSubmit.prop('disabled', false);

                            $input.click(function () {
                                if ($table.find('input[name="cids"]:checked').length == 0) {
                                    $buttonSubmit.prop('disabled', true);
                                }
                                else {
                                    $buttonSubmit.prop('disabled', false);
                                }
                            });
                        }                    
                    }
                });
            }
        }
    });
}

function chooseUnsetCategories() {
    if (selectedIds.length <= 0) { alert(CommonResources.NoOneSelected); return false; }

    $.ajax({
        contentType: 'application/json',
        url: 'Task/TasksUnsetCategoriesDialog',
        data: JSON.stringify({
            taskIds:selectedIds
        }),
        type: 'post',
        success: function (result1) {
            openModalOverlay(result1);

            var $unsetTaskCategoriesDialog = $('#unsetTaskCategoriesDialog');
            $unsetTaskCategoriesDialog.find('form').submit(function (e) {
                e.preventDefault();

                $.ajax({
                    url: 'Task/TasksUnsetCategories',
                    data:$(this).serialize(),
                    type: 'post',
                    success: function (result2) {
                        openModalOverlay(result2);
                        $('input.rowid.cb:checked').each(function (i, el) { selectRow(el.value, !el.checked && !el.disabled); });
                        $(tableRootDiv).load(tableUrl(), initTable);
                    }
                })

                return false;
            });

            var $table = $unsetTaskCategoriesDialog.find('#unsetTaskCategoriesDialogTable');
            var $buttonSubmit = $unsetTaskCategoriesDialog.find('button[type="submit"]');

            $table.find('input[name="cids"]').click(function () {
                if ($table.find('input[name="cids"]:checked').length == 0) {
                    $buttonSubmit.prop('disabled', true);
                }
                else {
                    $buttonSubmit.prop('disabled', false);
                }
            });
        }
    });   
}

function openModalOverlay(data) {

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

function closeModalOverlay() {
    var $modalOverlay = $('.modalOverlay');
    if ($modalOverlay.length) {
        $modalOverlay.remove();
        $('body').css("overflow", "visible");
    }
    return false;
}

//$element вспомогательное окно 
//img элемент благодаря которому показывается окно
// w ширина, может быть не определена
function positionPopup($element, img, w) {
    var padding = 60;
    var paddingArrow = 16; 
    var offsetWindow = img[0].getBoundingClientRect();
    var positionElTop = offsetWindow.top;
    var positionElLeft = offsetWindow.left;
    var table = img.closest('table');

    var rowfind = img.closest('tr'); 
    //если елемент за пределами видимости
    if (offsetWindow.top < 0 || table.offset().top > rowfind.offset().top) {

        if (rowfind.length) {
            rowfind[0].scrollIntoView(false);
            offsetWindow = img[0].getBoundingClientRect();
           
            positionElLeft = offsetWindow.left;
            positionElTop = offsetWindow.top ;
        }
    }  
    var innerH = $('body').height();
    if (w != undefined)
        $element.css('width', w);
    
    var h = $element.height() - paddingArrow;
    if (innerH - offsetWindow.top < innerH / 2) { //top  
        if (h > offsetWindow.top - padding)//если высота большье экрана с отступом 
            h = offsetWindow.top - padding;
            $element.find('.popup').css('height', h)
            .css('overflow', 'auto');   
        $element.removeClass("popupwrapperfixed").addClass("popupwrapperdownfixed").css('left', positionElLeft)
           .css('top', positionElTop - h - 21)
    }
    else {//bottom 
        if (h > innerH - offsetWindow.top - padding)//если высота большье экрана с отступом 
            h = innerH - offsetWindow.top - padding;
       
     $element
         .removeClass("popupwrapperdownfixed")
       .addClass("popupwrapperfixed"); 
     $element.find('.popup').css('height', h)
        .css('overflow', 'auto');
        $element.css('left', positionElLeft)
        .css('top', positionElTop + 21)

    }
    $element.show();
}

//Копипаст из Task.js
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;
}
