var ccid = 0;
var cord = '';
var selectingTabId = '';
var forceNRUsersReload = false;
var sttid = 0;
var ownerExists;
var ownerChanged = false;
var deletingOwnerId;
var childpropactive = false;
var dlg = null;
/// <reference path="jquery.intellisense.js"/>

$(function() {
    $('.tableform').submit(function() {
        return false;
    });
    $('body').on('submit', '.tableform', function() {
        return false;
    });
    $('input.companyid').live('click', function() {
        var cb = this;
        $(cb).parents('tr').toggleClass('selected');
    });

    $('#chooseexecutorgroupscategory input[name="gid"]').live('click', function () { var checked = this.checked; $('#chooseexecutorgroupscategory input[name="gid"]').each(function () { $(this).removeAttr('checked'); }); if (checked) $(this).attr('checked', true); });
    $('#chooseexecutorgroupsstatus input[name="gid"]').live('click', function () { var checked = this.checked; $('#chooseexecutorgroupsstatus input[name="gid"]').each(function () { $(this).removeAttr('checked'); }); if (checked) $(this).attr('checked', true); });
    $('#childprop').mouseover(function() { childpropactive = true; });
    $('#childprop').mouseout(function() { childpropactive = false; });
    $('body').mouseup(function() { if (!childpropactive) $('#childprop').hide(); });
    if ($('#createchild').length > 0)
        $('#childprop').css('top', $('#createchild').offset().top - $('#childprop').height() - 90).css('left', $('#createchild').offset().left);

    $('#movetasks').attr('disabled', true);
    $('#copysettings').click(handleChildSettings);

    if ($('#tab').val() == 'users') loadUsers();

    $('#roleid').click(function() { $('#roleswarning').show('fast'); });
    $('#uf_roleid').change(reloadUsers);
    $('#uf_companyid').change(reloadUsers);
    $('#uf_showarchive').bind("click", function() {
        reloadUsers();
    });
    prettyprinttree($('#uf_companyid'));

    $(window).resize(resize).trigger('resize');

    //$('#chooseowner').autocomplete(base + 'service.ivp/findusers/' + $('#id').val(), { minChars: 1 }).result(ownerFound);
    $('#chooseowner').devbridgeAutocomplete({
        serviceUrl: base + 'service.ivp/FindUsersJson/' + $('#id').val(),
        onSelect: ownerFound,
        minChars: 1,
        autoClearInputOnSelect: true //после выбора элемента очищаем инпут
    });
    //$('#choosesubstitute').autocomplete(base + 'service.ivp/findusers/' + $('#id').val(), { minChars: 1 }).result(substituteFound);
    $('#choosesubstitute').devbridgeAutocomplete({
        serviceUrl: base + 'service.ivp/FindUsersJson/' + $('#id').val(),
        onSelect: substituteFound,
        minChars: 1,
        autoClearInputOnSelect: true //после выбора элемента очищаем инпут
    });

    ownerExists = $('#ownerid').val() != "0";

    $('li:last span.hover a.delete', '#owner ul').bind('click', function() {
        return deleteOwner(this);
    });

    initFormChangeHandlers();

    $("#servicelist").live('change', function() {
        var addParam = "?workflowid=" + $(this).val();
        var entityType = $("#tab").val() == "notificationruleroles" ? "roles" : "users";

        var blockId = '#notificationrule' + entityType;
        var blockIdClear = 'notificationrule' + entityType;

        $(blockId).load(base + 'service.ivp/loadnotificationrulefor' + entityType + '/' + $('#id').val() + addParam, { date: new Date().toString() }, function() {
            setTab(blockIdClear);
            $("#anotificationruleroles").addClass("selected");
            if (entityType == 'users')
                $('#addUsersNotifications').devbridgeAutocomplete({
                    serviceUrl: base + 'service.ivp/FindUsersJson/' + $('#id').val(),
                    onSelect: userNotificationSelected,
                    minChars: 1,
                    autoClearInputOnSelect: true //после выбора элемента очищаем инпут
                });
                //$("#addUsersNotifications").autocomplete(base + 'service.ivp/findusers/' + $('#id').val(), { minChars: 1 }).result(userNotificationSelected);
        });

        return false;
    });

    $('#isexternal').change(function() {
            $('#externalserviceinfo').toggleClass('hidden');
            $('#innerserviceinfo').toggleClass('hidden');
            $('.innerservicetabs').toggleClass('hiddenrequired');
            $('#defaultpriorityid').toggleClass('required');
            $('#externalurl').toggleClass('required');
    });    
});

function toggleServiceDescription(elem) {
    toggle($(elem), '#servicefulldesc', CommonResources.ReadNext, CommonResources.Minimize);
    return false;
}
function toggleServiceOwnerDescription(elem) {
    toggle($(elem), '#serviceownerDescription', CommonResources.ReadNext, CommonResources.Minimize);
    return false;
}

function initFormChangeHandlers() {
    $('select, #description').on('change', function () {
        $("#savewarning").show();
        $(".inherit, .copy").attr("disabled", "disabled");
    });
}

    function resize() {
    var h = $(window).height() - $('#header').height() - $('#footer').height() - $('.formheader').height() - $('#tabs').height() - $('.formbottom').height() - 125;
    $('#users #iframeholder iframe').css('min-height', h);

    if ($.browser.mozilla && $("#tab").attr("value") == "executorstatusrules") { // ..жесткие костыли..
        $("div.pinbottom").each(function () {
            var _h = $(this).height();
            var ptd = $(this).closest("td");

            $(this).css("top", (ptd.position().top + ptd.height() + 20) + "px");
            $(this).width(ptd.width() + 4);
            $(this).height(_h);
        });
    }
}

function reloadUsers() {
    var params = new Array();
    params.push({ name: 'nolayout', value: true });
    params.push({ name: 'timestamp', value: new Date().toString() });
    params.push({ name: 'tb_search', value: $('#search').val() });
    params.push({ name: 'tb_serviceid', value: $('#id').val() });
    var rid = parseInt($('#uf_roleid').val(), 10);
    var cid = parseInt($('#uf_companyid').val(), 10);
    params.push({ name: 'fttRoleId', value: rid > 0 ? 1 : 0 }); params.push({ name: 'flt1RoleId', value: $('#uf_roleid').val() });
    params.push({ name: 'fttUser_CompanyId', value: cid > 0 ? 1 : 0 }); params.push({ name: 'flt1User_CompanyId', value: $('#uf_companyid').val() });
    params.push({ name: 'tb_showarchive', value: $('#uf_showarchive:checked').size() > 0 ? "True" : "False" });
    
    toggleSubmitButtons('users');
    selectedIds.length = 0;

    tableRootDiv = '#users #iframeholder';

    InitGridMenu = function ($menu) {
        if ($menu) {
            $menu.find('li.grid-filter').remove();
            $menu.find('li.grid-column-settings').remove();
        }
    };
    
    var uurl = 'serviceuser.ivp/list?reset=true&tb_serviceid=' + $('#id').val();
    $('#users #iframeholder').load(uurl, params, function () {
        initTable();
            isCurrentUserAddingToService();
       
           
    });
    
   return false;
}

function initServiceTable(tableid, idcol) {
    $(tableid + ' .rowid').unbind('click').bind('click', function (e) {
        if (!e)
            e = window.event;

        if (e.cancelBubble)
            e.cancelBubble = true;
        else if (e.stopPropagation)
            e.stopPropagation();

        selectRow(this.value, this.checked, undefined, idcol);
    });

    return false;
}

