// Set value for the single-user picker. Called from the popup window
window.UserPicker_SetUser = function(input_dom_id, user_id, user_name)
{
	var input_element = jq_$(input_dom_id);
	//input_element.select2('data', {'id': user_id, 'text': user_name});
	// The new select2 cannot use the data parameter to set a value that it has not seen yet (i.e. when using AJAX but setting it directly). It must be manually added to the select.
	input_element.html();
	input_element.append('<option selected value="' + user_id + '">' + _.escape(user_name) + '</option>');
	input_element.change();
	input_element.trigger('cla-user-change');
	return true;
};

// Delete value of the single-user picker
window.UserPicker_DeleteSelected = function(input_dom_id)
{
	var input_element = jq_$(input_dom_id);
	input_element.val('');
	input_element.trigger('change');
	return false;
};

// Initialize the "select2" element for the single-user picker
window.UserPicker_InitSelect2Single = function (element_id, query_params, placeholder, allow_unset) {
	var el = jq_$(element_id);

    var page_size = 50;
    var pickerInputGroup = el.parent('.js-picker-input-group');
    var pickerButton = pickerInputGroup.find('.js-input-group-append .js-input-btn');
    var containerWidth = 'calc(100% - '+ pickerButton.getHiddenOffsetWidth() +'px)';

	el.select2({
		placeholder: placeholder,
		minimumInputLength: 3,
		allowClear: allow_unset,
        width: containerWidth,
        ajax: {
			url: "/intranet/common/user_picker_popup.php?json=1"+query_params,
			dataType: 'json',
			delay: 250,
			data: function (params) {
				return {
					keywords: params.term, // search term
					page: params.page,
					page_size: page_size,
					st: (params.page-1) * page_size
				};
			},
			processResults: function (data, params) {
				params.page = params.page || 1;

				return {
					results: data.data,
					pagination: {
						more: ((params.page) * page_size) < data.total
					}
				};
			},
            escapeMarkup: function (text) {
                var element = document.createElement('span');
                element.textContent = text;

                return element.innerHTML;
            }
		}
	});
};

// Initialize the "select2" element for the SUGRE picker (Single User, Group, Role, Extranet)
window.UserPicker_InitSelect2SUGRE = function (element_id, query_params, placeholder, allow_unset, has_browse) {
    var el = jq_$(element_id);
    var inputWidth = String;

    if(has_browse) {
        var buttonOffsetWidth = el.siblings(".js-input-btn").getHiddenOffsetWidth() + 4;
        inputWidth = 'calc(100% - '+ buttonOffsetWidth +'px)';
    } else {
        inputWidth = '100%';
    }

	el.select2({
		placeholder: placeholder,
		minimumInputLength: 1,
		width: inputWidth,
		allowClear: allow_unset,
		ajax: {
			url: "/intranet/common/common_perms_owners_popup.php?json=1"+query_params,
			dataType: 'json',
			data: function (params) {
				return {
					query: params.term // search term
				};
			},
			processResults: function (data) {
				jQuery.each(data.data, function (idx, el){
					data.data[idx] = {'id': el[0]+'_'+el[1], 'text': data.suggestions[idx] };
				});
				return {results: data.data};
			},
            escapeMarkup: function (text) {
                var element = document.createElement('span');
                element.textContent = text;

                return element.innerHTML;
            }
		}
	});
};


// Initialize the "select2" element for the multi-user picker
window.UserPicker_InitSelect2 = function (element_id, query_params, placeholder) {
	var el = jq_$(element_id);
	var page_size = 50;
	el.select2({
		placeholder: placeholder,
		minimumInputLength: 1,
		ajax: {
			url: "/intranet/common/user_picker_popup.php?json=1&multi=1"+query_params,
			dataType: 'json',
			data: function (params) {
				return {
					keywords: params.term, // search term
					page: params.page,
					page_size: page_size,
					st: (params.page-1) * page_size
				};
			},
			processResults: function (data, params) {
				params.page = params.page || 1;

				return {
					results: data.data,
					pagination: {
						more: ((params.page) * page_size) < data.total
					}
				};
			},
            escapeMarkup: function (text) {
                var element = document.createElement('span');
                element.textContent = text;

                return element.innerHTML;
            }
		}
	});

};

// Add a user to the multi-user picker
window.UserPicker_AddUser = function(element_id, user_id, user_name)
{
	var select_element = jq_$(element_id);

	var option = jQuery('option[value='+user_id+']', select_element);
	if (option.size() > 0)
	{
		if (option.prop('selected'))
		{
			// User already selected in list
			return false;
		} else
		{
			// User in list but not selected
			option.prop('selected', true)
		}
	} else
	{
		// User not in the list at all
		select_element.append(jQuery('<option>&nbsp; &nbsp; &nbsp; </option>').val(user_id).text(user_name).prop('selected', true));
	}

	select_element.change();
	select_element.trigger('cla-user-change');
	return true;
};
