var dlg = null;

String.prototype.replaceAll = function (search, replace) {
    return this.split(search).join(replace);
};

var serviceId = 0;
$(function() { serviceId = parent.$('#id').val(); });

function reloadTable(params, callback) {
    if (!params) params = { nolayout: true, timestamp: new Date().toString() };
    $(tableRootDiv).load(tableUrl(), params, function() {
            if (callback && typeof(callback) === "function") {
                callback();
            }
            initTable();
        }
    );
}

var ServiceUsers = {
    selectUsers: function selectUsers() {
        var url = 'user.ivp/select?cbmode=ServiceUsers&tb_mode=free&tb_isnewserviceuser=true&tb_serviceid=' + serviceId + '';
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = ServiceUsers.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var rids = result["selectedRoles"]
        addSelectedServiceUsers(uids, rids);
    }
}

function addSelectedServiceUsers(uids, roles) {
    var rids = new Array();

    uids.forEach(function (id) {
        rids.push(roles['id' + id]);
    });
    var url = base + 'serviceuser.ivp/addusers';
    $.getJSON(url, { serviceid: serviceId, uids: uids.join(','), nolayout: true, timestamp: new Date().toString() }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alertDialog(CommonResources.Error, result.Description);
        else {
            reloadTable();
        }
    });
    //reloadUsers();
}
function reloadUsers() {
    alert('reloadUsers serviceusers');
    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', top.document).val() });

    var rid = parseInt($('#uf_roleid', top.document).val(), 10);
    var cid = parseInt($('#uf_companyid', top.document).val(), 10);

    params.push({ name: 'fttRoleId', value: rid > 0 ? 1 : 0 }); params.push({ name: 'flt1RoleId', value: $('#uf_roleid', top.document).val() });
    params.push({ name: 'fttUser_CompanyId', value: cid > 0 ? 1 : 0 }); params.push({ name: 'flt1User_CompanyId', value: $('#uf_companyid', top.document).val() });    

    reloadTable(params);

    return false;
}

function changeRole(link) {
    var link = $(link);
    var td = link.parent();
    $('.popupwrapper').hide();
    if (td.find('.popupwrapper').length > 0)
        td.find('.popupwrapper').show();
    else {
        var html = '<div class="popupwrapper"><div class="popup">' + $('#selectroletemplate').html() + '</div></div>';
        td.append(html).find('.popupwrapper').show(); //.css({left:td.position().left + 10, top: td.position().top + 10}).show();
    }
    return false;
}

function changeRoleMass() {    
    if (selectedIds.length == 0) { alert(ServiceResources.NoServiceSelectedRole); return false; }

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

    var table = holder.parents("div.k-grid-content");

    var row = holder.parents("tr");

    $(table).animate({
        scrollTop: $(row).offset().top
    }, 200);

    var link = $("#mbrplaceholder");

    $('.popupwrapper').hide();
    if (holder.find('.popupwrapper').length > 0)
        holder.find('.popupwrapper').show();
    else {
        var html = '<div class="popupwrapper"><div class="popup">' + $('#selectmassroletemplate').html() + '</div></div>';
        link.append(html);
        holder.append(link);
        holder.find('.popupwrapper').show();
    }        

    return false;
}

function hideRoles(link) {
    $(link).parents('.popupwrapper').fadeOut('fast');
    return false;
}

function hideMassRoles() {
    var link = $("#mbrplaceholder");
    $(link).find('.popupwrapper').fadeOut('fast');
    return false;
}

function setRole(link, roleid) {
    var td = $(link).parents('td');
    $(link).parents('.popupwrapper').remove();
    var url = base +'serviceuser.ivp/changerole';
    $.getJSON(url, { roleid: roleid, userid: getId(td.find('a:first').attr('id')), serviceid: serviceId, timestamp: new Date().toString() }, function(result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alertDialog(CommonResources.Error, result.Description);
        else {
            if (result.Result == 'reload')
                reloadTable();
            else {
                td.find('a:first').text($(link).text());
            }
        }
    });
    return false;
}

function selectUserAll() {
    $('#userTable input.rowid').each(function (i, el) { selectRow(el.value, !el.checked && !el.disabled); });
    if ($('#userTable #rowids').checked == false) {
        $('#userTable #rowids').attr('checked', true);
    }
    return false;
}

function setRoleMass(roleid) {     
    hideMassRoles();
    if (selectedIds.length > 0) {
        var url = base + 'serviceuser.ivp/changerolemass';
        $.ajax({
            type: 'POST',
            url: url,
            datatype: "json",
            data: { roleid: roleid, userids: selectedIds.join(","), serviceid: serviceId, timestamp: new Date().toString() },
            success: function (result) {
                if (result.hasOwnProperty('IsOK') && !result.IsOK)
                    alertDialog(CommonResources.Error, result.Description);
                else {
                    reloadTable();
                }
            }
        })
    }
    return false;
}

