var userSelectedIds = new Array();
var pass = "";
var dlg = null;
var managerIdCache = undefined;

var strongPassword = 0;

var passwordPolicy = {
    Length: 1,
    Letters: 2,
    Caps: 4,
    Digits: 8,
    Special: 16
}

var ethalonWeight = passwordPolicy.Special | passwordPolicy.Digits | passwordPolicy.Caps | passwordPolicy.Letters | passwordPolicy.Length;

$(function () {
    var q = $('form').data('validator');
    $('.autogrow').elastic();
    if ($('#closeaftersave').val() === 'true' && $('input[name="popup"]').val() === 'true') {
        opener.reloadUsers();
        self.close();
    }

    strongPassword = $('#strongPassword').val();

    $('body').on('change', '#roleid', function () {
        var $self = $(this);
        onRoleChange($self);
    });

    onRoleChange($('#roleid'));

    $('body').on('click', '.opentask', function () {
        var $self = $(this);
        var url = $self.attr('href');
        window.openDialog(url, 'usertasklist', { width: 900, height: 650 });
        return false;
    });

    if ($('#readonly').length > 0) {
        $('input,textarea').attr('readonly', true).addClass('disabled');
        $('select').attr('disabled', true).addClass('disabled');
    }

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

    $('#detectmanagerrule').on('change', detectManagerRuleChanged);

    //на карточке может не быть поля пароль. Например, когда открываем ее с карточки заявки. Тогда возникает ошибка скрипта    
    if ($("#password2").size() > 0) $("#password2").rules("add", { equalTo: "#password" });

    $('#companyid').on('change', function () {
        //если поле "руководитель" наследуется от подразделения
        if ($('#detectmanagerrule').val() == '1') {
            DisplayDepartmentManager();
        }
    });

    $('#choosemanager').autocomplete(base + 'user.ivp/findusers/', { minChars: 1 }).result(managerSelectedFromAutoComplete);

    $('#addDefaultService').autocomplete(base + 'service.ivp/searchidname/', { minChars: 1 }).result(defaultServiceSelectedFromAutoComplete);

    //$('#addCompany').autocomplete(base + 'company.ivp/SearchJson/', { minChars: 1 }).result(companySelectedFromAutoComplete);

    $('#addCompany').devbridgeAutocomplete({
        serviceUrl: base + 'company.ivp/SearchCompanyJson/',
        minChars: 1,
        autoClearInputOnSelect: true,
        autoQueryOnEmptyField: true,
        onSelect: companySelectedFromAutoComplete
    });

    //---------------------    

    $.validator.addMethod("validateCompany", function (value, element) {
        var result = Number($("#companyid").val()) > 0;

        return result;
    })
    if ($("#addCompany").size() > 0) {
        $("#addCompany").rules("add", {
            validateCompany: true,
            messages: {
                validateCompany: FormResources.FieldRequired
            }
        });
    }

    $.validator.addMethod("validatePasswordStrength", function (value, element) {
        var result = validatePasswordStrength($("#password").val());

        return result;
    });

    if (strongPassword == 1 && $("#password").size() > 0) {
        $("#password").rules("add", {
            validatePasswordStrength: true,
            messages: {
                validatePasswordStrength: UserResources.PasswordTooWeak
            }
        });

        $("#password").keyup(function () {
            var weight = getPasswordWeight($("#password").val());

            if (weight & passwordPolicy.Special) {
                $('#special').removeClass('invalid').addClass('valid');
            } else {
                $('#special').removeClass('valid').addClass('invalid');
            }

            if (weight & passwordPolicy.Digits) {
                $('#digits').removeClass('invalid').addClass('valid');
            } else {
                $('#digits').removeClass('valid').addClass('invalid');
            }

            if (weight & passwordPolicy.Caps) {
                $('#caps').removeClass('invalid').addClass('valid');
            } else {
                $('#caps').removeClass('valid').addClass('invalid');
            }

            if (weight & passwordPolicy.Letters) {
                $('#letters').removeClass('invalid').addClass('valid');
            } else {
                $('#letters').removeClass('valid').addClass('invalid');
            }

            if (weight & passwordPolicy.Length) {
                $('#length').removeClass('invalid').addClass('valid');
            } else {
                $('#length').removeClass('valid').addClass('invalid');
            }
        }).focus(function () {
            $('#pswd_info').show();
        }).blur(function () {
            $('#pswd_info').hide();
        });
    }

    $('body')
    .on('keyup', "#newPhone", function (event) {
        if (event.which == 13)
            savePhone();
        else
            checkPhone();
    })
    .on('focus', "#newPhone", function () {
        checkPhone();
    })
    .on('blur', "#newPhone", function () {
        checkPhone();
    })
    .on('click', 'a.deleteDevice', deleteDevice);

    $("form").submit(function (e) {
        if ($('#id').val()=="0") $('#user .save,#user  .saveandreturn').attr("disabled", true);
    });
});

function checkPhone() {
    if ($('#newPhone').size() === 0)
        return;
    var val = $('#newPhone').val();
    $("#phoneError").hide();
    if (!validatePhone(val))
        $("#phoneError").show();

}

function validatePhone(phone) {
    if (phone === null || phone === undefined || phone === "")
        return false;
    var phoneregexp=$('#phoneregexp').val();
    return /(^(8|\+\d{1,3})\d{10}$|^ext\d{1,10}$|^\d{4}$)/.test(phone) || (phoneregexp.length && (new RegExp(phoneregexp).test(phone)));
}

