var positionMax = 15;
var countStep = 5;
var currentListRequest = null;
var lastQuery = '';
var isSearchSubstring = false;
var usertype = '';
var categoryCondition = 'and';
var isnumber = false;
var suggestions = [];
var siteDomain = '';
var addServiceTag = false;

var intraObjects = [
           { priorityid: 1, isEmpty: false, type: 'status' },
           { priorityid: 2, isEmpty: false, type: 'category' },
           { priorityid: 3, isEmpty: false, type: 'user' },
           { priorityid: 4, isEmpty: false, type: 'executorgroup' },
           { priorityid: 5, isEmpty: false, type: 'company' },
           { priorityid: 6, isEmpty: false, type: 'asset' },
           { priorityid: 7, isEmpty: false, type: 'tasktype' },
           { priorityid: 8, isEmpty: false, type: 'service' }
];

$(function () {    
    siteDomain = $("#sitedomain").size() > 0 ? $('#sitedomain').val() : '';
    newsearchAutocomplete();
    handleFilterToolbarState();
});

function newsearchAutocomplete() {
    $('#newsearch')
    .devbridgeAutocomplete({
        serviceUrl: 'task/NewSearch/',
        minChars: 2,
        width: '500px !important',
        maxHeight: 'auto !important',
        widthImportant: true,
        autoClearInputOnSelect: true,
        closeAfterOnEnter: true,
        onSelect: searchAdded,
        onEnter: searchWord,
        onEnterWithEmptyValue: true,
        customAjaxFunction: multiAjax,
        otherResponseCache: getUserSearchCache,
        autoQueryOnEmptyField: true,
        autoSelectFirst: false,
        containerClass: 'autocomplete-suggestions tasksearchContainer',
        onFocusOverride: function (that) {
            showWideSearch(that);
            $(that.element).attr('placeholder', '');
        },
        onBlurStart: function (that) {
            if (!clickToggle)
                hideWideSearch();
            $(that.element).attr('placeholder', $(that.element).attr('text-placeholder'));
        },
        onValueChangeBeforeSuggestion: function (that) {
            showWideSearch(that);
        },
        onSearchStart: function (params) {
            usertype = '';
            isnumber = false;
            var testString = params['q'];
            var reg = /^[#№]?[0-9]+\s*$/;
            //если поиск по номеру - то сбрасываем фильтр
            if (testString != '' && reg.test(testString)) {
                isnumber = true;
            }
        },
        formatResult: function (suggestion, currentValue) {
            var pattern = '(' + currentValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ')';
            var cValue = '<span class="ac-value">' + suggestion.value
                .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/&lt;(\/?strong)&gt;/g, '<$1>') + '</span>';
            if (suggestion.data.type == "user") {
                cValue += ' <span class="userTag" onclick="addUser(\'creator\')">' + TaskResources.CreatorTitle + '</span>';
                cValue += ' <span class="userTag" onclick="addUser(\'executor\')">' + TaskResources.ExecutorTitle + '</span>';
                cValue += ' <span class="userTag" onclick="addUser(\'observer\')">' + TaskResources.ObserverTitle + '</span>';
            }
            else if (suggestion.data.type == "category" && $('div.bit-box[tagtype="category"]').size() > 0) {
                cValue += '<span class="searchTag">' + suggestion.data.tagresource;
                cValue += ' (<span class="categoryCondition">' + TaskResources.ConditionAnd + '</span>,';
                cValue += ' <span class="categoryCondition" onclick="addSearchCategory(\'or\')">' + TaskResources.ConditionOr + '</span>)';
                cValue += '</span>';
            }
            else {
                cValue += ' <span class="searchTag">' + suggestion.data.tagresource + '</span>';
            }
            return cValue;
        }
    });
}

function getUserSearchCache(q) {
    if ((q && q.length > 2) || localStorage == null || localStorage[siteDomain + "_tasksearchresult"] == null)
        return { "suggestions": [] };
    var result;
    try{
        result = JSON.parse('{ "suggestions": ' + localStorage[siteDomain + "_tasksearchresult"] + '}');
    }
    catch (e) {
        return { "suggestions": [] };
    }
    return result;
}

