var sid = 0;
var hid = 0;
var canedit = false;
var treeview;
var currentId = 0;

$(document).ready(function () {
    if ($("#documentId").length) {
        var dId = $("#documentId").val();
        var searchstring = "";
        var issearchstring = false;
        if ($("#searchstring").length) {
            searchstring = "?searchstring=" + $("#searchstring").val();
            issearchstring = true;
        }

        var searchselectedfolderid = "";
        if ($("#searchselectedfolderid").length) {
            searchselectedfolderid = issearchstring ? "&" : "?";
            searchselectedfolderid += "searchselectedfolderid=" + $("#searchselectedfolderid").val();
        }

        $("#kbdocumentholder").load(base + 'kbdocument.ivp/view/' + dId + searchstring + searchselectedfolderid, { nolayout: true }, function () {
            $("#documentId").remove();
            $("#searchstring").remove();
            $("#searchselectedfolderid").remove();

            handleTargetBlank();
        });
    }

    if ($('#taskid') && $('#taskid').val() > 0) {
        var tid = $('#taskid').val();
        $("#kbdocumentholder").load(base + 'kbdocument.ivp/create?taskid=' + tid, { nolayout: true }, function () {
            $('#taskid').remove();
            $("#name").focus();
            onContainerUpdate();
            changeParent();
        });
    }

    resize();
    $('#search').autocomplete(base + 'kbdocument.ivp/findtagsforsearch/', { minChars: 1 }).result(function (e, d) { searchTagSelected(d); });

    $("#content").on("click", "a:not('.file')", function () {

        var onclick = $(this).attr("onclick");

        if (!onclick) {
            if ($(this).closest('.document').length) {
                window.location = $(this).attr("href");
            } else {
                $("#kbdocumentholder").load($(this).attr("href"), { nolayout: true }, onContainerUpdate);

                return false;
            }
        } else {
            if (onclick.toLowerCase().indexOf("return true") < 0) {
                return false;
            }
        }

        return true;
    });

    $("#content").on("click", "button.return", function () {
        $("#kbdocumentholder").html("");
    });

    $("#content").on("click", ".min-height.description a", function () {
        if (this.href != "" || this.href != undefined)
            location.href = this.href;        
    });


    $("#kbtree").kendoTreeView({
        expand: onExpand,
        change: onChangeNode
    });

    treeview = $("#kbtree").data("kendoTreeView");

    if ($("#selectedfolderid").length) {
        var nodeId = $("#selectedfolderid").val();
        var node = $("#node_" + nodeId);
        if (node.length)
            node.find("span.k-in").first().addClass("k-state-selected");

    }

    canedit = ($('#canedit').val() == 'true');

    $("body").on("click", "span.cm", showContextMenu);

    $("body").on("mouseout", "span.cm", function () {
        clearTimeout(sid);
        hid = setTimeout('hideContextMenu()', 400);
    });

    $("#searchform").submit(onSearchSubmit);

    //автоматически раскрываем дерево разделов Базы Знаний, если включена соответствующая настройка
    if ($("#autoexpandkbtree").length) {
        //временный костыль - скрываем элемент kbdocumentholder, чтобы туда не подгружались все раскрывающиеся папки
        $("#kbdocumentholder").attr("id", "kbdocumentholderdisabled");
        $("li[id^='node_']").each(function () {
            treeview.expand(this);
        });
        $("#kbdocumentholderdisabled").attr("id", "kbdocumentholder");
    }

    if (window.location.search.length < 1) { //Подразумеваем, что отсутсвие параметров в запросе означает, что в правый фрейм нужно загрузить содержимое выбранной папки #43294
        var el = $('span.k-state-selected').parents('li')[0];
        treeview.select(el);
    }
    $('#treeholder').resizable({ minWidth: 380, maxWidth: 380 * 2, handles: 'e, w', resize: resizeWidth });

    $(document).on('click', '#kbtree', function () {        
        if (tinymce.activeEditor != null) {
            tinymce.remove();
        }
    })
  
});

function handleTargetBlank() {
    //обычный target=_blank в фрейме работает не корректно
    $('a[target="_blank"]').on('click', function () {
        window.open($(this).attr('href'), '_blank');
        return false;
    });
}

