/// <reference path="jquery.intellisense.js"/>
/// <reference path="common.js" />
/// <reference path="ru.js" />
var scid = 0;
var hcid = 0;
var showtd = true;
var dlg = null;
var filteridglobal = 0;

$(function () {
    $(document).on('click', '.state>span.hover', showContextMenu);
    $(document).on('mouseout', '.state>span.hover', function () {
        clearTimeout(scid);
    });
    $(document).on('click', '.contextmenu', hideContextMenu);
    $(document).on('change', '#periodid', function () {
        $('#description').empty();
        var value = $('#periodid').val();
        if (value != "") {
            if (value == 2)
                $('span#description').append(SubscribeDescriptions.day);
            if (value == 3)
                $('span#description').append(SubscribeDescriptions.week);
            if (value == 4)
                $('span#description').append(SubscribeDescriptions.month);
        }
    });

    //При откерытии списка подписок, при наличии соответствующего ключа, откроем на создание карточку подписки
    $(document).ready(function() {
        if (getURLParameter('subscribe') != null && getURLParameter('subscribe') != '') {
            $('a.controlbutton.btncreate').click();
        }
        if (getURLParameter('subscriptionid') != null && getURLParameter('subscriptionid') != '') {
            $('#subscription' + getURLParameter('subscriptionid')).click();
        }
    });
});

//#region Context menu
function showContextMenu() {
    var id = $(this).closest('.state').attr('id');
    var listid = $(this).closest('.filterlist').attr('id');
    var filterid = id.substring(11, id.length);
    clearTimeout(hcid);
    hideContextMenu();
    var popuppath = '#' + id + '>.contextmenu';
    var node = $('#' + id);
    var caneditcommonfilters = $('#caneditcommonfilters').val() == "True";
    var container = listid == 'editfilterform' ? 'savedstates' : 'savedfilter';

    if ($(popuppath).length == 0) {
        var popup = node.append('<ul class="contextmenu"></ul>').children('.contextmenu');
        //Построение контекстного меню

        popup.append('<li onclick="return applyFilter(' + filterid + ', true);">' + FilterResources.ToExcel + '</li>');

        if (listid == 'user' || caneditcommonfilters) {
            //Переименовать
            popup.append('<li onclick="return rename(' + "'" + container + filterid + "'" + ');">' + FilterResources.Rename + '</li>');
        }

        if (listid == 'user') {
            popup.append("<li onclick=\"return editFilter('" + filterid + "');\">" + FilterResources.Change + '</li>');
        } else if ((listid == 'common' && caneditcommonfilters))
            popup.append("<li onclick=\"return editFilter('" + filterid + "', true);\">" + FilterResources.Change + '</li>');

        if (listid == 'common' && caneditcommonfilters) {
            //Права доступа
            popup.append("<li onclick=\"return accessRights('" + filterid + "');\">" + FilterResources.AccessRights + '</li>');
        }

        var isReportFilter = $('#reportfilter').length > 0;

        if (!isReportFilter && (caneditcommonfilters || listid != 'common')) {
            var imgchecked = $('#savedfilter' + filterid).attr('isdefault') == "True" ? "<img src='img/tick.gif'/> " : "";
            //Сделать/Убрать пользовательский фильтр по умолчанию
            popup.append('<li onclick="return setDefault(' + filterid + ');">' + imgchecked + FilterResources.SetDefault + '</li>');
        }

        //сделать общим
        if (listid != 'common' && caneditcommonfilters) {
            popup.append('<li onclick="return setCommon(' + filterid + ');">' + FilterResources.SetCommon + '</li>');
        }

        //Создать подписку
        popup.append("<li onclick=\"return subscribeFromTableList('" + filterid + "')\";>" + FilterResources.Subscribe + "</li>");

        //Показать подписки
        popup.append('<li onclick="return showSubscriptions(' + filterid + ');">' + FilterResources.Sibscrptions + '</li>');

        if (caneditcommonfilters || listid == 'user') {
            //Удалить
            popup.append('<li onclick="return deleteState(' + filterid + ');">' + FilterResources.Delete + '</li>');
        }

        popup.find("li").css("padding-left", "16px");
        popup.find("img").css({ "position": "absolute", "left": "5px" });

        $(popuppath).mouseover(function () {
            clearTimeout(hcid);
        }).mouseout(function () {
            hcid = setTimeout('hideContextMenu()', 500);
        });
    }

    var offset = $('#' + id + '>.hover').offset();
    var parentoffset = listid=="editfilterform"? $('#editfilterform').offset(): $('#savedstates').offset();
    if ($('#reportfilter').val() != null) {
        $('.contextmenu').css('left', offset.left - parentoffset.left - $('.contextmenu').width() + 5).css('top', offset.top - parentoffset.top + 38).show();
    }
    else if (listid == "editfilterform") {
        $('.contextmenu').css('left', offset.left - parentoffset.left  + 10).css('top', offset.top - parentoffset.top + 17).show();
    }
    else {
        $('.contextmenu').css('left', offset.left - parentoffset.left - $('.contextmenu').width() + 5).css('top', offset.top - parentoffset.top + 70).show();
    }
    return false;
}

