aboutsummaryrefslogtreecommitdiff
path: root/js/lib/userpicker.js
blob: 2b3d78d6bd6d11f7fe700c1111437d422697c6e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
elgg.provide('elgg.userpicker');

elgg.userpicker.init = function() {
	// binding autocomplete.
	// doing this as an each so we can past this to functions.
	$('.elgg-input-user-picker').each(function() {
		
		var _this = this;
		
		$(this).autocomplete({
			source: function(request, response) {
				var params = elgg.userpicker.getSearchParams(this);
				
				elgg.get('pg/livesearch', {
					data: params,
					dataType: 'json',
					success: function(data) {
						response(data);
					}
				});
			},
			minLength: 2,
			select: elgg.userpicker.addUser
		})
		
		//@todo This seems convoluted
		.data("autocomplete")._renderItem = elgg.userpicker.formatItem;
	});
};

elgg.userpicker.formatItem = function(ul, item) {
	switch (item.type) {
		case 'user':
		case 'group':
			r = item.icon + item.name + ' - ' + item.desc;
			break;

		default:
			r = item.name + ' - ' + item.desc;
			break;
	}
	
	return $("<li/>")
		.data("item.autocomplete", item)
		.append(r)
		.appendTo(ul);
};

elgg.userpicker.addUser = function(event, ui) {
	var info = ui.item;
	
	// do not allow users to be added multiple times
	if (!(info.guid in elgg.userpicker.userList)) {
		elgg.userpicker.userList[info.guid] = true;
	
		var picker = $(this).closest('.elgg-user-picker');
		var users = picker.find('.elgg-user-picker-entries');
		var internalName = users.find('[type=hidden]').attr('name');
		
		// not sure why formatted isn't.
		var formatted = elgg.userpicker.formatItem(data);

		// add guid as hidden input and to list.
		var li = formatted + ' <div class="delete-button"><a onclick="elgg.userpicker.removeUser(this, ' + info.guid + ')"><strong>X</strong></a></div>'
		+ '<input type="hidden" name="' + internalName + '" value="' + info.guid + '" />';
		$('<li>').html(li).appendTo(users);

		$(this).val('');
	}
};

elgg.userpicker.removeUser = function(link, guid) {
	$(link).closest('.elgg-user-picker-entries > li').remove();
};

elgg.userpicker.getSearchParams = function(e) {
	if ($(e).closest('.elgg-user-picker').find('[name=match_on]').attr('checked')) {
		return {'match_on[]': 'friends'};
	} else {
		return {'match_on[]': 'users'};
	}
}

elgg.register_event_handler('init', 'system', elgg.userpicker.init);