function isIE() {
    var myNav = navigator.userAgent.toLowerCase();
    return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

function createFolder(parameters) {
    $("#kbdocumentholder").load(base + "kb.ivp/create", { nolayout: true }, function () {
        $("#name").focus();
    });
}

function newDocument(parentId) {
    $("#kbdocumentholder").load(base + "kbdocument.ivp/create?parentid=" + parentId, { nolayout: true }, function () {
        $("#name").focus();
        onContainerUpdate();
    });

    return false;
}

function onExpand(e) {
    //treeview.select(e.node);
}

function onCollapse(e) {
    treeview.select(e.node);
}


function onChangeNode() {
    var node = this._current;

    if (!$(node).data("expanded")) {
        treeview.expand(node);
    }

    var id = $(node).data("id");

    //Если у нас уже загружена папка -- незачем еще раз перезагружать
    // if (id != currentId) {
    currentId = id;

    removeAllSearchTags();
    $("#search").val("");
    $('#selectedfolderid').val(id);
    $('#searchselectedfolderid').val(id);

    var url = base + "kbdocument.ivp/list/" + id + '?reset=true';

    if ($(node).data("visible")) {
        $("#kbdocumentholder").load(url, { nolayout: true }, function () {
            /// treeview.select(node);
            initTable();

            if ($('#tableholder').length > 0) {
                $("#kbdocumentholder").css("overflow", "hidden");
                $('#tableholder').css('height', $('#kbdocumentholder').height() + 7 /*- $("#tableholder").prev().height() +20*/);
            }

            handleTargetBlank();
        });
    } else {
        var el = $(node).find("li:first");
        //treeview.select(el);
    }

    // }

}

function setReturnUrl(url) {
    $("#kbDocument").append("<input id='returnUrl' type='hidden' value = " + url + " />");
}

function onContainerUpdate() {
    currentId = 0;

    if ($("#content form").length > 0) {
        $("#content form.validate").validate();
    }

    if ($("#selectedfolderid").length) {
        var nodeId = $("#selectedfolderid").val();
        var node = $("#node_" + nodeId);
        if (node.length)
            node.find("span.k-in").first().addClass("k-state-selected-clicked");
    }

    if ($("#kbDocument").length > 0) {

        var url = false;

        $('#kbDocument').ajaxForm({
            beforeSubmit: function () {             
                url = $("#returnUrl").val();
                // Проверка длины поля "Короткое описание"
                var shortdescr = $("#shortdescription").siblings();
                $("label[for='shortdescription']").children().remove();
                if (shortdescr.length > 0)
                {
                    var textlength = shortdescr.contents().find("html body").html().length;
                    if (textlength > 2000)
                    {
                        $("<br/><div class = 'error'>").text(KBResources.ExceedMaxLengthDescription).appendTo("label[for='shortdescription']");
                        return false;
                    }
                }
            },
            dataType: 'json',
            success: function (entity) {
                if (entity.Id == null || entity.IsOK == false) {
                    $("#errorholder").children().remove();
                    $("<div class='error'>").text(entity.Description).appendTo("#errorholder");
                    $("#errorholder").show();
                }
                else {
                   tinymce.remove('#kbDocument textarea');
                    $("#errorholder").hide();
                    var id = entity.Id;
                    if (id) {
                        if (!url)
                            url = base + 'kbdocument.ivp/edit/' + id;
                        $("#kbdocumentholder").load(url, { nolayout: true }, onContainerUpdate);
                    }
                }
            }
        });

        addTinyEditor("#description", true, true);

        //если форма открыта на редактирование, подкючим плагин для работы с тегами
        if ($('#kbDocument #tid').length > 0) {
            //добавим класс 'selected' ко всем элементам скрытого списка уже существующих тегов
            //, т.к. мы должны их вижеть в строке ввода 
            $('#kbDocument #tid > option').addClass('selected');

            //инициализация плагина
            $('#kbDocument #tid').fcbkcomplete({
                json_url: base + 'kbdocument.ivp/findtags',
                filter_hide: true,
                complete_text: KBResources.TagFcbkCompleteMessage,
                maxitems: 100,
                newel: true
            });
        }
    }

    if ($('#tableholder').length > 0) {
        $("#kbdocumentholder").css("overflow", "hidden");
        $('#tableholder').css('height', $('#kbdocumentholder').height() + 7);
    }
}

function resize() {
    var h = $("#container").height() - $('#header').height() - $('#footer').height() - 30;
    $('#content').css('height', h);
    $('#treeholder').css('height', h - 40);
    $('#kbdocumentholder').css('height', h - 40);

    h = $("#treecontainer").height() - $('#taglistcontainer').height();
    $('#treenodecontainer').css('height', h - 7);

}

function resizeWidth() {
    var widthNode = $('#treeholder').offset().left + $('#treeholder').width();
    var widthContainer = $('#container').offset().left + $('#container').width();
    $('#kbdocumentholder').css('width', widthContainer - widthNode-10);
}

function hideContextMenu() {
    $('.contextmenu').hide();
}

function showContextMenu() {
    clearTimeout(hid);
    hideContextMenu();

    var node = $(this).closest('li');
    var popuppath = "#" + node.attr("id") + ' .contextmenu';
    var id = node.data("id");

    if ($(popuppath).length == 0) {
        var popup = node.append('<ul class="contextmenu"></ul>').children('.contextmenu');
        popup.append('<li onclick="return createChild(' + id + ')">' + KBResources.NewSection + '</li>');
        popup.append('<li onclick="return deleteKB(' + id + ')">' + KBResources.DeleteSection + '</li>');
        $(popuppath).mouseover(function () { clearTimeout(hid); }).mouseout(function () { hid = setTimeout('hideContextMenu()', 500); });
    }

    $(popuppath).css('left', node.find(".k-in").width() + 10).css('top', 5).show();
    return false;
}

function createChild(id) {
    var url = base + 'kb.ivp/create?parentid=' + id;
    $("#kbdocumentholder").load(url, { nolayout: true }, function () {
        $("#name").focus();
    });
    return false;
}

function deleteKB(id) {
    if (!confirm(KBResources.SureDeleteSection))
        return false;

    $.getJSON(base + 'kb.ivp/delete', { id: id, json: true, timestamp: new Date().toString() }, kbDeleted);

    return false;
}

function kbDeleted(result) {
    if (!result.IsOK)
        alert(result.Description);
    else {
        $('#node_' + result.Id).remove();
        $("#kbdocumentholder").html("");
    }
}

/*******************************search********************************/

function onSearchSubmit(e) {
    if (e)
        e.preventDefault();
    var searchForm = $("#searchform");
    var data = searchForm.serialize() + "&nolayout=true";
    
    tinymce.remove();
    $("#kbdocumentholder").load(searchForm.attr("action"), data, function () {     
        onContainerUpdate();        
        if ($('#tableholder').length > 0) {
            $("#kbdocumentholder").css("overflow", "hidden");
            $('#tableholder').css('height', $('#kbdocumentholder').height() + 7 /*- $("#tableholder").prev().height() +20*/);
        }
    });
    return false;
}

function tagSearch(id, value) {

    //удалим существующие теги поиска
    removeAllSearchTags();

    //добавим выбранный тег
    var arr = new Array();
    arr.push(value);
    arr.push(id);

    searchTagSelected(arr);

    return false;
}

function removeAllSearchTags() {
    $('ul#tagholder > li').each(function () { removeSearchTag($(this), true); });
}

function removeSearchTag(li, nosearch) {
    var tagId = li.attr('rel');
    $('select#tid > option[value="' + tagId + '"]').remove();
    li.remove();
    if (!nosearch)
        $('#searchbutton').trigger('click');
    return false;
}

function searchTagSelected(result) {
    if (result && result.length == 2) {
        var tagValue = result[0];
        var tagId = result[1];

        //добавляем элемент в скрытый селект, если его там еще нет
        var select = $('select#tid');
        if (select.find('option[value="' + tagId + '"]').length == 0) {
            select.append('<option class="selected" value="' + tagId + '" selected="true">' + tagId + '</option>');
            //добавляем тег в список
            var holder = $('ul#tagholder');

            var li = document.createElement("li");
            $(li).attr({
                "class": 'bit-box',
                "rel": tagId.toString()
            });
            $(li).append(tagValue.toString());

            var aclose = document.createElement("a");
            $(aclose).attr({
                "class": 'closebutton',
                "href": '#'
            });

            li.appendChild(aclose);
            holder.append(li);

            //"вешаем" событие на клик по ссылке удаления тега
            $(aclose).click(function () {
                removeSearchTag($(this).parent("li"));
                return false;
            });
        }
        $('#search').val('');
        $('#searchbutton').trigger('click');
    }
    return false;
}

function KBSearch(e) {
    onSearchSubmit(e);
}

function doKBSearch(event) {
    var e = event;
    var keycode = ($.browser.msie) ? e.keyCode : e.which;
    if (keycode == 13)
        return KBSearch(e);
    else return true;
}


/*******************************KB folders*****************************/

function saveKBFolder(e) {
    var kbFolderForm = $("#kbFolder");

    if (kbFolderForm.valid()) {

        if (e)
            e.preventDefault();
        var data = kbFolderForm.serialize() + "&nolayout=true&json=json";

        $.post(kbFolderForm.attr("action"),
            data,
            function (entity) {
                var id = $.parseJSON(entity).Id;
                $("#kbdocumentholder").load(base + 'kb.ivp/edit/' + id, { nolayout: true }, function () {

                    $("#content form.validate").validate();
                    $("#treenodecontainer").load(base + "/kb.ivp/getTree", { nolayout: true }, function () {
                        $("#kbtree").kendoTreeView({
                            expand: onExpand,
                            collapse: onCollapse,
                            select: onChangeNode
                        });

                        treeview = $("#kbtree").data("kendoTreeView");
                        expandNodes();
                    });
                });
            }
        );

        return false;
    }
    return false;
}
function selectKbNameLanguage() {
    var url = 'fieldlanguage.ivp/load?required=true&table=KBFolders&field=NameXml&id=' + $("#kbFolder #id").val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function selectKbDescriptionLanguage() {
    var url = 'fieldlanguage.ivp/load?textarea=true&table=KBFolders&field=DescriptionXml&id=' + $("#kbFolder #id").val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function expandNodes() {
    var nodeId = $("#selectedfolderid");
    if (nodeId.length) {
        var node = $("#node_" + nodeId.val());

        if (node.length) {
            treeview.expand(node);
            node.parents().each(function () {
                treeview.expand(this);
            });

            var oldSel = $("span.k-state-selected");
            if (oldSel.length) {
                oldSel.removeClass("k-state-selected");
                oldSel.removeClass("k-state-focused");
            }
            var sel = node.find("span.k-in").first();
            sel.addClass("k-state-selected");
        }
    }
}

/****************delete ******************************/
function deletePermission(link, permissionId) {
    if (!confirm(CommonResources.SureDeletePermission)) return false;

    var groupName = $(link).parents('div:first').attr('id');
    $.getJSON(base + 'kbfolderpermission.ivp/delete', { id: permissionId, json: true, timestamp: new Date().toString() }, function () { reloadPermissions(groupName); });
    return false;
}
function reloadPermissions(groupName) {
    $('#permissionsholder').load(base + 'kb.ivp/ReloadPermissions/' + $('#id').val(), { timestamp: new Date().toString(), nolayout: true }, function () { reloadPermissionsComplete(groupName); });
    return false;
}
function reloadPermissionsComplete(groupName) {
    toggle($('#' + groupName).prev().prev(), '#' + groupName);
    return false;
}
function reload(type) {
    if (type == "language") {
        var id = $("#kbFolder #id").val();
        $("#kbdocumentholder").load(base + 'kb.ivp/edit/' + id, { nolayout: true });
    }
}

/******distribution********/
function openDistributionForm(id) {
    var allVals = [];
    $("input:checkbox[name='distributionids']:checked:enabled").each(function () {
        allVals.push($(this).val());
    });
    if (allVals.length <= 0) {
        alert(KBResources.SelectAnyDocument);
        return false;

    }

    $("#kbdocumentholder").load(base + 'kb.ivp/runnewsletter',
        {
            documentids: allVals,
            id: id,
            nolayout: true
        });
    return false;
}

function selectAll() {
    $("input:checkbox[name='usersemails']").each(function () {
        $(this).attr("checked", true);
    });
}

function deselectAll() {
    $("input:checkbox[name='usersemails']").each(function () {
        $(this).attr("checked", false);
    });
}


function preview() {
    var userid = $("input:checkbox[name='usersemails']").val();
    var message = $('#message').val();
    var subject = $('#subject').val();
    $.post(base + 'kb.ivp/preview', { userid: userid, message: message, subject: subject, preview: true, timestamp: new Date() },
        function (result) {
            var html = $.parseJSON(result);
            $('body').append('<div id="loadingdiv" class="loadingdiv" style="height:100%;"></div><div id="previewform" class="popuppreview"></div>');
            $('#previewform').append(html);
            $('#previewform').show();
            $('#previewform').css('left', '10%').css('top', 100);
        }, "html");
}


function send() {
    var allVals = [];
    $("input:checkbox[name='usersemails']:checked:enabled").each(function () {
        allVals.push($(this).val());
    });
    if (allVals.length <= 0) {
        alert(KBResources.SelectAnyUser);
        return;
    }
    $('.send').attr("disabled", true);
    $('.preview').attr("disabled", true);
    $.ajax({
        url: base + 'kb.ivp/send',
        type: "POST",
        data: ({ users: allVals, subject: $('#subject').val(), message: $('#message').val() }),
        dataType: "json",
        success: function (result) {
            if (result.hasOwnProperty('IsOK') && !result.IsOK) {
                $('.send').attr("disabled", false);
                $('.preview').attr("disabled", false);
                $('#errorholder').empty().css("background-color", "#ffd8d8").css("border-color", "#fca6a6").html("<div id='error'><div class='kberror'>" + result.Description + "</div></div>").show();
                $('#errorholder').css("height", $('#error').height() + 20);
            }
            else {
                $('.send').attr("disabled", false);
                $('.preview').attr("disabled", false);
                $('#errorholder').empty().css("background-color", "#e3ffd8").css("border-color", "#96e577").html("<div id='error'><div class='kberror'>" + KBResources.Success + "</div></div>").show();
                $('#errorholder').css("height", $('#error').height() + 20);
            }
        }
    });
}


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

function inheritKbFolderPermissions() {
    var params = {
        id: $('#id').val(),
        users: $('#inheritusers').is(':checked'),
        departments: $('#inheritdepartments').is(':checked'),
        services: $('#inheritservices').is(':checked')
    };
    $.ajax({
        type: 'POST',
        url: base + 'KBFolderPermission.ivp/InheritPermissions',
        data: params,
        success: function() {
            alert(KBResources.InheritPermissionsSuccess);
            $('#inheritprop').hide();
        },
        error: function (request, status, error) {
            alert(error);
        }
    });
}

/******************************filter**********************************/

function loadFilter() {
    if ($('#filterholder #filter').length > 0) { $('#filterholder').show(); return false; }
    var url = base + 'kbdocument.ivp/LoadFilter';
    $('body').append('<div id="filterholder" style="display: none;" class="popupwrapper"></div>').find('#filterholder').load(url, {
        timestamp: new Date().toString(),
        action: tableAction()
    }, initFilter);
    return false;
}

function clearFilter() {
    if ($('#clearfilter').hasClass('disabled')) return false;

    var params = { reset: true, nolayout: true, timestamp: new Date().toString() };
    //Уберем фильтр чтобы сбросить его состояние
    $('#filterholder').remove(); $('ul.filterlist li.selected').removeClass('selected');
    $('#showfilter').attr('src', $('#showfilter').attr('src').replace('_active', ''));
    //$('#search').val('');
    disableSaveAndClear();

    reloadKBFrame(params);

    return false;
}


function initFilter() {
    if ($('#filter').length > 0) {
        if ($.fn.calendar) {
            $('#filter input.date, #filter input.dateTime').change(function () {
                var $this = $(this);
                var date = $.parseDate($this.val());
                if (!date) {
                    $this.attr("date", '');
                    return;
                }
                if (date.getHours() == 0 && date.getMinutes() == 0)
                    $this.attr("date", date.print('%Y-%m-%d'));
                else
                    $this.attr("date", date.print('%Y-%m-%d %H:%M'));
            });
        }
        //Фильтр. Скрыть/показать поля для даты при изменении "равно" на "между"
        //Фильтр. Скрыть/показать поля для выбора при изменении условия с/на "задано","не задано"
        $('#filter .fttdate').change(function () {
            switch (this.value) {
                case "1":
                    $(this).parents('table').find('.fltdate').show();
                    $(this).parents('table').find('.date2').hide();
                    break;
                case "2":
                case "3":
                    $(this).parents('table').find('.fltdate').show();
                    $(this).parents('table').find('.date2').show();
                    break;
                case "4":
                case "5":
                    $(this).parents('table').find('.fltdate').hide();
                    $(this).parents('table').find('.date2').hide();
            }
        });
        //Фильтр. Скрыть/показать поля для чисел при изменении "равно" на "между"
        //Фильтр. Скрыть/показать поля для выбора при изменении условия с/на "задано","не задано"
        $('#filter .fttnumeric').change(function (el) {
            $(this).parents('table').find('.numeric').show();
            if (this.value == 5) $(this).parents('table').find('.numeric2').show(); else $(this).parents('table').find('.numeric2').hide();
            if (this.value == 4) { $('.numeric3', this.parentNode).show(); $(this).parents('table').find('.numeric').css('width', 150); } else { $(this).parents('table').find('.numeric3').hide(); $(this).parents('table').find('.numeric').css('width', 50); }
            if (this.value == 6 || this.value == 7) $(this).parents('table').find('.numeric').hide();
        });

        //Установка значений по умолчанию
        $('#filter .flttext').change(function () { var ftt = '#ftt' + this.id.substr(3); if ($(ftt).val() == 0 && this.value.length > 0) $(ftt).val(1); });
        $('#filter .numeric').change(function () { var ftt = '#ftt' + this.id.substr(4); if ($(ftt).val() == 0 && this.value.length > 0) $(ftt).val(1); });
        //В зависимости от количества опций, выбрать "Входит в" или "Содержит любое из"
        $('#filter .fltselect').change(function () { var ftt = '#ftt' + this.id.substr(3); if ($(ftt).val() == 0 && this.selectedIndex >= 0) $(ftt).val(($('option', ftt).length > 5) ? 3 : 1); });
        $('#filter .flttree').change(function () { var ftt = '#ftt' + this.id.substr(3); if ($(ftt).val() == 0 && this.selectedIndex >= 0) $(ftt).val(3); });
        $('#filter .fltdate').change(function () { var ftt = '#ftt' + this.id.substr(4); if ($(ftt).val() == 0 && this.value.length > 0) $(ftt).val(1); });

        ////Заменим выпадающие списки на спец. контрол
        if ($.multipleSelect) $.multipleSelect.initByClassName('.multipleselect', { maxwidth: '300px', init: true });

        //Фильтр. Скрыть/показать поля для выбора при изменении условия с/на "задано","не задано"
        $('#filter .fttselect').change(function () {
            if (this.value == 3 || this.value == 4) $(this).parents('tr').find('.tdvalue div').hide(); else $(this).parents('tr').find('.tdvalue div').show();
        });
        $('#filter .fttrelation').change(function () {
            if (this.value == 7 || this.value == 8) $(this).parents('tr').find('.tdvalue div').hide(); else $(this).parents('tr').find('.tdvalue div').show();
        });
        $('#filter .ftttext').change(function () {
            if (this.value == 7 || this.value == 8) $(this).parents('tr').find('.flttext').hide(); else $(this).parents('tr').find('.flttext').show();
        });
        $('#filter .ftttree').change(function () {
            var self = this;
            var flt = $('#flt' + self.id.substr(3));
            var ms = flt.data('multipleselect');
            if (self.value == 1 || self.value == 2) {
                flt.attr('multiple', false);
                ms.unwrapControl();
            }
            else {
                flt.attr('multiple', true);
                ms.wrapControl(true);
            }
        }).trigger('change');
        $('#filterholder').show();
    }
}

function applyFilter() {
    var params = $('#filter form').serializeArray();
    for (var i = 0; i < params.length; i++) {
        if (params[i].name.indexOf("flt") >= 0) {
            var filterfield = $("#filter input[name = " + params[i].name + "][date]");
            if (filterfield.length > 0 && filterfield.attr("date")) {
                params[i].value = filterfield.attr("date");
            }
        }
    }

    var orderby = '';
    $('select.orderby option:selected').each(function (i, el) { if (el.value) orderby += ((orderby.length > 0) ? ',' : '') + el.value; });

    params[params.length] = { name: 'tb_stateid', value: '' };
    if ($('#search').length > 0) params[params.length] = { name: 'tb_search', value: $('#search').val() };
    params[params.length] = { name: 'timestamp', value: new Date().toString() };
    params[params.length] = { name: 'nolayout', value: true };

    $('div.multipleselectpopup').hide();
    $('#filterholder').hide(); $('ul.filterlist li.selected').removeClass('selected');
    $('#showfilter').attr('src', $('#showfilter').attr('src').replace('_active', '').replace('.gif', '_active.gif'));

    enableSaveAndClear();
    reloadKBFrame(params);

    return false;
}
function reloadKBFrame(params) {
    params[params.length] = { name: 'searchstring', value: '' };
    var url = base + 'kbdocument.ivp/search';
    $("#kbdocumentholder").load(url, params, onContainerUpdate);
    return false;
    }

function clearFilter() {
    if ($('#clearfilter').hasClass('disabled')) return false;

    var params = [
        { name: "reset", value: true },
        { name: "nolayout", value: true },
        { name: "timestamp", value: new Date().toString() }];

    //Уберем фильтр чтобы сбросить его состояние
    $('#filterholder').remove(); $('ul.filterlist li.selected').removeClass('selected');
    $('#showfilter').attr('src', $('#showfilter').attr('src').replace('_active', ''));

    disableSaveAndClear();
    reloadKBFrame(params);

    return false;
}
function enableSaveAndClear() {
    $('#showsavefilter').attr('src', 'img/buttons/savefilter.gif'); $('#showsavefilter').removeClass('disabled');
    $('#clearfilter').attr('src', 'img/buttons/clearfilter.gif'); $('#clearfilter').removeClass('disabled');
}
function disableSaveAndClear() {
    $('#showsavefilter').attr('src', 'img/buttons/savefilter_disabled.gif'); $('#showsavefilter').addClass('disabled');
    $('#clearfilter').attr('src', 'img/buttons/clearfilter_disabled.gif'); $('#clearfilter').addClass('disabled');
}

/*
function enableOrDisableClear() {
    if ($("#search").val() != '') {
        $('#clearfilter').attr('src', 'img/buttons/clearfilter.gif'); $('#clearfilter').removeClass('disabled');
    }
    if ($("#search").val() == '') {
        $('#clearfilter').attr('src', 'img/buttons/clearfilter_disabled.gif'); $('#clearfilter').addClass('disabled');
    }
    return false;
}



/**********search options*****************/

function chooseSearchLocation(link) {
    return showPopupSelect(link, 'selectsearchlocationtemplate');
}

function showPopupSelect(link, templateName) {
    link = $(link);
    var wrapperId = templateName + 'wrapper';
    var td = link.parent();

    hideOtherPopups(wrapperId);

    if (td.find('#' + wrapperId).length > 0)
        td.find('#' + wrapperId).toggle();
    else {
        var html = '<div id="' + wrapperId + '" class="popupwrapper px150"><div class="popup">' + $('#' + templateName).html() + '</div></div>';
        td.append(html).find('#' + wrapperId).css({ left: link.position().left, top: 15 }).show();
    }
    return false;
}

function hideOtherPopups(id) {
    $('.popupwrapper').not('#' + id).hide();
    return false;
}

function hidePopupSelect(link) {
    $(link).parents('.popupwrapper').hide();
    return false;
}


function setSearchToFolder(link) {
    setSearchOptions(link, 'searchwhere', 'folder');

    return false;
}

function setSearchOptions(link, group, value) {
    link = $(link);
    var radio = $('#' + group + value);
    radio.attr('checked', 'checked');
    var targetlink = $('a#searchlocationlink');
    targetlink.text(link.html());
    hideOtherPopups();
    $('#searchbutton').trigger('click');
    return false;
}

function resetSearchOptions(value) {
    //установим местоположение поиска
    setSearchOptions($('a#' + value), 'searchwhere', value);
    //сбросим строку поиска
    $('#search').val('');
    //удалим теги
    removeAllSearchTags();
    return false;
}


/*
function chooseSearchType(link) {
	return showPopupSelect(link, 'selectsearchtypetemplate');
}


/***************kbdocument **/

function saveKBDocument(url, e) {
    var kbDocumentForm = $("#kbDocument");

    if (kbDocumentForm.valid()) {

        if (e)
            e.preventDefault();
        var data = kbDocumentForm.serialize() + "&nolayout=true&json=json";

        $.post(kbDocumentForm.attr("action"),
            data,
            function (entity) {
                var id = $.parseJSON(entity).Id;
                if (!url)
                    url = base + 'kbdocument.ivp/edit/' + id;

                $("#kbdocumentholder").load(url, { nolayout: true }, onContainerUpdate);
            }
        );

        return false;
    }
    return false;
}

function deleteDocument(id) {
    if (!confirm(KBResources.SureDeleteDocument)) return false;
    $.getJSON(base + 'kbdocument.ivp/delete',
            {
                json: true,
                id: id,
                date: new Date().toString()
            },
            function (result) {
                if (result.hasOwnProperty('IsOK') && !result.IsOK)
                    alert(result.Description);
                else {
                    $('#doc' + result.Id).fadeOut('fast');
                    $('#docdescr' + result.Id).fadeOut('fast');
                }
            });
    return false;
}


function changeParent() {
    $('#parentadvice').show();
    $('#changelocationlink').hide();
    //
    $("#kbtree").on("click.setParent", "li", function (e) {
        debugger;
        e.preventDefault();
        var folder = $(this);
        var folderid = $(this).data("id");
        var foldername = $(this).find(".k-in").first().text();
        $.getJSON(base + 'kbdocument.ivp/getfolderpermissions', { folderid: folderid, timestamp: new Date().toString() }, function (permission) {
            if (permission.CanCreate) {
                $("#kbtree").data("kendoTreeView").toggle(folder);
                setParent(folderid, foldername);
                if (permission.CanPublicate || permission.IsAdmin) {
                    $('#ispublished').removeAttr("disabled");
                } else {
                    $('#ispublished').attr("disabled", "disabled");
                }
            } else {

                var childFolder =  $(folder).find('ul.k-group');
                if ($(childFolder).length !== 0 && $(childFolder).is(':hidden')) {
                    $(childFolder).show();
                } else {
                    alert(KBResources.CantMoveToCatalog);
                }
            }
        });
        $("#kbDocument").submit(function (event) {
            $("#kbtree").off("click.setParent");
        });

        return false;
    });
    //

    return false;
}

function setParent(id, breadcrumbs) {
    $('#changelocationlink').show();
    if (id < 0) {
        //parent.frames.tree.setMode('NORMAL');
        $('#parentadvice').hide();
        return false;
    }
    if (!$('#oldparentid').val())
        $('#oldparentid').val($('#parentid').val());

    $('#parentid').val(id);
    $('#breadcrumbs').removeClass('hidden');
    $('#breadcrumbs').addClass('changed').text(breadcrumbs);
    $('#parentadvice').hide();
    $('.save').removeAttr("disabled");
    $('.saveandreturn').removeAttr("disabled");
    $('.saveandreturn').unbind('click');
    $("#kbDocument").append("<input id='returnUrl' type='hidden' value = " + base + 'kbdocument.ivp/list/' + id + " />");



    return true;
}

/*****************choose members***************************/

/******users******/
function chooseUser(folderid) {
    var url = 'user.ivp/select?tb_mode=kbfolder&tb_serviceid=0&tb_kbfolderid=' + folderid;
    var dialog = openDialog(url, 'selectusers', { width: 980, height: 650 });
    dialog.callback = usersCallback;
    return false;
}

function usersCallback(result) {
    var uids = result["selectedIds"];
    var pid = result["permissionId"];
    addSelectedUsers(uids, pid);
}

function addSelectedUsers(uids, pid) {
    var folderId = $('#kbFolder #id').val();
    $.post(base + 'kb.ivp/addpermissions', {
        folderId: folderId, permissionid: pid, uids: uids.join(','), timestamp: new Date().toString(), nolayout: true
    }, function () { reloadPermissions('Users'); });
}

/******companies******/
function chooseCompany(folderid) {
    var url = 'company.ivp/select?reset=true&tb_custom_mode=kbfolder&tb_kbfolderid=' + folderid;
    var dialog = openDialog(url, 'selectcompanies', { width: 980, height: 650 });
    dialog.callback = companiesCallback;
    return false;
}

function companiesCallback(result) {
    var ids = result["selectedIds"];
    var pid = result["permissionId"];
    addSelectedCompanies(ids, pid);
}

function addSelectedCompanies(cids, pid) {
    var folderId = $('#id').val();
    $.post(base + 'kb.ivp/addpermissions', { folderId: folderId, permissionid: pid, cids: cids.join(','), timestamp: new Date().toString(), nolayout: true }, function () { reloadPermissions('Departments'); });
}

/******services******/
function chooseService(folderid) {
    var url = 'service.ivp/select?reset=true&tb_custom_mode=kbfolder&tb_kbfolderid=' + folderid;
    var dialog = openDialog(url, 'selectservices', { width: 980, height: 650 });
    dialog.callback = servicesCallback;
    return false;
}

function servicesCallback(result) {
    var ids = result["selectedIds"];
    var pid = result["permissionId"];
    addSelectedServices(ids.join(','), pid);
}

function addSelectedServices(sids, pid) {
    var folderId = $('#id').val();
    $.post(base + 'kb.ivp/addpermissions', { folderId: folderId, permissionid: pid, sids: sids, timestamp: new Date().toString(), nolayout: true }, function () { reloadPermissions('_Services'); });
}

/**************permissions***********************/

function changePermission(link) {
    link = $(link);
    var td = link.parent();
    $('.popupwrapper').hide();
    if (td.find('.popupwrapper').length > 0)
        td.find('.popupwrapper').show();
    else {
        var html = '<div class="popupwrapper"><div class="popup">' + $('#selectpermissiontemplate').html() + '</div></div>';
        td.append(html).find('.popupwrapper').css({ left: td.position().left + 10, top: td.position().top + 10 }).show();
    }
    return false;
}

function hidePermission(link) {
    $(link).closest('.popupwrapper').hide();
    return false;
}

function setPermission(link, permissionid) {
    var dd = $(link).closest('dd');
    $(link).parents('.popupwrapper').remove();
    var url = base + 'kb.ivp/changepermission';

    $.getJSON(url, { permissionid: permissionid, kbfpermissionid: getId(dd.find('a:first').attr('id')), timestamp: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else {
            dd.find('a:first').text($(link).text());
        }
    });
    return false;
}



function closeForm(url) {
  
    if (url) {
        tinymce.remove('#kbDocument textarea');
        $("#kbdocumentholder").load(url, { nolayout: true });
        return;
    } else {
        $("#kbdocumentholder").html("");
    }

    return;
}

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

function removeFile(id) {
    $.getJSON('kbdocument.ivp/removefile/' + id, { date: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true)
            $('#file' + result.Id).fadeOut('fast').remove();
        else
            alert(result.Description);
    });
    return false;
}

function changePage(page) {
    var searchstring = $("#search").val();
    var selectedfolderid = $('#selectedfolderid').val();
    var searchwhere = $('#searchlocationholder input.rb:checked').val();
    if (page) {
        $("#kbdocumentholder").load(tableUrl(), { searchstring: searchstring, searchwhere: searchwhere, selectedfolderid: selectedfolderid, tb_page: page, page: page, nolayout: true, timestamp: new Date().toString() }, function () {
            // initTable();
            if ($('#tableholder').length > 0) {
                $("#kbdocumentholder").css("overflow", "hidden");
                $('#tableholder').css('height', $('#kbdocumentholder').height() + 7);
            }
        });
    } else {
        $("#kbdocumentholder").load(tableUrl(), { searchstring: searchstring, searchwhere: searchwhere, selectedfolderid: selectedfolderid, nolayout: true, timestamp: new Date().toString() }, function () {
            //initTable();
            if ($('#tableholder').length > 0) {
                $("#kbdocumentholder").css("overflow", "hidden");
                $('#tableholder').css('height', $('#kbdocumentholder').height() + 7);
            }
        });
    }

    return false;
}

//Написан на основе метода toggle из common.js
function togglePermissions(link, id) {
    if ($(id).is(':visible')) {
        $(link).html('&darr;&#160;' + CommonResources.Show);
    }
    else {
        //Скроем все элементы кроме текущего, которые имеют класс permissionsholder
        $('div.permissionsholder[id!=' + id.substr(1) + ']').addClass('hidden');
        $('a.toggle').html('&darr;&#160;' + CommonResources.Show);

        $(link).html('&uarr;&#160;' + CommonResources.Hide);
    }
    // fix. for IE8
    $(id).toggleClass('hidden'); // it work	
    return false;
}

function rollList() {
    $(".k-minus").click();
    $(this).scrollTop(0);
    return false;
}


function addTinyEditor(selector,isHideToolBar,isOpenDialog) {
    tinymce.init({
        selector: selector,
        menubar: false, 
        toolbar_items_size: 'small',
        statusbar: false,//убирает нижний бар с ссылкой на плагин
        themes: 'modern',
        width: isOpenDialog ? '98%':'100%',      
        plugins: isHideToolBar ? 'preview' : 'print  paste autoresize preview link   autolink     fullscreen image link media   table charmap hr   anchor   advlist lists  wordcount  imagetools    contextmenu  textcolor colorpicker code',
        toolbar: isHideToolBar ? false : 'saveButton cancel Mypreview | undo redo | fontsizeselect bold italic strikethrough | forecolor backcolor | link  code | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent | table | removeformat  ',
        plugin_preview_width: 1000,
        language: CommonResources.LanguagePrefix,      
        table_default_attributes: {
            border: 1
        },
        automatic_uploads: true,
        paste_data_images :true,
       
        images_no_converturl: true,
        table_default_styles: {
            border: '1px solid black',
            width: '50%'
        },
        relative_urls: false,
        convert_urls:false,
        file_picker_types: 'image', 
    
        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');  

            input.onchange = function() {
                var file = this.files[0];
      
                var reader = new FileReader();
                reader.onload = function () {
                  
                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);
                   
                    cb(blobInfo.blobUri(), { title: file.name });
                };
                reader.readAsDataURL(file);
            };    
             input.click();
           
        },
        autoresize_min_height:isOpenDialog?400: 780,
        autoresize_max_height: 1000, 
        default_link_target: "_blank",      
        setup: function (editor) {   
            editor.addButton('saveButton', {
                text: KBResources.Save,
                icon: false,
                classes: 'mybutton',
                onclick: function () {
                    var content = tinymce.get('dialogTiny').getContent();
                    tinymce.get('description').setContent(content);
                    $('body').find('#kbDocument textarea').val(content);
                    $('body').find('#kbDocument textarea').closest('.field').addClass('changed')                  
                    $("#mainfielddialog").dialog("close");
                    tinymce.get('description').getDoc().body.style.backgroundColor = "#f9f8e0";
                   
                }
            });
            editor.on('init', function () {
                if (!isOpenDialog)
                    editor.focus();  
            });
            editor.addButton('cancel', {
                text: CommonResources.Cancel,
                icon: false,
                classes: 'mybutton',
                onclick: function () {                 
                    $("#mainfielddialog").dialog("close");
                }
            });
            editor.addButton('Mypreview', {
                text: KBResources.Preview,
                icon: false,
                classes: 'mybutton',
                onclick: function () {
                    tinymce.activeEditor.execCommand('mcePreview');
                }
            });
        },
        init_instance_callback: function (editor) { 
            if (isOpenDialog) {
                editor.on('click', function (e) {
                    var content = tinymce.get('description').getContent()
                    showDiscription(content)
                });
            }
        }          
    });
}

function showDiscription(content) {   
    var dialog = $('<div id="mainfielddialog" class="hidden"><div class="warning">' + KBResources.PasteImageInfo + '</div><textarea style="height:98%" id="dialogTiny"/></div>').dialog({
        width: '80%',      
        position: ['top',40],       
        open: function () {
            $('#dialogTiny').val(content);  
            addTinyEditor("#dialogTiny", false, false);
            jQuery('.ui-widget-overlay').on('click', function () {
                jQuery('#mainfielddialog').dialog('close');
            });
        },      
        modal: true,

        close: function () {            
            tinymce.remove('#dialogTiny');
            $(this).dialog("destroy");
            $(this).remove();           
        }
    });
    dialog.dialog('open');
    dialog.dialog("option", "title", CommonResources.Change + ": "+  $('#name').val());  
}

function previewTiny() {
    tinymce.activeEditor.execCommand('mcePreview');  
}