function searchDate(q, autocomplete, cacheKey) {
    var dateReg = /^[0-9]{1,2}[./][0-9]{1,2}[/.]([0-9]{2,4})?$/;
    testString = q;
    if (testString != '' && dateReg.test(testString)) {
        var char = testString.indexOf('.')>0 ? '.' : testString.indexOf('/')>0 ? '/' : '';
        if (char != '') {
            var dateParts = testString.split(char);
            var isEngFormat = char == '/';
            var day = (isEngFormat) ? parseInt(dateParts[1]) : parseInt(dateParts[0]);
            var month = (isEngFormat) ? parseInt(dateParts[0]) : parseInt(dateParts[1]);
            var year = '';
            if (dateParts[2] == '') {
                year = new Date().getFullYear();
            }
            else {
                var yearPart = dateParts[2];
                year = yearPart.length == 4 ? parseInt(yearPart) : parseInt(new Date().getFullYear().toString().substr(0, 2) + yearPart);
            }
            if (parseInt(month) > 0 && parseInt(month) < 13) {
                var monthString = month < 10 ? '0' + month : month;
                var dayString = day <10 ? '0' + day : day;
                var date = year + '-' + monthString + '-' + dayString;
                var dateString = (isEngFormat) ? monthString + '/' + dayString + '/' + year : dayString + '.' + monthString + '.' + year;
                var suggestions = {
                    suggestions: [{ value: dateString + ' → ', data: { id: 'datedeadline_' + date, tagname: dateString, tagresource: TaskResources.SearchDeadline, type: 'datedeadline' } },
                    { value: dateString + ' → ', data: { id: 'dateresolutionfact_' + date, tagname: dateString, tagresource: TaskResources.SearchResolutionFact, type: 'dateresolutionfact' } },
                    { value: dateString + ' → ', data: { id: 'datecreated_' + date, tagname: dateString, tagresource: TaskResources.SearchCreated, type: 'datecreated' } }]
                };
                var result = autocomplete.options.transformResult(suggestions, q);;
                customProcessResponse(autocomplete, result, q, cacheKey, true);
                return true;
            }           
            return false;
        }
    }
    return false;
}

//#region Search autocomplete functions
function multiAjax(autocomplete, params, options, q, cacheKey) {
    isSearchSubstring = false;
    usertype = '';    
    var positionEmpty = 0;
    var top = 0;
    var searchResultCount = 0;
    var positionEmpty = 0;
    var listObjects = intraObjects;
    if (lastQuery && lastQuery.length>0 && q.length > 0) {
        isSearchSubstring = q.indexOf(lastQuery) === 0;//уточнение поиска
    }
    if (!isSearchSubstring) {
        $.each(intraObjects, function (index, value) {           
            intraObjects[index].isEmpty = false;
        });
    }
    lastQuery = q;
    var isFindDate = searchDate(q, autocomplete, cacheKey);
    //$.merge(listObjects, $.grep(intraObjects, function (n, i) { return n.isEmpty == false; }));
    if (options.customSuggestionIndex) { options.customSuggestionIndex = 0; }
    doAjax(autocomplete, params, options, q, cacheKey, listObjects, searchResultCount, positionEmpty, !isFindDate, 0)
    
}