function hideContextMenu() {
    $('.contextmenu').hide().remove();
}
//#endregion

//#region subscriptions
function subscribe(mode, id, el) {
    var name = $("#filtername").text();
    if (!name && el)
        name = $(el).text();

    //перед открытием формы очистим её, чтоб исключить дублирование параметров
    if ($('#subscribe').length > 0) {
        $('#subscribe').remove();
    }
    var url = base + 'savedfilter.ivp/subscribe';
    $('body').append('<div id="subscribe"></div>');
    
    $('#subscribe').dialog({
        autoOpen: false,
        width: 'auto',
        height: 'auto',
        minHeight: 135,
        minWidth: 510,
        modal: true,
        resizable: true,
        title: mode==1?FilterResources.FilterSubscription+' "'+name+'"':FilterResources.SubscribeToFilter + ' "' + name + '"',
        close: function () {
            $("#subscribe").remove();
        }
    });
    
    $('#subscribe').load(url, { mode: mode, id: id }, function() {
        $('#subscribe').show();
        if (mode != 1) {
            
            $('#addsubscribeuser').autocomplete(base + 'user.ivp/findusers/', { minChars: 1 }).result(userAdded);
            $('#addsubscribeuser').bind("blur", function() {
                if ($('#addsubscribeuser').val() != $('#username').val())
                    $('#addsubscribeuser').val($('#username').val());
            });
        }
        $('#subscribe').dialog("open");
    });
    return false;
}

function subscribeFromTableList(filterId) {
    var url = 'filternotification.ivp/list?tb_mode=filter&subscribe=true&tb_filterid=' + filterId;
    dlg = window.openDialog(url, 'subscriptions', { width: 900, height: 650 });
    dlg.callback = function (isopener) { reloadSavedStates(isopener); }
    return false;
}

function savesubscription()
{
    $('#subscribe').hide();
    $.post(base + 'savedfilter.ivp/savesubscription/', $('#subscribeform').serializeArray(),function() {
        var url = base + tableController() + 'list';
        $(tableRootDiv).load(url, { nolayout: true, timestamp: new Date().toString()}, cutomInitTable);
    });
	$('#subscribe').remove();
	return false;
}

function showSubscriptions(filterId,subscriptionId) {
    var url = 'filternotification.ivp/list?tb_mode=filter&tb_filterid=' + filterId;
    if (subscriptionId) url += "&subscriptionid=" + subscriptionId;
    dlg = window.openDialog(url, 'subscriptions', { width: 900, height: 650 });
    dlg.callback = function (isopener) { reloadSavedStates(isopener); }
    return false;
}

function addSubscriber(uids, names) {
    var id = uids[0];
    $('#userid').val(id);
    $('#username').val($.trim(names['id' + id]));
    $('#addsubscribeuser').val($.trim(names['id' + id]));
}

