var del = false;
var parentChange = false;
var deletingParentId = null;
var dlg = null;

$(function () {    
    if ($('#addParent')) {
        $('#addParent').devbridgeAutocomplete({
            serviceUrl: 'Category/Find/',
            minChars: 1,
            params: {exceptId: $('#Id').val()},
            triggerSelectOnValidInput: false,
            autoClearInputOnSelect: true, //после выбора элемента очищаем инпут
            autoQueryOnEmptyField: true,
            onSelect: addParent
        })
    }
    if ($('.js-delete-parent')) $('.js-delete-parent').bind('click', function() {
        return deleteParent(this);
    });
    $('body').on('click', '.deletechild', function () {
        if (!confirm(CommonResources.SureDeleteElement))
            return false;
        var elem = $(this);
        $.ajax({
            contentType: 'application/json',
            url: base + 'Category/DeleteChild/' + elem.attr('data-id'),           
            type: 'POST',
            success: function (result) {
                if (result) {
                    if (!result.IsOK)
                        alert(result.Description);
                    else {
                        elem.parent('li').remove();
                    }
                }                
            }
        });
        return false;
    });
    $('textarea.autogrow').elastic();
});

function addParent(suggestion) {
    var id = suggestion.data.id;
    var name = suggestion.value;  
    parentSelected(id, name);
}

function addSelectedCategories(ids, names) {   
    ids.forEach(function (id) {
        var lb = $.trim(names['id' + id]);
        parentSelected(id, lb);
    });
}

function parentSelected(id, name) {
    if (id != $('#ParentId').val()) {
        parentChange = true;
        if (del) {
            $('.parentName').removeClass('archive changed');
        }
        if ($('.js-delete-parent').hasClass('hidden'))
            $('.js-delete-parent').removeClass('hidden')
        deletingParentId = null;
        del = false;
        $('.parentName').empty();
        $('.parentName').html(name);
        $('#ParentId').val(id);
        $('#editparent').hide();
    }   
}

function deleteParent(elem) {
    if (!del) {
        $('.parentName').addClass('archive changed');
        del = true;
        deletingParentId = $('#ParentId').val();
        $('#ParentId').val('');
        $('#editparent').show();
    }
    else if(!parentChange) {
        $('.parentName').removeClass('archive changed');
        $('#ParentId').val(deletingParentId);
        $('#editparent').hide();
    }
    return false;
}

function selectCategory() {
    var url = 'category/select?reset=true&tb_excludeIds='+$('#Id').val();
    dlg = openDialog(url, 'selectcategory', { width: 990, height: 660 });
    dlg.callback = categoriesCallback;
    return false;
}

function categoriesCallback(result) {
    var ids = result["selectedIds"];
    var names = result["selectedNames"];
    addSelectedCategories(ids, names);
}

function loadServices(reload) {
    if (reload || $.trim($('#services').html()).length == 0) {
        var params = new Array();
        params.push({ name: 'timestamp', value: new Date().toString() });
        if ($('#popup').length > 0) params.push({ name: 'popup', value: true });
        $('#services').load(base + 'category/services/' + $('#Id').val(), params, function () { setTab('services'); });
    }
    else setTab('services');
}

var Category = {
    chooseServices: function chooseServices() {
        var url = 'service.ivp/select?cbmode=Category&tb_categoryid=' + $('#Id').val();
        dlg = openDialog(url, 'selectservice', { width: 980, height: 650 });
        dlg.callback = Category.servicesCallback;
        return false;
    },
    servicesCallback: function servicesCallback(result) {
        var serviceids = result["selectedIds"];
        addSelectedServices(serviceids);
    }
}

function addSelectedServices(serviceids) {
    $.ajaxSettings.traditional = true;
    $('#services').load(base + 'Category/AddServices', {
        id: $('#Id').val(),
        serviceIds: serviceids
    },
        function () {
            $('#selectservices').hide();
            $('#addservices').show(),
                function () { date: new Date().toString(); },
                function () { $('#availableservices').fadeIn('fast'); };
        });

    return false;
}

function deleteSelectedServices() {
    var selected = new Array();
    $('#services table td input:checked').each(function (i, el) { selected.push(el.value); });
    $.ajaxSettings.traditional = true;
    $('#services').load(base + 'Category/DeleteServices', {
        id: $('#Id').val(),
        serviceIds: selected
    });

    return false;
}

function setArchiveOnService(element, categoryid) {
    $.ajax({
        contentType: 'application/json',
        url: base + 'Category/SetArchiveOnService',
        data: JSON.stringify({ categoryid: categoryid, serviceid: $(element).attr('data-service'), isarchive: $(element).attr('data-archive') }),
        type: 'POST',
        success: function (result) {
            var getSuccessMessage = false;
            if (result) {
                if (!result.IsOK)
                    alert(result.Description);
                else {
                    getSuccessMessage = true;
                }
            }
            loadServices(true);
        },
        error: function () {
            alert(CommonResources.Error);
        }
    });
    return false;
}

function setAllArchiveOnService(issetarchive) {
    var ids = new Array();
    $('#services input.serviceid:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(CategoryResources.ServicesNotSelected); return false; }
    var resource = issetarchive ? CategoryResources.SureArchiveOnServices : CategoryResources.SureNotArchiveOnServices
    if (!confirm(resource)) return false;
    $.ajax({
        contentType: 'application/json',
        url: base + 'Category/SetAllArchiveOnService',
        data: JSON.stringify({ categoryid: $('#Id').val(), serviceid: ids, issetarchive: issetarchive }),
        type: 'POST',
        success: function (result) {
            var getSuccessMessage = false;
            if (result) {
                if (!result.IsOK)
                    alert(result.Description);
                else {
                    getSuccessMessage = true;
                }
            }
            loadServices(true);
        },
        error: function () {
            alert(CommonResources.Error);
        }
    });
    return false;
}