var categoryArrays = new Array();
$(function () {
    $('#addService').devbridgeAutocomplete({
        serviceUrl: 'service.ivp/SearchServicesJson/',
        autoClearInputOnSelect: true, //после выбора элемента очищаем инпут       
        autoQueryOnEmptyField: true,
        minChars: 1,
        onSelect: addService
    });

    $('body').on('click', '.js-delete-service', function () {
        $('#serviceName').addClass('hidden');
        $('#tb_serviceid').val('');
        $('#serviceName .serviceName').empty();
        ReloadTable({ tb_serviceid: '', nolayout: true, timestamp: new Date().toDateString() });
        return false;
    });
    $('body').on('click', '.js-mergeToCategory', function (e) {
        e.preventDefault();
        mergeToCategory(this);
    });
    $('body').on('click', '.js-close-mergeCategoryDialog', function (e) {
        e.preventDefault();
        $('#mergecategories').remove();
    });
    $('body').on('click', '.js-tree-mode', setTreeMode);
    $('body').on('click', '.js-table-mode', setTableMode);
    $('body').on('click', '.js-toggle-categorydescription', function () {
        toggle(this, '#categoryfulldesc', TaskTypeResources.ReadNext, TaskTypeResources.Minimize);
        return false;
    });
});

function setTreeMode() {   
    location.href = base + "category/tree?reset=true";
    return false;
}

function setTableMode() {
    location.href = base + "category/list?reset=true";    
    return false;
    }

function addService(suggestion) {
    var name = suggestion.value;
    var id = suggestion.data.id;
    var path = suggestion.data.path;
    _selectService(id, name);
}

function _selectService(id, name) {
    $('#tb_serviceid').val(id);
    $('#serviceName').removeClass('hidden');
    $('#serviceName .serviceName').html(name);
    selectedIds.length = 0;
    ReloadTable({ tb_serviceid: id, nolayout: true, timestamp: new Date().toDateString() });  
}

window.afterInitTable = function () {
    InitGridMenu = function ($menu) {
        if ($menu) {
            $menu.find('li.grid-filter').remove();
            $menu.find('li.grid-column-settings').remove();
        }
    };
    InitResizableGrid('table.resizable-grid', getHeightTableHolder(95));
};
window.afterSearchAndInitTable = function () {
    selectedIds.length = 0;
    InitResizableGrid('table.resizable-grid', getHeightTableHolder(95));
}


window.afterClearSearch = function () {
    selectedIds.length = 0;
    _search();
}

function ReloadTable(params) {     
    $.ajax({
        url: tableUrl(),
        data: params,
        success: function (data) {
            try {
                var dataJ = eval('(' + data + ')');;
            }
            catch (e) { }           
                $(tableRootDiv).empty().append(data);
                initTable();
                window.afterInitTable();
        }
    });
    return false;
}

function mergeCategories() {
    if (selectedIds.length <= 1) { alert(TableResources.NoMergeRecordsSelected); return false; }
    if (!$('#tb_serviceid').val()) {
        alert(CategoryResources.NeedAddService); return false;
    }    
    categoryArrays = selectedIds;    
    this.$content = $('#content');
    $.ajax({
        contentType: 'application/json',
        url: 'Category/MergeCategoriesDialog',
        data: JSON.stringify({
            categoryids: categoryArrays
        }),
        type: 'POST',
        success: function (html) {
            $content.append(html);
            $('html').scrollTop(0);
        }
    });   
    return false;    
}

function deleteSelected() {
    if (selectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(CategoryResources.SureDeleteFromSystem)) return false;

    $.ajax({
        contentType: 'application/json',
        url: base + tableController() + 'DeleteCategoriesFromSystem',
        data: JSON.stringify({ ids: selectedIds }),
        type: 'POST',
        success: function (result) {
            if (result) {
                if (!result.IsOK)
                    alert(result.Description);
                else {
                    alert(CategoryResources.SelectedCategoriesWasDeleted);
                }
            }
            var action = $('#treeMode').size()>0?"Tree":"List";
            $.get(base + tableController() + action + '?nolayout=true', function (data) {
                selectedIds= new Array();
                $(tableRootDiv).html(data);
                if (initTable)
                    initTable();
            });
        }
    });

    return false;
}

function setArchiveOnService() {
    if (selectedIds.length == 0) { alert(CategoryResources.CategoriesNotSelected); return false; }
    if (!confirm(CategoryResources.SureArchiveOnService)) return false;
    $.ajax({
        contentType: 'application/json',
        url: base + tableController() + 'ArchiveOnServices',
        data: JSON.stringify({ ids: selectedIds }),
        type: 'POST',
        success: function (result) {
            var getSuccessMessage = false;
            if (result) {
                if (!result.IsOK)
                    alert(result.Description);
                else {
                    getSuccessMessage = true;
                }
            }
            var action = $('#treeMode').size() > 0 ? "Tree" : "List";
            $.get(base + tableController() + action + '?nolayout=true', function (data) {
                selectedIds = new Array();
                $(tableRootDiv).html(data);
                if (initTable)
                    initTable();
                if (getSuccessMessage)
                    alert(CategoryResources.SuccessArchiveOnService);
            });
        },
        error: function () {
            alert(CommonResources.Error);
        }
    });
    return false;
}

function mergeToCategory(el) {
    var parentId = el.getAttribute('data-id');
    $.ajax({
        contentType: 'application/json',
        url: 'Category/IsDeletedCategoriesPartOfTree',
        data: JSON.stringify({
            maincategoryId: parentId,
            categoryids: categoryArrays
        }),
        type: 'POST',
        success: function (result) {
            var isUnbindChilds = false;
            if (result.IsPartOfTree) {
                if (!confirm(result.Description)) {
                    $('#mergecategories').remove();                   
                    return false;
                }                  
                isUnbindChilds = true;
            }
            $.ajax({
                contentType: 'application/json',
                url: 'Category/MergeCategories',
                data: JSON.stringify({
                    maincategoryId: parentId,
                    categoryids: categoryArrays,
                    isUnbindChilds : isUnbindChilds
                }),
                type: 'POST',
                success: function (result) {
                    if (!result.IsOK) {
                        alert(result.Description);
                        $('#mergecategories').remove();
                        return false;
                    }
                    else {
                        $('#mergecategories').remove();
                        selectedIds.length = 0;
                        ReloadTable({ nolayout: true, timestamp: new Date().toDateString() });
                    }
                }
            });           
        }
    });
   
    return false;
}

function triggerAction() {
    var action = $('#actions').val();
    $('#actions').val('');
    eval(action);
}
