var dlg = null;
var managerExists;
var managerChanged = false;
var contactpersonExist = false;
var contactpersonChanged = false;
var deletingManagerId;
var deletingContactPersonId;

//#region BaseInit
$(function () {
    $('.autogrow').elastic();
    $('input').keydown(function(e) {
        if (e.keyCode == 13) {
            return false;
        }
    });

    if ($('#customerkey').val()) {
        $('#allowregistration').attr('checked', true);
        switchRegistrationFields(true, true);
    }

    $('#typeid').change(changeType);

    $('#parentid').change(function() { $('#parentidwarning').show(); });
    if ($('#tab').val() == 'documents') loadDocuments(true);
    if ($('#tab').val() == 'info') setTab('info');
    if ($('#tab').val() == 'documentsrules') loadDocumentsRules(true);

    $('#choosemanager').autocomplete(base + 'company.ivp/findusers/' + $('#id').val(), { minChars: 1 }).result(managerFound);
    $('#choosesubstitute').autocomplete(base + 'company.ivp/findusers/' + $('#id').val(), { minChars: 1 }).result(substituteFound);
    $('#choosecontactperson').autocomplete(base + 'company.ivp/findusers/' + $('#id').val(), { minChars: 1 }).result(contactPersonFound);


    managerExists = $('#managerid').val() != "0";
    contactpersonExist = $('#contactpersonid').val != "0";

    $('li:last span.hover a.delete', '#manager ul').bind('click', function() {
        return deleteManager(this);
    });
    $('li:last span.hover a.delete', '#contactperson ul').bind('click', function() {
        var a = $(this);
        a.parents('li:first').addClass('archive');
        deletingManagerId = $('#contactpersonid').val();
        $('#contactpersonid').val(0);
        $('#contactperson').hide();
        $('#selectcontactperson').show();
        return false;
    });

    $("#uf_roleid").change(reloadUsers);
    $('#uf_showarchive').bind("click",function() {
        reloadUsers();
    });

    $("#exportTemplate").click(function () {
        $('#actionholder').toggle();
    });

    $('#addParent').autocomplete(base + 'company.ivp/searchidname/', { minChars: 1 }).result(parentSelectedFromAutoComplete);    
});

$('#usersmenu #search').keydown(function (e) {
    if (e.keyCode == 13) {
        reloadUsers();
    }
});

window.afterInitTable = function () {
    if ($('#links #tableholder').length > 0) {
        initCluetip();
    }
    InitResizableGrid('table.resizable-grid', 300);
};

function initCheckboxes() {
    $('.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(undefined, this.value, this.checked);
    });
}

function selectRow(table, val, check, skip) {
        table = table || '';
        if (table)
            table = table + ' ';
        var cb = $(table + "#id" + val).get(0);
        var tid = $(cb).closest('table').attr('id') || 'id';
        if (check) {
            if (!skip) userSelectedIds.push({ name: tid, value: val });
            if (cb) {
                cb.checked = true;
                $(cb).parents('tr').addClass('selected');
            }
        }
        else {
            userSelectedIds = $.grep(userSelectedIds, function (i) { if (i.name == tid) { return i.value != val; } });
            if (cb) {
                cb.checked = false;
                $(cb).parents('tr').removeClass('selected');
            }
        }
        try { if (rowChecked) rowChecked(val, check); } catch (e) { }
    }
//#endregion

