// fill selector with values from perms_arr
function InitPermsDialog(perms_list)
{
	allperms = perms_list;
	owners_sel.length = 0;
	for (var id in allperms) {
		var text = allperms[id][0];
		owners_sel.options[owners_sel.length] = new Option(text, id, false, false);
	}
	owners_sel.selectedIndex = 0;
	onOwnersClick();

	InitAutocomplete();

	if (jQuery('#InheritCheck'))
		InheritDisable(jQuery('#InheritCheck').prop('checked'));
}

function InitAutocomplete() {
	jQuery('#pd_owner_search').autocomplete({
		serviceUrl: "/intranet/common/common_perms_owners_popup.php",
        params: {'pp': parent_perm_id, pc: parent_class, sho: show_owner, json: 1, mpp: window.max_public_perms},
		deferRequestBy: 100,
		fnFormatResult: formatAutocompleteResult,
		onSelect: addOwnerFromAutocomplete
	});
}

function formatAutocompleteResult(value, data, currentValue) {
	currentValue = currentValue.replace(/^\w{0,10}(\+?|\[\+\]):\s*/, '');
	if (currentValue.length == 0)
		return value;

    // sanitize value
    var element = document.createElement('span');
    element.textContent = value;
    value = element.innerHTML;

	var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
	var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
	return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
}

function InheritDisable(perms_inherited)
{
	var pd_button_add = document.getElementById('pd_button_add');
	var pd_button_remove = document.getElementById('pd_button_remove');
	var $child_permission_info = jQuery('.js-child-permission-info')

	if (!pd_button_add || !pd_button_remove) return;

	if (perms_inherited){
		pd_button_add.disabled = true;
		pd_button_remove.disabled = true;
		jQuery('#pd_owner_search').prop('disabled', true);
		$child_permission_info.hide();
	}else{
		pd_button_add.disabled = false;
		pd_button_remove.disabled = false;
		jQuery('#pd_owner_search').prop('disabled', false);

		if (perms_inherited !== undefined)
			$child_permission_info.show();
	}

	var sec_level = perm_form.security_level;
	if (sec_level) sec_level.disabled = perms_inherited;

	if (perms_inherited)
		disableAllCheckboxes()

	onOwnersClick();
}

function openEffectivePermissionsWindow()
{
	onPermsSubmit(perm_form);
	var perms = perm_form.perms.value;

	var perm_values = '';
	for (var pid in pnames)
	{
		if (!isNaN(pid))
		{
			if (perm_values)
				perm_values += ',';

			perm_values += encodeURIComponent(pid+'_'+pnames[pid][0].replace(/,/g, "\u201a"));
		}
	}

	window.open("/intranet/common/common_perms_effective.php?perms="+perms+"&perm_values="+perm_values,
		"effective_popup", "width=1040,height=550,scrollbars=yes,resizable=yes,hotkeys=no,maximize=no");
}

function addOwnerFromAutocomplete(value, data) {
	if (data[0] != 0)
		addOwner(data[0], data[1], data[2], 'owners');
	else
		addOwner(data[1], 0, data[2], 'owners');
	jQuery('#pd_owner_search').val('');
}

function addOwner(oclass, id, name, selector_name) {
	if (selector_name == 'owners') {
		if (allperms[oclass + '_' + id] == null) {
			allperms[oclass + '_' + id] = [name, 1];
			var element = new Option((id != 0 ? (onames[oclass] + ': ') : '') + name, oclass + '_' + id, false, false);
			owners_sel.options[owners_sel.length] = element;
			return true;
		} else {
			return false;
		}
	}
	return false;
}

function setPerms(id, perms) {
    if (allperms[id] == null) return;
    allperms[id][1] = perms;
}

function setPermCheckbox(perm, value) {
	var cb = perm_form['perm_' + perm];
	if (cb) cb.checked = value;
}

function getPermCheckbox(perm) {
	var cb = perm_form['perm_' + perm];
	return cb ? cb.checked : false;
}

// set checkoxes according to flags in parameters 'perms'
function setPermCheckboxes(perms) {
	for (var i = 1; i<pnames.length; ++i)
		if (pnames[i])
			setPermCheckbox(i, (perms & i) == i);
}