function bindPwEvents() {
    $("#pass").keyup(function () {
        var weight = getPasswordWeight($("#pass").val());

        if (weight & passwordPolicy.Special) {
            $('#pwspecial').removeClass('invalid').addClass('valid');
        } else {
            $('#pwspecial').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Digits) {
            $('#pwdigits').removeClass('invalid').addClass('valid');
        } else {
            $('#pwdigits').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Caps) {
            $('#pwcaps').removeClass('invalid').addClass('valid');
        } else {
            $('#pwcaps').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Letters) {
            $('#pwletters').removeClass('invalid').addClass('valid');
        } else {
            $('#pwletters').removeClass('valid').addClass('invalid');
        }

        if (weight & passwordPolicy.Length) {
            $('#pwlength').removeClass('invalid').addClass('valid');
        } else {
            $('#pwlength').removeClass('valid').addClass('invalid');
        }
    });
}

function getPasswordWeight(password) {
    var weight = 0;

    $.ajax({
        type: 'POST',
        url: base + "login.ivp/getpasswordweightajax",
        data: { password: password },
        async: false,
        dataType: "json",
        success: function (result) {
            weight = ((result.hasOwnProperty('IsOK') && result.IsOK)) ? Number(result.Result) : 0;
        }
    });

    return weight;
}

function validatePasswordStrength(password) {
    var isValid = 0;

    $.ajax({
        type: 'POST',
        url: base + "login.ivp/validatepasswordstrengthajax",
        data: { password: password },
        async: false,
        dataType: "json",
        success: function (result) {
            isValid = ((result.hasOwnProperty('IsOK') && result.IsOK)) ? result.Result == "TRUE" : false;
        }
    });

    return isValid;
}

function onRoleChange($self) {
    var $supportForExternalClients = $('#supportForExternalClients');

    if ($supportForExternalClients.val() === 'True') {
        var roleId = $self.val();

        if (roleId) {
            var $login = $('#login');
            var $loginLabel = $('label[for="login"]');

            var $password = $('#password, #password2');
            var $passwordLable = $('label[for="password"], label[for="password2"]');

            var $email = $('#email');
            var $emailLable = $('label[for="email"]');

            $.getJSON('user.ivp/GetRoleType/' + roleId, function (typeId) {
                if (typeId && typeId == 2) {
                    $login.removeClass('required').addClass('valid');
                    $loginLabel.removeClass('required');

                    $password.removeClass('required').addClass('valid');
                    $passwordLable.removeClass('required');

                    $email.removeClass('required').addClass('valid');
                    $emailLable.removeClass('required');

                    $loginLabel.closest('label.error').remove();
                    $passwordLable.closest('label.error').remove();
                    $emailLable.closest('label.error').remove();
                } else {
                    $login.removeClass('valid').addClass('required');
                    $loginLabel.addClass('required');

                    $password.removeClass('valid').addClass('required');
                    $passwordLable.addClass('required');

                    $email.removeClass('valid').addClass('required');
                    $emailLable.addClass('required');
                }
            });
        }
    }
}

//#region services
function loadServices(reload) {
    if (reload || $.trim($('#services').html()).length == 0) {
        $('.save').attr('disabled', true);
        $('.saveandreturn').attr('disabled', true);
        var params = new Array();
        params.push({ name: 'timestamp', value: new Date().toString() });
        if ($('#popup').length > 0) params.push({ name: 'popup', value: true });
        $('#services').load(base + 'user.ivp/services/' + $('#id').val(), params, function () { setTab('services'); initUserTable("#serviceid"); });
    }
    else setTab('services');

}