function doAjax(autocomplete, params, options, q, cacheKey, listObjects, searchResultCount, positionEmpty, isFirstStep, index) {        
    var searchTicket = isnumber && isFirstStep;
    var searchTerm = q;    
    if (searchTicket || (listObjects.length!=0 && listObjects.length >= index+1)) {
        var elem;
        var top;
        if (isnumber && isFirstStep) {
            elem = { type: 'task', isEmpty : false };
            top = 1;
            searchTerm = searchTerm.replace('#', '').replace('№', '');
        }
        else {
            elem = listObjects[index];
            top = positionEmpty + countStep;
            if (searchResultCount + top > positionMax)
                top = positionMax - searchResultCount;           
        }
        index = index + 1;
        if (!elem.isEmpty) {
            var newparams = { queryType: elem.type, top: top };
            newparams['q'] = searchTerm;
            ajaxSettings = {
                url: autocomplete.options.serviceUrl,
                data: newparams,
                type: options.type,
                dataType: options.dataType,
                beforeSend: function () {
                    if ($('.tasksearchContainer').size() > 0) {
                        $('.tasksearchContainer').append('<div class="autocomplete-suggestion loadingSuggestion"><span class="smallloading"><span>' + CommonResources.LoadingData + '</span></span></div>');
                        if ($('.tasksearchContainer:visible').size() == 0)
                            $('.tasksearchContainer').show();
                    }                    
                }
            };

            $.extend(ajaxSettings, options.ajaxSettings);

            autocomplete.currentRequest = $.ajax(ajaxSettings).done(function (data) {
                var result;
                autocomplete.currentRequest = null;
                result = options.transformResult(data, q);
                var countItems = result.suggestions.length;
                if (!searchTicket)
                    searchResultCount += countItems;
                if ($('.tasksearchContainer div.loadingSuggestion').size() > 0) {
                    $('.tasksearchContainer div.loadingSuggestion').remove();
                }
                customProcessResponse(autocomplete, result, q, cacheKey, isFirstStep);
                options.onSearchComplete.call(autocomplete.element, q, result.suggestions);
                if (!searchTicket && countItems == 0) {
                    setIntraObjectValueEmpty(elem);
                }
                isFirstStep = false;
                if (searchTicket || positionMax - searchResultCount > 0) {
                    if (!searchTicket)
                        positionEmpty = top - countItems;
                    doAjax(autocomplete, newparams, options, q, cacheKey, listObjects, searchResultCount, positionEmpty, isFirstStep, index);
                }
            }).fail(function (jqXHR, textStatus, errorThrown) {
                options.onSearchError.call(autocomplete.element, q, jqXHR, textStatus, errorThrown);
                isFirstStep = false;
                if ($('.tasksearchContainer div.loadingSuggestion').size() > 0) {
                    $('.tasksearchContainer div.loadingSuggestion').remove();
                }
                doAjax(autocomplete, newparams, options, q, cacheKey, listObjects, searchResultCount, positionEmpty, isFirstStep, index);
            });
        }
        else {
            doAjax(autocomplete, newparams, options, q, cacheKey, listObjects, searchResultCount, top, isFirstStep, index);
        }
        
    }
    return false;
}

function customProcessResponse(autocomplete, result, originalQuery, cacheKey, isFirstStep) {
    var that = autocomplete,
        options = that.options;
    that.setFirstStep(isFirstStep);
    if (isFirstStep) {
        $(that.suggestionsContainer).html('');
        that.setCustomIndex(null);        
    }    
    var currentResult = that.verifySuggestionsFormat(result.suggestions);
    var fullResult;
    if (!isFirstStep && that.suggestions.length > 0) {
        that.setCustomIndex(that.suggestions.length - 1);        
        fullResult = that.suggestions;
        $.merge(fullResult, currentResult);
    }
    else {
        fullResult = currentResult
    }
    result.suggestions = fullResult;    
    // Cache results if cache is not disabled:
    if (!options.noCache) {
        that.cachedResponse[cacheKey] = result;
        //if (options.preventBadQueries && result.suggestions.length === 0) {
        //    if(!(options.autoQueryOnEmptyField && originalQuery == ''))
        //        that.badQueries.push(originalQuery);
        //}
    }

    // Return if originalQuery is not matching current query:
    if (originalQuery !== that.getQuery(that.currentValue)) {
        return;
    }

    that.suggestions = result.suggestions;
    that.suggest();
}

//помечаем сущности, у которых в результате поиска было 0 результатов
function setIntraObjectValueEmpty(element) {
    $.each(intraObjects, function (index, value) {
        if (value.priorityid == element.priorityid) {
            intraObjects[index].isEmpty = true;
        }
    });
}