// get permissions flags according to current checkboxes combination
function getPermCheckboxes() {
    var perms = 0;

	for (var i = 1; i<pnames.length; ++i)
		if (pnames[i] && getPermCheckbox(i))
			perms |=  i;

	return perms;
}

function disableEditCheckboxes() {

	for (var i = 1; i<pnames.length; ++i)
	{
		if (pnames[i] && perm_form['perm_' + i])
			perm_form['perm_' + i].disabled = !((max_public_perms & i) == i && pnames[i][1]);
	}
}

function enableEditCheckboxes() {
	var inherit_check = jQuery('#InheritCheck');
	if (inherit_check.length && inherit_check.prop('checked')) return;
	for (var i = 1; i<pnames.length; ++i)
		if (pnames[i] && perm_form['perm_' + i])
			perm_form['perm_' + i].disabled = !pnames[i][1];
}

function disableAllCheckboxes() {
	for (var i = 1; i<pnames.length; ++i)
		if (pnames[i] && perm_form['perm_' + i])
		{
			perm_form['perm_' + i].disabled = true;
			perm_form['perm_' + i].checked = false;
		}
}
// event handlers

// Set permissions checkboxes for selected owner
function onOwnersClick() {
	var id = 0;
    var selected = owners_sel.selectedIndex;

    if (selected >= 0)
    	id = owners_sel.options[selected].value;

    if (id == public_id)
        disableEditCheckboxes();
    else
        enableEditCheckboxes();
    if (id)
        setPermCheckboxes(allperms[id][1]);
}

function onCheckboxChange(value) {
	var id = 0;
	var checked = getPermCheckbox(value);
    var selected = owners_sel.selectedIndex;
    var perms;
    if (selected >= 0)
    	id = owners_sel.options[selected].value;
    if (id) {
        if (!checked) { // if a checkbox was unchecked
            perms = 0;
            for (var i = 1; i<pnames.length; ++i)
                if (pnames[i] && getPermCheckbox(i) && ((value & i) !== value))
                    perms |=  i;
        } else {
            perms = getPermCheckboxes();
        }
	    setPermCheckboxes(perms);
	    perms = getPermCheckboxes();
        setPerms(id, perms);
        if (!perms) {
            if (window.confirm(lmsg("common.perms.ask_delete", allperms[id][0]))) {
                deleteSelectedOwner();
            }
        }
    }
}

function unsetArrayElement(input_array, key_to_unset) {
	var output_array = {};
	for (var key in input_array) {
		if (key != key_to_unset) output_array[key] = input_array[key];
	}
	return output_array;
}

function deleteSelectedOwner() {
	var i = owners_sel.selectedIndex;
	if (i < 0) return;
	var id = owners_sel.options[i].value;

	var new_perms = allperms[id][1];
	var full_perms = 0;
	for (var key in pnames) {
		full_perms = full_perms | key;
	}
	new_perms &= full_perms;

	for (var key in pnames) {
		if (pnames[key][1])
			new_perms &= ~key;
	}

	if (new_perms == 0) {
		if (owners_sel.options[i]) {
			owners_sel.options[i] = null;
			allperms = unsetArrayElement(allperms, id);
			disableAllCheckboxes();
			//		allperms[id] = null
		}
	} else
	{
		alert('Some permissions are revoked, but some stayed as they are not editable for you');
		setPerms(id, new_perms);
		onOwnersClick();
	}
}

function addOwnerPopup(selector_name) {
	var extra = '';

	if (window.max_public_perms !== undefined && window.max_public_perms !== null)
		extra = '&mpp=' + window.max_public_perms;

	var osw = window.open("/intranet/common/common_perms_owners_popup.php?pp="+parent_perm_id+
    	"&pc="+parent_class+"&selector_name="+selector_name+'&sho='+show_owner + extra, 'name_popup',
    	'width=380,height=512,scrollbars=no,resizable=yes,hotkeys=no,maximize=no,visible=no');
	osw.focus();
}

// deprecated, use onPermsSubmit instead
function onSubmit(form) {
	return onPermsSubmit(form);
}

function onPermsSubmit(form) {
	var result = form.perms;
	result.value = "";
	for (var id in allperms) {
		result.value += ',' + id + '_' + allperms[id][1];
	}
	if (result.value.length > 0) {
		result.value = result.value.substring(1);
	}
}
