var KBDeatailsState = { show: false, showTimeoutId: 0, hideTimeoutId: 0, selector: '#ikb' };

$(function () {
    $('#KBSearch')//.autocomplete('kbdocument.ivp/findtagsforsearch', { minChars: 3 }).result(kBtagAdded);
    .devbridgeAutocomplete({
        serviceUrl: 'kbdocument.ivp/findtagsforsearchjson/',
        minChars: 1,
        autoClearInputOnSelect: true,
        onSelect: kBtagAdded,
        onEnter: function () {
            searchKBDialog();
        },
        onEnterWithEmptyValue: true
    });
});

function kBtagAdded(tag) {
    var tagValue = tag.value;
    var tagId = tag.data.id;

    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#KBTags');

        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',
            'style': 'cursor: pointer',
            'onclick': 'removeKBTag($(this).parent().attr("rel"))'
        });

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

function removeKBTag(tagId) {
    $('select#tid > option[value="' + tagId + '"]').remove();
    $('#KBTags li[rel="' + tagId + '"]').remove();
    if ($('#KBTags li').length == 0) {
        $('#KBTags').hide();
        $('#dialog #KBTags').hide();
    }
    return false;
}

function searchKBInitResults() {
    $('.kb-search-option').on({
        mouseover: function (event) {
            showKbDocumentDetails($(this).attr('id'), event);
        },
        mouseout: hideKbDocumentDetails
    });
}

function searchKBDialog() {
    var tagIds = $('#tid').val();
    if (tagIds != null) tagIds = tagIds.join('&tid=');
    var searchString = $('#KBSearch').val();
    $.get(base + 'Task/KbSearchDialog?q=' + searchString + '&tid=' + tagIds, function (response) {
        createModalDialog(TaskResources.SearchInKB, response);
        $('#DialogKBSearch')//.autocomplete('kbdocument.ivp/findtagsforsearch', { minChars: 3 }).result(kBtagAdded);
        .devbridgeAutocomplete({
            serviceUrl: 'kbdocument.ivp/findtagsforsearchjson/',
            minChars: 1,
            autoClearInputOnSelect: true,
            onSelect: kBtagAdded,
            onEnter: function () {
                searchKbDocuments();
            },
            onEnterWithEmptyValue:true
        }).val(searchString);
        searchKBInitResults();
        var dialogTags = $('#dialog #KBTags');
        dialogTags.html($('#KBTags').html());
        dialogTags.find('a.closebutton').on('click', function () {
            removeKBTag($(this).parent().attr('rel'));
        });
        if (dialogTags.find('li').length > 0)
            dialogTags.show();
    });
    return false;
}



function searchKbDocuments() {
    var tagIds = $('#tid').val();
    if (tagIds != null) tagIds = tagIds.join(',');
    $.get(base + 'Task/FindKbDocuments?q=' + $('#DialogKBSearch').val() + '&tid=' + tagIds, function (response) {
        $('#kbSearchResults').html(response);
        searchKBInitResults();
    });
    return false;
}

function hideKbDocumentDetails() {
    KBDeatailsState.show = false;
    clearTimeout(KBDeatailsState.showTimeoutId);
    KBDeatailsState.hideTimeoutId = setTimeout(function () {
        if ($(KBDeatailsState.selector + ':hover').length == 0)
            $(KBDeatailsState.selector).hide();
    }, 400);
}

function showKbDocumentDetails(id, e) {
    KBDeatailsState.show = true;
    clearTimeout(KBDeatailsState.hideTimeoutId);
    KBDeatailsState.showTimeoutId = setTimeout(function () { _showKbDocumentDetails(id, e) }, 500);
}

function _showKbDocumentDetails(id, e) {
    if (!KBDeatailsState.show) return;
    var $kbDetails = $(KBDeatailsState.selector);
    if ($kbDetails.length == 0) {
        $('body').append('<div id="ikb" class="taskdescription popupwrapper"><div class="popup"></div></div>');
        $kbDetails = $(KBDeatailsState.selector);
        $kbDetails.on('mouseout', hideKbDocumentDetails);
    }
    $kbDetails.find('.popup').load('Task/KbDocumentDetails/' + id, function () {
        var $li = e.target.nodeName == 'LI' ? $(e.target) : $(e.target).parent();
        var offset = $li.offset();
        $kbDetails.css({
            top: offset.top + $li.height(),
            left: offset.left + 20
        }).show();
    });
}

function kbDocumentAsText(id) {
    $.get(base + 'Task/KbDocumentPaste/' + id, function (response) {
        addToComment(response, id);
    });
}
function kbDocumentAsLink(id) {
    addToComment(base + 'kb.ivp/tree?documentId=' + id + " ", id);
}
function addToComment(text, documentId) {
    //Добавляем текст к комментарию
    var $currentcomment = $('#currentcomment');
    $currentcomment.val($currentcomment.val() + text);
    $('#currentcommentdiv').html($currentcomment.val().replace(/\r?\n/g, '<br/>'));
    $currentcomment.trigger('paste');

    //Увеличиваем рейтинг документа
    $.post(base + 'kbdocument.ivp/IncrimentDocumentRating/' + documentId, function (response) { });

    //Прячем попап, закрываем диалог, убираем теги и отчищаем поиск
    KBDeatailsState.show = false;
    $(KBDeatailsState.selector).hide();
    $('#dialog').dialog('close');
    var $tagsSelect = $('#tid');
    var tagIds = $tagsSelect.val();
    if (tagIds != null) {
        tagIds.forEach(function (e) {
            $('li[rel=' + e + ']').remove();
        });
    }
    $tagsSelect.find('option').remove();
    $('#DialogKBSearch').val('');
    $('#KBSearch').val('');
}