function block(options) {
    if (selectedIds.length == 0) { alert(ServiceResources.SelectUsersToBlock); return false; }
    if (!confirm(ServiceResources.SureBlockUsers)) return false;

    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toString() };
    if (options != null) $.extend(params, options);

    var url = base + tableController() + 'Block';
    selectedIds.length = 0;
    $(tableRootDiv).load(url, params, initTable);
    return false;
}

function unblock(options) {
    if (selectedIds.length == 0) { alert(ServiceResources.SelectUsersToUnblock); return false; }
    if (!confirm(ServiceResources.SureUnblockUsers)) return false;

    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toString() };
    if (options != null) $.extend(params, options);

    var url = base + tableController() + 'Unblock';
    selectedIds.length = 0;    
    $.getJSON(url, params, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alertDialog(CommonResources.Error, result.Description);
        else {           
            reloadTable();
        }
    });
    //$(tableRootDiv).load(url, params, initTable);
    return false;
}

function deleteUsers(options) {    
    if (selectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }

    var hasCompany = false;
    var hasGroup = false;
    var hasCompanyGroup = false;
    for (var i = 0; i < selectedIds.length; i++) {
        var cb = $('#id' + selectedIds[i]);
        if (cb.parents('tr:first').hasClass('company')) {
            cb.attr('checked', false).parents('tr:first').removeClass('selected');
            selectedIds[i] = -1;
            hasCompany = true;
        }

        if (cb.parents('tr:first').hasClass('companygroup')) {
            cb.attr('checked', false).parents('tr:first').removeClass('selected');
            selectedIds[i] = -1;
            hasCompanyGroup = true;
        }

        if (cb.parents('tr:first').hasClass('group')) {
            cb.attr('checked', false).parents('tr:first').removeClass('selected');
            selectedIds[i] = -1;
            hasGroup = true;
        }
    }
    var partText = '';
    if (hasCompany)
        partText += ServiceResources.UserCompany;
    if (hasGroup) {
        if (partText.length > 0) {
            partText += ', ';
        }
        partText += ServiceResources.UserGroup;
    }
    if (hasCompanyGroup) {
        if (partText.length > 0) {
            partText += ', ';
        }
        partText += ServiceResources.UserCompanyGroup;
    }
    if (hasCompany || hasGroup || hasCompanyGroup) alert(ServiceResources.CantDeleteCompanyUsers.replace('{0}', partText));

    var companyUsers = [];
    var companyGroupUsers = [];
    var groupUsers = [];
    for (var i = 0; i < selectedIds.length; i++) {
        var cb = $('#id' + selectedIds[i]);
        if (cb.parents('tr:first').hasClass('usercompany') || cb.parents('tr:first').hasClass('usercompanydeleted')) {
            companyUsers.push(selectedIds[i]);
        }
        if (cb.parents('tr:first').hasClass('usergroup') || cb.parents('tr:first').hasClass('usergroupdeleted')) {
            groupUsers.push(selectedIds[i]);
        }
        if (cb.parents('tr:first').hasClass('usercompanygroup') || cb.parents('tr:first').hasClass('usercompanygroupdeleted')) {
            companyGroupUsers.push(selectedIds[i]);
        }
    }
    if (companyUsers.length > 0 || companyGroupUsers.length > 0 || groupUsers.length > 0) {
        var userPartText = '';
        if (companyUsers.length > 0)
            userPartText += ServiceResources.UserCompany;
        if (groupUsers.length > 0) {
            if (userPartText.length > 0) {
                userPartText += ', ';
            }
            userPartText += ServiceResources.UserGroup;
        }
        if (companyGroupUsers.length > 0) {
            if (userPartText.length > 0) {
                userPartText += ', ';
            }
            userPartText += ServiceResources.UserCompanyGroup;
        }
        if (!confirm(ServiceResources.SureDeleteCompanyUsers.replaceAll('{0}', userPartText))) {
            if (companyUsers.length > 0) {
                selectedIds.removeItems(companyUsers);
                $(companyUsers).each(function(i, el) { $('#id' + el).attr('checked', false).parents('tr:first').removeClass('selected'); });
            }
            if (companyGroupUsers.length > 0) {
                selectedIds.removeItems(companyGroupUsers);
                $(companyGroupUsers).each(function(i, el) { $('#id' + el).attr('checked', false).parents('tr:first').removeClass('selected'); });
            }
            if (groupUsers.length > 0) {
                selectedIds.removeItems(groupUsers);
                $(groupUsers).each(function(i, el) { $('#id' + el).attr('checked', false).parents('tr:first').removeClass('selected'); });
            }
        }
    }

    selectedIds.removeItems(-1);
    if (!selectedIds || selectedIds.length == 0) return false;
    
    if (!confirm(TableResources.SureDeleteUsers)) return false;

    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toString() };
    if (options != null) $.extend(params, options);

    var url = base + tableController() + 'Delete';
   
    $(tableRootDiv).load(url, params, function () { initTable(); isCurrentUserAddingToService(); });
    
    selectedIds.length = 0;
    return false;
}


window.afterInitTable = function () {
    InitResizableGrid('table.resizable-grid', getHeightTableHolder(250));
};