function selectServiceAll(check) {
    var tableid = $(check).closest('table').attr('id') || 'body';
    if (tableid)
        tableid = '#' + tableid + ' ';
    var idcol;
    switch (tableid) {
        case '#assettable ':
            idcol = "assetid";
            break;
        case '#tasktypetable ':
            idcol = "tasktypeid";
            break;
        case '#companytable ':
            idcol = "companyid";
            break;
        case '#escalationruletable ':
            idcol = "escalationruleid";
            break;
        case '#executorgrouptable ':
            idcol = "groupid";
            break;
        default:
            idcol = "id";
            break;
    }

    $(tableid + '.rowid.cb').each(function (i, el) {
        selectRow(el.value, !el.checked, undefined, "#" + idcol);
        el.checked = !el.checked;
    });
    return false;
}

function setTab(id) {
    if (!documentReady)
        return;

    if (id == 'users') {
        $('#actionblock').show();
    } else {
        $('#actionblock').hide();
    }


    $('#tab').val(id);
    //$('.tab').each(function(i, el) { if (el.id == id) $(el).show(); else $(el).hide(); });

    $('.tab').hide();
    $("#" + id).show();

    $('#tabid').val(id);

    /*
    $('#tabs>ul>li>a').each(
        function(i, el) {
            if (el.id == 'a' + id)
                $(el).addClass('selected');
            else $(el).removeClass('selected');
        }); AAAAAAblya */
    $("#tabs a").removeClass('selected');
    $("#a" + id).addClass('selected');


    $('.rm').hide();
    if ($('#executorgroupholder:visible').length == 0)
        $('#' + id + 'menu').show();

    toggleSubmitButtons(id);

    return false;
}

function toggleSubmitButtons(id) {
    if (id != 'general') {
        $('.save').attr('disabled', true);
        $('.saveandreturn').attr('disabled', true);
    }
    else {
        $('.save').attr('disabled', false);
        $('.saveandreturn').attr('disabled', false);
    }
}

function dosearch(evt) {
    var e = ($.browser.msie) ? event : evt;
    var keycode = ($.browser.msie) ? e.keyCode : e.which;
    if (keycode == 13) return reloadUsers();
    else return true;
}
function searchCategory(evt) {
    var e = ($.browser.msie) ? event : evt;
    var keycode = ($.browser.msie) ? e.keyCode : e.which;
    if (keycode == 13) return reloadCategories();
    else return true;
}

function loadUsers() {    
    
    toggleSubmitButtons('users');
    selectedIds.length = 0;
    
    tableRootDiv = '#users #iframeholder';

    InitGridMenu = function ($menu) {
        if ($menu) {
            $menu.find('li.grid-filter').remove();
            $menu.find('li.grid-column-settings').remove();
        }
    };
    if (!$('#users #iframeholder').children().length) {
        
        var uurl = 'serviceuser.ivp/list?reset=true&tb_serviceid=' + $('#id').val();
        $('#users #iframeholder').load(uurl, { nolayout: true }, function () {
             initTable();            
        });       
    }
    return setTab('users');
}

function resetUsers() {
    $('#users #iframeholder iframe').remove();
        isCurrentUserAddingToService();
}

function loadCompanies() {
    toggleSubmitButtons('companies');
    
    if (!$.trim($('#companies').html())) {
        $('#companies').load(base + 'servicecompany.ivp/list/', { tb_serviceid: $('#id').val(), reset: true, timestamp: new Date().toString() }, function () { setTab('companies'); initTable();  });
    }
    else setTab('companies');
    return false;
}
function changeCompanyPage(page) {
    if (page) {
        $('#companytableholder').load(base + 'servicecompany.ivp/list/', { tb_serviceid: $('#id').val(), tb_page: page, nolayout: true, timestamp: new Date().toString(), generateReport: true }, initTable);
    } else {
        $('#companytableholder').load(base + 'servicecompany.ivp/list/', { tb_serviceid: $('#id').val(), nolayout: true, timestamp: new Date().toString(), generateReport: true }, initTable);
    }
    return false;
}

function selectCompaniesAll() {
    $('#companyTable input.rowid').each(function (i, el) {
        if (!el.checked && !el.disabled) {
            selectedIds.push(el.value);
            el.checked = true;
        }
        else {
            selectedIds = $.grep(selectedIds, function (i) { return i != el.value; });
            el.checked = false;
        }
        selectRow(el.value, el.checked, undefined, "#companyid");
    });
    if ($('#companyTable #rowids').checked == false) {
        $('#rowids').attr('checked', true);
    }
    return false;
}

function showAvailableTaskTypes() {
    $('#availabletasktypes').load(base + 'service.ivp/availabletasktypes/' + $('#id').val(), { date: new Date().toString() }, function () { $('#availabletasktypes').fadeIn('fast'); });
    return false;
}

function loadTaskTypes() {
    toggleSubmitButtons('tasktypes');
    
    if (!$.trim($('#tasktypes').html())) {
        $('#tasktypes').load(base + 'servicetasktype.ivp/list/' + $('#id').val(), { timestamp: new Date().toString() }, function () {
            setTab('tasktypes');
            initServiceTable('#tasktypetable', '#tasktypeid');
        });
    }
    else
        setTab('tasktypes');
    return false;
}

function addTaskTypes() {
    var selected = new Array();
    $('#availabletasktypes input:checked').each(function (i, el) { selected.push(el.value); });
    $('#tasktypes').load(base + 'servicetasktype.ivp/addselectedtasktypes', { serviceid: $('#id').val(), ids: selected }, function () { $('#availabletasktypes').hide(); initServiceTable('#tasktypetable', '#tasktypeid'); });
    return false;
}

function deleteTaskTypes() {
    var ids = new Array();
    $('#tasktypes input[name=tasktypeid]:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(ServiceResources.NoTaskTypeSelected); return false; }
    $.getJSON(base + 'servicetasktype.ivp/istypewithtask', { serviceid: $('#id').val(), ids: ids }, function (result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true) {
            if (!confirm(result.Result)) return false;
        }
        else { if (!confirm(ServiceResources.SureDeleteTaskTypes)) return false; }
        $('#tasktypes').load(base + 'servicetasktype.ivp/deletetasktypes', { serviceid: $('#id').val(), ids: ids }, function () { initServiceTable('#tasktypetable', '#tasktypeid'); });
        return false;
    });
    return false;
}

function chooseRoles(tid) {
    sttid = tid;
    $('#chooseroles').load(base + 'servicetasktype.ivp/getroles/' + tid, { date: new Date().toString() }, function () {
        var offset = $('#chooseroletrigger' + tid).offset();
        $('#chooseroles').css('top', offset.top - 130).css('left', offset.left).fadeIn('fast');
        $('#chooseroles').show();
    });
    return false;
}

function rolesSelected() {
    var ids = new Array();
    $('#chooseroles input:checked').each(function (i, el) { ids.push(el.value); });
    $('#tasktypes').load(base + 'servicetasktype.ivp/saveroles', { workflowroleids: ids, servicetasktypeid: sttid, serviceid: $('#id').val() }, function () { $('#chooseroles').hide(); });
    return false;
}

function loadAssets() {
    toggleSubmitButtons('assets');
    
    if (!$.trim($('#assets').html())) {
        $('#assets').load(base + 'serviceasset.ivp/list/' + $('#id').val(), { timestamp: new Date().toString() }, function () { setTab('assets'); initTable(); initServiceTable("#assettable", "#assetid");
    });
    }
    else setTab('assets');
    return false;
}