//#region Common

    function setTab(id) {
    if (!documentReady) return;
    $('#tab').val(id);
    $('.tab').each(function (i, el) { if (el.id == id) $(el).show(); else $(el).hide(); });
    $('#tabid').val(id);
    $('#tabs>ul>li>a').each(function (i, el) { if (el.id == 'a' + id) $(el).addClass('selected'); else $(el).removeClass('selected'); });
    $('.rm').hide();
    if (id == 'documents' || id == 'assets' || id == 'users' || id == 'services' || id == 'templates') {
        //$('#' + id + 'menu').show();
        $('.save').attr('disabled', true);
        $('.saveandreturn').attr('disabled', true);
    }
    else {
        if (id == 'info')
            $('#infofields .autogrow').elastic();
        $('.save').attr('disabled', false);
        $('.saveandreturn').attr('disabled', false);
    }
    $('#' + id + 'menu').show();
    return false;
}

    function beforeSubmitForm() {
    var linkOld = $('#companyform').attr('action');
    if (linkOld.indexOf('?') < 0)
        $('#companyform').attr('action', linkOld + '?tab=' + $('#tab').val());
}

    function initCluetip() {
    $('img.link').cluetip({
        arrows: true,
        dropShadow: false,
        cluetipClass: 'jtip',
        showTitle: false
    });
    $('span.assetlink').cluetip({
        arrows: false,
        dropShadow: false,
        cluetipClass: 'jtipnew',
        showTitle: false
    });
}

    function switchRegistrationFields(show, instant) {
    var speed = instant ? null : 'fast';
    if (show) {
        $('#selfregistrationfields').show(speed);
        $('#customerkey').addClass('required'); $('#customerkeylabel').addClass('required');
        $('#defaultroleid').addClass('required'); $('#defaultrolelabel').addClass('required');
    }
    else {
        $('#selfregistrationfields').hide(speed);
        $('#customerkey').removeClass('required'); $('#customerkeylabel').removeClass('required');
        $('#defaultroleid').removeClass('required'); $('#defaultrolelabel').removeClass('required');
        $('#customerkey').val(''); $('#defaultroleid').val(''); $('#notifydirectoronregistration').attr('checked', false);
    }
    return false;
}

    function changeType() {
    if ($('#typeid').val() != "3") {
        $('#aregistration').hide();
        $('#customerkey').val('');
        $('#defaultroleid').val('');
        $('#allowregistration').removeAttr('checked');
        $('#denyregistration').click();
    }
    else
        $('#aregistration').show();
    return false;
}

    //функция для правильного возвращения к списку
    function closeFormCompany() {
    if (formchanged == true && !confirm(FormResources.FormChanged)) return;
    var f = $('form:first');
    var actionForm = f.attr('action');
    var controller = actionForm.substr(0, actionForm.indexOf('/'));
    var action = $('#typeid').val();
    switch (action) {
        case "1":
            document.location.href = base + controller + '/list';
            break;
        case "2":
            document.location.href = base + controller + '/ExternalCompany';
            break;
        case "3":
        default:
            document.location.href = base + controller + '/ClientsCompany';
            break;
    }

}

    function returnToCompanyAfterSave() {
    var href;
    var f = $('form:first');
    var actionForm = f.attr('action');
    var controller = actionForm.substr(0, actionForm.indexOf('/'));
    var action = $('#typeid').val();
    if ($("#attributeholder .required:not(label, [value != ''])").length) {
        setTab('info');
    }
    switch (action) {
        case "1":
            href = base + controller + '/list';
            break;
        default:
            href = base + controller + '/ClientsCompany';
            break;
    }
    $('#returnaftersave').val(href);
    // return false;
}

//#endregion

//#region Tabs

    //#region General
//#region Contact person

var CompanyPerson = {
    selectPerson: function selectPerson(companyid) {
        var url = 'user.ivp/select?cbmode=CompanyPerson&tb_mode=companyuser&tb_companyid=' + companyid;
        dlg = window.openDialog(url, 'selectpersons', { width: 900, height: 650 });
        dlg.callback = CompanyPerson.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        addPerson(uids);
    }
}

var CompanyContactPerson = {
    selectContactPerson: function selectContactPerson(companyid) {
        var url = 'user.ivp/select?cbmode=CompanyContactPerson&tb_mode=companyuser&tb_companyid=' + companyid;
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = CompanyContactPerson.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        contactPersonSelected(uids, names);
    }
}

var CompanyManager = {
    selectManager: function selectManager() {
        var url = 'user.ivp/select?cbmode=CompanyManager&reset=true&tb_mode=companyuser';
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = CompanyManager.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        managerSelected(uids, names);
    }
}

var CompanySubstitutes = {
    selectSubstitutes: function selectSubstitutes() {
        var url = 'user.ivp/select?cbmode=CompanySubstitutes&reset=true&tb_mode=companyusers';
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = CompanySubstitutes.usersCallback;
        return false;
    },

    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        substitutesSelected(uids, names);
    }
}

