Welcome to mirror list, hosted at ThFree Co, Russian Federation.

multiselect.js « js « php « frontends - github.com/zabbix/zabbix.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f52885b93029013004b96a7c98a7760140e31661 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
/*
** Zabbix
** Copyright (C) 2001-2020 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/


jQuery(function($) {
	var ZBX_STYLE_CLASS = 'multiselect-control',
		KEY = {
			ARROW_DOWN: 40,
			ARROW_LEFT: 37,
			ARROW_RIGHT: 39,
			ARROW_UP: 38,
			BACKSPACE: 8,
			DELETE: 46,
			ENTER: 13,
			ESCAPE: 27,
			TAB: 9
		};

	/**
	 * Multi select helper.
	 *
	 * @param string options['objectName']		backend data source
	 * @param object options['objectOptions']	parameters to be added the request URL (optional)
	 *
	 * @see jQuery.multiSelect()
	 */
	$.fn.multiSelectHelper = function(options) {
		options = $.extend({objectOptions: {}}, options);

		var curl = new Curl('jsrpc.php', false);
		curl.setArgument('type', 11); // PAGE_TYPE_TEXT_RETURN_JSON
		curl.setArgument('method', 'multiselect.get');
		curl.setArgument('objectName', options.objectName);

		for (var key in options.objectOptions) {
			curl.setArgument(key, options.objectOptions[key]);
		}

		options.url = curl.getUrl();

		return this.each(function() {
			$(this).empty().multiSelect(options);
		});
	};

	/*
	 * Multiselect methods
	 */
	var methods = {
		/**
		 * Get multi select selected data.
		 *
		 * @return array    array of multiselect value objects
		 */
		getData: function() {
			var $obj = $(this).first(),
				ms = $obj.data('multiSelect');

			var data = [];
			for (var id in ms.values.selected) {
				var item = ms.values.selected[id];

				data.push({
					id: id,
					name: item.name,
					prefix: (typeof item.prefix === 'undefined') ? '' : item.prefix
				});
			}

			return data;
		},

		/**
		 * Insert outside data
		 *
		 * @param object    multiselect value object
		 *
		 * @return jQuery
		 */
		addData: function(items) {
			return this.each(function() {
				var $obj = $(this),
					ms = $obj.data('multiSelect');

				if (ms.options.selectedLimit == 1) {
					for (var id in ms.values.selected) {
						removeSelected($obj, id);
					}
				}

				for (var i = 0, l = items.length; i < l; i++) {
					addSelected($obj, items[i]);
				}

				$obj.trigger('change', ms);
			});
		},

		/**
		 * Enable multi select UI control.
		 *
		 * @return jQuery
		 */
		enable: function() {
			return this.each(function() {
				var $obj = $(this),
					ms = $obj.data('multiSelect');

				if (ms.options.disabled === true) {
					$obj.removeAttr('aria-disabled');
					$('.multiselect-list', $obj).removeClass('disabled');
					$('.multiselect-button > button', $obj.parent()).prop('disabled', false);
					$obj.append(makeMultiSelectInput($obj));

					ms.options.disabled = false;

					cleanSearch($obj);
				}
			});
		},

		/**
		 * Disable multi select UI control.
		 *
		 * @return jQuery
		 */
		disable: function() {
			return this.each(function() {
				var $obj = $(this),
					ms = $obj.data('multiSelect');

				if (ms.options.disabled === false) {
					$obj.attr('aria-disabled', true);
					$('.multiselect-list', $obj).addClass('disabled');
					$('.multiselect-button > button', $obj.parent()).prop('disabled', true);
					$('input[type="text"]', $obj).remove();

					ms.options.disabled = true;

					cleanSearch($obj);
				}
			});
		},

		/**
		 * Clean multi select object values.
		 *
		 * @return jQuery
		 */
		clean: function() {
			return this.each(function() {
				var $obj = $(this),
					ms = $obj.data('multiSelect');

				for (var id in ms.values.selected) {
					removeSelected($obj, id);
				}

				cleanSearch($obj);

				$obj.trigger('change', ms);
			});
		},

		/**
		 * Modify one or more multiselect options after multiselect object has been created.
		 *
		 * @return jQuery
		 */
		modify: function(options) {
			return this.each(function() {
				var $obj = $(this),
					ms = $obj.data('multiSelect');

				var addNew_modified = ('addNew' in options) && options['addNew'] != ms.options['addNew'];

				for (var key in ms.options) {
					if (key in options) {
						ms.options[key] = options[key];
					}
				}

				if (addNew_modified) {
					/*
					 * When modifying the "addNew" option, few things must be done:
					 *   1. Search input must be reset.
					 *   2. The already selected "(new)" items must be either hidden and disabled or shown and enabled.
					 *      Note: hidden and disabled items will not submit to the server.
					 *   3. The "change" trigger must fire.
					 */

					cleanSearch($obj);

					$('input[name*="[new]"]', $obj)
						.prop('disabled', !ms.options['addNew'])
						.each(function() {
							var id = $(this).val();
							$('.selected li[data-id]', $obj).each(function() {
								if ($(this).data('id') == id) {
									$(this).toggle(ms.options['addNew']);
								}
							});
						});

					$obj.trigger('change', ms);
				}
			});
		},

		/**
		 * Return option value.
		 *
		 * @return string
		 */
		getOption: function(key) {
			var ret = null;
			this.each(function() {
				var $obj = $(this);

				if ($obj.data('multiSelect') !== undefined) {
					ret = $obj.data('multiSelect').options[key];
				}
			});

			return ret;
		}
	};

	/**
	 * Create multi select input element.
	 *
	 * @param string options['url']					backend url
	 * @param string options['name']				input element name
	 * @param object options['labels']				translated labels (optional)
	 * @param object options['data']				preload data {id, name, prefix} (optional)
	 * @param string options['data'][id]
	 * @param string options['data'][name]
	 * @param string options['data'][prefix]		(optional)
	 * @param bool   options['data'][inaccessible]	(optional)
	 * @param bool   options['data'][disabled]		(optional)
	 * @param string options['placeholder']			set custom placeholder (optional)
	 * @param array  options['excludeids']			the list of excluded ids (optional)
	 * @param string options['defaultValue']		default value for input element (optional)
	 * @param bool   options['disabled']			turn on/off readonly state (optional)
	 * @param bool   options['addNew']				allow user to create new names (optional)
	 * @param int    options['selectedLimit']		how many items can be selected (optional)
	 * @param int    options['limit']				how many available items can be received from backend (optional)
	 * @param object options['popup']				popup data {parameters, width, height} (optional)
	 * @param string options['popup']['parameters']
	 * @param int    options['popup']['width']
	 * @param int    options['popup']['height']
	 * @param string options['styles']				additional style for multiselect wrapper HTML element (optional)
	 * @param string options['styles']['property']
	 * @param string options['styles']['value']
	 *
	 * @return object
	 */
	$.fn.multiSelect = function(options) {
		// Call a public method.
		if (methods[options]) {
			return methods[options].apply(this, Array.prototype.slice.call(arguments, 1));
		}

		var defaults = {
				url: '',
				name: '',
				labels: {
					'No matches found': t('No matches found'),
					'More matches found...': t('More matches found...'),
					'type here to search': t('type here to search'),
					'new': t('new'),
					'Select': t('Select')
				},
				placeholder: t('type here to search'),
				data: [],
				only_hostid: 0,
				excludeids: [],
				addNew: false,
				defaultValue: null,
				disabled: false,
				selectedLimit: 0,
				limit: 20,
				popup: {},
				styles: {}
			};

		options = $.extend({}, defaults, options);

		return this.each(function() {
			var $obj = $(this);

			if ($obj.data('multiSelect') !== undefined) {
				return;
			}

			options.required_str = $obj.attr('aria-required') === undefined ? 'false' : $obj.attr('aria-required');
			$obj.removeAttr('aria-required');

			var ms = {
					options: options,
					values: {
						search: '',
						searches: {},
						searching: {},
						selected: {},
						available: {},
						available_div: $('<div>', {'class': 'multiselect-available'}),

						/*
						 * Indicates a false click on an available list, but not on some actual item.
						 * In such case the "focusout" event (IE) of the search input should not be processed.
						 */
						available_false_click: false
					}
				};

			ms.values.available_div.on('mousedown', 'li', function() {
				/*
				 * Cancel event propagation if actual available item was clicked.
				 * As a result, the "focusout" event of the search input will not fire in all browsers.
				 */
				return false;
			});

			if (IE) {
				ms.values.available_div.on('mousedown', function() {
					ms.values.available_false_click = true;
				});
			}

			$obj.data('multiSelect', ms);

			$obj.wrap($('<div>', {
				'class': ZBX_STYLE_CLASS,
				css: ms.options.styles
			}));

			var $selected_div = $('<div>', {'class': 'selected'}).on('click', function() {
					/*
					 * Focus without options because here it don't matter.
					 * Click used instead focus because in patternselect listen only click.
					 */
					$('input[type="text"]', $obj).click().focus();
				}),
				$selected_ul = $('<ul>', {'class': 'multiselect-list'});

			$obj.append($selected_div.append($selected_ul));

			if (ms.options.disabled) {
				$obj.attr('aria-disabled', true);
				$selected_ul.addClass('disabled');
			}
			else {
				$obj.append(makeMultiSelectInput($obj));
			}

			$obj
				.on('mousedown', function() {
					if (isSearchFieldVisible($obj) && ms.options.selectedLimit != 1) {
						$obj.addClass('active');
						$('.selected li.selected', $obj).removeClass('selected');
					}
				});

			if (empty(ms.options.data)) {
				addDefaultValue($obj);
			}
			else {
				$.each(ms.options.data, function(i, item) {
					addSelected($obj, item);
				});
			}

			if (ms.options.popup.parameters != null) {
				if (typeof ms.options.popup.parameters['only_hostid'] !== 'undefined') {
					ms.options.only_hostid = ms.options.popup.parameters['only_hostid'];
				}

				var popup_button = $('<button>', {
						type: 'button',
						'class': 'btn-grey',
						text: ms.options.labels['Select']
					});

				if (ms.options.disabled) {
					popup_button.prop('disabled', true);
				}

				popup_button.on('click', function(event) {
					// Click used instead focus because in patternselect listen only click.
					$('input[type="text"]', $obj).click();
					return PopUp('popup.generic', ms.options.popup.parameters, null, event.target);
				});

				$obj.after($('<div>', {'class': 'multiselect-button'}).append(popup_button));
			}
		});
	};

	function makeMultiSelectInput($obj) {
		var ms = $obj.data('multiSelect'),
			$label = $('label[for=' + $obj.attr('id') + '_ms]'),
			$aria_live = $('[aria-live]', $obj),
			$input = $('<input>', {
				'id': $label.length ? $label.attr('for') : null,
				'class': 'input',
				'type': 'text',
				'placeholder': ms.options.placeholder,
				'aria-label': ($label.length ? $label.text() + '. ' : '') + ms.options.placeholder,
				'aria-required': ms.options.required_str
			})
				.on('keyup', function(e) {
					switch (e.which) {
						case KEY.ARROW_DOWN:
						case KEY.ARROW_LEFT:
						case KEY.ARROW_RIGHT:
						case KEY.ARROW_UP:
						case KEY.ESCAPE:
							return false;
					}

					clearSearchTimeout($obj);

					// Maximum results selected already?
					if (ms.options.selectedLimit != 0 && $('.selected li', $obj).length >= ms.options.selectedLimit) {
						return false;
					}

					var search = $input.val();

					if (search !== '') {
						search = search.trim();

						$('.selected li.selected', $obj).removeClass('selected');
					}

					if (search !== '') {
						/*
						 * Strategy:
						 * 1. Load the cached result set if such exists for the given term and show the list.
						 * 2. Skip anything if already expecting the result set to arrive for the given term.
						 * 3. Schedule result set retrieval for the given term otherwise.
						 */

						if (search in ms.values.searches) {
							ms.values.search = search;
							loadAvailable($obj);
							showAvailable($obj);
						}
						else if (!(search in ms.values.searching)) {
							ms.values.searchTimeout = setTimeout(function() {
								ms.values.searching[search] = true;

								$.ajax({
									url: ms.options.url + '&curtime=' + new CDate().getTime(),
									type: 'GET',
									dataType: 'json',
									cache: false,
									data: {
										search: search,
										limit: getLimit($obj)
									}
								})
									.then(function(response) {
										ms.values.searches[search] = response.result;

										if (search === $input.val().trim()) {
											ms.values.search = search;
											loadAvailable($obj);
											showAvailable($obj);
										}
									})
									.done(function() {
										delete ms.values.searching[search];
									});

								delete ms.values.searchTimeout;
							}, 500);
						}
					}
					else {
						hideAvailable($obj);
					}
				})
				.on('keydown', function(e) {
					switch (e.which) {
						case KEY.TAB:
						case KEY.ESCAPE:
							hideAvailable($obj);
							cleanSearchInput($obj);
							break;

						case KEY.ENTER:
							if ($input.val() !== '') {
								var $selected = $('li.suggest-hover', ms.values.available_div);

								if ($selected.length) {
									select($obj, $selected.data('id'));
									$aria_live.text(sprintf(t('Added, %1$s'), $selected.data('label')));
								}

								return false;
							}
							break;

						case KEY.ARROW_LEFT:
							if ($input.val() === '') {
								var $collection = $('.selected li', $obj);

								if ($collection.length) {
									var $prev = $collection.filter('.selected').removeClass('selected').prev();
									$prev = ($prev.length ? $prev : $collection.last()).addClass('selected');

									$aria_live.text(($prev.hasClass('disabled'))
										? sprintf(t('%1$s, read only'), $prev.data('label'))
										: $prev.data('label')
									);
								}
							}
							break;

						case KEY.ARROW_RIGHT:
							if ($input.val() === '') {
								var $collection = $('.selected li', $obj);

								if ($collection.length) {
									var $next = $collection.filter('.selected').removeClass('selected').next();
									$next = ($next.length ? $next : $collection.first()).addClass('selected');

									$aria_live.text(($next.hasClass('disabled'))
										? sprintf(t('%1$s, read only'), $next.data('label'))
										: $next.data('label')
									);
								}
							}
							break;

						case KEY.ARROW_UP:
						case KEY.ARROW_DOWN:
							var $collection = $('li', ms.values.available_div.filter(':visible')),
								$selected = $collection.filter('.suggest-hover').removeClass('suggest-hover');

							if ($selected.length) {
								$selected = (e.which == KEY.ARROW_UP)
									? ($selected.is(':first-child') ? $collection.last() : $selected.prev())
									: ($selected.is(':last-child') ? $collection.first() : $selected.next());

								$selected.addClass('suggest-hover');
								$aria_live.text($selected.data('label'));
							}

							scrollAvailable($obj);

							return false;

						case KEY.BACKSPACE:
						case KEY.DELETE:
							if ($input.val() === '') {
								var $selected = $('.selected li.selected', $obj);

								if ($selected.length) {
									var id = $selected.data('id'),
										item = ms.values.selected[id];

									if (typeof item.disabled === 'undefined' || !item.disabled) {
										var aria_text = sprintf(t('Removed, %1$s'), $selected.data('label'));

										$selected = (e.which == KEY.BACKSPACE)
											? ($selected.is(':first-child') ? $selected.next() : $selected.prev())
											: ($selected.is(':last-child') ? $selected.prev() : $selected.next());

										removeSelected($obj, id);

										$obj.trigger('change', ms);

										if ($selected.length) {
											var $collection = $('.selected li', $obj);
											$selected.addClass('selected');

											aria_text += ', ' + sprintf(
												($selected.hasClass('disabled'))
													? t('Selected, %1$s, read only, in position %2$d of %3$d')
													: t('Selected, %1$s in position %2$d of %3$d'),
												$selected.data('label'),
												$collection.index($selected) + 1,
												$collection.length
											);
										}

										$aria_live.text(aria_text);
									}
									else {
										$aria_live.text(t('Can not be removed'));
									}
								}
								else if (e.which == KEY.BACKSPACE) {
									/*
									 * Pressing Backspace on empty input field should select last element in
									 * multiselect. For next Backspace press to be able to remove it.
									 */
									var $selected = $('.selected li:last-child', $obj).addClass('selected');
									$aria_live.text($selected.data('label'));
								}

								return false;
							}
							break;
					}
				})
				.on('focusin', function($event) {
					$obj.addClass('active');
				})
				.on('focusout', function($event) {
					if (ms.values.available_false_click) {
						ms.values.available_false_click = false;
						$('input[type="text"]', $obj)[0].focus({preventScroll:true});
					}
					else {
						$obj.removeClass('active');
						$('.selected li.selected', $obj).removeClass('selected');
						cleanSearchInput($obj);
						hideAvailable($obj);
					}
				});

		return $input;
	}

	function addDefaultValue($obj) {
		var ms = $obj.data('multiSelect');

		if (!empty(ms.options.defaultValue)) {
			$obj.append($('<input>', {
				type: 'hidden',
				name: ms.options.name,
				value: ms.options.defaultValue,
				'data-default': 1
			}));
		}
	}

	function removeDefaultValue($obj) {
		$('input[data-default="1"]', $obj).remove();
	}

	function select($obj, id) {
		var ms = $obj.data('multiSelect');

		addSelected($obj, ms.values.available[id]);

		if (isSearchFieldVisible($obj)) {
			$('input[type="text"]', $obj)[0].focus({preventScroll:true});
		}

		$obj.trigger('change', ms);
	}

	function addSelected($obj, item) {
		var ms = $obj.data('multiSelect');

		if (item.id in ms.values.selected) {
			return;
		}

		removeDefaultValue($obj);
		ms.values.selected[item.id] = item;

		var prefix = (item.prefix || ''),
			item_disabled = (typeof item.disabled !== 'undefined' && item.disabled);

		$obj.append($('<input>', {
			type: 'hidden',
			name: (ms.options.addNew && item.isNew) ? ms.options.name + '[new]' : ms.options.name,
			value: item.id,
			'data-name': item.name,
			'data-prefix': prefix
		}));

		var $li = $('<li>', {
				'data-id': item.id,
				'data-label': prefix + item.name
			})
				.append(
					$('<span>', {
						'class': 'subfilter-enabled'
					})
						.append($('<span>', {
							text: prefix + item.name,
							title: item.name
						}))
						.append($('<span>')
							.addClass('subfilter-disable-btn')
							.on('click', function() {
								if (!ms.options.disabled && !item_disabled) {
									removeSelected($obj, item.id);
									if (isSearchFieldVisible($obj)) {
										$('input[type="text"]', $obj)[0].focus({preventScroll:true});
									}

									$obj.trigger('change', ms);
								}
							})
						)
				)
				.on('click', function() {
					if (isSearchFieldVisible($obj) && ms.options.selectedLimit != 1) {
						$('.selected li.selected', $obj).removeClass('selected');
						$(this).addClass('selected');
					}
				});

		if (typeof item.inaccessible !== 'undefined' && item.inaccessible) {
			$li.addClass('inaccessible');
		}

		if (item_disabled) {
			$li.addClass('disabled');
		}

		$('.selected ul', $obj).append($li);

		cleanSearch($obj);
	}

	function removeSelected($obj, id) {
		var ms = $obj.data('multiSelect');

		$('.selected li[data-id]', $obj).each(function(){
			if ($(this).data('id') == id) {
				$(this).remove();
			}
		});
		$('input', $obj).each(function(){
			if ($(this).val() == id) {
				$(this).remove();
			}
		});

		delete ms.values.selected[id];

		if (!$('.selected li', $obj).length) {
			addDefaultValue($obj);
		}

		cleanSearch($obj);
	}

	function addAvailable($obj, item) {
		var ms = $obj.data('multiSelect'),
			is_new = item.isNew || false,
			prefix = item.prefix || '',
			search = ms.values.search.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/[*]/g, '\\\*?'),
			$li = $('<li>', {
				'data-id': item.id,
				'data-label': prefix + item.name
			})
				.on('mouseenter', function() {
					$('li.suggest-hover', ms.values.available_div).removeClass('suggest-hover');
					$li.addClass('suggest-hover');
				})
				.on('click', function() {
					select($obj, item.id);
				});

		if (prefix !== '') {
			$li.append($('<span>', {'class': 'grey', text: prefix}));
		}

		// Highlight matched.
		$li
			.append(item.name.replace(new RegExp(search, 'gi'), function(match) {
				return '<span' + (!is_new ? ' class="suggest-found"' : '') + '>' + match + '</span>';
			}))
			.toggleClass('suggest-new', is_new);

		$('ul', ms.values.available_div).append($li);
	}

	function loadAvailable($obj) {
		var ms = $obj.data('multiSelect'),
			data = ms.values.searches[ms.values.search];

		cleanAvailable($obj);

		var addNew = false;

		if (ms.options.addNew && ms.values.search.length) {
			if (data.length || objectSize(ms.values.selected) > 0) {
				var names = {};

				// Check if value exists among available values.
				$.each(data, function(i, item) {
					if (item.name === ms.values.search) {
						names[item.name.toUpperCase()] = true;
					}
				});

				if (typeof names[ms.values.search.toUpperCase()] === 'undefined') {
					addNew = true;
				}

				// Check if value exists among selected values.
				if (!addNew && objectSize(ms.values.selected) > 0) {
					$.each(ms.values.selected, function(i, item) {
						if (typeof item.isNew === 'undefined') {
							names[item.name.toUpperCase()] = true;
						}
						else {
							names[item.id.toUpperCase()] = true;
						}
					});

					if (typeof names[ms.values.search.toUpperCase()] === 'undefined') {
						addNew = true;
					}
				}
			}
			else {
				addNew = true;
			}
		}

		var available_more = false;

		$.each(data, function(i, item) {
			if (ms.options.limit == 0 || objectSize(ms.values.available) < ms.options.limit) {
				if (typeof ms.values.available[item.id] === 'undefined'
						&& typeof ms.values.selected[item.id] === 'undefined'
						&& ms.options.excludeids.indexOf(item.id) === -1) {
					ms.values.available[item.id] = item;
				}
			}
			else {
				available_more = true;
			}
		});

		if (addNew) {
			ms.values.available[ms.values.search] = {
				id: ms.values.search,
				name: ms.values.search + ' (' + ms.options.labels['new'] + ')',
				isNew: true
			};
		}

		var found = 0,
			preselected = '';

		if (objectSize(ms.values.available) == 0) {
			var div = $('<div>', {
					'class': 'multiselect-matches',
					text: ms.options.labels['No matches found']
				})
					.on('click', function() {
						$('input[type="text"]', $obj)[0].focus({preventScroll:true});
					});

			ms.values.available_div.append(div);
		}
		else {
			ms.values.available_div.append($('<ul>', {
				'class': 'multiselect-suggest',
				'aria-hidden': true
			}));

			$.each(ms.values.available, function (i, item) {
				if (found == 0) {
					preselected = (item.prefix || '') + item.name;
				}
				addAvailable($obj, item);
				found++;
			});
		}

		if (found > 0) {
			$('[aria-live]', $obj).text(
				(available_more
					? sprintf(t('More than %1$d matches for %2$s found'), found, ms.values.search)
					: sprintf(t('%1$d matches for %2$s found'), found, ms.values.search)) +
				', ' + sprintf(t('%1$s preselected, use down,up arrow keys and enter to select'), preselected)
			);
		}
		else {
			$('[aria-live]', $obj).text(ms.options.labels['No matches found']);
		}

		if (available_more) {
			var div = $('<div>', {
					'class': 'multiselect-matches',
					text: ms.options.labels['More matches found...']
				})
					.on('click', function() {
						$('input[type="text"]', $obj)[0].focus({preventScroll:true});
					});

			ms.values.available_div.prepend(div);
		}
	}

	function showAvailable($obj) {
		var ms = $obj.data('multiSelect'),
			$available = ms.values.available_div;

		if ($available.parent().is(document.body)) {
			return;
		}

		$('.multiselect-available').not($available).each(function() {
			hideAvailable($(this).data('obj'));
		});

		$available.data('obj', $obj);

		// Will disconnect this handler in hideAvailable().
		var hide_handler = function() {
			hideAvailable($obj);
		};

		$available.data('hide_handler', hide_handler);

		$obj.parents().add(window).one('scroll', hide_handler);
		$(window).one('resize', hide_handler);

		// For auto-test purposes.
		$available.attr('data-opener', $obj.attr('id'));

		var obj_offset = $obj.offset(),
			obj_padding_y = $obj.outerHeight() - $obj.height(),
			// Subtract 1px for borders of the input and available container to overlap.
			available_top = obj_offset.top + $obj.height() + obj_padding_y / 2 - 1,
			available_left = obj_offset.left,
			available_width = $obj.width(),
			available_max_height = Math.max(50, Math.min(400,
				// Subtract 10px to make available box bottom clearly visible, for better usability.
				$(window).height() + $(window).scrollTop() - available_top - obj_padding_y - 10
			));

		if (objectSize(ms.values.available) > 0) {
			available_width_min = Math.max(available_width, 300);

			// Prevent less than 15% width difference for the available list and the input field.
			if ((available_width_min - available_width) / available_width > .15) {
				available_width = available_width_min;
			}

			available_left = Math.min(available_left, $(window).width() + $(window).scrollLeft() - available_width);
			if (available_left < 0) {
				available_width += available_left;
				available_left = 0;
			}
		}

		$available.css({
			'top': available_top,
			'left': available_left,
			'width': available_width,
			'max-height': available_max_height
		});

		$available.scrollTop(0);

		if (objectSize(ms.values.available) != 0) {
			// Remove selected item selected state.
			$('.selected li.selected', $obj).removeClass('selected');

			// Pre-select first available item.
			if ($('li', $available).length > 0) {
				$('li.suggest-hover', $available).removeClass('suggest-hover');
				$('li:first-child', $available).addClass('suggest-hover');
			}
		}

		$available.appendTo(document.body);
	}

	function hideAvailable($obj) {
		var ms = $obj.data('multiSelect'),
			$available = ms.values.available_div;

		clearSearchTimeout($obj);

		if (!$available.parent().is(document.body)) {
			return;
		}

		$available.detach();

		var hide_handler = $available.data('hide_handler');
		$obj.parents().add(window).off('scroll', hide_handler);
		$(window).off('resize', hide_handler);

		$available
			.removeData(['obj', 'hide_handler'])
			.removeAttr('data-opener');
	}

	function cleanAvailable($obj) {
		var ms = $obj.data('multiSelect');

		hideAvailable($obj);

		ms.values.available = {};
		ms.values.available_div.empty();
	}

	function scrollAvailable($obj) {
		var ms = $obj.data('multiSelect'),
			$available = ms.values.available_div,
			$selected = $available.find('li.suggest-hover');

		if ($selected.length > 0) {
			var	available_height = $available.height(),
				selected_top = 0,
				selected_height = $selected.outerHeight(true);

			if ($('.multiselect-matches', $available)) {
				selected_top += $('.multiselect-matches', $available).outerHeight(true);
			}

			$available.find('li').each(function() {
				var item = $(this);
				if (item.hasClass('suggest-hover')) {
					return false;
				}
				selected_top += item.outerHeight(true);
			});

			if (selected_top < $available.scrollTop()) {
				var prev = $selected.prev();

				$available.scrollTop((prev.length == 0) ? 0 : selected_top);
			}
			else if (selected_top + selected_height > $available.scrollTop() + available_height) {
				$available.scrollTop(selected_top - available_height + selected_height);
			}
		}
		else {
			$available.scrollTop(0);
		}
	}

	function cleanSearchInput($obj) {
		$('input[type="text"]', $obj).val('');

		clearSearchTimeout($obj);
	}

	function cleanSearchHistory($obj) {
		var ms = $obj.data('multiSelect');

		ms.values.search = '';
		ms.values.searches = {};
		ms.values.searching = {};
	}

	function clearSearchTimeout($obj) {
		var ms = $obj.data('multiSelect');

		if (ms.values.searchTimeout !== undefined) {
			clearTimeout(ms.values.searchTimeout);
			delete ms.values.searchTimeout;
		}
	}

	function cleanSearch($obj) {
		cleanAvailable($obj);
		cleanSearchInput($obj);
		cleanSearchHistory($obj);
		updateSearchFieldVisibility($obj);
	}

	function updateSearchFieldVisibility($obj) {
		var ms = $obj.data('multiSelect'),
			visible_now = !$obj.hasClass('search-disabled'),
			visible = !ms.options.disabled
				&& (ms.options.selectedLimit == 0 || $('.selected li', $obj).length < ms.options.selectedLimit);

		if (visible === visible_now) {
			return;
		}

		if (visible) {
			var $label = $('label[for=' + $obj.attr('id') + '_ms]');

			$obj.removeClass('search-disabled')
				.find('input[type="text"]')
				.attr({
					placeholder: ms.options.placeholder,
					'aria-label': ($label.length ? $label.text() + '. ' : '') + ms.options.placeholder,
					readonly: false
				});
		}
		else {
			$obj.addClass('search-disabled')
				.find('input[type="text"]')
				.attr({
					placeholder: '',
					'aria-label': '',
					readonly: true
				});
		}
	}

	function isSearchFieldVisible($obj) {
		return !$obj.hasClass('.search-disabled');
	}

	function getLimit($obj) {
		var ms = $obj.data('multiSelect');

		return (ms.options.limit != 0)
			? ms.options.limit + objectSize(ms.values.selected) + ms.options.excludeids.length + 1
			: null;
	}
});