function loadCategories() {
    toggleSubmitButtons('categories');
    if (!$.trim($('#categories').html())) {
        $('#searchcategory').val('');
        $('#categories').load(base + 'servicecategory/list/', { serviceid: $('#id').val(), reset: true, tb_search: '', tb_mode: 'service', timestamp: new Date().toString() },
            function () {
                setTab('categories'); initTable(); initServiceTable("#categorytable", "#categoryid");
                $('#addcategoryonservice').devbridgeAutocomplete({
                    serviceUrl: base + 'service.ivp/findcategories/' + $('#id').val(),
                    params: { isnotonservice: true },
                    onSelect: ServiceCategory.addCategoryOnServiceAutocomplete,
                    onEnter: function () {
                        createCategory($(this));
                        $(this).val('');
                    },
                    minChars: 1,
                    transformResult: function (response) {
                        var result = typeof response === 'string' ? $.parseJSON(response) : response;
                        result.suggestions.push({ value: CategoryResources.CreateCategory, data: { id: 0, iscreatecategory: true } });
                        return result;
                    },
                    formatDivClassResult: function (suggestion) {
                        return suggestion.data.iscreatecategory ? 'topBorder' : '';
                    },
                    formatResult: function (suggestion, currentValue) {
                        var pattern = '(' + currentValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ')';
                        var createValue = '';
                        var createClass = '';
                        if(suggestion.data.iscreatecategory){
                            createClass = ' italictext';
                            createValue = ' "' + currentValue + '"';
                        }
                        var cValue = '<span class="ac-value' + createClass + '">' + suggestion.value + createValue
                            .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>';
                        return cValue;
                    }
                    //autoClearInputOnSelect: true //после выбора элемента очищаем инпут
                });
        });
    }
    else setTab('categories');
    return false;
}

function createCategory(element) {
    var elementValue = $(element).val();
    //element = $(element);
    setTimeout(function () {
        if (!confirm(TaskResources.WantCreateCategory.replace('{0}', elementValue)))
            return false;
        $(element).val('');
        setTimeout(function () { $('.autocomplete-suggestions').css("display", "none"); }, 10);
        createCategoryAndAddOnService(elementValue);
    }, 0);
    return false;
}

function reloadCategories() {
    var params = new Array();
    //params.push({ name: 'nolayout', value: true });
    params.push({ name: 'timestamp', value: new Date().toString() });
    params.push({ name: 'tb_search', value: $('#searchcategory').val() });
    params.push({ name: 'tb_mode', value: 'service' });
    params.push({ name: 'serviceid', value: $('#id').val() });

    toggleSubmitButtons('categories');
    selectedIds.length = 0;     

    var uurl = base+'servicecategory/list';
    $('#categories').load(uurl, params, function () {
        initTable();
        initServiceTable("#categorytable", "#categoryid");
        $('#addcategoryonservice').devbridgeAutocomplete({
            serviceUrl: base + 'service.ivp/findcategories/' + $('#id').val(),
            params: { isnotonservice: true },
            onSelect: ServiceCategory.addCategoryOnServiceAutocomplete,
            onEnter: function () {
                createCategory($(this));
                $(this).val('');
            },
            minChars: 1,
            transformResult: function (response) {
                var result = typeof response === 'string' ? $.parseJSON(response) : response;
                result.suggestions.push({ value: CategoryResources.CreateCategory, data: { id: 0, iscreatecategory: true } });
                return result;
            },
            formatDivClassResult: function (suggestion) {
                return suggestion.data.iscreatecategory ? 'topBorder' : '';
            },
            formatResult: function (suggestion, currentValue) {
                var pattern = '(' + currentValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ')';
                var createValue = '';
                var createClass = '';
                if (suggestion.data.iscreatecategory) {
                    createClass = ' italictext';
                    createValue = ' "' + currentValue + '"';
                }
                var cValue = '<span class="ac-value' + createClass + '">' + suggestion.value + createValue
                    .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>';
                return cValue;
            }
            //autoClearInputOnSelect: true //после выбора элемента очищаем инпут
        });
        $('#addcategoryonservice').focus();
    });

    return false;
}

function createCategoryAndAddOnService(categoryname) {
    $.ajax({
        url: base + 'Category/AddCategoryFromService',
        data: { serviceId: $('#id').val(), categoryName: categoryname },
        type: 'POST',
        success: function (result) {
            if (result != null && result.IsOK != null) {
                if (result.IsOK) {
                    reloadCategories();
                    afterAjaxMessage($('.afterAjaxMessage'), 'success', CategoryResources.WasCreateAndAddToService);
                    //alert(CategoryResources.WasCreateAndAddToService);
                }
                else if (result.Description != null) {
                    afterAjaxMessage($('.afterAjaxMessage'), 'error', result.Description);
                    //alert(result.Description);
                }
                else {
                    return false;
                }
            }
        }
    });
    return false;
}


function setCategoryDefault(element, categoryid) {
    $.ajax({
        contentType: 'application/json',
        url: 'ServiceCategory/SetCategoryDefault',
        data: JSON.stringify({
            categoryid: categoryid,
            serviceid: $('#id').val(),
            isdefault: $(element).attr('data-value')
        }),
        type: 'POST',
        success: function (result) {
            if (result.IsOk) {
                var params = { nolayout: true, serviceid: $('#id').val() };
                $("#categories #tableholder").load('servicecategory/list', params, function () { initTable(); initServiceTable("#categorytable", "#categoryid"); });
            }
            else {
                alert(result.Description);
                return false;
            }
        }
    });
}

function setCategoryArchive(element, categoryid) {
    $.ajax({
        contentType: 'application/json',
        url: 'ServiceCategory/SetCategoryArchive',
        data: JSON.stringify({
            categoryid: categoryid,
            serviceid: $('#id').val(),            
            isarchive: $(element).attr('data-value')
        }),
        type: 'POST',
        success: function (result) {
            if (result.IsOk) {
                var params = { nolayout: true, serviceid: $('#id').val() };
                $("#categories #tableholder").load('servicecategory/list', params, function () { initTable(); initServiceTable("#categorytable", "#categoryid"); });
            }
            else {
                alert(result.Description);
                return false;
            }
        }
    });
}