function addTagToCache(tag) {
    if (localStorage == null)
        return;
    if (localStorage[siteDomain + "_tasksearchresult"] != null && localStorage[siteDomain + "_tasksearchresult"] != '') {
        try{
            suggestions = JSON.parse(localStorage[siteDomain + "_tasksearchresult"]);
        }
        catch(e){
            suggestions = [];
            localStorage.removeItem(siteDomain + "_tasksearchresult");
        }        
    }
    var searcTagInCacheIndexes = $.map(suggestions, function (obj, index) {
        if (obj.data.id == tag.data.id)
            return index;
    });
    if (searcTagInCacheIndexes.length == 0) {
        Array.prototype.unshift.call(suggestions, tag);
        if (suggestions.length > 10)
            suggestions.pop();
        localStorage[siteDomain + "_tasksearchresult"] = JSON.stringify(suggestions);
    }
    else if (searcTagInCacheIndexes[0] != 0) {
        var searcTagInCache = suggestions[searcTagInCacheIndexes[0]];
        suggestions.splice(searcTagInCacheIndexes[0],1);
        Array.prototype.unshift.call(suggestions, searcTagInCache);
        localStorage[siteDomain + "_tasksearchresult"] = JSON.stringify(suggestions);
    }
}
//добавление тэга "поисковое слово"
function searchWord() {
    var elementValue = $(this).val();
    var reg = /^[#№][0-9]+\s*$/;
    var isNumber = elementValue != '' && reg.test(elementValue);
    var taskid = 0;
    if (isNumber)
        taskId = parseInt(elementValue.replace('#', '').replace('№', ''), 10);
    //если поиск по номеру
    if (isNumber && taskId > 0 && taskId < 2147483647) {//если это число и в пределах инта
        var number = elementValue.replace('#', '').replace('№', '');
        if (noexistTag('task_' + number)) {
            var tag = { value: number + ' → ', data: { id: 'task_' + number, type: 'task', tagresource: TaskResources.Ticket, tagname: number } };
            addTagToCache(tag);
            hideWideSearch();
            var tagFullName = number + ' (' +  TaskResources.Ticket + ')';
            addTag(tagFullName, 'task_' + number, tagFullName, "task");
            $(this).val('');
            $('#searchwordcache').val('');
        }
    }
    else { 
        if ($('#searchwordcache').val()==elementValue)//если поисковое слово не изменилось, то не ищем
            return false;
        else {
            if (elementValue != '') {//если ввели другое поисковое слово
                var tag = { value: elementValue, data: { id: 'searchword_' + elementValue, type: 'searchword', tagresource: '', tagname: elementValue } };
                addTagToCache(tag);
                hideWideSearch();
                $('#searchwordcache').val(elementValue);
                $('#btnClearSearch').removeClass('hiddenClearSearch');
            }
            else {//если сбросили поисковое слово
                $('#searchwordcache').val('');
                if ($('div#newsearchul div.bit-box').size() == 0)
                    $('#btnClearSearch').addClass('hiddenClearSearch');
            }
            _taskSearch();
        }
    }
}

//добавление тэга фильтрации
function searchAdded(tag) {
    var tagValue = tag.value;
    var tagId = tag.data.id;
    var tagname = tag.data.tagname;
    var tagtype = tag.data.type;
    if (tag.data.type == 'user') {
        tagtype = (usertype == '') ? 'creator' : usertype;
        tagId = tagtype + tagId.replace('user','');
        taskResource = tagtype == "executor" ? TaskResources.ExecutorTitle : tagtype == 'observer' ? TaskResources.ObserverTitle : TaskResources.CreatorTitle;
        tagname = tag.data.tagname + ' (' + taskResource + ')';
    }
    else if(tag.data.type != "searchword"){
        tagname = tag.data.tagname + ' (' + tag.data.tagresource + ')';
    }
    if (noexistTag(tagId.toString())) {
        addTagToCache(tag);
        if (tag.data.type == "searchword") {
            $('#newsearch').val(tag.value);
            $('#searchwordcache').val(tag.value);
            _taskSearch();
        }
        else {
            addTag(tagValue, tagId, tagname, tagtype);
        }
    }
}

//проверка на существование добавляемого тэга поиска
function noexistTag(id) {
    return $('div#newsearchul div[rel="' + id + '"]').size() == 0;
}
//определение условия для категории - ИЛИ
function addSearchCategory(condition) {
    categoryCondition = 'or';
}
//определение типа пользователя (для фильтрации)
function addUser(typeUser) {
    usertype = typeUser;
}
//добавление тэга поиска и запуск поиска
function addTag(tagtitle, tagid, tagname, tagtype) {
    hideWideSearch();
    abortAjaxSearch();
    var searchHolder = $('div#newsearchul');   
    //создание тега поиска
    var li = document.createElement("div");
    $(li).attr({
        'class': 'bit-box filtertag',
        'rel': tagid,
        'tagtype': tagtype
    });
    var span = document.createElement('span');
    tagname = tagname.replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
    $(span).attr({ 'title': tagname }).append((tagname.toString().length > 31) ? tagname.toString().substring(0, 30) + '..' : tagname);
    var aclose = document.createElement("a");
    $(aclose).attr({
        'class': 'closebutton',
        'style': 'cursor: pointer',
        'onclick': 'removeSearchTag($(this))'
    });
    li.appendChild(aclose);
    $(li).append(span);
    var orderGroupCategory = 0;    
    //var orderGroupCategory = $('.taggroup[type="category"]').size();
    var groupHolder;
    if ((tagtype == 'category' && ($('div.bit-box[tagtype="category"]').size() < 1 || categoryCondition == 'and')) || tagtype == 'searchword') {//если категории не добавлены или добавляем с условием И
        if (tagtype == 'category') {
            $.each($('.taggroup[type="category"]'), function (i, elem) {
                if ($(elem).attr('ordergroup') != null && $.isNumeric($(elem).attr('ordergroup')) && parseInt($(elem).attr('ordergroup')) > orderGroupCategory) {
                    orderGroupCategory = parseInt($(elem).attr('ordergroup'));
                }
            });
        }        
        var parentDiv = document.createElement('div');
        groupHolder = document.createElement('div');
        $(groupHolder).attr({ 'class': 'singlegroup taggroup' });
        if (tagtype == 'category') {
            var orderGroup = 
            $(groupHolder).attr('type', 'category').attr('orderGroup', orderGroupCategory + 1);
            var elementInFloat = document.createElement('div');
            $(elementInFloat).attr({ 'class': 'ingroupfloat' })            
            $(li).attr({ 'categoryDetails': '-' + (orderGroupCategory + 1) });
            $(elementInFloat).append(li);            
            $(groupHolder).append(elementInFloat);
            $(groupHolder).append('<div class="clear"></div>');
        }
        else {
            $(groupHolder).append(li);
        }        
        $(parentDiv).append(groupHolder);
        $(parentDiv).append('<div class="clear"></div>');
        $(searchHolder).append(parentDiv);        
    }
    else {//если категория и добавляем ее по ИЛИ, то надо прицепить к последней категории
        var addClear = false;
        var parent = null;
            if ($('div#newsearchul div.taggroup[type="' + tagtype + '"]').size() > 0) {
                groupHolder =  $('div#newsearchul div.taggroup[type="' + tagtype + '"]').last();
                if ($(groupHolder).hasClass('singlegroup')) {
                    $(groupHolder).removeClass('singlegroup').addClass('grouptype');
                    var groupDelete = document.createElement('a');
                    $(groupDelete).attr({ 'class': 'closebutton removegroup', 'style': 'cursor: pointer', 'onclick': 'removeSearchGroup($(this).parent());' });
                    $(groupHolder).prepend(groupDelete);
                }
                if (tagtype == 'category' && categoryCondition == 'or') {
                    parent = $(groupHolder).parent('.bottom5');
                    $(li).attr({ 'categoryDetails': '-' + ($(groupHolder).attr('orderGroup') != null ? $(groupHolder).attr('orderGroup') : 0) });
                }
                var lastChild = $(groupHolder).children('.ingroupfloat').last();
                $(lastChild).append('<div class="orCondition"> ' + CommonResources.Or + ' </div>');
            }
            else {
                groupHolder = document.createElement('div');
                $(groupHolder).attr({ 'class': 'singlegroup taggroup', 'type': tagtype });
                addClear = true;
            }
            
        var ingroupdiv = document.createElement('div');
        $(ingroupdiv).attr({ 'class': 'ingroupfloat' });
        $(ingroupdiv).append(li);
        $(groupHolder).append(ingroupdiv);
        $(groupHolder).append('<div class="clear"></div>');
        $(searchHolder).append(groupHolder);
        if(parent != null && $(parent).size()>0)
            $(parent).remove();
    }
    categoryCondition = 'and';
    $('#btnClearSearch').removeClass('hiddenClearSearch');
    $('#searchwordcache').val('');
    addServiceTag = tagtype == 'service';
    _taskSearch();
}
//удаление тэга поиска и запуск поиска
function removeSearchTag(elem) {
    var tag = $(elem).parent();
    var parentGroup = $(tag).parent().parent();
    if ($(parentGroup).hasClass('singlegroup')) {
        $(parentGroup).remove();
    }
    else {
        var currenttagGroupfloat = $(tag).parent();
        if (!$(currenttagGroupfloat).next().next().hasClass('ingroupfloat')) {
            $(currenttagGroupfloat).prev().prev().children('.orCondition').remove();
        }            
        $(currenttagGroupfloat).next().remove();
        $(currenttagGroupfloat).remove();
        if ($(parentGroup).children('.ingroupfloat').size() == 1) {
            $(parentGroup).removeClass('grouptype').addClass('singlegroup');
            $(parentGroup).children('.removegroup').remove();
        }
    }
    
   // $('#newsearchul div[rel="' + tagId + '"]').remove();
    abortAjaxSearch();
    _taskSearch();
    if ($('div#newsearchul div.taggroup').size() == 0 && $('#newsearch').val() == '') {
        $('#btnClearSearch').addClass('hiddenClearSearch');
    }
    return false;
}

function removeSearchGroup(elemGroup) {
    $(elemGroup).remove();
    abortAjaxSearch();
    _taskSearch();
    if ($('div#newsearchul div.bit-box').size() == 0 && $('#newsearch').val() == '') {
        $('#btnClearSearch').addClass('hiddenClearSearch');
    }
    return false;
}
//#endregion Search autocomplete functions

//#region Task Search
function searchMore(thisLink) {    
    _taskSearch(true);
    $('.searchMore').addClass('hidden');
    $('.searchMoreDisabled ').removeClass('hidden');
    toggleSearchSetting($('.btnSearchSetting'), false);
    return false;
}

//надо ли показывать ссылку "искать по подстроке"
function isSearchMore() {
    if ($('#islikesearch').val().toLowerCase() == 'true' || $('#searchwordcache').val() == '') {
        $('.searchMore').addClass('hidden');
        $('.searchMoreDisabled ').removeClass('hidden');
    } else {
        $('.searchMore').removeClass('hidden');
        $('.searchMoreDisabled ').addClass('hidden');
    }
}

function _taskSearch(isLikeSearch) {
    abortAjaxSearch();
    var isSearchWithoutFilter = $('#tb_issearchwithoutfilter') && $('#tb_issearchwithoutfilter').val() == "True";
    var stringValue = '';
    var searchWords = $('#searchwordcache').val();
    //если поиск по номеру - то сбрасываем фильтр
    if ($('div#newsearchul div[tagtype="task"]').size()>0) {      
        isSearchWithoutFilter = true;
        toggleSearchWithoutFilter(false);
    }
    $.each($('div#newsearchul div.bit-box'), function (i, elem) {
        stringValue += ($(elem).attr('categoryDetails')!=null) ? $(elem).attr('rel') + $(elem).attr('categoryDetails') + '|' : $(elem).attr('rel') + '|';
    });
    stringValue = (stringValue.length > 0) ? stringValue.substring(0, stringValue.length - 1) : '';
    if ($('#tb_issearchwithoutfilter')) $('#tb_issearchwithoutfilter').val('False');
    var isLike = isLikeSearch != null ? isLikeSearch : false;
    $('#islikesearch').val(isLike);
    toggleSearchSetting($('.btnSearchSetting'), false);
    params = {};
    if (isSearchWithoutFilter && !isFilterAndServiceNotApply()) {
        if ($('div#newsearchul div').size() == 0 && $('#newsearch').val()=='')
            return false;
        params = mergeTableDefaultLoadParams();

        params["tb_stateid"] = "";
        params["reset"] = true;
        params["tb_serviceid"] = 0;
        $("#serviceid").val('0');
        $("#serviceid").trigger("chosen:updated");
        params["tb_page"] = 1;
        params["nolayout"] = true;
        params["tb_tasksearchfilter"] = stringValue;
        params["tb_searchwords"] = searchWords;
        params["timestamp"] = new Date().toDateString();
        params["initsearch"] = true;
        if (isLike) {
            params["tb_islikesearch"] = true;
        }
        //Уберем фильтр чтобы сбросить его состояние
        $('#filterholder').remove();
        $('ul.filterlist li.selected').removeClass('selected');
        $('#columnsholder').remove();
        $('#showfilter img').attr('src', $('#showfilter img').attr('src').replace('_active', ''));
        $('#showcolumns img').attr('src', $('#showcolumns img').attr('src').replace('_active', ''));
        currentListRequest = $.ajax({
            url: tableUrl(),
            data: params,
            success: function (data) {
                try {
                    var dataJ = eval('(' + data + ')');
                }
                catch (e) { }
                if (dataJ != null && dataJ.hasOwnProperty('IsOK')) {
                    try { window.afterSearch(dataJ); } catch (e) { }
                }
                else {
                    $(tableRootDiv).empty().append(data);
                    initTable();
                    window.afterSearchAndInitTable();
                    //searchPopup();
                }
            }
        });
        return false;
    } else {
        var stateId = $('#stateid').val();
        var searchparams = {};
        searchparams['tb_tasksearchfilter'] = stringValue;
        searchparams['tb_searchwords'] = searchWords;
        searchparams['tb_stateid'] = '';
        searchparams['tb_islikesearch'] = isLike;
        searchparams['tb_page'] = 1;
        searchparams['nolayout'] = true;
        searchparams['timestamp'] = new Date().toDateString();
        searchparams['initsearch'] = true;
        if (addServiceTag) {
            searchparams['tb_serviceid'] = 0;
            $("#serviceid").val('0');
            $("#serviceid").trigger("chosen:updated");
            addServiceTag = false;
        }
        currentListRequest = $.ajax({
            url: tableUrl(),
            data: searchparams,
            success: function (data) {
                try {
                    var dataJ = eval('(' + data + ')');
                }
                catch (e) { }
                if (dataJ != null && dataJ.hasOwnProperty('IsOK')) {
                    try { window.afterSearch(dataJ); } catch (e) { }
                }
                else {
                    $(tableRootDiv).empty().append(data);
                    initTable();
                    window.afterSearchAndInitTable();
                    $("#savedfilter" + stateId).addClass("selected");
                }
            }
        });
        return false;
    }
    return false;
}

function clearSearch(elem) {
    if ($(elem).hasClass('hiddenClearSearch') || ($('div#newsearchul div').size() == 0 && $('#newsearch').val() == ''))
        return false;
    $('#newsearch').val('');
    $('#searchwordcache').val('');
    $('div#newsearchul div').remove();
    $(elem).addClass('hiddenClearSearch');
    _taskSearch();
    return false;
}
//отмена аякс запроса на поиск заявок
function abortAjaxSearch() {
    if (currentListRequest) {
        currentListRequest.abort();
        currentListRequest = null;
    }
}
//#endregion Task Search



//раздвигаем область поиска
function showWideSearch(that) {
    if (!$('#rightmenucontent').hasClass('searchMode')) {
        $('#rightmenucontent').addClass('searchMode');
        $('#filter-sticker').hide();
        $('#rightmenucontent').animate({ width: 530 }, 200, function () {
            $("#rightmenu").removeClass("non-border");
        });
        $('#rightmenu').animate({ width: 530 }, 200);

        $('#newsearch').animate({ width: 460 }, 200);
        if ($('#pagination').offset() && $('#pagination').offset().left < 1015) {
            $('#pagination').hide();
        }
        if ($('.table-action-buttons a.btndelete').size() > 0) {
            if($('div#content').width() < 968){
                $('.table-action-buttons a.btndelete').hide();
            }
        }
        $('#content').animate({ marginRight: 540 }, 200, function () {
            if (that) {              
                that.fixPosition();

                if ((that.options.autoQueryOnEmptyField && that.el.val().length == 0) || (that.el.val().length >= that.options.minChars)) {
                    that.onValueChange();
                }
            }
        });
        $('#pagination').animate({ right: 600 }, 200);
    }
}
//задвигаем область поиска до нормального положения
function hideWideSearch() {
    $('#rightmenucontent').removeClass('searchMode');
    $('#filter-sticker').show();
    var hasArrowRight = $("#filter-sticker").hasClass('arrow-right');
    var marginSticker = hasArrowRight ? 0 : 264;  
    $('#rightmenucontent').animate({ width: 260 }, 200);
    $('#rightmenu').animate({ width: 260 }, 200);
    $('#newsearch').animate({ width: 190 }, 200);
    $('#content').animate({ marginRight: 270 }, 100, function () {
        $('#pagination').show();
        if ($('.table-action-buttons a.btndelete').size() > 0) {
            $('.table-action-buttons a.btndelete').show();
        }
    });
}