var FilterUserSubscriber = {
    selectUser: function selectUser() {
        var filterid = $('#filterid').val();
        var url = 'user.ivp/select?cbmode=FilterUserSubscriber&tb_mode=subscribe&tb_filterid=' + filterid;
        dlg = window.openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = FilterUserSubscriber.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"]
        addSubscriber(uids, names);
    }
}

var FilterUserPermission = {
    chooseUsers: function chooseUsers(filterid) {
        filteridglobal = filterid;
        var url = 'user.ivp/select?cbmode=FilterUserPermission&tb_mode=filterpermissions';
        dlg = window.openDialog(url, 'addpermissions', { width: 900, height: 650 });
        dlg.callback = FilterUserPermission.usersCallback;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        addUserPermission(uids, names);        
    }
}

function userAdded(e, d) {
    var name = $.trim(d[0].toString());
    var id = $.trim(d[1].toString());
    $('#userid').val(id);
    $('#addsubscribeuser').val(name);
    $('#username').val(name);
    return false;
}

function deleteSubscriptions(options) {
    if (selectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(TableResources.SureDeleteRecords)) return false;
    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toString() };
    if (options != null) $.extend(params, options);
    var url = base + tableController() + 'Delete';
    selectedIds.length = 0;
    $(tableRootDiv).load(url, params, cutomInitTable);
    return false;
}

function cutomInitTable() {
    initTable();
    if (getURLParameter('callback') != null && getURLParameter('callback') != '') {
        eval('opener.' + getURLParameter('callback'))(true);
    }
}
//#endregion

