var roleIds = new Array();
var companyNames = new Array();
var positionNames = new Array();
var Emails = new Array();

$(function () {
    $('input.rowid').on("click", function () {
        var cb = this;
        rowCheckedUser($(cb).val(), cb.checked);
    });

    $('.selectall').unbind('click');
    $('.selectall').click(function () { selectAllUser('.rowid'); });

    if ($('#mode').size() > 0 && $('#mode').val() == 'KBFOLDER')
        $("#wrapper").css("min-width", "1048px");
});

window.afterInitTable = function () {
    InitResizableGrid('table.resizable-grid', getHeightTableHolder(95));
}
//opera 11.11 fail :(
/* Array.prototype.lastIndexOf = function(n, f) {
     for (var l = this.length, j = ~ ~f, i = (1 in arguments && j <= l) ? j < 0 ? j + l : j : l - 1; i > -1; i--) {
        if (i in this && this[i] === n) {
            return i;
        }
    }  
    return -1;
}  */
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
 Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/)
   {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = len;
    if (arguments.length > 1)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    var k = n >= 0
          ? Math.min(n, len - 1)
          : len - Math.abs(n);

    for (; k >= 0; k--)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
 
Array.prototype.filter = function(fn, obj) {
    for (var l = this.length, i = 0, a = []; i < l; i++) {
        fn.apply(obj, [this[i], i, this]) && a.push(this[i]);
    }
    return a;
}


Array.prototype.unique = function() {
    return this.filter(function(e, i, a) {
        return a.lastIndexOf(e) == i;
    });
}

function addSelectedUsers(id) {
    if (id) { selectedIds.length = 0; selectedIds.push(id); rowChecked(id, true); rowCheckedUser(id, true); }
	if (selectedIds.length == 0) { alert(UserResources.NoUsersSelected); return false; }	

    //var uids = selectedIds.join(',');
    //var rids = roleids.join(',');
    //var pid = $('#permissionid').length > 0 ? $('#permissionid').val() : 0;

	var result = new Array();
	result["selectedIds"] = selectedIds;
	result["selectedNames"] = selectedNames;
	result["selectedPaths"] = selectedPaths;
	result["selectedRoles"] = roleIds;
	result["selectedCompanies"] = companyNames;
	result["selectedPositions"] = positionNames;
	result["selectedEmails"] = Emails;	

    if (getURLParameter('msName') != null && getURLParameter('msName') != '') {
        result["msName"]= getURLParameter('msName');
    }

	if ($('#permissionid').length > 0)
	    result["permissionId"] = $('#permissionid').val();

	if (self.callback == null) {
	    if (getURLParameter('cbmode') != null && getURLParameter('cbmode') != '') {
	        eval('opener.' + getURLParameter('cbmode') + '.usersCallback(result)');
	    } else {
	        self.callback = opener.usersCallback;
	        self.callback(result);
	    }
	} else {
	    self.callback(result);
	}

	self.close();
    return false;
}

function changeRole(link) {
    var link = $(link);
    var td = link.parent();
    var html = '<div class="popupwrapper"><div class="popup">' + $('#selectroletemplate').html() + '</div></div>';
    td.append(html).find('.popupwrapper').show();
    selectRow(getId(link.attr('id')),true);
    return false;
}

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

function setRole(link, roleid) {
    var td = $(link).parents('td');
    $(link).parents('.popupwrapper').remove();
    var url = base + 'serviceuser.ivp/changerole';
    td.find('a:first').text($(link).text());
    td.find('input').val(roleid);
    td.addClass('changed');

    var id = td.find('a:first').attr('id').split('_')[1];
    roleIds['id'+id] = roleid;
    
    return false;
}

function rowCheckedUser(id, check) {
    rowChecked(id, check);
    if ($('#id' + id).length > 0) {        
        companyNames['id' + id] = $('#id' + id).attr('companyname');
        positionNames['id' + id] = $('#id' + id).attr('positionname');
        Emails['id' + id] = $('#id' + id).attr('email');
        roleIds['id'+id] = $('#id' + id).attr('roleid');
    }
}

//для выбора исполнителей на заявке
function showUserSchedule(userId, isAvailable) {
    if (isAvailable != "") {
        var url = 'schedule.ivp/showUserSchedule/' + userId;
        dlg = openDialog(url, 'showSchedule', { width: 900, height: 650 });
    }
    return false;
}


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

function hidePermission(link) {
    $(link).parents('.popupwrapper').hide();
    return false;
}

function setPermission(link, permissionid) {
    var parent = $(link).parents('h1');
    $(link).parents('.popupwrapper').remove();	
	$('#permissionid').val(permissionid);	
	parent.find('a#kbpermissionlink:first').text($(link).text());
    return false;
}

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

function selectRow(val, check, skip, idcol) {
    var cb = idcol ? idcol + val : $((document.getElementsByName('_id').length > 0) ? "#_id" + val : "#id" + val).get(0);
    //разрешено выбрать только одного пользователя
    if ($('#mode').val() == 'CREATORS' || $('#mode').val() == 'SUBSCRIBE' || $('#mode').val() == 'COMPANYUSER' || $('#mode').val() == 'SERVICEUSER' || $('#mode').val() == 'EXTERNALCONTRACTORS' || $('#mode').val() == 'ASSETOWNERS' || (getURLParameter('selectmode') != null && getURLParameter('selectmode') != '' && getURLParameter('selectmode') == "SINGLE") || (getURLParameter('tb_mode') != null && getURLParameter('tb_mode') != '' && getURLParameter('tb_mode') == "SERVICEGROUPS")) {
        $("input:checked").attr('checked', false);
        $('td[class="cb"]').parents('tr').removeClass('selected');
        if ($('#mode').val() == 'EXTERNALCONTRACTORS')
            $('.cb').parents('tr').removeClass('selected');
    }

    if (check) {
        if (!skip) selectedIds.push(val);
        if (cb) {
            cb.checked = true;
            $(cb).parents('tr').addClass('selected');
        }

        //разрешено выбрать только одного пользователя
        if ($('#mode').val() == 'CREATORS' || $('#mode').val() == 'COMPANYUSER' || $('#mode').val() == 'SUBSCRIBE' || $('#mode').val() == 'SERVICEUSER' || $('#mode').val() == 'EXTERNALCONTRACTORS' || (getURLParameter('selectmode') != null && getURLParameter('selectmode') != '' && getURLParameter('selectmode') == "SINGLE") || (getURLParameter('tb_mode') != null && getURLParameter('tb_mode') != '' && getURLParameter('tb_mode') == "SERVICEGROUPS")) selectedIds.reverse();
    }
    else {
        selectedIds = $.grep(selectedIds, function (i) { return i != val; });
        if (cb) {
            cb.checked = false;
            $(cb).parents('tr').removeClass('selected');
        }
    }
    try { if (rowCheckedUser) rowCheckedUser(val, check); } catch (e) { }
}