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

var dlg = null;

$(function () {
    if ($.browser.msie && parseInt($.browser.version, 10) <= 6) $("#filter-sticker").hide();
    
    initNotificationHolder();
 });

window.afterSearch = function (json) {
    if (json.hasOwnProperty('IsOK'))
        //redirect to ticket
        window.location = base + 'task.ivp/view/' + json.Id;
};

window.afterInitTable = function () {
    $('.taskname span').mouseover(showTaskDescription).mouseout(function () {
        showtd = false;
        clearTimeout(sid);
        hid = setTimeout('hideTaskDescription()', 400);
    }).click(function () { showtd = false; });
    $('.statusicon').click(chooseStatus);
    $('.priorityicon').click(choosePriority);
    $('.mirowid').click(function () { selectRow(this.value, this.checked); });

    $('#serviceid').change(function () {
        //Уберем фильтр чтобы сбросить его состояние, ведь список статусов может измениться
        $('#filterholder').remove();
        selectedIds.length = 0;
        hideTaskDescription();
        $(tableRootDiv).load(base + tableController() + 'list', { tb_serviceid: $('#serviceid').val(), nolayout: true, timestamp: new Date().toDateString() }, initTable);
        initNotificationHolder();
    });
    
    InitResizableGrid('table.resizable-grid', window.getHeightTableHolder(95));
    setFooterTop();       

};

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() {
    $('#notificationholder').empty();
    if (!$('#hasChildServices').size())
        return false;
    var hasChildServices = $('#hasChildServices').val().split('|');
    if ($('#serviceid').val() <= 0 || $.inArray($('#serviceid').val(), hasChildServices) > -1)
        $('#notificationholder').hide();
    else if ($('#tableaction').length) {
        $('#notificationholder').show();
        var $link = $('<a/>').attr('href', '#').click(loadNotificationRule).addClass('link').text(TaskResources.NotificationRules);
        $('#notificationholder').append($link);
    }

    return false;
}



function loadNotificationRule() {
    $('#notificationholder').load(base + 'task.ivp/loadnotificationrule', { serviceid: $('#serviceid').val(), timestamp: new Date().toString() }, function () {
        $('#statusid').multipleSelect({});

        $("#notificationruleform input[type='checkbox']").on("change", function () { $("#notificationruleform .controlelements a").show(); });
        $("#statusid").on("change", function () { $("#notificationruleform .controlelements a").show(); });

        initStatusTemplates(true);

        $('#statusid').off('addStatus');

        $('#statusid').on('addStatus', function (event, checkbox, select) {
            addStatusNoIcon(checkbox); setHeight(select);
            $("#addstatus .checklist").css("width", "200px");
        });

        $(".dellink").click(function () { $("#statusid").change(); });

    });
    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 showTaskDescription() {
    var id = this.id;
    showtd = true;
    sid = setTimeout('_showTaskDescription("' + id + '")', 500);
    clearTimeout(hid);
}
function hideTaskDescription() {
    $('.taskdescription').hide();
}
function _showTaskDescription(tid) {
    if (!showtd) return;
    var id = getId(tid);
    if ($('#taskname_' + id).length == 0) return;

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

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

    if ($(tdkey).length > 0) {
        $(tdkey).css('top', offset.top + h + 5).css('left', offset.left + 60).css('width', w);
        $(tdkey).fadeIn('fast');
    }
    else {
        $('body').append('<div id="taskdescription_' + id + '" class="taskdescription popupwrapper"><div class="popup"></div></div>');
        $(tdkey).css('top', offset.top + h + 5).css('left', offset.left + 40).css('width', w);
        $(tdkey).mouseover(function () { clearTimeout(hid); }).mouseout(function () { hid = setTimeout('hideTaskDescription()', 500); });
        $('.popup', $(tdkey)).load(base + 'task.ivp/taskdetails/' + id, { date: new Date().toString() }, function() {
            if (!showtd) return;
            $('.popup', $(tdkey)).bgiframe();
            $(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;
    }
    $(tableRootDiv).load(base + 'task.ivp/marktasksasread', { ids: selectedIds, timestamp: new Date().toDateString(), nolayout: true }, function () {
        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 ($('#taskname_' + taskid).length == 0) return;
    if ($('#choosestatus').length == 0) $('body').append('<div id="choosestatus" class="popupwrapper"></div>');
    $('#choosestatus').load(base + 'task.ivp/getpossiblestatuses', { taskid: taskid, statusid: statusid, isMass: mass, timestamp: new Date().toString() }, function () {
        var offset = img.offset();
        $('#choosestatus').css('top', offset.top + 21).css('left', offset.left).show();
    });
}
function changeStatus(taskid, statusid) {
    $('#choosestatus').hide();

    var ids = selectedIds;
    if (ids.length == 0) ids = taskid;
    $.getJSON(base + 'task.ivp/changestatus', { taskids: ids, statusid: statusid, timestamp: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else {
            selectedIds.length = 0;

            if (result.Id == null) {
                $(tableRootDiv).load(tableUrl(), { nolayout: true, timestamp: new Date().toString() }, initTable);
            }
            else {
                var curl = base + "task.ivp/" + result.Action + "/";
                if (result.Action != "list")
                    curl += result.StatusId + "/" + result.Id
                document.location = curl;
            }
        }
    });

    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?tb_mode=self&tb_serviceid=' + serviceid;
    } else {
        if ($('#assignotherexecutors').length > 0 && $('#assignotherexecutors').val().toLowerCase() == 'true')
            url = 'user.ivp/select?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 = usersCallback;
}

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

function addusersselect(uids) {
    var ids = selectedIds;
    var folderId = $('#id').val();
    
    $.getJSON(base + 'task.ivp/SaveExecutorsToManyTask', { userids: uids, taskids: ids, serviceid: $('#serviceid option:selected').val(), timestamp: new Date().toString(), nolayout: true }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            alert(result.Description);
            $(tableRootDiv).load(tableUrl(), { nolayout: true, timestamp: new Date().toString() }, initTable);
        }
        else {
            selectedIds.length = 0;
            $(tableRootDiv).load(tableUrl(), { nolayout: true, timestamp: new Date().toString() }, 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');
    var priorityid = img.attr('priorityid');

    if ($('#taskname_' + taskid).length == 0) return;
    if ($('#choosepriority').length == 0) $('body').append('<div id="choosepriority" class="popupwrapper"></div>');
    $('#choosepriority').load(base + 'task.ivp/getpossiblepriorities', { taskid: taskid, timestamp: new Date().toString() }, function () {
        var offset = img.offset();
        $('#choosepriority').css('top', offset.top + 21).css('left', offset.left).show();
    });
}


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;
    $.getJSON(base + 'task.ivp/changepriority', { taskids: ids, priorityid: priorityid }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else {
            selectedIds.length = 0;
            $(tableRootDiv).load(tableUrl(), { nolayout: true, timestamp: new Date().toString() }, initTable);
        }
    });

    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 exportReportExcel(parameters) {
    
}