function changeRole(pid) {
    $.getJSON(base + 'service.ivp/rolesforservice/' + pid, { date: new Date().toString() }, function (roles) {
        if (roles.hasOwnProperty('IsOK') && !roles.IsOK) {
            alert(roles.Description);
            return;
        }
        $('.selectrole').remove();
        $('.selectrolemass').remove();
        $('#role' + pid).append('<div class="popupwrapper selectrole"><div class="popup"></div></div>');
        var popup = $('.popup', $('#role' + pid));
        var offset = $('#role' + pid).offset();
        popup.css('top', offset.top + 20).css('left', offset.left);
        popup.append('<p>' + UserResources.SetUserRoleOnService + '</p><ul></ul>');
        var ul = popup.children('ul');
        $(roles).each(function (i, role) { ul.append('<li><a class="button" href="#" onclick="return setRole(' + $('#id').val() + ',' + pid + ',' + 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 changeRoleCommon() {
    closeActionPopup();

    if (userSelectedIds.length == 0) { alertDialog(CommonResources.Error, ServiceResources.NoServiceSelectedRole); return false; }

    var selectedServiceIds = [];

    $.each(userSelectedIds, function (id, el) {
        var sId = $("#serviceid" + el.value).parent().find("#serviceid").val();
        selectedServiceIds.push(sId);
    });

    if (selectedServiceIds.length == 0) { alert(ServiceResources.NoServiceSelectedRole); return false; }

    $.post(base + 'service.ivp/rolescommonforservices/', { serviceids: selectedServiceIds, date: new Date().toString() }, function (rolesResult) {
        if (rolesResult.hasOwnProperty('IsOK') && !rolesResult.IsOK) {
            alert(rolesResult.Description);
            return;
        }
        var roles = jQuery.parseJSON(rolesResult);
        $('.selectrole').remove();
        $('.selectrolemass').remove();

        var holder = $("input.rowid.cb:checked").first().parents("tr").children("[id*=role]");

        $(holder).append('<div class="popupwrapper selectrolemass"><div class="popup"></div></div>');
        var popup = $('.popup', $(holder));

        popup.append('<p>' + UserResources.SetUserRoleOnService + '</p><ul></ul>');
        var ul = popup.children('ul');
        $(roles).each(function (i, role) { ul.append('<li><a class="button" href="#" onclick="return setRoleMass(' + $('#id').val() + ',' + 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>');

        var offset = $(holder).offset();
        popup.css('top', offset.top).css('left', offset.left);

        $('.selectrolemass').fadeIn('fast');

        $('html, body').animate({
            scrollTop: $(holder).offset().top
        }, 200);
    });
    return false;
}

function setRole(uid, pid, rid) {
    //$('#services').load(base + 'user.ivp/changerole/', { userid: uid, serviceid: pid, roleid: rid, date: new Date().toString() });
    var url = base + 'user.ivp/changerole/';
    $.getJSON(url, { userid: uid, serviceid: pid, roleid: rid, date: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alertDialog(CommonResources.Error, result.Description);
        else {
            loadServices(true);
        }
    });
    return false;
}

function setRoleMass(uid, rid) {
    $('#changerolemass').hide();
    $('.selectrolemass').remove();

    if (userSelectedIds.length == 0) { alertDialog(CommonResources.Error, ServiceResources.NoServiceSelectedRole); return false; }

    var selectedServiceIds = [];

    $.each(userSelectedIds, function (id, el) {
        var sId = $("#serviceid" + el.value).parent().find("#serviceid").val();
        selectedServiceIds.push(sId);
    });

    //$('#services').load(base + 'user.ivp/changerolemass/', { userid: uid, serviceids: selectedServiceIds, roleid: rid, date: new Date().toString() }, function() {
    //    $('#changerolemass').show();
    //    initUserTable("#serviceid");
    //    recheckUserServices();
    //});
    var url = base + 'user.ivp/changerolemass/';
    $.post(url, { userid: uid, serviceids: selectedServiceIds, roleid: rid, date: new Date().toString() }, function (result) {
        userSelectedIds = new Array();
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            //alert(result.Description);
            alertDialog(CommonResources.Error, result.Description);
            loadServices(true);
            $('#changerolemass').show();
        }
        else {
            loadServices(true);
            $('#changerolemass').show();
        }
    }, 'json');
    return false;
}
function recheckUserServices() {
    if (userSelectedIds.length == 0)
        return;
    $.each(userSelectedIds, function (id, el) {
        selectUserRow(undefined, "#serviceid", el.value, !el.checked && !el.disabled);
    });
}

function delService(id) {
    if (!confirm('Вы уверены, что хотите удалить пользователя с выбранного сервиса?')) return false;

    $.getJSON(base + 'serviceuser.ivp/delete', { id: id, json: true }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else
            $('#tr' + id).fadeOut('fast').remove();
        $('#availableservices').hide(); $('#addservices').show();
    });
    return false;
}

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

var UserDefaultService = {
    selectDefaultService: function selectDefaultService() {
        dlg = openDialog('service.ivp/selectlist?cbmode=UserDefaultService');
        dlg.callback = UserDefaultService.servicesCallback;
        return false;
    },
    servicesCallback: function servicesCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        defaultServiceSelected(ids, names);
    }
}

function addSelectedServices(serviceids) {
    var selected = new Array();
    $('#selectservices input:checked').each(function (i, el) { selected.push(el.value); });
    //$('#services').load(base + 'user.ivp/addselectedservices', { userid: $('#id').val(), serviceids: serviceids }, function () { $('#selectservices').hide(); $('#addservices').show(); initUserTable("#serviceid"), function () { date: new Date().toString() }, function () { $('#availableservices').fadeIn('fast'); }; });
    var url = base + 'user.ivp/addselectedservices';
    $.post(url, { userid: $('#id').val(), serviceids: serviceids }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alertDialog(CommonResources.Error, result.Description);
        else {
            loadServices(true);
        }
    });
    return false;
}

function selectUserAll(check) {
    var tableid = $(check).closest('table').attr('id') || 'body';
    if (tableid)
        tableid = '#' + tableid + ' ';
    var idcol;
    switch (tableid) {
        case '#servicetable ':
            idcol = "#serviceid";
            break;
        case '#ownertable ':
            idcol = "#assetid";
            break;
        case '#linktable ':
            idcol = "#assetid";
            break;
        default:
            idcol = "#id";
            break;
    }
    $(tableid + '.rowid.cb').each(function (i, el) { selectUserRow(tableid, idcol, el.value, !el.checked && !el.disabled); });
    if ($(tableid + '#rowids').checked == false) {
        $(tableid + '#rowids').attr('checked', true);
    }
    return false;
}

function selectUserRow(table, idcol, val, check, skip) {
    table = table || '';
    if (table)
        table = table + ' ';
    var cb = $(table + idcol + 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) { }
}

function delUserService() {
    if (userSelectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(TableResources.SureDeleteRecords)) return false;
    var ids = new Array();
    $(userSelectedIds).each(function () { if (this.name == 'servicetable' && $.inArray(this.value, ids) === -1) ids.push(this.value); });
    var params = { serviceid: ids.join(','), userid: $('#id').val(), nolayout: true, timestamp: new Date().toString() };
    userSelectedIds.length = 0;
    var url = base + 'user.ivp/DeleteServices';
    $('#services').load(url, params, function () { setTab('services'); initUserTable("#serviceid"); });
    //$.ajax({ url: url, type: "POST", data: params, success: function() { loadServices(true); } });
    var arr = params.serviceid.split(',');
    for (var i = 0, len = arr.length; i < len; i++) {
        var arrsub = arr[i].substring(1, 0);
        if (arrsub == 0) {
            alert(UserResources.CanNotDeleteService);
            break;
        }
    }
    return false;
}

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

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

        selectUserRow(undefined, idcol, this.value, this.checked);
    });
}
//#endregion

function openPhoneForm() {
    $('#phoneHolder').hide();
    $('#phoneEditor').fadeIn(300, function () {
        $('#phoneEditor').focus();
    });
    $('#description').fadeIn(300);
    return false;
}

function loadPhones(reload) {
    DisableSaveButtons();
    if (reload || !$.trim($('#phones').html())) {
        $('#phones').load(base + 'user.ivp/Phones/' + $('#id').val(), { popup: $('#popup').val(), readonly: $('#readonly').val(), readonlyform: $('#readonlyform').val() }, function () { setTab('phones'); c2c("#phones"); });
        return false;
    }
    setTab('phones');
    return false;
}

function savePhone() {
    var val = $('#newPhone').val().replace(/[\(\)-]/gmi,"");
    var userid = $('#id').val();
    var phoneid = $('#phoneId').val();
    if (!validatePhone(val))
        return false;
    var params = new Array();
    params.push(
        { name: 'userid', value: userid },
        { name: 'phoneid', value: phoneid },
        { name: 'phonenumber', value: val }
    );

    $.post(base + 'user.ivp/SavePhone/', params, function (result) {
        var res = JSON.parse(result);
        if (res.hasOwnProperty("IsOK") && res.IsOK === false) {
            $("#phoneErrorContainer").html(res.Description);
            $("#phoneErrorContainer").show();
            return false;
        }
        loadPhones(true);
    })
    return false;
}

function editPhone(p) {
    var row = $(p).parents("tr");
    var cols = row.children("td");
    //Очищаем форму во избежание..
    $('#newPhone').val("");
    $('#phoneId').val("");

    openPhoneForm();
    var col1 = $(cols[1]).clone();
    $(col1).find("div").remove();
    $("#phoneId").val($(cols[0]).text().trim());
    $("#newPhone").val($(col1).text().trim().replace(/[\(\)-]/gmi,""));
    $("#newPhone").focus();
    return false;
}

function deletePhone(p) {
    if (!confirm(TableResources.SureDeleteRecords)) return false;
    var row = $(p).parents("tr");
    var cols = row.children("td");

    var userid = $('#id').val();
    var phoneid = $(cols[0]).text().trim();

    var params = new Array();
    params.push(
        { name: 'userid', value: userid },
        { name: 'phoneid', value: phoneid }
    );

    $.post(base + 'user.ivp/DeletePhone/', params, function (result) {
        var res = JSON.parse(result);
        if (res.hasOwnProperty("IsOK") && res.IsOK === false) {
            $("#phoneErrorContainer").html(res.Description);
            $("#phoneErrorContainer").show();
            return false;
        }
        loadPhones(true);
    })
    if (phoneid === $('#mainphoneid').val()) {
        $('#mainphoneid').val("");
        $('#phone').val("");
        $('#mainPhoneInput').hide();
        $('#mainPhoneNotSet').show();
    }

    if (phoneid === $('#mobilephoneid').val()) {
        $('#mobilephoneid').val("");
        $('#mobilePhone').val("");
        $('#mobilePhoneInput').hide();
        $('#mobilePhoneNotSet').show();
    }

    return false;
}

function cancelEditPhone() {
    $('#newPhone').val("");
    $('#phoneId').val("");

    $('#phoneEditor').fadeOut(100, function () {
        $('#phoneHolder').fadeIn();
    });
    $('#description').fadeOut(300);
    return false;
}

function setMainPhone(p) {
    var row = $(p).parents("tr");
    var cols = row.children("td");
    var phoneid = $(cols[0]).text().trim();
    var userid = $('#id').val();

    c2c("#mainPhoneInput");

    var params = new Array();
    params.push(
        { name: 'userid', value: userid },
        { name: 'phoneid', value: phoneid }
    );

    $.post(base + 'user.ivp/SetMainPhone/', params, function (result) {
        var res = JSON.parse(result);
        if (res.hasOwnProperty("IsOK") && res.IsOK === false) {
            $("#phoneErrorContainer").html(res.Description);
            $("#phoneErrorContainer").show();
            return false;
        }
        loadPhones(true);

        $('#mainphoneid').val(res.Id);
        $('#phone').val(res.Result);
        $('#mainPhoneInput').text(res.Result);

        $('#mainPhoneNotSet').hide();
        $('#mainPhoneInput').show();
    })

    return false;
}

function setMobilePhone(p) {
    var row = $(p).parents("tr");
    var cols = row.children("td");
    var phoneid = $(cols[0]).text().trim();
    var userid = $('#id').val();

    c2c("#mobilePhoneInput");

    var params = new Array();
    params.push(
        { name: 'userid', value: userid },
        { name: 'phoneid', value: phoneid }
    );

    $.post(base + 'user.ivp/SetMobilePhone/', params, function (result) {
        var res = JSON.parse(result);
        if (res.hasOwnProperty("IsOK") && res.IsOK === false) {
            $("#phoneErrorContainer").html(res.Description);
            $("#phoneErrorContainer").show();
            return false;
        }
        loadPhones(true);
        $('#mobilephoneid').val(res.Id);
        $('#mobilePhone').val(res.Result);
        $('#mobilePhoneInput').text(res.Result);
        $('#mobilePhoneNotSet').hide();
        $('#mobilePhoneInput').show();
    })

    return false;
}

//#region assets
function loadAssets(reload) {
    DisableSaveButtons();
    if (reload || !$.trim($('#assets').html())) {
        $('#assets').load(base + 'user.ivp/LoadAssets/' + $('#id').val(), { popup: $('#popup').val(), readonly: $('#readonly').val() }, function () { setTab('assets'); initUserTable("#assetid"); initCluetip(); $('#assetfilters').empty(); });
        return false;
    }
    setTab('assets');
    return false;
}

function ownerSelected(ids) {
    $.post(base + 'user.ivp/setOwner/', { assetids: ids.join(','), userid: $('#id').val() }, function () { if ($('#fullassetview').length == 0) { loadAssets(true); } else loadFullAssetsOwner(); });
}

function delOwner() {
    if (userSelectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(TableResources.SureDeleteRecords)) return false;
    var ids = new Array();
    $(userSelectedIds).each(function () { if (this.name == 'ownertable' && $.inArray(this.value, ids) === -1) ids.push(this.value); });
    userSelectedIds.length = 0;
    $.post(base + 'user.ivp/deleteOwner/', { assetids: ids, userid: $('#id').val() }, function () { if ($('#fullassetview').length == 0) { loadAssets(true); } else loadFullAssetsOwner(); });
    return false;
}

function removeAssetLink() {
    if (userSelectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(TableResources.SureDeleteRecords)) return false;
    var ids = new Array();
    $(userSelectedIds).each(function () { if (this.name == 'linktable' && $.inArray(this.value, ids) === -1) ids.push(this.value); });
    userSelectedIds.length = 0;
    $.post(base + 'user.ivp/deleteLinks/', { assetids: ids, userid: $('#id').val() }, function () {
        if ($('#fulllinkview').length == 0) {
            loadAssets(true);
            initCluetip();
        } else loadFullLinkTable();
    });
    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();//!!!1
    $popupwrapper.load(base + 'assetlink.ivp/createfromform', { typeid: 2, linkassetid: $('#id').val(), linkid: linkid, from: 'user' }, 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 ($('#fulllinkview').length == 0) { loadAssets(true); initCluetip(); } else loadFullLinkTable(); });
        $('#assetlinkform').remove();
    }
    return false;
}