//#region rename filter
function rename(containerid) {
    if ($('#filternewname').length > 0) return false;
    var id = containerid.substring(11, containerid.length);
    var container = $('#' + containerid);
    var link = container.children('a');
    var hover = $('.hover');
    container.prepend('<input type="text" id="filternewname" name="filtername" value="' + $.trim(link.text().toString().replace(/"/g, "&quot;")) + '"/>' +
                      '<a id="button1" href="#" onclick="confirmRename(' + "'" + containerid + "'" + '); return false;"><img class="icons16" src="img/accept.png"/></a>' +
                      '<a id="button2" href="#" onclick="cancelRename(' + "'" + containerid + "'" + '); return false;"><img class="icons16" src="img/delete.gif"/></a>' +
                      '<label for="filtername" generated="true" class="error" style="display:none"></label>');
    var $lang = $('<a/>').attr('href', '#').attr('id', 'langbtn').addClass('controlbutton languagebtn').text(CommonResources.Language);
    var $div = $('<div/>').append($lang);
    if (container.closest('ul#common').length) {
        container.append($div);
        $lang.click(function() {return selectFilterNameLanguage(id); });
    }
    link.hide();
    hover.hide();
    $('input#filternewname').keyup(function(e) {
        if (e.keyCode == '13') {
            confirmRename(containerid);
        }
        if (e.keyCode == '27') {
            cancelRename(containerid);
        }
        return false;
    });
    return false;
}

function confirmRename(containerid) {
    var container = $('#' + containerid);
    var id = containerid.substring(11, containerid.length);
    var link = container.children('a');
    var name = $('#filternewname').val();
    if (name == "") {
        $('label[for="filtername"]').text(FormResources.FieldRequired);
        $('label[for="filtername"]').show();
    } else if (name.length > 100) {
        $('label[for="filtername"]').text(jQuery.validator.messages.maxlength(100));
        $('label[for="filtername"]').show();
    } else {
        if (name != link.text()) {
            $.post(base + 'savedfilter.ivp/rename', { id: id, name: name }, function () { link.text(name); });
            cancelRename(containerid);
        } else return cancelRename(containerid);
    }
    if (opener && opener.reloadSavedStates) opener.reloadSavedStates(true);
    return false;
}

function cancelRename(containerid) {
    var container = $('#' + containerid);
    var link = container.children('a');
    var hover = $('.hover');
    $('input#filternewname').remove();
    $('#button1').remove();
    $('#button2').remove();
    $('#langbtn').parent().remove();
    $('label[for="filtername"]').remove();
    link.show();
    hover.show();
    return false;
}

function selectFilterNameLanguage(id) {
    var url = 'fieldlanguage.ivp/load?required=true&table=Filter&field=NameXml&id=' + id;
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}
//#endregion

//Set filter as default
function setDefault(id) {
    var currentFilter = $('#savedfilter' + id + ':first');
    var filterName = currentFilter.attr('filtername');
    var isCommon = currentFilter.attr('iscommon');
    var isDefault = currentFilter.attr('isdefault');
    var olddeffilter = $("li[iscommon=" + isCommon + "][isdefault='True']:first");
    var confirmText;
    if (isDefault == "False")
        confirmText = FilterResources.SureFilter + '"' + filterName + '"' + FilterResources.Default;
    else
        confirmText = FilterResources.RemoveFilter + ' "' + filterName + '"' + FilterResources.Default;
    if (!confirm(confirmText)) return false;
    $.post(base + 'savedfilter.ivp/setdefault',
        { id: id },
        function() {
            if (olddeffilter.attr("id") == currentFilter.attr("id")) {
                isDefault == 'True' ? olddeffilter.attr('isdefault', 'False') : olddeffilter.attr('isdefault', 'True');
            }
            else {
                olddeffilter.attr('isdefault', 'False');
                $('#savedfilter' + id).attr('isdefault', 'True');
            }
        });
    return false;
}

function setCommon(id) {
    var currentFilter = $('#savedfilter' + id + ':first');
    
    $.getJSON(base + 'savedfilter.ivp/setcommon', { id: id }, function (result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true) {
            if ($('ul#common').length == 0)
                $("#savedstates").append('<ul id="common" class="filterlist"></ul>');
            $(currentFilter).detach().appendTo('ul#common');
        }
    });

    return false;
}

function editFilter(id, isCommonFilter) {
    $('#filtercontrol').remove();

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

    var url = base + 'savedfilter.ivp/EditTaskFilter';
    $('body').append('<div id="filterholder" style="display: none;" class="nopopupwrapper"></div>').find('#filterholder').load(url, { stateid: id, serviceid: serviceid, fill: true }, function () {
        initFilter(true);
        if ($('#filter form').size()) {
            $('#filter form').validate({ ignore: '.ignore' });
        }

        if (isCommonFilter != 'undefined' && isCommonFilter)
            $('#filter form').append('<input class="hidden" id="commonfilter" name="commonfilter">');
    });

    return false;
}


//#region configure filter(s) permissions
function accessRights(id) {
    var name = $.trim($("#savedfilter" + id).closest('.state').find('a').text());
    //перед открытием формы очистим её, чтоб исключить дублирование параметров
    if ($('#editfilter').length == 0) {
        $('body').append('<div id="editfilter"></div>');
        $('#editfilter').dialog({
            autoOpen: false,
            width: '500',
            height: 'auto',
            //minHeight: 135,
            //minWidth: 510,
            modal: true,
            resizable: true,
            title: FilterResources.AccessRights+' "'+name+'"',
            close: function () {
                $("#editfilter").remove();
            }
        });
    }
    var url = base + 'savedfilter.ivp/editaccessrights';
    $('#editfilter').load(url, { id: id }, function () {
        initAccessRightsForm();
        $('#editfilter').dialog("open");
    });
    return false;
}

//Инициализация формы (расставляем радио переключатели)
function initAccessRightsForm() {
    $('#editfilter input.radio.all').each(function (i, el) {
        if ($('#fp').prop('checked')) {
            $(el).prop('checked', true);
        } else {
            $('#ispublicFalse').prop('checked', true);
        }
    });
    $('#editfilter input.radio').on('click', function () {
        if ($(this).hasClass("all")) {
            $('#custompermissions').hide();
        } else {
            $('#custompermissions').show();
        }
    });
}

//Вызов диалога выбора ролей
function chooseRoles(filterid) {
    filteridglobal = filterid;
    var url = 'role.ivp/select?tb_mode=filterpermissions&tb_serviceid=-1';
    dlg = window.openDialog(url, 'addpermissions', { width: 900, height: 650 });
    dlg.callback = rolesCallback;
}

function rolesCallback(result) {
    var rids = result["selectedIds"];
    var names = result["selectedNames"];
    addRolePermission(rids, names);
}

//добавить права для пользователей из массива
function addUserPermission(uids, names) {
    uids.forEach(function (id) {
        var name = $.trim(names['id' + id]);
        addPermission('users', id, name);
    });
    return;
}

//Добавить права для ролей из массива
function addRolePermission(rids, names) {
    rids.forEach(function (id) {
        var name = $.trim(names['id' + id]);
        addPermission('roles', id, name);
    });
    return;
}

//Добавить на форму права для роли/пользователя
function addPermission(type, id, name) {
    var source = $('#' + type);
    var holder = $('ul#' + type + 'holder');
    var elems = source.val() != "" ? (source.val()).split(',') : [];

    //Игнорируем уже существующие элементы
    if (elems.contains(id)) return false;
    elems.push(id);
    source.val(elems.join(','));
    
    holder.append('<li class="bit-box" id="li_' + id + '">'
        + '<span class="title">' + name + '</span>'
        + '<a class="closebutton" onclick="removePermission(\'' + type + '\'' + ',$(this).parent()); return false;" href="#"></a>'
        + '</li>');
    
    return false;
}

//Удалить полномочие
function removePermission(type, entity) {
    var source = $('#' + type);
    var id = getId(entity.attr('id'));
    var elems = (source.val()).split(',');
    var newelems = [];
    for (var i = 0; i <= elems.length - 1; i++) {
        if (elems[i] != id) newelems.push(elems[i]);
    }
    source.val(newelems.join(','));
    entity.remove();
    return false;
}

//Сохранить изменения
function saveFilterPermissions() {
    $.post(base + 'savedfilter.ivp/save/', $('#editfilterform').serializeArray(), function () {
        reloadSavedStates();
    });
    return false;
}
//#endregion

//Удалить один или несколько фильтров
function deleteSavedStates(id) {
    if (!confirm(TableResources.SureDeleteRecords)) return false;
    if (id) {
        var url = base + tableController() + 'DeleteState/' + id;
        $('#savedstates').load(url, { timestamp: new Date().toString() });
        $('tr[filterid=' + id + ']').remove();
    } else {
        if (selectedIds.length == 0) {
            alert(TableResources.NoRecordsSelected);
            return false;
        }
        $.post(base + 'savedfilter.ivp/deletesavedstates/', { id: selectedIds.join(',') }, function () {
            reloadSavedStates();
        });
    }
    return false;
}

//Перезагружает фильтры после их редактирования
function reloadSavedStates(isopener) {
    if ($("#filterslist").length>0) {
        $('#wrapper').load(base + 'savedfilter.ivp/filterslist', { controller: $('#controller').val(), companytypeid: $('#companytypeid').val(), nolayout: true }, function () {
            $('#editfilter').dialog("close");
        });
    } else {
        $('#savedstates').load(base + tableController() + 'loadsavedstates', { islist: true }, function () {
            $('#editfilter').remove();
        });
    }
    if (!isopener && opener && opener.reloadSavedStates) opener.reloadSavedStates(true);
}

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

//Открыть список всех фильтров для текущего контроллера
function configureFilters() {
    var url = 'savedfilter.ivp/filterslist?controller=' + $('#tablecontroller').val();
    if ($('#companytypeid') && $('#companytypeid').val()) {
        url += '&companytypeid=' + $('#companytypeid').val();
    }
    dlg = window.openDialog(url, 'filterslist', { width: 900, height: 650 });
    return false;
}