function contactPersonFound(e, d) {
    var id = d[2];
    var name = d[0];
    $(e.target).val('');
    _contactPersonSelected(id, name);
}

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

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

                $('li:last span.hover a.delete', '#contactperson ul').unbind('onclick');
                $('li:last span.hover a.delete', '#contactperson ul').click(function () {
                    var a = $(this);
                    var del = !a.parents('li:first').hasClass('archive');
                    if (contactpersonExist) {
                        if (del) {
                            a.parents('li:first').addClass('archive');
                            deletingContactPersonId = $('#contactpersonid').val();
                            $('#contactpersonid').val(0);
                            $('#contactperson').hide();
                            $('#selectcontactperson').show();
                        }
                        else {
                            a.parents('li:first').removeClass('archive');
                            $('#contactpersonid').val(deletingContactPersonId);
                            $('#selectcontactperson').hide();
                            $('#contactperson').show();
                        }
                    }
                    else {
                        $('#contactpersonid').val(0);
                        $('#contactperson').hide();
                        $('#selectcontsctperson').show();
                    }

                    return false;
                });
                if (contactpersonExist) contactpersonChanged = true;
                $('#contactpersonid').val(id);
                $('#contactperson').show();
                $('#selectcontactperson').hide();
            }

            function addPerson(uids) {
                var userid = uids[0];
                $('#contactpersonid').val(userid);
                $.getJSON(base + 'user.ivp/GetUserNameById', { userid: userid, date: new Date().toString() }, function (fio) {
                    $('#contactPerson').val(fio);
                });
                return false;
            }
        //#endregion

        //#region Manager
        function managerFound(e, d) {
            var id = d[2];
            var name = d[0];
            $(e.target).val('');
            _managerSelected(id, name);
        }

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

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

            $('li:last span.hover a.delete', '#manager ul').unbind('onclick');
            $('li:last span.hover a.delete', '#manager ul').click(function () {
                var a = $(this);
                var del = !a.parents('li:first').hasClass('archive');
                if (managerExists) {
                    if (del) {
                        a.parents('li:first').addClass('archive');
                        deletingManagerId = $('#managerid').val();
                        $('#managerid').val(0);
                        $('#selectmanager').show();
                    }
                    else {
                        a.parents('li:first').removeClass('archive');
                        $('#managerid').val(deletingManagerId);
                        $('#selectmanager').hide();
                    }
                }
                else {
                    $('#managerid').val(0);
                    $('#manager').hide();
                    $('#selectmanager').show();
                }

                return false;
            });
            if (managerExists) managerChanged = true;
            $('#managerid').val(id);
            $('#manager').show();
            $('#selectmanager').hide();
        }

        function deleteManager(a) {
            var a = $(a);
            var del = !a.parents('li:first').hasClass('archive');
            if (del) {
                a.parents('li:first').addClass('archive changed');
                deletingManagerId = $('#managerid').val();
                $('#managerid').val(0);
                $('#selectmanager').show();
            } else if (!managerChanged) {
                a.parents('li:first').removeClass('archive changed');
                $('#managerid').val(deletingManagerId);
                $('#selectmanager').hide();
            }
            return false;
        }
        //#endregion

        //#region Substitutes
            function substituteFound(e, d) {
                var id = d[2];
                var name = d[0];
                $(e.target).val('');
                _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">' + $.trim(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) {
                var 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;
            }
        //#endregion
    //#endregion

    //#region Users
        function loadUsers() {
            selectedIds.length = 0;
            tableRootDiv = '#users #iframeholder';
            InitGridMenu = function ($menu) {
                if ($menu) {
                    $menu.find('li.grid-filter').remove();
                    $menu.find('li.grid-column-settings').remove();
                }
            };
            DisableSaveButtons();
            if (!$('#users #iframeholder').children().length) {        
                var uurl = 'companyuser.ivp/list?reset=true&tb_companyid=' + $('#id').val();

                $('#users #iframeholder').load(uurl, { nolayout: true }, function () {
                    setTab('users');
                    initTable();
                    c2c("#users");
                });              
            } else {
                setTab('users');
            }
            return false;
        }

        function changeRole(uid) {
            $.getJSON(base + 'user.ivp/roles/', { date: new Date().toString() }, function (roles) {
                if (roles.hasOwnProperty('IsOK') && !roles.IsOK) {
                    alert(roles.Description);
                    return;
                }
                $('.selectrole').remove();
                $('#role' + uid).append('<div class="popupwrapper selectrole"><div class="popup"></div></div>');
                var popup = $('.popup', $('#role' + uid));
                var offset = $('#role' + uid).offset();
                popup.css('top', offset.top + 20).css('left', offset.left);
                popup.append('<p>' + UserResources.SetSystemRole + '</p><ul></ul>');
                var ul = popup.children('ul');
                $(roles).each(function (i, role) { ul.append('<li><a class="button" href="#" onclick="return setRole(' + uid + ',' + role.Id + ');">' + role.Name + '</a></li>'); });
                popup.append('<div class="spacer5"></div><a class="button" href="#" onclick="$(this).parents(\'.popupwrapper\').fadeOut(\'fast\'); return false;">&uarr; ' + UserResources.ChangedMind + '</a>');
                $('.selectrole').fadeIn('fast');
            });
            return false;
        }

        function setRole(uid, rid) {
            $('#services').load(base + 'user.ivp/changesystemrole/', { userid: uid, roleid: rid, date: new Date().toString() }, function () {
                loadUsers(true);
            });
            return false;
        }

        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: $('#usersmenu #search').val() });
            params.push({ name: 'tb_companyid', value: $('#id').val() });
            var rid = parseInt($('#uf_roleid').val(), 10);
            params.push({ name: 'fttRoleId', value: rid > 0 ? 1 : 0 }); params.push({ name: 'flt1RoleId', value: $('#uf_roleid').val() });
            params.push({ name: 'tb_showarchive', value: $('#uf_showarchive:checked').size() > 0 ? "True" : "False" });
            var uurl = 'companyuser.ivp/list';
            $('#users #iframeholder').load(uurl, params, function () {
                initTable();
            });
            return false;
        }
    //#endregion

    //#region Documents
        function loadDocuments(reload) {
        selectedIds.length = 0;
        InitGridMenu = null;
        $('#links').empty();
        tableRootDiv = '#documents #tableholder';
        selectedIds.length = 0;
        DisableSaveButtons();
        if (reload || !$.trim($('#documents').html())) {
            var popup = $('#popup').val() == "True" ? "?popup=true" : "";
            $('#documents').load(base + 'companydocument.ivp/list/' + $('#id').val() + popup, { timestamp: new Date().toDateString() }, function() {
                setTab('documents');
                initTable();
            });
            if ($('#popup').val() != 'True')
                $('#documentsmenu').load(base + 'companydocument.ivp/loadrightmenu', { tb_companyid: $('#id').val(), popup: $('#popup').val(), Readonlyform: $('#Readonlyform').val() });
        } else {
            setTab('documents');
        }
    
        return false;
    }

        function savedFilter(stateid) {
        var popup = $('#popup').val() == "True" ? "?popup=true" : "";
        $('#documents').load(base + 'companydocument.ivp/list/' + $('#id').val() + popup + '?stateid=' + stateid, { timestamp: new Date().toDateString() }, function () {
            setTab('documents');
            var action = $('#tableaction').val() + $('#id').val()
            $('#tableaction').attr('value', action);
            initTable();
            // return false;
        });
    }

        function applySavedAjaxFilter(stateid) {
        var reloadPanel = '#' + $("#tableholder").parent(".tab").attr('id');
        //alert(reloadPanel);
        $(reloadPanel).load(base + tableController() + tableAction() + '?stateid=' + stateid, { timestamp: new Date().toString() }, function () {
            initTable();
            $('#documentsmenu').load(base + 'companydocument.ivp/loadrightmenu', { tb_companyid: $('#id').val(), popup: $('#popup').val(), Readonlyform: $('#Readonlyform').val() });
        });
    
    }
        //#endregion
        
    //#region DocumentsRules
        function loadDocumentsRules(reload) {          
        // DisableSaveButtons();          
        setTab('documentsrules');
        if (reload || !$.trim($('#documentsrules').html())) {
            var popup = $('#popup').val() == "True" ? "?popup=true" : "";
            $('#documentsrules').load(base + 'companydocumentrule.ivp/list/' + $('#id').val() + popup, { timestamp: new Date().toDateString() }, function () {
                initTable();
                setNotActiveRules();
            });

        }
       return false;
    }

    function changeCurrentBlockCreateTask(value) {
        if (!value && $("#documentsrules").find("#tableholder").length !=0 && !confirm(CompanyResources.SureDeleteDocumentsRules)) return false;
        $('#IsBlockTaskCreate').val(value);
        $.ajax({
            type: "POST",
            url: "company.ivp/changecurrentblockcreatetask",
            data: { id: $('#id').val(), value: value },
            success: function () {
                loadDocumentsRules(true);
            }
        });

        return false;
    }

    //#endregion

    //#region Assets
        function loadAssets() {
            DisableSaveButtons();
            $('#assets').load(base + 'company.ivp/loadassets', { companyid: $('#id').val(), popup: $('#popup').val(), Readonlyform: $('#Readonlyform').val() }, function () {
                $('#assetsmenu').empty();
                setTab('assets');
                initTable();
                initCheckboxes();
                initCluetip();
            });
            return false;
        }

        function loadFullLinkTable() {
            selectedIds.length = 0;
            InitGridMenu = null;
            tableRootDiv = '#assets #tableholder';
            $('#documents').empty();
            selectedIds.length = 0;
            DisableSaveButtons();
            $('#assets').load(base + 'assetlink.ivp/companylink', { tb_companyid: $('#id').val(), popup: $('#popup').val(), Readonlyform: $('#Readonlyform').val(), reset: true }, function () {
                setTab('assets');
                initTable();
            });
            $('#assetsmenu').load(base + 'assetlink.ivp/loadcompanyrightmenu', { tb_companyid: $('#id').val(), popup: $('#popup').val(), Readonlyform: $('#Readonlyform').val(), reset:true });
            return false;
        }

        function loadFullAssetsOwner() {
            $('#assets').load(base + 'assettable.ivp/companyasset', { tb_companyid: $('#id').val(), popup: $('#popup').val(), readOnly: true, reset:true }, function () {
                initTable();
            });
            if ($('#assetsmenu').length)
                $('#assetsmenu').load(base + 'assettable.ivp/loadrightmenu', { tb_companyid: $('#id').val(), popup: $('#popup').val(), readOnly: true, reset: 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 openAssetLinkPanel(link, linkid) {
            $('#assetlinkform').remove();
            var $link = $(link);
            var $popupwrapper = $('<div id="assetlinkform" class="popupwrapper"/>');
            $('body').append($popupwrapper);

            var offset = $link.offset();
            $popupwrapper.load(base + 'assetlink.ivp/createfromform', { typeid: 3, linkassetid: $('#id').val(), linkid: linkid, from: 'company' }, function () {
                $popupwrapper.css('top', offset.top + $link.height() + 5).css('left', offset.left);
                autoComplete();
                afterLinkFormCreated();
                $popupwrapper.show();
            });
            return false;
        }

        function saveAssetLink() {
            if ($("#linkform").valid()) {
                $('#assetlinkform').hide();
                $.post(base + 'assetlink.ivp/save/', $('#linkform').serializeArray(), function() {
                    if ($("#assetspreview").size()>0) {
                        loadAssets();
                    } else {
                        loadFullLinkTable();
                    }
                });
                $('#assetlinkform').remove();
            }
            return false;
        }

        function removeAssetLink() {
            if (selectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
            if (!confirm(TableResources.SureDeleteRecords)) return false;
            $.post(base + 'company.ivp/deleteLinks/', { ids: selectedIds, companyid: $('#id').val() }, function () {
                if ($("#assetspreview").size() > 0) {
                    loadAssets();
                } else {
                    loadFullLinkTable();
                }
            });
            return false;
        }
    //#endregion

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

function showAvailableServices() {
    var url = 'service.ivp/select?tb_custom_mode=company&tb_companyid=' +$('#id').val();
    dlg = openDialog(url, 'selectservice', { width: 980, height: 650 });
    dlg.callback = servicesCallback;
    return false;
}

function servicesCallback(result) {
    var ids = result["selectedIds"];
    addSelectedServices(ids);
};

        function addSelectedServices(serviceids) {
            var selected = new Array();
            $('#selectservices input:checked').each(function (i, el) { selected.push(el.value); });
            var url = base + 'company.ivp/addselectedservices';
            $.getJSON(url, { companyid: $('#id').val(), ids: serviceids }, function (result) {
                if (result.hasOwnProperty('IsOK') && !result.IsOK)
                    alertDialog(CommonResources.Error, result.Description);
                else {
                    loadServices(true);
                }
            });
            return false;
        }

        function delSelectedServices() {
            var selected = new Array();
            $('#servicetable td input:checked').each(function (i, el) { selected.push(el.value); });
            if (selected.length == 0) { alert('Отметьте галочками записи, которые вы хотите удалить.'); return false; }
            if (!confirm('Вы уверены, что хотите удалить выбранные записи?')) return false;
            $('#services').load(base + 'company.ivp/deletebyserviceid', { companyid: $('#id').val(), ids: selected.join(',') }, function () { loadServices(true); });
            return false;
        }
    //#endregion

    //#region Templates
        function loadTemplates() {
            DisableSaveButtons();
            if (!$.trim($('#templates').html())) {
                var popup = $('#popup').val() == "True" ? "?popup=true" : "";
                $('#templates').load(base + 'companyquerytemplates.ivp/list/' + $('#id').val() + popup, { timestamp: new Date().toDateString() }, function () { setTab('templates'); });
            }
            else setTab('templates');
            return false;
        }

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

        function addTemplates() {
            var selected = new Array();
            $('#availabletemplates input:checked').each(function (i, el) { selected.push(el.value); });
            $('#templates').load(base + 'companyquerytemplates.ivp/addselectedtemplates', { companyid: $('#id').val(), ids: selected }, function () { $('#availabletemplates').hide(); });
            return false;
        }

        function deleteTemplates() {
            var ids = new Array();
            $('#templates input[name=templateid]:checked').each(function (i, el) { ids.push(el.value); });
            if (ids.length == 0) { alert(CompanyResources.NoTemplatesSelected); return false; }
            if (!confirm(CompanyResources.SureDeleteTemplates)) return false;
            $('#templates').load(base + 'companyquerytemplates.ivp/deletetemplates', { companyid: $('#id').val(), ids: ids });
            return false;
        }
    //#endregion

//#endregion

function selectParent() {
    dlg = openDialog('company.ivp/selectlist');
    dlg.callback = companiesCallback;
    return false;
}

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

function parentSelected(ids, names) {
    var id = ids[0];
    var sn = names['id'+id];
    _parentSelected(id, sn);
}

function _parentSelected(id, name, canRemove) {
    removeParent();
    $('#parentid').val(id).attr('changed', true);
    $('#parentid').trigger("change");
    var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', 'company.ivp/view/' + id).click(function () { return parentDetails(id); });
    $('#parentholder').append($ag);

    $('#parentholder').removeClass("removed");
}

function removeParent() {
    $('#parentid').attr('changed', true).val('');
    $('#parentholder').empty();

    return false;
}

function parentSelectedFromAutoComplete(e, d) {
    _parentSelected(d[1], d[0], $('#readonly').length > 0);
    $('#addParent').val('');
    return false;
}

//#region field handlers

function changeFieldFile(fieldid, link) {
    //Удаляем идентификатор из коллекции удаляемых файлов
    var elems = ($('#deletingfileids').val()).split('|');
    var newelems = [];
    for (var i = 0; i <= elems.length - 1; i++) {
        if (elems[i] != fieldid) newelems.push(elems[i]);
    }
    $('#deletingfileids').val(newelems.join('|'));

    var link = $(link);
    link.next('.changed').show().find('input').attr('disabled', false);
    link.hide();
    $('#filedeleted').val('true');
    return false;
}

function removeFile(fieldid, link) {
    //Пополняем коллекцию удаляемых файлов новым идентификатором
    var elems = $('#deletingfileids').val() != '' ? ($('#deletingfileids').val()).split('|') : [];
    elems.push(fieldid);
    $('#deletingfileids').val(elems.join('|'));

    var $link = $(link);
    $link.next('a').next('.changed').show().find('input').attr('disabled', false);
    $link.next('a').hide();
    $link.prev('a').hide();
    $link.hide();
    return false;
}
//#endregion