function initCluetip() {
    $('img.link').cluetip({
        arrows: true,
        dropShadow: false,
        cluetipClass: 'jtipnew',
        showTitle: false
    });
    $('span.assetlink').cluetip({
        arrows: false,
        dropShadow: false,
        cluetipClass: 'jtipnew',
        showTitle: 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;
}
//#endregion

function loadExecutorGroups(reload) {
    DisableSaveButtons();
    if (reload || !$.trim($('#executorgroups').html())) {
        $('#executorgroups').load(base + 'user.ivp/LoadExecutorGroups/' + $('#id').val(), {
            popup: $('#popup').val()
        }, function () { setTab('executorgroups'); });
        return false;
    }
    setTab('executorgroups');
    return false;
}

//#region shedule
function getCreateScheduleForm() {
    closeCreateScheduleForm();
    closeActionPopup();
    var userId = $('#id').val();

    var url = base + 'user.ivp/GetCreateScheduleForm';

    $.get(url, { userid: userId }, function (data) {
        $('body').append('<div id="createscheduleform"></div>');
        var $createScheduleForm = $('#createscheduleform');

        $createScheduleForm.dialog({
            autoOpen: false,
            width: 'auto',
            height: 'auto',
            minHeight: 135,
            minWidth: 510,
            modal: true,
            resizable: true,
            title: CommonResources.ChooseAction,
            close: closeCreateScheduleForm
        });
        $createScheduleForm.html(data).show().dialog("open");
    });
    return false;
}

function closeCreateScheduleForm() {
    $('#createscheduleform').remove();
    return false;
}

function confirmCreateSchedule() {
    var userid = $('#id').val();
    var createNewSchedule = $('input[name="createNewSchedule"]:checked').val();
    if (createNewSchedule === "True") {
        createSchedule(userid);
    } else {
        var copyFromScheduleId = $('#copyFromScheduleId').val();
        if (parseInt(copyFromScheduleId, 10) > 0) {
            createSchedule(userid, copyFromScheduleId);
        }
    }
    return false;
}

function createSchedule(userid, copyFromScheduleId) {
    var $schedule = $('#userschedule');
    var params = new Array();
    params.push({ name: 'userid', value: userid });
    if (copyFromScheduleId) {
        params.push({ name: 'copyFromScheduleId', value: copyFromScheduleId });
    }
    var url = base + 'user.ivp/CreateSchedule';

    $.get(url, params, function (data) {
        $schedule.html(data);
        closeCreateScheduleForm();
        closeActionPopup();
        $('#addschedule').hide();
        $('#auserschedule').closest('li').show();
        $('#removeschedule').show();
        resize();
        setTab('userschedule');
    });
}

function removeSchedule() {
    if (!confirm(ScheduleResources.SureDelete)) {
        closeActionPopup();
        return false;
    }
    var $schedule = $('#userschedule');
    var url = base + 'user.ivp/RemoveSchedule';
    var userid = $('#id').val();
    var params = new Array();
    params.push({ name: 'userid', value: userid });
    $.post(url, params, function () {
        $schedule.empty();
        setTab('general');
        closeActionPopup();
        $('#removeschedule').hide();
        $('#auserschedule').closest('li').hide();
        $('#addschedule').show();
    });
    return false;
}

function switchCreateScheduleFields(type) {
    if (type === 'new') {
        $('#copyFromScheduleId').attr('disabled', true);
    } else {
        $('#copyFromScheduleId').removeAttr('disabled');
    }
}

function loadSchedule(userid) {
    var $schedule = $('#userschedule');

    //Отобразим расписание если оно уже было загружено
    if ($schedule.find('#schedule').length > 0) {
        setTab('userschedule');
        return false;
    }

    var url = base + 'schedule.ivp/UserSchedule/' + userid;

    $.get(url, function (data) {
        $schedule.html(data);
        if ($('#readonlyform').length > 0) {
            $('#confirmationstatus').remove();
            $('#userschedule .warning').remove();
        }
        $('#addschedule').hide();
        $('#removeschedule').show();
        resize();
        setTab('userschedule');
    });
}


//#endregion

//#region subscriptions

function showSubscriptions(userId) {
    var url = 'filternotification.ivp/list?tb_mode=user&tb_userid=' + userId;
    dlg = window.openDialog(url, 'subscriptions', { width: 900, height: 650 });
    return false;
}
//#endregion

//#region common handlers
function expandTextArea(id) {
    var rows = $(id).attr('rows');
    var labelName;
    //var labelName = $(id + 'expand').html();
    if (rows == 24) {
        rows = 40;
        labelName = NotificationTemplateResources.Collapse;
    }
    else {
        rows = 24;
        labelName = NotificationTemplateResources.Expand;
    }
    $(id).attr('rows', rows);
    $(id + 'expand').html(labelName);
    $('#loadingusercard').height($(document).height());
    return false;
}

//в IE некорректно отрабатывает селектор ".is(':hidden')", поэтому будем оперировать классами
function showHideCustomFields() {
    if ($('#attributes').hasClass('hidden')) {
        $('#attributes').removeClass('hidden');
        $('#showcustomfields').text('↑ ' + FilterResources.HideAdditionalFields);
    } else {
        $('#attributes').addClass('hidden');
        $('#showcustomfields').text("↓ " + FilterResources.ShowAdditionalFields);
    }
}

function setTab(id) {
    $('#actionholder').hide();
    if (!documentReady) return;
    $('.tab').each(function (i, el) { if (el.id == id) $(el).show(); else $(el).hide(); });
    $('#tabs>ul>li>a').each(function (i, el) { if (el.id == 'a' + id) $(el).addClass('selected'); else $(el).removeClass('selected'); });
    if (id == 'services') {
        $('#projectmenu').show();
        $('#changerolemass').show();
    }
    else {
        $('#projectmenu').hide();
        $('#changerolemass').hide();
    }
    if (id === 'services' || id === 'assets' || id === 'userschedule' || id === 'phones') {
        $('.save').attr('disabled', true);
        $('.saveandreturn').attr('disabled', true);
        $('.formbottom .warning').show();
    }
    else {
        $('.save').attr('disabled', false);
        $('.saveandreturn').attr('disabled', false);
        $('.formbottom .warning').hide();
    }
}

function expandGroupElement(link) {
    var $link = $(link);
    var targetId = $link.attr('data-target');
    $('#' + targetId).toggle();
    var $img = $(link).find('img');
    if ($img.attr('src') == 'img/tree/minus.gif')
        $img.attr('src', 'img/tree/plus.gif');
    else
        $img.attr('src', 'img/tree/minus.gif');

    return false;
}
//#endregion

//#region field handlers

function changeFile(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 enableGuid() {
    var $guid = $('#guid');
    var $input = $('<input type="text"/>').addClass('px300').attr('name', 'ADGuid').val($.trim($guid.text()));
    $('#guidholder').append($input);
    $guid.remove();
    return false;
}

function EmailToLogin() {
    if ($('#login').size() != 0 && ($('#login').val().length == 0) && ($('#email').val().length != 0))
        $('#login').val($('#email').val());
}

function removeFile(fieldid, link) {
    //if (!confirm(CommonResources.SureDeleteFile)) return false;

    //$('#filedeleted').val('true');
    //Пополняем коллекцию удаляемых файлов новым идентификатором
    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;
}

function DisplayDepartmentManager() {
    $('#manageractions').hide();
    $('#managername').empty().show();
    $('#displayname').show();
    if ($.trim($('#companyid').val()) == '') return false;
    var url = base + 'company.ivp/getmanagerid/';
    $.getJSON(url, { companyId: $('#companyid').val() }, function (result) {
        //$('#managername').append(result);
        //return false;
        if (result) {
            getManagerLinkRequest(result.managerId).done(function () {

            });
        }
    });
    return false;
}

function detectManagerRuleChanged() {

    var $li = $('#managername').closest('li');
    $li.removeClass('archive').addClass('changed');
    $('#choosemanager').val('');
    var managerid = parseInt($('#managerid').val(), 10) || managerIdCache;
    switch ($('#detectmanagerrule').val()) {
        //not set
        case '0':
            {
                $('#selectmanager').hide();
                $('#displayname').hide();
                $('#manageractions').hide();
                break;
            }
            //inherit from department
        case '1':
            {
                $('#selectmanager').hide();
                $('#manageractions').hide();
                DisplayDepartmentManager();
                break;
            }
            //synchronize with AD
        case '2':
            {
                $('#changemanager').hide();
                $('#selectmanager').hide();
                $('#manageractions').hide();
                $('#managername').show();
                $('#displayname').show();
                if (managerid && managerid > 0 && $('#managerid').val()) {
                    getManagerLinkRequest(managerid);
                } else {
                    $('#managername').empty();
                    $('#managerid').empty();
                }
                break;
            }
            //manually set
        case '3':
            {
                if (managerid && managerid > 0) {
                    getManagerLinkRequest(managerid).done(function (result) {
                        if (result) {
                            if (!$('#managerid').val()) {
                                $li.addClass('archive');
                            }
                            changeManager();
                            $('#manageractions').show();
                        }
                    });
                } else {
                    changeManager();
                    $('#displayname').hide();
                }
                break;
            }
    }
    return false;
}

function managerSelectedFromAutoComplete(e, d) {
    updateManager(d[1], d[0]);
    return false;
}

function managerSelectedFromPopup(ids, names) {
    var id = ids[0];
    var name = names['id' + id];
    updateManager(id, $.trim(name));
    return false;
}

var managerLinkTemplate = '<a href="user.ivp/viewhash/{0}" class="nounderline" onclick="return userDetails(\'{1}\');">{2}</a>';
//возвращает запрос на получение имени и хеша юзера
//и сразу же обновляем элемент на форме
function getManagerLinkRequest(id) {
    return $.getJSON(base + 'user.ivp/GetUserLinkData', { userid: id, date: new Date().toString() }, function (result) {
        if (result) {
            if (result.noset) {
                $('#managername').html(result.name);
            }
            else {
                $('#managername').html(managerLinkTemplate.replace('{0}', result.viewhash).replace('{1}', result.viewhash).replace('{2}', result.name));
            }
        }

    });
}

function updateManager(id, name) {
    if ($.trim($('#id').val()) == $.trim(id)) {
        alert('вы не можете выбрать себя руководителем');
        return false;
    }
    var $li = $('#managername').closest('li');
    $('#selectmanager').hide();
    $('#managerid').val(id);
    //$('#managername').empty().append(name).show();
    getManagerLinkRequest(id).done(function () {
        $('#manageractions').show();
        $li.removeClass('archive').addClass("changed");
        $('#displayname').show();
    });
    return false;
}

function changeManager(del) {
    $('#choosemanager').val('');
    var $li = $('#managername').closest('li');
    $li.addClass('changed');
    if (!del) {
        $('#selectmanager').toggle();
        return false;
    }
    if ($('#managerid').val() === '') {
        $('#managerid').val(managerIdCache);
        $li.removeClass('archive');
        $('#selectmanager').hide();
    } else {
        managerIdCache = parseInt($('#managerid').val(), 10);
        $('#managerid').val('');
        $li.addClass('archive');
        $('#selectmanager').show();
    }
    return false;
}


//#endregion

//#region actionpopup

function showActionPopup() {
    $('#actionholder').toggle();
    return false;
}

function closeActionPopup() {
    $('#actionholder').hide();
}

//#region отправка карточки пользователя и изменение пароля
function getUserCard(userid) {
    closeActionPopup();
    if ($('#pwhash').length == 1) {
        processUserCardRequest(userid, $('#pwhash').val());
        return false;
    }
    if ($("#password").is(":visible")) {
        jAlert(UserResources.MustSaveUserCard, CommonResources.Warning);
        return false;
    } else {
        $.ajax({
            url: base + 'user.ivp/getusercardform/',
            data: { userid: userid },
            success: function (data, textStatus, jqXHR) {
                createModalDialog(UserResources.EnterNewPassword, data, function () { return tryProcessUserCardRequest(userid); }, dialogInit, true);
            }
        });
        return false;
    }
    return false;
}

function dialogInit() {
    $('#pass').focus();

    if (strongPassword == 1) {
        bindPwEvents();
    }
}

function tryProcessUserCardRequest(userid) {
    var pass = $("#pass").val();

    var needToProcess = true;

    if (strongPassword == 1) {
        var isValid = validatePasswordStrength(pass);

        if (!isValid) {
            needToProcess = false;
        }
    }

    if (needToProcess) {
        processUserCardRequest(userid, null, pass);
    } else {
        return false;
    }

    return true;
}

function closeUserCarRequestDialog() {
    $('#userCardPassDialog').dialog('close');
}

function processUserCardRequest(userid, pwhash, pass) {
    $('body').append('<div id="loadingusercard" class="loadingdiv" style="height:100%;"><div id="loadingtext" class="loadingtext">' + MeetingResources.Loading + '</div></div>');
    $('#loadingusercard').height($(document).height());
    var url = base + 'user.ivp/getusercard/' + userid;
    var params;
    if (pwhash) {
        params = { id: userid, pwhash: pwhash, timestamp: new Date().toString() };
    } else {
        params = { id: userid, password: pass, timestamp: new Date().toString() };
    }

    $('body').append('<div id="usercardform" class="popupdiv"></div>').find('#usercardform').load(url, params, function () {
        $('#loadingtext').hide();
        $('#usercardform').show();
        var divheight = $('#usercardform').height() + 50;
        var offsettop = $('div.formbottom').offset().top;

        $('#usercardform').css("top", Math.max(0, (($(window).height() - $('#usercardform').outerHeight()) / 2) +
                                            $(window).scrollTop()) + "px");

        if (Number($("#hasErrors").val()) == 1) {
            $('#usercardform').css('left', '35%').css('width', '20%')
        } else {
            $('#usercardform').css('left', '5%').css('width', '80%')
        }
    });
    return false;
}

function sendUserCard() {
    //if (!$('#usercardform').valid()) return false;
    $.post(base + 'user.ivp/sendusercard', { Recipient: $('#recipient').val(), Subject: $('#subject').val(), Body: $('#message').val() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else
            alert(result.Description);
        closecardpreview();
    }, 'json');
    return false;
}

function closecardpreview() {
    $('#loadingusercard').remove();
    $('#usercardform').remove();
}

//обработчик изменения поля pass
function passChanged() {
    if ($('#pass').val().length > 0) {
        $('#popup_ok').removeAttr("disabled");
    } else {
        $('#popup_ok').attr("disabled", "disabled");
    }
}
//#endregion

//#endregion

function loadTaskList(reload) {
    if (reload || !$.trim($('#tasklist').html())) {
        $('#tasklist').load(base + 'user.ivp/GetTaskList/' + $('#id').val(), { popup: $('#popup').val(), readonly: $('#readonly').val() }, function () {
            setTab('tasklist');
        });
        return false;
    }
    setTab('tasklist');
    return false;
}

function loadAssetList(reload) {
    if (reload || !$.trim($('#assets').html())) {
        $('#assets').load(base + 'user.ivp/LoadAssets/' + $('#id').val(), { popup: $('#popup').val(), readonly: true }, function () {
            setTab('assets');
            initUserTable("#assetid");
            initCluetip();
        });
        return false;
    }
    setTab('assets');
    return false;
}

function unblockUser() {
    var url = base + 'user.ivp/Unblock';
    var userid = $('#id').val();
    var params = new Array();
    params.push({ name: 'id', value: userid });
    $.post(url, params, function () {
        setTab('general');
        $('#blockHolder').empty();
        closeActionPopup();
    });
    return false;
}

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

function _defaultServiceSelected(id, name, canRemove) {
    removeDefaultService(true);
    $('#defaultserviceid').val(id).attr('changed', true);
    var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', 'service.ivp/view/' + id).click(function () { return defaultServiceDetails(id); });
    var $ar = $('<a href="#"/>').click(function () { return removeDefaultService(false); });
    $ar.append($('<img/>').attr('src', 'img/trash.gif').attr('title', CommonResources.Remove));
    $('#defaultserviceholder').append($ag);

    if (canRemove) {
        $('#defaultserviceholder').append($ar);
    }

    if (canRemove === undefined)
        $('#defaultserviceholder').append($ar);


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

function removeDefaultService(notext) {
    $('#defaultserviceid').attr('changed', true).val('');
    $('#defaultserviceholder').empty();
    if (notext == false) {
        var $nogroup = $('<div/>').addClass('details').attr('id', 'nodefaultservice').text(CommonResources.NotSet);
        $('#defaultserviceholder').append($nogroup);
    }
    return false;
}

function defaultServiceSelectedFromAutoComplete(e, d) {
    _defaultServiceSelected(d[1], d[0], $('#readonly').length > 0);
    $('#addDefaultService').val('');
    return false;
}

function deleteDevice() {
    if (!confirm(UserResources.DeleteDeviceSure)) return false;
    var id = $(this).attr('data-id');
    $.getJSON(base + 'user.ivp/deletedevice', { id: id, json: true }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else
            $('tr#userdevice' + id).fadeOut('fast').remove();
    });
    return false;
}

var User = {
    selectCompany: function selectCompany() {
        dlg = openDialog('company.ivp/selectlist?cbmode=User');
        dlg.callback = User.companiesCallback;
        return false;
    },
    companiesCallback: function companiesCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        userCompanySelected(ids, names);
    },

    addAssetOwner: function addAssetOwner() {
        var url = 'assettable.ivp/select?cbmode=User&tb_select_mode=owner&tb_userid=' + $('#id').val();
        dlg = openDialog(url, 'owner', { width: 980, height: 650 });
        dlg.callback = User.assetsCallback;
        return false;
    },
    assetsCallback: function assetsCallback(result) {
        var ids = result["selectedIds"];
        ownerSelected(ids);
    },

    selectManager: function selectManager() {
        var url = 'user.ivp/select?cbmode=User&tb_mode=ALLUSERS&selectmode=SINGLE';
        dlg = openDialog(url, 'selectmanager', { width: 900, height: 650 });
        dlg.callback = User.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        managerSelectedFromPopup(ids, names);
    }
}

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

function _companySelected(id, name, canRemove) {
    removeCompany();
    $('#companyid').val(id).attr('changed', true);
    var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', '#').click(function () { return companyDetails(id); });
    $('#companyholder').append($ag);

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

function removeCompany() {
    $('#companyid').attr('changed', true).val('');
    $('#companyholder').empty();

    return false;
}

function companySelectedFromAutoComplete(d) {
    _companySelected(d.id, d.value, $('#readonly').length > 0);
    $('#addCompany').val('');
    $('#addCompany').focusout();

    return false;
}

function companyDetails(id) {
    window.open(base + 'company.ivp/view/' + id);
    return false;
}

function serviceDetails(id) {
    window.open(base + 'service.ivp/view/' + id);
    return false;
}

function getMobileAppEmailForm(userId, platform) {
    $('body').append('<div id="loadingmobileappform" class="loadingdiv" style="height:100%;"><div id="loadingtext" class="loadingtext">' + MeetingResources.Loading + '</div></div>');
    $('#loadingmobileappform').height($(document).height());
    var url = base + 'user.ivp/getMobileAppEmailForm';
    var params = {
        userid: userId,
        platform: platform
    };

    $('body').append('<div id="mobileappform" class="popupdiv"></div>').find('#mobileappform').load(url, params, function () {
        $('#loadingtext').hide();
        $('#mobileappform').show();
        var divheight = $('#mobileappform').height() + 50;
        var offsettop = $('div.formbottom').offset().top;

        $('#mobileappform').css("top", Math.max(0, (($(window).height() - $('#mobileappform').outerHeight()) / 2) +
                                            $(window).scrollTop()) + "px");

        $('#mobileappform').css('left', '5%').css('width', '80%');
    });
    return false;
}

function sendMobileAppEmailForm() {
    $.post(base + 'user.ivp/SendMobileAppEmailForm', { Recipient: $('#recipient').val(), Subject: $('#subject').val(), Body: $('#message').val() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else
            alert(result.Description);
        closeMobileAppEmailForm();
    }, 'json');
    return false;
}

function closeMobileAppEmailForm() {
    $('#loadingmobileappform').remove();
    $('#mobileappform').remove();
}