function setArchiveCategories(isSetArchive) {
    var ids = new Array();
    $('#categories input[name=categoryid]:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(ServiceResources.NoCategoriesSelected); return false; }
    SetCategoriesArchive(ids, isSetArchive);
    return false;
}

function SetCategoriesArchive(ids, isSetArchive) {
    var text = isSetArchive ? ServiceResources.SureArchiveCategories : ServiceResources.SureNotArchiveCategories;
    if (!confirm(text)) return false;
    $.ajax({
        contentType: 'application/json',
        url: 'ServiceCategory/SetCategoriesArchive',
        data: JSON.stringify({
            serviceid: $('#id').val(),
            ids: ids,
            issetarchive: isSetArchive
        }),
        type: 'POST',
        success: function (result) {
            if (result.IsOk) {
                var params = { nolayout: true, serviceid: $('#id').val() };
                $("#categories #tableholder").load('servicecategory/list', params, function () { initTable(); initServiceTable("#categorytable", "#categoryid"); });
            } else {
                alert(result.Description);
            }
        }
    });
    return false;
}

function orderCategoryBy(sort) {
    var params = { tb_orderby: sort, nolayout: true, serviceid:$('#id').val() };
    $(tableRootDiv).load('servicecategory/list', params, function () { initTable(); initServiceTable("#categorytable", "#categoryid"); });
    return false;
}

function orderAssetsBy(sort) {
    var params = { tb_orderby: sort, nolayout: true, timestamp: new Date().toString() };
    $(tableRootDiv).load('serviceasset.ivp/list/' + $('#id').val(), params, function () { initTable(); initServiceTable("#assettable", "#assetid"); });
    return false;
}

var ServiceCategory = {
    addCategoryOnService: function addCategoryOnService() {
        dlg = openDialog('category/selecttoservice?cbmode=ServiceCategory&reset=true&tb_select_mode=service&tb_service_id=' + $('#id').val(), 'category', { width: 990, height: 660 });
        dlg.callback = ServiceCategory.categoriesCallback;
        return false;
    },
    addCategoryOnServiceAutocomplete: function addCategoryOnServiceAutocomplete(suggestion) {
        if (suggestion.data.id == 0 && suggestion.data.iscreatecategory)
            createCategory($('#addcategoryonservice'));
        else {
            var resultArr = new Array();
            resultArr.push(suggestion.data.id);
            addSelectedCategories(resultArr);
        }
        $('#addcategoryonservice').val('');
    },
    categoriesCallback: function categoriesCallback(result) {
        var ids = result["selectedIds"];
        addSelectedCategories(ids);
    }
}

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

function addSelectedCategories(cids) {
    var resultArr = new Array();
    $.each(cids, function (id, el) {
        resultArr.push(el);
    });

    $.ajax({
        contentType: 'application/json',
        url: 'ServiceCategory/AddCategories',
        data:  JSON.stringify({
            serviceid: $('#id').val(),
            ids: resultArr
        }),
        type: 'POST',
        success: function (result) {
            if (result.IsOk) {
                var params = { nolayout: true, serviceid: $('#id').val() };
                $("#categories #tableholder").load('servicecategory/list', params, function () {
                    initTable(); initServiceTable("#categorytable", "#categoryid");
                    var message = resultArr.length > 1 ? CategoryResources.WasAddManyToService : CategoryResources.WasAddToService;
                    //alert(message);
                    afterAjaxMessage($('.afterAjaxMessage'), 'success', message);
                });
            }
            else {
                afterAjaxMessage($('.afterAjaxMessage'), 'error', result.Description);
                //alert(result.Description);
                return false;
            }
        }
    });
    return false;
}

function changeServiceCategoryPage(page) {
    if (page) {
        $(tableRootDiv).load(base+'servicecategory/list', { serviceid: $('#id').val(), tb_page: page, nolayout: true, timestamp: new Date().toString() }, function() { initTable(); initServiceTable("#categorytable", "#categoryid"); });
    } else {
        $(tableRootDiv).load(base + 'servicecategory/list', { serviceid: $('#id').val(), nolayout: true, timestamp: new Date().toString() }, function () { initTable(); initServiceTable("#categorytable", "#categoryid"); });
    }
    return false;
}

function deleteSelectedCategories() {
    var ids = new Array();   
    $('#categories input[name=categoryid]:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(ServiceResources.NoCategoriesSelected); return false; }   
    DeleteCategoriesFromServiceOrSystem(ids);
    return false;
}

function DeleteCategoriesFromServiceOrSystem(ids) {
    if (!confirm(ServiceResources.SureDeleteCategories)) return false;
    $.ajax({
        contentType: 'application/json',
        url: 'Category/DeleteCategoriesFromService',
        data: JSON.stringify({
            serviceid: $('#id').val(),
            ids: ids
        }),
        type: 'POST',
        success: function (result) {
            if (result.IsOK) {
                var params = { nolayout: true, serviceid: $('#id').val() };
                $("#categories #tableholder").load('servicecategory/list', params, function () { initTable(); initServiceTable("#categorytable", "#categoryid");
            });
            } else {
                alert(result.Description);
            }
        }
    });
    return false;
}

function selectAllCategories() {
    $('#categories input.rowid').each(function (i, el) {
        if (!el.checked && !el.disabled) {
            selectedIds.push(el.value);
            el.checked = true;
        }
        else {
            selectedIds = $.grep(selectedIds, function (i) { return i != el.value; });
            el.checked = false;
        }
        selectRow(el.value, el.checked, undefined, "#categoryid");
    });
    if ($('#rowids').checked == false) {
        $('#rowids').attr('checked', true);
    }
    return false;
}

      

function assetDescription(e, id) {
    if (!e)
        e = window.event;

    if (e.cancelBubble)
        e.cancelBubble = true;
    else if (e.stopPropagation)
        e.stopPropagation();

    openDialog('assettable.ivp/view/' + id + '?popup=true&read=true', 'asset', { width: 980, height: 650 });
    return false;
}

function deleteCompanies() {
    var ids = new Array();
    //$('#companies input[name=companyid]:checked').each(function(i, el) { ids.push(el.value); });
    $('#companytableholder input[name=compid]:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(ServiceResources.NoCompaniesSelected); return false; }
    if (!confirm(ServiceResources.SureDeleteCompanies)) return false;
    $('#companytableholder').load(base + 'servicecompany.ivp/deletecompanies', { serviceid: $('#id').val(), nolayout:true, ids: ids }, function () {
        resetUsers();
        $('#companytableholder').load(base + 'servicecompany.ivp/list/', { tb_serviceid: $('#id').val(), nolayout: true, timestamp: new Date().toString(), generateReport: true }, initTable);
    });
    return false;
}

var ServiceOwner = {
    selectOwner: function selectOwner(serviceid) {
        var url = 'user.ivp/select?cbmode=ServiceOwner&reset=true&tb_mode=serviceuser&tb_serviceid=' + serviceid;
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = ServiceOwner.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        ownerSelected(uids, names);
    },
}

var ServiceSubstitutes = {
    selectSubstitutes: function selectSubstitutes(serviceid) {
        var url = 'user.ivp/select?cbmode=ServiceSubstitutes&reset=true&tb_mode=serviceusers&tb_serviceid=' + serviceid;
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = ServiceSubstitutes.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        substitutesSelected(uids, names);
    }
}

var Service = {    
    chooseAssets: function chooseAssets() {
        dlg = openDialog('assettable.ivp/select?cbmode=Service&tb_select_mode=service&tb_service_id=' + $('#id').val(), 'assets', { width: 900, height: 490 });
        dlg.callback = Service.assetsCallback;
        return false;
    },
    assetsCallback: function assetsCallback(result) {
        var ids = result["selectedIds"];
        assetSelected(ids);
    },
    chooseCompanies: function chooseCompanies() {
        dlg = openDialog('company.ivp/select?cbmode=Service&tb_custom_mode=notarchive&tb_serviceid=' + $('#id').val() + '&exclude=' + $('#companyIds').val(), 'company', { width: 900, height: 490 });
        dlg.callback = Service.companiesCallback;
        return false;
    },
    companiesCallback: function companiesCallback(result) {
        ids = result["selectedIds"];
        companiesSelected(ids);
    }
}

function companiesSelected(ids) {
    //$('#companytableholder').load(base + 'servicecompany.ivp/addcompanies', { companyids: ids.join(','), nolayout: true, serviceid: $('#id').val(), timestamp: new Date().toString() }, function () {
    //    $('#companytableholder').load(base + 'servicecompany.ivp/list/', { tb_serviceid: $('#id').val(), nolayout: true, timestamp: new Date().toString(), generateReport: true }, initTable);
    //});
    //resetUsers();
    var url = base + 'servicecompany.ivp/addcompanies';
    $.getJSON(url, { companyids: ids.join(','), nolayout: true, serviceid: $('#id').val(), timestamp: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alertDialog(CommonResources.Error, result.Description);
        else {
            $('#companytableholder').load(base + 'servicecompany.ivp/list/', { tb_serviceid: $('#id').val(), nolayout: true, timestamp: new Date().toString(), generateReport: true }, initTable);
            resetUsers();
        }
    });
}

function isCurrentUserAddingToService() {
    if ($('#hasChildServices') && $('#hasChildServices').val() != 'True') {
        $.getJSON(base + 'service.ivp/IsUserOnService/', { serviceId: $("#id").val() }, function (result) {
            if (result && result.hasOwnProperty('IsOK') && result.IsOK == true) {
                $('#cannotCreateService').addClass('hidden');
            } else {
                $('#cannotCreateService').removeClass('hidden');
            }
        });
    }
}

function assetSelected(ids) {
    var id = ids.join(',');
    $('#assets').load(base + 'serviceasset.ivp/addasset', { assetid: id, serviceid: $('#id').val(), timestamp: new Date().toString() }, function () { initTable(); initServiceTable("#assettable", "#assetid"); });
}

function assetSelectedTree(id) {
    $('#assets').load(base + 'serviceasset.ivp/addasset', { assetid: id, serviceid: $('#id').val(), timestamp: new Date().toString() }, function () { initServiceTable("#assettable", "#assetid"); });
}

function deleteAssets() {
    var ids = new Array();
    $('#assets input[name=id]:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(ServiceResources.NoAssetsSelected); return false; }
    if (!confirm(ServiceResources.SureDeleteAssets)) return false;
    $('#assets').load(base + 'serviceasset.ivp/deleteassets', { serviceid: $('#id').val(), ids: ids }, function () { initTable(); initServiceTable("#assettable", "#assetid"); });    

    return false;
}

function selectCategoryForRule() {
    dlg = openDialog('category/select?cbmode=ServiceRule&reset=true&tb_mode=single&tb_serviceid=' + $('#id').val(), 'category', { width: 990, height: 660 });
    dlg.callback = ServiceRule.categoriesCallback;
    return false;
}
function categoriesForRuleSelected(ids, names) {
    ids.forEach(function (id) {
        var lb = $.trim(names['id' + id]);
        //addCategory(null, [lb, id]);
        addCategory({ value:lb, data:{ id: id}});
    });
}

function loadExecutorRules(entityType, reload) {
    var blockId = '#executor' + entityType + 'rules';
    var blockIdClear = 'executor' + entityType + 'rules';

    toggleSubmitButtons(blockIdClear);

    if (reload || !$.trim($(blockId).html()))
        $(blockId).load(base + 'service.ivp/loadexecutorrules/' + $('#id').val(), { type: entityType, date: new Date().toString() }, function () {
            setTab(blockIdClear);
            if ($.browser.mozilla && $.browser.version < 37 && entityType == 'status') { // ..жесткие костыли..
                $("div.pinbottom").each(function () {
                    var _h = $(this).height();
                    var ptd = $(this).closest("td");

                    $(this).css("top", (ptd.position().top + ptd.height() + 20) + "px");
                    $(this).width(ptd.width() + 4);
                    $(this).height(_h);
                });
            }

            $("#aexecutorcategoryrules").addClass("selected");
            addCategoryAutocomplete();
        });
    else {
        setTab(blockIdClear);
        $("#aexecutorcategoryrules").addClass("selected");
    }

    return false;
}

function addCategoryAutocomplete() {
    //$('#addcategory').autocomplete(base + 'service.ivp/findcategories/' + $('#id').val(), { minChars: 1 }).result(addCategory);
    $('#addcategory').devbridgeAutocomplete({
        serviceUrl: base + 'service.ivp/findcategories/' + $('#id').val(),
        onSelect: addCategory,
        minChars: 1,
        autoClearInputOnSelect: true //после выбора элемента очищаем инпут
    });
}

function addCategory(suggestion) {
    var name = suggestion.value;
    var id = "" + suggestion.data.id;

    // Отсеить дублирование категорий
    var tablerows = $("#executorcategoryrules table tr");
    for (var i = 2; i < tablerows.length - 1; i++) {
        if ($(tablerows[i]).find("td:first-child div:first-child").text().trim() == name)
            return false;
    }

    // Добавить новый блок
    var newblock= $("<tr><td><ul class='clear'></ul></td><ul class='clear'></ul><td></td><tr/>").insertBefore(tablerows[tablerows.length - 1]);
    var maincol = $(tablerows[1]).find("td:first-child").clone();
    maincol.find("#chooseexectriggercategory0")
            .attr({ "id": "chooseexectriggercategory" + id, "onclick": "return chooseExecutors('category'," + id + ");" });
    maincol.find("#chooseexecgrouptriggercategory0")
            .attr({ "id": "chooseexecgrouptriggercategory" + id, "onclick": "return chooseExecutorGroup('category'," + id + ");" });
    maincol.find("#chooseobsertriggercategory0")
            .attr({ "id": "chooseobsertriggercategory" + id, "onclick": "return chooseObservers('category'," + id + ");" });
    maincol.find("div:first-child").text(name);
    maincol.insertBefore(newblock.find("td:first-child"));
}

function loadStages() {
    $('#stages').load(base + 'service.ivp/stages/' + $('#id').val(), { date: new Date().toString() });
}

function deleteStage(id) {
    $.getJSON(base + 'servicestage.ivp/delete', { json: true, id: id, date: new Date().toString() }, function (result) { if (result.hasOwnProperty('IsOK') && !result.IsOK) alert(result.Description); else $('#stage' + result.Id).fadeOut('fast'); });
    return false;
}

function deleteChildService(id) {
    if (confirm(ServiceResources.SureDeleteChildService)) {
        $.getJSON(base + 'service.ivp/delete', { json: true, id: id, date: new Date().toString() }, function(result) {
            if (result.hasOwnProperty('IsOK') && !result.IsOK)
                alert(result.Description); else $('#childservice' + result.Id).fadeOut('fast');
        });
    }
    return false;
}

function chooseExecutors(type, cid) {
    ccid = cid;
    var offset = $('#chooseexectrigger' + type + cid).offset();
    $('#chooseexecutors' + type + ' input').removeAttr("checked");
    $('#chooseexecutors' + type).css('top', offset.top - 60).css('left', offset.left).fadeIn('fast');
    return false;
}

function chooseObservers(type, cid) {
    ccid = cid;
    var offset = $('#chooseobsertrigger' + type + cid).offset();
    $('#chooseobservers' + type + ' input').removeAttr("checked");
    $('#chooseobservers' + type).css('top', offset.top - 60).css('left', offset.left).fadeIn('fast');
    return false;
}

function addObservers(type) {
    var url = 'taskuser.ivp/selectobservers?tb_serviceid=' + $('#id').val();
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = function (response) { return addObserversCallback(response, type); };
    return false;
}

function addObserversCallback(response, type)
{
    $('#chooseexecutorgroups' + type).fadeOut('fast');
    var ids = response.selectedIds;
    $('#executor' + type + 'rules').load(base + 'service.ivp/createobserverrule', { userids: ids, id: ccid, type: type, serviceid: $('#id').val() }, addCategoryAutocomplete);
    resize();
}

function addAbselsersCategoryTextChanged()
{
    var strFilter = $("#addobselserscategory").val();
    if (strFilter.length > 1 || strFilter.length === 0)
    {
        $("#chooseobserverscategory").find("li.user").empty();
        var chooseobserverscategoryul$ = $("#chooseobserverscategory").find("ul");
        chooseobserverscategoryul$.load(base + 'service.ivp/findparticipantsfromfilter/' + $('#id').val(), { "q": strFilter })
    }
}

function addAbselsersStatusTextChanged() {
    var strFilter = $("#addobselsersstatus").val();
    if (strFilter.length > 1 || strFilter.length === 0) {
        $("#chooseobserversstatus").find("li.user").empty();
        var chooseobserverscategoryul$ = $("#chooseobserversstatus").find("ul");
        chooseobserverscategoryul$.load(base + 'service.ivp/findparticipantsfromfilter/' + $('#id').val(), { "q": strFilter })
    }
}

function chooseExecutorGroup(type, cid) {
    ccid = cid;
    var offset = $('#chooseexecgrouptrigger' + type + cid).offset();
    $('#chooseexecutorgroups' + type + ' input').removeAttr("checked");
    $('#chooseexecutorgroups' + type).css('top', offset.top - 60).css('left', offset.left).fadeIn('fast');

    return false;
}

function executorsSelected(type) {
    var ids = new Array();
    $('#chooseexecutors' + type + ' input:checked').each(function (i, el) { ids.push(el.value); });
    $('#executor' + type + 'rules').load(base + 'service.ivp/createexecutorrule', { userids: ids, id: ccid, type: type, serviceid: $('#id').val() }, addCategoryAutocomplete);
    resize();
    return false;
}

function observersSelected(type) {
    var ids = new Array();
    $('#chooseobservers' + type + ' input:checked').each(function (i, el) { ids.push(el.value); });
    $('#executor' + type + 'rules').load(base + 'service.ivp/createobserverrule', { userids: ids, id: ccid, type: type, serviceid: $('#id').val() }, addCategoryAutocomplete);
    resize();
    return false;
}

function assignExecutorGroupsSelected(type) {
    var id = $('#chooseexecutorgroups' + type + ' input:checked').get(0).value;
    $('#executor' + type + 'rules').load(base + 'service.ivp/creategroupexecutorrule', { groupid: id, id: ccid, type: type, serviceid: $('#id').val() }, addCategoryAutocomplete);
    resize();
    return false;
}


function deleteRule(type, rid) {
    $('#executor' + type + 'rules').load(base + 'service.ivp/deleteexecutorrule', { ruleid: rid, type: type, date: new Date().toString() }, function () { setTab('executor' + type + 'rules'); addCategoryAutocomplete(); });
    resize();
}

function toggleDeleteCurrentParticipants(a, statusid, participanttype) {
    var url = base + 'service.ivp/changedelete' + participanttype + 'attribute';

    $.getJSON(url, { json: true, serviceid: $('#id').val(), statusid: statusid, date: new Date().toString() },
        function (result) {
            if (result.hasOwnProperty('IsOK') && !result.IsOK)
                alert(result.Description);
            else {
                if ($(a).html().indexOf(CommonResources.Yes) >= 0) {
                    $(a).html(CommonResources.No);
                }
                else if ($(a).html().indexOf(CommonResources.No) >= 0)
                    $(a).html(CommonResources.Yes);

                $(a).closest(".toggleDelete").toggleClass('toggleDeleteNo').toggleClass('toggleDeleteYes');
            }
        });
    return false;
}

function companyDetails(id) {
    window.open(base + 'company.ivp/view/' + id);
    //openDialog('company.ivp/view/' + id + '?popup=true', 'company' + id);
    return false;
}

function loadNotificationRule(entityType) {
    var reload = false;
    
    toggleSubmitButtons('notifications');

    //если метод вызван без аргумента, значит это callback после работы с карточкой правила
    if (entityType == null) {
        reload = true; //перезагружаем список
        entityType = ($('#tab').val() == 'notificationruleusers') ? 'users' : 'roles'; //определяем сущность
        if (entityType == 'roles') forceNRUsersReload = true; //если список ролей, н.б. перезагрузить список пользователей принудительно
    }
    var blockId = '#notificationrule' + entityType;
    var blockIdClear = 'notificationrule' + entityType;

    if (entityType == 'users' && forceNRUsersReload) //в случае принудительной перезагрузки списка пользователей 
    {
        reload = forceNRUsersReload;
        forceNRUsersReload = false;
    }

    if (reload || !$.trim($(blockId).html())) {
        var addParam = ""; 
        var wfId = $("#servicelist").val();
        if (wfId != undefined)
            addParam = "?workflowid=" + wfId;

        $(blockId).load(base + 'service.ivp/loadnotificationrulefor' + entityType + '/' + $('#id').val() + addParam, { date: new Date().toString() }, function () {
            if (entityType == 'users')
                $('#addUsersNotifications').devbridgeAutocomplete({
                    serviceUrl: base + 'service.ivp/FindUsersJson/' + $('#id').val(),
                    onSelect: userNotificationSelected,
                    minChars: 1,
                    autoClearInputOnSelect: true //после выбора элемента очищаем инпут
                });
                //$("#addUsersNotifications").autocomplete(base + 'service.ivp/findusers/' + $('#id').val(), { minChars: 1 }).result(userNotificationSelected);

            setTab(blockIdClear);
            $("#anotificationruleroles").addClass("selected");
        });
    } else {
        setTab(blockIdClear);
        $("#anotificationruleroles").addClass("selected");
    }

    return false;
}

function ownerFound(suggestion) {
    var name = suggestion.value;
    var id = "" + suggestion.data.id;
    _ownerSelected(id, name);
}

var ServiceNotifications = {
    selectServiceUsers: function selectServiceUsers() {
        var url = 'user.ivp/select?cbmode=ServiceNotifications&tb_mode=serviceusers&tb_serviceid=' + $("#id").val();
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = ServiceNotifications.usersCallback;
        return false;
    }, 
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        addSelected(uids);
    }
}

function ownerSelected(uids, names) {
    var id = uids[0];
    var un = names['id' + id];
    _ownerSelected(id, un);
}

function _ownerSelected(id, name) {
    $('#ownername').remove();
    var html = '<span id="ownername">' + name + '</span>';
    $('#owner ul li').html(html + $('#owner ul li').html());
    $('#owner ul li').removeClass('archive').addClass('changed');

    $('li:last span.hover a.delete', '#owner ul').unbind('onclick');
    $('li:last span.hover a.delete', '#owner ul').click(function () {
        var a = $(this);
        var del = !a.parents('li:first').hasClass('archive');
        if (ownerExists) {
            if (del) {
                a.parents('li:first').addClass('archive');
                deletingOwnerId = $('#ownerid').val();
                $('#ownerid').val(0);
                $('#selectowner').show();
            }
            else {
                a.parents('li:first').removeClass('archive');
                $('#ownerid').val(deletingOwnerId);
                $('#selectowner').hide();
            }
        }
        else {
            $('#ownerid').val(0);
            $('#owner').hide();
            $('#selectowner').show();
        }

        return false;
    });
    if (ownerExists) ownerChanged = true;
    $('#ownerid').val(id);
    $('#owner').show();
    $('#selectowner').hide();
}

function deleteOwner(a) {
    a = $(a);
    var del = !a.parents('li:first').hasClass('archive');
    if (del) {
        a.parents('li:first').addClass('archive changed');
        deletingOwnerId = $('#ownerid').val();
        $('#ownerid').val(0);
        $('#selectowner').show();
    } else if (!ownerChanged) {
        a.parents('li:first').removeClass('archive changed');
        $('#ownerid').val(deletingOwnerId);
        $('#selectowner').hide();
    }
    return false;
}

function substituteFound(suggestion) {
    var name = suggestion.value;
    var id = "" + suggestion.data.id;
    _substituteSelected(id, name);
}

function substitutesSelected(uids, names) {    
    uids.forEach(function (id) {
        var un = names['id' + id];
        _substituteSelected(id, un);
    });
}

function _substituteSelected(id, name) {
    var wrapper = $("#substitutes");
    var ul = wrapper.find('ul:first');
    var select = wrapper.find('select:first');

    if ($('option[value="' + id + '"]', select).length > 0) return;

    select.append('<option selected value="' + id + '">' + name + '</option>');
    var html = '<li class="changed">' + name;
    html += '<span class="hover"><a href="#"><img src="img/trash.gif" /></a></span>';
    ul.append(html);
    $('li:last span.hover a', ul).click(function () { var a = $(this); a.parents('li.changed').remove(); $('option[value="' + id + '"]', select).remove(); return false; });
}

function deleteSubstitute(a, id) {
    a = $(a);
    var del = !a.parents('li:first').hasClass('archive');
    $('select option[value="' + id + '"]', a.parents('div:first')).attr('selected', !del);
    if (del) a.parents('li:first').addClass('archive changed'); else a.parents('li:first').removeClass('archive changed');
    return false;
}

function handleChildSettings() {
    var check = $('#copysettings').is(':checked');
    if (!check) {
        $('#movetasks').attr('disabled', true).removeAttr('checked');
    }
    else {
        $('#movetasks').removeAttr('disabled');
    }
}

function createChildService() {
    if ($('#newname').val() == "" || $('#newcode').val() == "") {
        alert(ServiceResources.NameCodeRequired);
        return false;
    }
    if ($.browser.msie)
        window.location = base + 'service.ivp/createchildservice?id=' + $('#id').val() + '&copysettings=' + $('#copysettings').is(':checked') + '&movetasks=' + $('#movetasks').is(':checked') + '&newname=' + encodeURIComponent($('#newname').val()) + '&newcode=' + encodeURIComponent($('#newcode').val());
    else {
        window.location = base + 'service.ivp/createchildservice?id=' + $('#id').val() + '&copysettings=' + $('#copysettings').is(':checked') + '&movetasks=' + $('#movetasks').is(':checked') + '&newname=' + $('#newname').val() + '&newcode=' + $('#newcode').val();
    }
}

function copyService(self) {
    if ($('#copyprop').find('#newname').val() == "" || $('#copyprop').find('#newcode').val() == "") {
        alert(ServiceResources.NameCodeRequired);
        return false;
    }
    $(self).prop('disabled', true);
    window.location = base + 'service.ivp/copyservice?id=' + $('#id').val() + '&copysettings=' + $('#copyprop').find('#copysettings').val() + '&movetasks=' + $('#copyprop').find('#movetasks').is(':checked') + '&newname=' + $('#copyprop').find('#newname').val() + '&newcode=' + $('#copyprop').find('#newcode').val() + '&executorgroups=' + $('#copyprop').find('#executorgroups').val() + '&copychildrens=' + $('#copyprop').find('#copychildrens').is(':checked');
}

function inheritService() {
    /*
        $.getJSON(base + 'service.ivp/inheritservice', { 
            json: true, 
            id: $('#id').val(), 
            generalsettings: $('div#inheritprop #generalsettings').is(':checked'), 
            tasktypes: $('div#inheritprop #tasktypes').is(':checked'),
            departaments: $('div#inheritprop #departaments').is(':checked'),
            users: $('div#inheritprop #users').is(':checked'),
            actives: $('div#inheritprop #actives').is(':checked'),
            executorsappointment: $('div#inheritprop #executorsappointment').is(':checked'),
            notifications: $('div#inheritprop #notifications').is(':checked'),
            date: new Date().toString() 
        },
            
            function(result) {
                 if (result.hasOwnProperty('IsOK') && !result.IsOK)
                    alert(result.Description);
                else {
                    alert(result.Description);
                    //if ($(a).html().indexOf(CommonResources.Yes)>=0)
                    //    $(a).html(CommonResources.No);
                    //else if ($(a).html().indexOf(CommonResources.No)>=0)
                    //    $(a).html(CommonResources.Yes);
                }
            });
        return false; */

    window.location = base + 'service.ivp/inheritservice?id=' +
	$('#id').val() +
	'&generalsettings=' + $('div#inheritprop #generalsettings').is(':checked') +
    '&categories=' + $('div#inheritprop #categories').is(':checked') +
	'&tasktypes=' + $('div#inheritprop #tasktypes').is(':checked') +
	'&departaments=' + $('div#inheritprop #departaments').is(':checked') +
	'&users=' + $('div#inheritprop #users').is(':checked') +
	'&actives=' + $('div#inheritprop #actives').is(':checked') +
	'&executorsappointment=' + $('div#inheritprop #executorsappointment').is(':checked') +
	'&notifications=' + $('div#inheritprop #notifications').is(':checked') +
	'&escalations=' + $('div#inheritprop #escalations').is(':checked') +
	'&executorgroups=' + $('div#inheritprop #executorgroups').is(':checked');
}

// code of service escalation rules
////////////////////////////////////////////////////////////////////
//function createEscalationRule(link) {
//    var url = base + 'ServiceEscalationRule.ivp/editableform/' + 0;

//    showRulePanelEscalationRule(url, $(link), { date: new Date().toString() });

//    return false;
//}




//function showRulePanelEscalationRule(url, link, params) {

//    var offset = link.offset();

//    if ($('#aescalationrule').length == 0) $('body').append('<div id="aescalationrule" class="aescalationrule hidden"></div>');
//    var panel = $('#aescalationrule');
//    panel.load(url, params, function () {
//        //позиционируем форму
//        if (link.hasClass("button")) //для меню на списке заявок
//            panel.css('position', 'absolute').css('top', offset.top - 100).css('right', 300);
//        else //для списков правил
//            panel.addClass('popupwrapper').css('top', offset.top + link.height() - 75).css('left', 40);//offset.left

//        panel.bgiframe().show();
//    });
//    return false;
//}


//function showEditableFormEscalationRule(id) {
//    if (id == undefined)
//        $('#aescalationrule').load(base + 'ServiceEscalationRule.ivp/editableform/' + 0, { date: new Date().toString() }, function () { $('#aescalationrule').fadeIn('fast'); });
//    else
//        $('#aescalationrule').load(base + 'ServiceEscalationRule.ivp/editableform/' + id, { date: new Date().toString() }, function () { $('#aescalationrule').fadeIn('fast'); });
//    return false;
//}


function getName(data, id) {
    //data eq [{Key:uid,Value:Name},{Key:uid,Value:Name},{Key:uid,Value:Name}]
    for (var k in data) {
        if (data[k].Key == id)
            return data[k].Value;
    }
    return null;
}



/*
true/false возвращает есть ли элемент в массиве
*/
Array.prototype.in_array = function (value) {
    for (var i = 0, l = this.length; i < l; i++)
        if (this[i] == value)
            return true;

    return false;
};







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

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

function showUsers() {
    var $divholder = $('#usertabholder');
    var $link = $('<a href="#"/>').addClass('switch').text(ServiceResources.ExecutorGroup).click(loadExecutorGroups);
    var $active = $('<span/>').addClass('activeswitch').text(ServiceResources.Users);
    $divholder.empty().append($active).append($link);
    $('#executorgroupholder').hide();
    $('#users #iframeholder').show();
    $('#usersmenu').show();
    return false;
}

function loadExecutorGroups() {
    var $divholder = $('#usertabholder');
    var $link = $('<a href="#"/>').addClass('switch').text(ServiceResources.Users).click(showUsers);
    var $active = $('<span/>').addClass('activeswitch').text(ServiceResources.ExecutorGroup);
    $divholder.empty().append($link).append($active);
    $('#users #iframeholder').hide();
    if (!$.trim($('#executorgroupholder').html())) {
        $('#executorgroupholder').load(base + 'serviceexecutorgroup.ivp/list/' + $('#id').val(), {}, function () { $('#executorgroupholder').show(); initServiceTable('#executorgrouptable', '#groupid'); });
    }
    else
        $('#executorgroupholder').show();
    $('#usersmenu').hide();
    return false;
}

function chooseGroups() {
    dlg = openDialog('executorgroup/select?tb_mode=NOTONSERVICE&tb_serviceid=' + $('#id').val(), 'selectgroups');
    dlg.callback = executorGroupsCallback;
    return false;
}

function executorGroupsCallback(result) {
    var ids = result["selectedIds"];
    executorGroupsSelected(ids);
}

function executorGroupsSelected(ids) {
    $('#executorgroupholder').load(base + 'serviceexecutorgroup.ivp/addgroups', { groupsids: ids.join(','), serviceid: $('#id').val(), timestamp: new Date().toString() }, function() {
        resetUsers(); loadUsers(); initServiceTable('#executorgrouptable', '#groupid');
    });
}

function executorGroupDetails(id) {
    openDialog('executorgroup/view/' + id + '?popup=true', 'executorgroup' + id);
    return false;
}

function deleteGroups() {
    var ids = new Array();
    $('#executorgroupholder input.groupid:checked').each(function (i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert(ExecutorGroupResources.NoGroupsSelected); return false; }
    if (!confirm(ServiceResources.SureDeleteGroups)) return false;
    $('#executorgroupholder').load(base + 'serviceexecutorgroup.ivp/deletegroups', { serviceid: $('#id').val(), ids: ids }, function() {
        resetUsers(); loadUsers(); initServiceTable('#executorgrouptable', '#groupid');
    });
    return false;
}

function showUserRolesRules(params, link) {
    link = $(link);
    var offset = link.offset();

    if ($('#notificationuserrulesedit').length == 0) $('body').append('<div id="notificationuserrulesedit" class="notificationuserrulesedit hidden"></div>');
    var panel = $('#notificationuserrulesedit');
    var url = base + 'service.ivp/LoadNotificationRuleForUserRoles/' + $("#id").val();
    panel.load(url, params, function () {
        //позиционируем форму
        panel.addClass("popupwrapper");
        panel.css("position", "absolute").css('top', offset.top + link.height() + 5).css('left', offset.left).css("width", "70%").css("box-shadow", "0 0 0 9999px rgba(0,0,0,.3)").css("background-color", "white");
        panel.show();
    });
    return false;
}

function userNotificationSelected(suggestion) {
    var id = "" + suggestion.data.id;
    addUserNotifications(id);
}

function addUserNotifications(id) {
    var table = $("#usersnotificationrules");
    table.show();
    if ($('#usersnotificationrules tr td[id="' + id + '"]').size() > 0)
        return;
    var workflowId = $("#servicelist").val();
    if (workflowId == undefined)
        workflowId = $("#CurrentUsersWorkflowId").val();

    var addParam = "?workflowid=";
    addParam += (workflowId != undefined ? workflowId: "0") ;

    $.get(
        base + 'service.ivp/GetUserNotificationRuleTableElement/' + $("#id").val() + addParam,
        { userId: id },
        function (html) {
            table.append(html);
        }
    );
}

function addSelected(uids) {
    $.each(uids, function () {
        addUserNotifications(this);
    });
}

function deleteUserNotificationRules(userId) {
    $.get(
        base + 'service.ivp/DeleteUserNotificationRule/' + $("#id").val(),
        { userId: userId },
        function () {
            loadNotificationRule("users");
        }
    );
}

function saveEmailFrom() {
    $.get(base + "service.ivp/SaveEmailFrom/" + $("#id").val(),
        { eMail: $("#email_from").val() },
        function () {
            $('#email_from').attr('disabled', 'disabled').data("currentvalue", $("#email_from").val());;
            $('#email_from').closest('div').find('span').toggle();
        }
    );

    return false;
}

function setDefaultEmailFrom() {
    $.get(base + "service.ivp/SetDefaultEmailFrom/" + $("#id").val(),
        {},
        function () {
            $('#email_from').attr('disabled', 'disabled').attr('value', $('#email_from').data('defaultvalue')).data("currentvalue", $("#email_from").data("defaultvalue"));
            $('#email_from').closest('div').find('span').toggle();
        }
    );
}

function cancelEditEmailFrom() {
    $('#email_from').attr('disabled', 'disabled').attr('value', $('#email_from').data('currentvalue'));

    $('#email_from').closest('div').find('label.error').remove();
    $('#email_from').closest('div').find('span').toggle();


    return false;
}

function showActionPopup() {
    var actionsDiv = $('.actions');
    var actionblockDiv = $('#actionblock');    
    
    var panel = $('#actionhoder');
        
    panel.css('top', $('.shadowbg').height() + $('#header').height() - $('#actionhoder').height() - 5).css('left', actionblockDiv.width() - actionsDiv.width())
        .css('right', '-130px').css('width', '300px');
    
    $('#actionhoder').toggle();
    return false;
}

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

function reloadClearCompany(elem) {
   
   
    if ($(elem).hasClass('hiddenClearSearch') || $('#searchCompany').val()=='')
        return false;
    $('#searchCompany').val('');
   
    if (!$(elem).hasClass('hiddenClearSearch'))
        $(elem).toggleClass('hiddenClearSearch');

    var params = new Array();
    params.push({ name: 'nolayout', value: true });
    params.push({ name: 'tb_search', value: "" });
    params.push({ name: 'tb_serviceid', value: $('#id').val() });

    var uurl = 'servicecompany.ivp/list?reset=true';
    $('#companies #companytableholder').load(uurl, params, function () {
        initTable();
    });

    return false;
}

function reloadCompany() {
    var params = new Array();
    if ($("#btnClearSearch").hasClass('hiddenClearSearch'))
        $("#btnClearSearch").toggleClass('hiddenClearSearch');

    params.push({ name: 'nolayout', value: true }); 
    params.push({ name: 'tb_search', value: $('#searchCompany').val() });
    params.push({ name: 'tb_serviceid', value: $('#id').val() }); 
   
    var uurl = 'servicecompany.ivp/list?reset=true';
    $('#companies #companytableholder').load(uurl, params, function () {
        initTable();       
    });

    return false;
}

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