42839abb2b0bf4f4b34dfc62a52adfffd5079f38
[motion.git] / public / bower_components / angular-ui-select / select.js
1 /*!
2  * ui-select
3  * http://github.com/angular-ui/ui-select
4  * Version: 0.16.0 - 2016-03-23T20:51:56.609Z
5  * License: MIT
6  */
7
8
9 (function () { 
10 "use strict";
11 var KEY = {
12     TAB: 9,
13     ENTER: 13,
14     ESC: 27,
15     SPACE: 32,
16     LEFT: 37,
17     UP: 38,
18     RIGHT: 39,
19     DOWN: 40,
20     SHIFT: 16,
21     CTRL: 17,
22     ALT: 18,
23     PAGE_UP: 33,
24     PAGE_DOWN: 34,
25     HOME: 36,
26     END: 35,
27     BACKSPACE: 8,
28     DELETE: 46,
29     COMMAND: 91,
30
31     MAP: { 91 : "COMMAND", 8 : "BACKSPACE" , 9 : "TAB" , 13 : "ENTER" , 16 : "SHIFT" , 17 : "CTRL" , 18 : "ALT" , 19 : "PAUSEBREAK" , 20 : "CAPSLOCK" , 27 : "ESC" , 32 : "SPACE" , 33 : "PAGE_UP", 34 : "PAGE_DOWN" , 35 : "END" , 36 : "HOME" , 37 : "LEFT" , 38 : "UP" , 39 : "RIGHT" , 40 : "DOWN" , 43 : "+" , 44 : "PRINTSCREEN" , 45 : "INSERT" , 46 : "DELETE", 48 : "0" , 49 : "1" , 50 : "2" , 51 : "3" , 52 : "4" , 53 : "5" , 54 : "6" , 55 : "7" , 56 : "8" , 57 : "9" , 59 : ";", 61 : "=" , 65 : "A" , 66 : "B" , 67 : "C" , 68 : "D" , 69 : "E" , 70 : "F" , 71 : "G" , 72 : "H" , 73 : "I" , 74 : "J" , 75 : "K" , 76 : "L", 77 : "M" , 78 : "N" , 79 : "O" , 80 : "P" , 81 : "Q" , 82 : "R" , 83 : "S" , 84 : "T" , 85 : "U" , 86 : "V" , 87 : "W" , 88 : "X" , 89 : "Y" , 90 : "Z", 96 : "0" , 97 : "1" , 98 : "2" , 99 : "3" , 100 : "4" , 101 : "5" , 102 : "6" , 103 : "7" , 104 : "8" , 105 : "9", 106 : "*" , 107 : "+" , 109 : "-" , 110 : "." , 111 : "/", 112 : "F1" , 113 : "F2" , 114 : "F3" , 115 : "F4" , 116 : "F5" , 117 : "F6" , 118 : "F7" , 119 : "F8" , 120 : "F9" , 121 : "F10" , 122 : "F11" , 123 : "F12", 144 : "NUMLOCK" , 145 : "SCROLLLOCK" , 186 : ";" , 187 : "=" , 188 : "," , 189 : "-" , 190 : "." , 191 : "/" , 192 : "`" , 219 : "[" , 220 : "\\" , 221 : "]" , 222 : "'"
32     },
33
34     isControl: function (e) {
35         var k = e.which;
36         switch (k) {
37         case KEY.COMMAND:
38         case KEY.SHIFT:
39         case KEY.CTRL:
40         case KEY.ALT:
41             return true;
42         }
43
44         if (e.metaKey) return true;
45
46         return false;
47     },
48     isFunctionKey: function (k) {
49         k = k.which ? k.which : k;
50         return k >= 112 && k <= 123;
51     },
52     isVerticalMovement: function (k){
53       return ~[KEY.UP, KEY.DOWN].indexOf(k);
54     },
55     isHorizontalMovement: function (k){
56       return ~[KEY.LEFT,KEY.RIGHT,KEY.BACKSPACE,KEY.DELETE].indexOf(k);
57     },
58     toSeparator: function (k) {
59       var sep = {ENTER:"\n",TAB:"\t",SPACE:" "}[k];
60       if (sep) return sep;
61       // return undefined for special keys other than enter, tab or space.
62       // no way to use them to cut strings.
63       return KEY[k] ? undefined : k;
64     }
65   };
66
67 /**
68  * Add querySelectorAll() to jqLite.
69  *
70  * jqLite find() is limited to lookups by tag name.
71  * TODO This will change with future versions of AngularJS, to be removed when this happens
72  *
73  * See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586
74  * See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598
75  */
76 if (angular.element.prototype.querySelectorAll === undefined) {
77   angular.element.prototype.querySelectorAll = function(selector) {
78     return angular.element(this[0].querySelectorAll(selector));
79   };
80 }
81
82 /**
83  * Add closest() to jqLite.
84  */
85 if (angular.element.prototype.closest === undefined) {
86   angular.element.prototype.closest = function( selector) {
87     var elem = this[0];
88     var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;
89
90     while (elem) {
91       if (matchesSelector.bind(elem)(selector)) {
92         return elem;
93       } else {
94         elem = elem.parentElement;
95       }
96     }
97     return false;
98   };
99 }
100
101 var latestId = 0;
102
103 var uis = angular.module('ui.select', [])
104
105 .constant('uiSelectConfig', {
106   theme: 'bootstrap',
107   searchEnabled: true,
108   sortable: false,
109   placeholder: '', // Empty by default, like HTML tag <select>
110   refreshDelay: 1000, // In milliseconds
111   closeOnSelect: true,
112   skipFocusser: false,
113   dropdownPosition: 'auto',
114   generateId: function() {
115     return latestId++;
116   },
117   appendToBody: false
118 })
119
120 // See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913
121 .service('uiSelectMinErr', function() {
122   var minErr = angular.$$minErr('ui.select');
123   return function() {
124     var error = minErr.apply(this, arguments);
125     var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), '');
126     return new Error(message);
127   };
128 })
129
130 // Recreates old behavior of ng-transclude. Used internally.
131 .directive('uisTranscludeAppend', function () {
132   return {
133     link: function (scope, element, attrs, ctrl, transclude) {
134         transclude(scope, function (clone) {
135           element.append(clone);
136         });
137       }
138     };
139 })
140
141 /**
142  * Highlights text that matches $select.search.
143  *
144  * Taken from AngularUI Bootstrap Typeahead
145  * See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340
146  */
147 .filter('highlight', function() {
148   function escapeRegexp(queryToEscape) {
149     return ('' + queryToEscape).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
150   }
151
152   return function(matchItem, query) {
153     return query && matchItem ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem;
154   };
155 })
156
157 /**
158  * A read-only equivalent of jQuery's offset function: http://api.jquery.com/offset/
159  *
160  * Taken from AngularUI Bootstrap Position:
161  * See https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js#L70
162  */
163 .factory('uisOffset',
164   ['$document', '$window',
165   function ($document, $window) {
166
167   return function(element) {
168     var boundingClientRect = element[0].getBoundingClientRect();
169     return {
170       width: boundingClientRect.width || element.prop('offsetWidth'),
171       height: boundingClientRect.height || element.prop('offsetHeight'),
172       top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
173       left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
174     };
175   };
176 }]);
177
178 uis.directive('uiSelectChoices',
179   ['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile', '$window',
180   function(uiSelectConfig, RepeatParser, uiSelectMinErr, $compile, $window) {
181
182   return {
183     restrict: 'EA',
184     require: '^uiSelect',
185     replace: true,
186     transclude: true,
187     templateUrl: function(tElement) {
188       // Needed so the uiSelect can detect the transcluded content
189       tElement.addClass('ui-select-choices');
190
191       // Gets theme attribute from parent (ui-select)
192       var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
193       return theme + '/choices.tpl.html';
194     },
195
196     compile: function(tElement, tAttrs) {
197
198       if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression.");
199
200       return function link(scope, element, attrs, $select, transcludeFn) {
201
202         // var repeat = RepeatParser.parse(attrs.repeat);
203         var groupByExp = attrs.groupBy;
204         var groupFilterExp = attrs.groupFilter;
205
206         $select.parseRepeatAttr(attrs.repeat, groupByExp, groupFilterExp); //Result ready at $select.parserResult
207
208         $select.disableChoiceExpression = attrs.uiDisableChoice;
209         $select.onHighlightCallback = attrs.onHighlight;
210
211         $select.dropdownPosition = attrs.position ? attrs.position.toLowerCase() : uiSelectConfig.dropdownPosition;
212
213         if(groupByExp) {
214           var groups = element.querySelectorAll('.ui-select-choices-group');
215           if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length);
216           groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression());
217         }
218
219         var choices = element.querySelectorAll('.ui-select-choices-row');
220         if (choices.length !== 1) {
221           throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length);
222         }
223
224         choices.attr('ng-repeat', $select.parserResult.repeatExpression(groupByExp))
225             .attr('ng-if', '$select.open'); //Prevent unnecessary watches when dropdown is closed
226         if ($window.document.addEventListener) {  //crude way to exclude IE8, specifically, which also cannot capture events
227           choices.attr('ng-mouseenter', '$select.setActiveItem('+$select.parserResult.itemName +')')
228               .attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',$select.skipFocusser,$event)');
229         }
230
231         var rowsInner = element.querySelectorAll('.ui-select-choices-row-inner');
232         if (rowsInner.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length);
233         rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat
234         if (!$window.document.addEventListener) {  //crude way to target IE8, specifically, which also cannot capture events - so event bindings must be here
235           rowsInner.attr('ng-mouseenter', '$select.setActiveItem('+$select.parserResult.itemName +')')
236               .attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',$select.skipFocusser,$event)');
237         }
238
239         $compile(element, transcludeFn)(scope); //Passing current transcludeFn to be able to append elements correctly from uisTranscludeAppend
240
241         scope.$watch('$select.search', function(newValue) {
242           if(newValue && !$select.open && $select.multiple) $select.activate(false, true);
243           $select.activeIndex = $select.tagging.isActivated ? -1 : 0;
244           if (!attrs.minimumInputLength || $select.search.length >= attrs.minimumInputLength) {
245             $select.refresh(attrs.refresh);
246           } else {
247             $select.items = [];
248           }
249         });
250
251         attrs.$observe('refreshDelay', function() {
252           // $eval() is needed otherwise we get a string instead of a number
253           var refreshDelay = scope.$eval(attrs.refreshDelay);
254           $select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay;
255         });
256       };
257     }
258   };
259 }]);
260
261 /**
262  * Contains ui-select "intelligence".
263  *
264  * The goal is to limit dependency on the DOM whenever possible and
265  * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
266  */
267 uis.controller('uiSelectCtrl',
268   ['$scope', '$element', '$timeout', '$filter', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector', '$window',
269   function($scope, $element, $timeout, $filter, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector, $window) {
270
271   var ctrl = this;
272
273   var EMPTY_SEARCH = '';
274
275   ctrl.placeholder = uiSelectConfig.placeholder;
276   ctrl.searchEnabled = uiSelectConfig.searchEnabled;
277   ctrl.sortable = uiSelectConfig.sortable;
278   ctrl.refreshDelay = uiSelectConfig.refreshDelay;
279   ctrl.paste = uiSelectConfig.paste;
280
281   ctrl.removeSelected = false; //If selected item(s) should be removed from dropdown list
282   ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function
283   ctrl.skipFocusser = false; //Set to true to avoid returning focus to ctrl when item is selected
284   ctrl.search = EMPTY_SEARCH;
285
286   ctrl.activeIndex = 0; //Dropdown of choices
287   ctrl.items = []; //All available choices
288
289   ctrl.open = false;
290   ctrl.focus = false;
291   ctrl.disabled = false;
292   ctrl.selected = undefined;
293
294   ctrl.dropdownPosition = 'auto';
295
296   ctrl.focusser = undefined; //Reference to input element used to handle focus events
297   ctrl.resetSearchInput = true;
298   ctrl.multiple = undefined; // Initialized inside uiSelect directive link function
299   ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function
300   ctrl.tagging = {isActivated: false, fct: undefined};
301   ctrl.taggingTokens = {isActivated: false, tokens: undefined};
302   ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function
303   ctrl.clickTriggeredSelect = false;
304   ctrl.$filter = $filter;
305
306   // Use $injector to check for $animate and store a reference to it
307   ctrl.$animate = (function () {
308     try {
309       return $injector.get('$animate');
310     } catch (err) {
311       // $animate does not exist
312       return null;
313     }
314   })();
315
316   ctrl.searchInput = $element.querySelectorAll('input.ui-select-search');
317   if (ctrl.searchInput.length !== 1) {
318     throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length);
319   }
320
321   ctrl.isEmpty = function() {
322     return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === '' || (ctrl.multiple && ctrl.selected.length === 0);
323   };
324
325   function _findIndex(collection, predicate, thisArg){
326     if (collection.findIndex){
327       return collection.findIndex(predicate, thisArg);
328     } else {
329       var list = Object(collection);
330       var length = list.length >>> 0;
331       var value;
332
333       for (var i = 0; i < length; i++) {
334         value = list[i];
335         if (predicate.call(thisArg, value, i, list)) {
336           return i;
337         }
338       }
339       return -1;
340     }
341   }
342
343   // Most of the time the user does not want to empty the search input when in typeahead mode
344   function _resetSearchInput() {
345     if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) {
346       ctrl.search = EMPTY_SEARCH;
347       //reset activeIndex
348       if (ctrl.selected && ctrl.items.length && !ctrl.multiple) {
349         ctrl.activeIndex = _findIndex(ctrl.items, function(item){
350           return angular.equals(this, item);
351         }, ctrl.selected);
352       }
353     }
354   }
355
356     function _groupsFilter(groups, groupNames) {
357       var i, j, result = [];
358       for(i = 0; i < groupNames.length ;i++){
359         for(j = 0; j < groups.length ;j++){
360           if(groups[j].name == [groupNames[i]]){
361             result.push(groups[j]);
362           }
363         }
364       }
365       return result;
366     }
367
368   // When the user clicks on ui-select, displays the dropdown list
369   ctrl.activate = function(initSearchValue, avoidReset) {
370     if (!ctrl.disabled  && !ctrl.open) {
371       if(!avoidReset) _resetSearchInput();
372
373       $scope.$broadcast('uis:activate');
374
375       ctrl.open = true;
376
377       ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex;
378
379       // ensure that the index is set to zero for tagging variants
380       // that where first option is auto-selected
381       if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) {
382         ctrl.activeIndex = 0;
383       }
384
385       var container = $element.querySelectorAll('.ui-select-choices-content');
386       if (ctrl.$animate && ctrl.$animate.on && ctrl.$animate.enabled(container[0])) {
387         ctrl.$animate.on('enter', container[0], function (elem, phase) {
388           if (phase === 'close') {
389             // Only focus input after the animation has finished
390             $timeout(function () {
391               ctrl.focusSearchInput(initSearchValue);
392             });
393           }
394         });
395       } else {
396         $timeout(function () {
397           ctrl.focusSearchInput(initSearchValue);
398           if(!ctrl.tagging.isActivated && ctrl.items.length > 1) {
399             _ensureHighlightVisible();
400           }
401         });
402       }
403     }
404   };
405
406   ctrl.focusSearchInput = function (initSearchValue) {
407     ctrl.search = initSearchValue || ctrl.search;
408     ctrl.searchInput[0].focus();
409   };
410
411   ctrl.findGroupByName = function(name) {
412     return ctrl.groups && ctrl.groups.filter(function(group) {
413       return group.name === name;
414     })[0];
415   };
416
417   ctrl.parseRepeatAttr = function(repeatAttr, groupByExp, groupFilterExp) {
418     function updateGroups(items) {
419       var groupFn = $scope.$eval(groupByExp);
420       ctrl.groups = [];
421       angular.forEach(items, function(item) {
422         var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn];
423         var group = ctrl.findGroupByName(groupName);
424         if(group) {
425           group.items.push(item);
426         }
427         else {
428           ctrl.groups.push({name: groupName, items: [item]});
429         }
430       });
431       if(groupFilterExp){
432         var groupFilterFn = $scope.$eval(groupFilterExp);
433         if( angular.isFunction(groupFilterFn)){
434           ctrl.groups = groupFilterFn(ctrl.groups);
435         } else if(angular.isArray(groupFilterFn)){
436           ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn);
437         }
438       }
439       ctrl.items = [];
440       ctrl.groups.forEach(function(group) {
441         ctrl.items = ctrl.items.concat(group.items);
442       });
443     }
444
445     function setPlainItems(items) {
446       ctrl.items = items;
447     }
448
449     ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems;
450
451     ctrl.parserResult = RepeatParser.parse(repeatAttr);
452
453     ctrl.isGrouped = !!groupByExp;
454     ctrl.itemProperty = ctrl.parserResult.itemName;
455
456     //If collection is an Object, convert it to Array
457
458     var originalSource = ctrl.parserResult.source;
459
460     //When an object is used as source, we better create an array and use it as 'source'
461     var createArrayFromObject = function(){
462       var origSrc = originalSource($scope);
463       $scope.$uisSource = Object.keys(origSrc).map(function(v){
464         var result = {};
465         result[ctrl.parserResult.keyName] = v;
466         result.value = origSrc[v];
467         return result;
468       });
469     };
470
471     if (ctrl.parserResult.keyName){ // Check for (key,value) syntax
472       createArrayFromObject();
473       ctrl.parserResult.source = $parse('$uisSource' + ctrl.parserResult.filters);
474       $scope.$watch(originalSource, function(newVal, oldVal){
475         if (newVal !== oldVal) createArrayFromObject();
476       }, true);
477     }
478
479     ctrl.refreshItems = function (data){
480       data = data || ctrl.parserResult.source($scope);
481       var selectedItems = ctrl.selected;
482       //TODO should implement for single mode removeSelected
483       if (ctrl.isEmpty() || (angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.removeSelected) {
484         ctrl.setItemsFn(data);
485       }else{
486         if ( data !== undefined ) {
487           var filteredItems = data.filter(function(i) {
488             return selectedItems.every(function(selectedItem) {
489               return !angular.equals(i, selectedItem);
490             });
491           });
492           ctrl.setItemsFn(filteredItems);
493         }
494       }
495       if (ctrl.dropdownPosition === 'auto' || ctrl.dropdownPosition === 'up'){
496         $scope.calculateDropdownPos();
497       }
498     };
499
500     // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259
501     $scope.$watchCollection(ctrl.parserResult.source, function(items) {
502       if (items === undefined || items === null) {
503         // If the user specifies undefined or null => reset the collection
504         // Special case: items can be undefined if the user did not initialized the collection on the scope
505         // i.e $scope.addresses = [] is missing
506         ctrl.items = [];
507       } else {
508         if (!angular.isArray(items)) {
509           throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
510         } else {
511           //Remove already selected items (ex: while searching)
512           //TODO Should add a test
513           ctrl.refreshItems(items);
514           ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
515         }
516       }
517     });
518
519   };
520
521   var _refreshDelayPromise;
522
523   /**
524    * Typeahead mode: lets the user refresh the collection using his own function.
525    *
526    * See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
527    */
528   ctrl.refresh = function(refreshAttr) {
529     if (refreshAttr !== undefined) {
530
531       // Debounce
532       // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155
533       // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177
534       if (_refreshDelayPromise) {
535         $timeout.cancel(_refreshDelayPromise);
536       }
537       _refreshDelayPromise = $timeout(function() {
538         $scope.$eval(refreshAttr);
539       }, ctrl.refreshDelay);
540     }
541   };
542
543   ctrl.isActive = function(itemScope) {
544     if ( !ctrl.open ) {
545       return false;
546     }
547     var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
548     var isActive =  itemIndex == ctrl.activeIndex;
549
550     if ( !isActive || ( itemIndex < 0 && ctrl.taggingLabel !== false ) ||( itemIndex < 0 && ctrl.taggingLabel === false) ) {
551       return false;
552     }
553
554     if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) {
555       itemScope.$eval(ctrl.onHighlightCallback);
556     }
557
558     return isActive;
559   };
560
561   ctrl.isDisabled = function(itemScope) {
562
563     if (!ctrl.open) return;
564
565     var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
566     var isDisabled = false;
567     var item;
568
569     if (itemIndex >= 0 && !angular.isUndefined(ctrl.disableChoiceExpression)) {
570       item = ctrl.items[itemIndex];
571       isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); // force the boolean value
572       item._uiSelectChoiceDisabled = isDisabled; // store this for later reference
573     }
574
575     return isDisabled;
576   };
577
578
579   // When the user selects an item with ENTER or clicks the dropdown
580   ctrl.select = function(item, skipFocusser, $event) {
581     if (item === undefined || !item._uiSelectChoiceDisabled) {
582
583       if ( ! ctrl.items && ! ctrl.search && ! ctrl.tagging.isActivated) return;
584
585       if (!item || !item._uiSelectChoiceDisabled) {
586         if(ctrl.tagging.isActivated) {
587           // if taggingLabel is disabled, we pull from ctrl.search val
588           if ( ctrl.taggingLabel === false ) {
589             if ( ctrl.activeIndex < 0 ) {
590               item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search;
591               if (!item || angular.equals( ctrl.items[0], item ) ) {
592                 return;
593               }
594             } else {
595               // keyboard nav happened first, user selected from dropdown
596               item = ctrl.items[ctrl.activeIndex];
597             }
598           } else {
599             // tagging always operates at index zero, taggingLabel === false pushes
600             // the ctrl.search value without having it injected
601             if ( ctrl.activeIndex === 0 ) {
602               // ctrl.tagging pushes items to ctrl.items, so we only have empty val
603               // for `item` if it is a detected duplicate
604               if ( item === undefined ) return;
605
606               // create new item on the fly if we don't already have one;
607               // use tagging function if we have one
608               if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) {
609                 item = ctrl.tagging.fct(item);
610                 if (!item) return;
611               // if item type is 'string', apply the tagging label
612               } else if ( typeof item === 'string' ) {
613                 // trim the trailing space
614                 item = item.replace(ctrl.taggingLabel,'').trim();
615               }
616             }
617           }
618           // search ctrl.selected for dupes potentially caused by tagging and return early if found
619           if ( ctrl.selected && angular.isArray(ctrl.selected) && ctrl.selected.filter( function (selection) { return angular.equals(selection, item); }).length > 0 ) {
620             ctrl.close(skipFocusser);
621             return;
622           }
623         }
624
625         $scope.$broadcast('uis:select', item);
626
627         var locals = {};
628         locals[ctrl.parserResult.itemName] = item;
629
630         $timeout(function(){
631           ctrl.onSelectCallback($scope, {
632             $item: item,
633             $model: ctrl.parserResult.modelMapper($scope, locals)
634           });
635         });
636
637         if (ctrl.closeOnSelect) {
638           ctrl.close(skipFocusser);
639         }
640         if ($event && $event.type === 'click') {
641           ctrl.clickTriggeredSelect = true;
642         }
643       }
644     }
645   };
646
647   // Closes the dropdown
648   ctrl.close = function(skipFocusser) {
649     if (!ctrl.open) return;
650     if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched();
651     _resetSearchInput();
652     ctrl.open = false;
653
654     $scope.$broadcast('uis:close', skipFocusser);
655
656   };
657
658   ctrl.setFocus = function(){
659     if (!ctrl.focus) ctrl.focusInput[0].focus();
660   };
661
662   ctrl.clear = function($event) {
663     ctrl.select(undefined);
664     $event.stopPropagation();
665     $timeout(function() {
666       ctrl.focusser[0].focus();
667     }, 0, false);
668   };
669
670   // Toggle dropdown
671   ctrl.toggle = function(e) {
672     if (ctrl.open) {
673       ctrl.close();
674       e.preventDefault();
675       e.stopPropagation();
676     } else {
677       ctrl.activate();
678     }
679   };
680
681   ctrl.isLocked = function(itemScope, itemIndex) {
682       var isLocked, item = ctrl.selected[itemIndex];
683
684       if (item && !angular.isUndefined(ctrl.lockChoiceExpression)) {
685           isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); // force the boolean value
686           item._uiSelectChoiceLocked = isLocked; // store this for later reference
687       }
688
689       return isLocked;
690   };
691
692   var sizeWatch = null;
693   ctrl.sizeSearchInput = function() {
694
695     var input = ctrl.searchInput[0],
696         container = ctrl.searchInput.parent().parent()[0],
697         calculateContainerWidth = function() {
698           // Return the container width only if the search input is visible
699           return container.clientWidth * !!input.offsetParent;
700         },
701         updateIfVisible = function(containerWidth) {
702           if (containerWidth === 0) {
703             return false;
704           }
705           var inputWidth = containerWidth - input.offsetLeft - 10;
706           if (inputWidth < 50) inputWidth = containerWidth;
707           ctrl.searchInput.css('width', inputWidth+'px');
708           return true;
709         };
710
711     ctrl.searchInput.css('width', '10px');
712     $timeout(function() { //Give tags time to render correctly
713       if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) {
714         sizeWatch = $scope.$watch(calculateContainerWidth, function(containerWidth) {
715           if (updateIfVisible(containerWidth)) {
716             sizeWatch();
717             sizeWatch = null;
718           }
719         });
720       }
721     });
722   };
723
724   function _handleDropDownSelection(key) {
725     var processed = true;
726     switch (key) {
727       case KEY.DOWN:
728         if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
729         else if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; }
730         break;
731       case KEY.UP:
732         if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
733         else if (ctrl.activeIndex > 0 || (ctrl.search.length === 0 && ctrl.tagging.isActivated && ctrl.activeIndex > -1)) { ctrl.activeIndex--; }
734         break;
735       case KEY.TAB:
736         if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true);
737         break;
738       case KEY.ENTER:
739         if(ctrl.open && (ctrl.tagging.isActivated || ctrl.activeIndex >= 0)){
740           ctrl.select(ctrl.items[ctrl.activeIndex], ctrl.skipFocusser); // Make sure at least one dropdown item is highlighted before adding if not in tagging mode
741         } else {
742           ctrl.activate(false, true); //In case its the search input in 'multiple' mode
743         }
744         break;
745       case KEY.ESC:
746         ctrl.close();
747         break;
748       default:
749         processed = false;
750     }
751     return processed;
752   }
753
754   // Bind to keyboard shortcuts
755   ctrl.searchInput.on('keydown', function(e) {
756
757     var key = e.which;
758
759     if (~[KEY.ENTER,KEY.ESC].indexOf(key)){
760       e.preventDefault();
761       e.stopPropagation();
762     }
763
764     // if(~[KEY.ESC,KEY.TAB].indexOf(key)){
765     //   //TODO: SEGURO?
766     //   ctrl.close();
767     // }
768
769     $scope.$apply(function() {
770
771       var tagged = false;
772
773       if (ctrl.items.length > 0 || ctrl.tagging.isActivated) {
774         _handleDropDownSelection(key);
775         if ( ctrl.taggingTokens.isActivated ) {
776           for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
777             if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) {
778               // make sure there is a new value to push via tagging
779               if ( ctrl.search.length > 0 ) {
780                 tagged = true;
781               }
782             }
783           }
784           if ( tagged ) {
785             $timeout(function() {
786               ctrl.searchInput.triggerHandler('tagged');
787               var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim();
788               if ( ctrl.tagging.fct ) {
789                 newItem = ctrl.tagging.fct( newItem );
790               }
791               if (newItem) ctrl.select(newItem, true);
792             });
793           }
794         }
795       }
796
797     });
798
799     if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){
800       _ensureHighlightVisible();
801     }
802
803     if (key === KEY.ENTER || key === KEY.ESC) {
804       e.preventDefault();
805       e.stopPropagation();
806     }
807
808   });
809
810   ctrl.searchInput.on('paste', function (e) {
811     var data;
812
813     if (window.clipboardData && window.clipboardData.getData) { // IE
814       data = window.clipboardData.getData('Text');
815     } else {
816       data = (e.originalEvent || e).clipboardData.getData('text/plain');
817     }
818
819     // Prepend the current input field text to the paste buffer.
820     data = ctrl.search + data;
821
822     if (data && data.length > 0) {
823       // If tagging try to split by tokens and add items
824       if (ctrl.taggingTokens.isActivated) {
825         var separator = KEY.toSeparator(ctrl.taggingTokens.tokens[0]);
826         var items = data.split(separator || ctrl.taggingTokens.tokens[0]); // split by first token only
827         if (items && items.length > 0) {
828         var oldsearch = ctrl.search;
829           angular.forEach(items, function (item) {
830             var newItem = ctrl.tagging.fct ? ctrl.tagging.fct(item) : item;
831             if (newItem) {
832               ctrl.select(newItem, true);
833             }
834           });
835           ctrl.search = oldsearch || EMPTY_SEARCH;
836           e.preventDefault();
837           e.stopPropagation();
838         }
839       } else if (ctrl.paste) {
840         ctrl.paste(data);
841         ctrl.search = EMPTY_SEARCH;
842         e.preventDefault();
843         e.stopPropagation();
844       }
845     }
846   });
847
848   ctrl.searchInput.on('tagged', function() {
849     $timeout(function() {
850       _resetSearchInput();
851     });
852   });
853
854   // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431
855   function _ensureHighlightVisible() {
856     var container = $element.querySelectorAll('.ui-select-choices-content');
857     var choices = container.querySelectorAll('.ui-select-choices-row');
858     if (choices.length < 1) {
859       throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length);
860     }
861
862     if (ctrl.activeIndex < 0) {
863       return;
864     }
865
866     var highlighted = choices[ctrl.activeIndex];
867     var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
868     var height = container[0].offsetHeight;
869
870     if (posY > height) {
871       container[0].scrollTop += posY - height;
872     } else if (posY < highlighted.clientHeight) {
873       if (ctrl.isGrouped && ctrl.activeIndex === 0)
874         container[0].scrollTop = 0; //To make group header visible when going all the way up
875       else
876         container[0].scrollTop -= highlighted.clientHeight - posY;
877     }
878   }
879
880   $scope.$on('$destroy', function() {
881     ctrl.searchInput.off('keyup keydown tagged blur paste');
882   });
883
884   angular.element($window).bind('resize', function() {
885     ctrl.sizeSearchInput();
886   });
887
888 }]);
889
890 uis.directive('uiSelect',
891   ['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout',
892   function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) {
893
894   return {
895     restrict: 'EA',
896     templateUrl: function(tElement, tAttrs) {
897       var theme = tAttrs.theme || uiSelectConfig.theme;
898       return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html');
899     },
900     replace: true,
901     transclude: true,
902     require: ['uiSelect', '^ngModel'],
903     scope: true,
904
905     controller: 'uiSelectCtrl',
906     controllerAs: '$select',
907     compile: function(tElement, tAttrs) {
908
909       // Allow setting ngClass on uiSelect
910       var match = /{(.*)}\s*{(.*)}/.exec(tAttrs.ngClass);
911       if(match) {
912         var combined = '{'+ match[1] +', '+ match[2] +'}';
913         tAttrs.ngClass = combined;
914         tElement.attr('ng-class', combined);
915       }
916
917       //Multiple or Single depending if multiple attribute presence
918       if (angular.isDefined(tAttrs.multiple))
919         tElement.append('<ui-select-multiple/>').removeAttr('multiple');
920       else
921         tElement.append('<ui-select-single/>');
922
923       if (tAttrs.inputId)
924         tElement.querySelectorAll('input.ui-select-search')[0].id = tAttrs.inputId;
925
926       return function(scope, element, attrs, ctrls, transcludeFn) {
927
928         var $select = ctrls[0];
929         var ngModel = ctrls[1];
930
931         $select.generatedId = uiSelectConfig.generateId();
932         $select.baseTitle = attrs.title || 'Select box';
933         $select.focusserTitle = $select.baseTitle + ' focus';
934         $select.focusserId = 'focusser-' + $select.generatedId;
935
936         $select.closeOnSelect = function() {
937           if (angular.isDefined(attrs.closeOnSelect)) {
938             return $parse(attrs.closeOnSelect)();
939           } else {
940             return uiSelectConfig.closeOnSelect;
941           }
942         }();
943
944         scope.$watch('skipFocusser', function() {
945             var skipFocusser = scope.$eval(attrs.skipFocusser);
946             $select.skipFocusser = skipFocusser !== undefined ? skipFocusser : uiSelectConfig.skipFocusser;
947         });
948
949         $select.onSelectCallback = $parse(attrs.onSelect);
950         $select.onRemoveCallback = $parse(attrs.onRemove);
951
952         //Limit the number of selections allowed
953         $select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined;
954
955         //Set reference to ngModel from uiSelectCtrl
956         $select.ngModel = ngModel;
957
958         $select.choiceGrouped = function(group){
959           return $select.isGrouped && group && group.name;
960         };
961
962         if(attrs.tabindex){
963           attrs.$observe('tabindex', function(value) {
964             $select.focusInput.attr('tabindex', value);
965             element.removeAttr('tabindex');
966           });
967         }
968
969         scope.$watch('searchEnabled', function() {
970             var searchEnabled = scope.$eval(attrs.searchEnabled);
971             $select.searchEnabled = searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled;
972         });
973
974         scope.$watch('sortable', function() {
975             var sortable = scope.$eval(attrs.sortable);
976             $select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable;
977         });
978
979         attrs.$observe('disabled', function() {
980           // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string
981           $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false;
982         });
983
984         attrs.$observe('resetSearchInput', function() {
985           // $eval() is needed otherwise we get a string instead of a boolean
986           var resetSearchInput = scope.$eval(attrs.resetSearchInput);
987           $select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true;
988         });
989
990         attrs.$observe('paste', function() {
991           $select.paste = scope.$eval(attrs.paste);
992         });
993
994         attrs.$observe('tagging', function() {
995           if(attrs.tagging !== undefined)
996           {
997             // $eval() is needed otherwise we get a string instead of a boolean
998             var taggingEval = scope.$eval(attrs.tagging);
999             $select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined};
1000           }
1001           else
1002           {
1003             $select.tagging = {isActivated: false, fct: undefined};
1004           }
1005         });
1006
1007         attrs.$observe('taggingLabel', function() {
1008           if(attrs.tagging !== undefined )
1009           {
1010             // check eval for FALSE, in this case, we disable the labels
1011             // associated with tagging
1012             if ( attrs.taggingLabel === 'false' ) {
1013               $select.taggingLabel = false;
1014             }
1015             else
1016             {
1017               $select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)';
1018             }
1019           }
1020         });
1021
1022         attrs.$observe('taggingTokens', function() {
1023           if (attrs.tagging !== undefined) {
1024             var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER'];
1025             $select.taggingTokens = {isActivated: true, tokens: tokens };
1026           }
1027         });
1028
1029         //Automatically gets focus when loaded
1030         if (angular.isDefined(attrs.autofocus)){
1031           $timeout(function(){
1032             $select.setFocus();
1033           });
1034         }
1035
1036         //Gets focus based on scope event name (e.g. focus-on='SomeEventName')
1037         if (angular.isDefined(attrs.focusOn)){
1038           scope.$on(attrs.focusOn, function() {
1039               $timeout(function(){
1040                 $select.setFocus();
1041               });
1042           });
1043         }
1044
1045         function onDocumentClick(e) {
1046           if (!$select.open) return; //Skip it if dropdown is close
1047
1048           var contains = false;
1049
1050           if (window.jQuery) {
1051             // Firefox 3.6 does not support element.contains()
1052             // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
1053             contains = window.jQuery.contains(element[0], e.target);
1054           } else {
1055             contains = element[0].contains(e.target);
1056           }
1057
1058           if (!contains && !$select.clickTriggeredSelect) {
1059             var skipFocusser;
1060             if (!$select.skipFocusser) {
1061               //Will lose focus only with certain targets
1062               var focusableControls = ['input','button','textarea','select'];
1063               var targetController = angular.element(e.target).controller('uiSelect'); //To check if target is other ui-select
1064               skipFocusser = targetController && targetController !== $select; //To check if target is other ui-select
1065               if (!skipFocusser) skipFocusser =  ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea
1066             } else {
1067               skipFocusser = true;
1068             }
1069             $select.close(skipFocusser);
1070             scope.$digest();
1071           }
1072           $select.clickTriggeredSelect = false;
1073         }
1074
1075         // See Click everywhere but here event http://stackoverflow.com/questions/12931369
1076         $document.on('click', onDocumentClick);
1077
1078         scope.$on('$destroy', function() {
1079           $document.off('click', onDocumentClick);
1080         });
1081
1082         // Move transcluded elements to their correct position in main template
1083         transcludeFn(scope, function(clone) {
1084           // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html
1085
1086           // One day jqLite will be replaced by jQuery and we will be able to write:
1087           // var transcludedElement = clone.filter('.my-class')
1088           // instead of creating a hackish DOM element:
1089           var transcluded = angular.element('<div>').append(clone);
1090
1091           var transcludedMatch = transcluded.querySelectorAll('.ui-select-match');
1092           transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr
1093           transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes
1094           if (transcludedMatch.length !== 1) {
1095             throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length);
1096           }
1097           element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch);
1098
1099           var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices');
1100           transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr
1101           transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes
1102           if (transcludedChoices.length !== 1) {
1103             throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length);
1104           }
1105           element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices);
1106         });
1107
1108         // Support for appending the select field to the body when its open
1109         var appendToBody = scope.$eval(attrs.appendToBody);
1110         if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) {
1111           scope.$watch('$select.open', function(isOpen) {
1112             if (isOpen) {
1113               positionDropdown();
1114             } else {
1115               resetDropdown();
1116             }
1117           });
1118
1119           // Move the dropdown back to its original location when the scope is destroyed. Otherwise
1120           // it might stick around when the user routes away or the select field is otherwise removed
1121           scope.$on('$destroy', function() {
1122             resetDropdown();
1123           });
1124         }
1125
1126         // Hold on to a reference to the .ui-select-container element for appendToBody support
1127         var placeholder = null,
1128             originalWidth = '';
1129
1130         function positionDropdown() {
1131           // Remember the absolute position of the element
1132           var offset = uisOffset(element);
1133
1134           // Clone the element into a placeholder element to take its original place in the DOM
1135           placeholder = angular.element('<div class="ui-select-placeholder"></div>');
1136           placeholder[0].style.width = offset.width + 'px';
1137           placeholder[0].style.height = offset.height + 'px';
1138           element.after(placeholder);
1139
1140           // Remember the original value of the element width inline style, so it can be restored
1141           // when the dropdown is closed
1142           originalWidth = element[0].style.width;
1143
1144           // Now move the actual dropdown element to the end of the body
1145           $document.find('body').append(element);
1146
1147           element[0].style.position = 'absolute';
1148           element[0].style.left = offset.left + 'px';
1149           element[0].style.top = offset.top + 'px';
1150           element[0].style.width = offset.width + 'px';
1151         }
1152
1153         function resetDropdown() {
1154           if (placeholder === null) {
1155             // The dropdown has not actually been display yet, so there's nothing to reset
1156             return;
1157           }
1158
1159           // Move the dropdown element back to its original location in the DOM
1160           placeholder.replaceWith(element);
1161           placeholder = null;
1162
1163           element[0].style.position = '';
1164           element[0].style.left = '';
1165           element[0].style.top = '';
1166           element[0].style.width = originalWidth;
1167
1168           // Set focus back on to the moved element
1169           $select.setFocus();
1170         }
1171
1172         // Hold on to a reference to the .ui-select-dropdown element for direction support.
1173         var dropdown = null,
1174             directionUpClassName = 'direction-up';
1175
1176         // Support changing the direction of the dropdown if there isn't enough space to render it.
1177         scope.$watch('$select.open', function() {
1178
1179           if ($select.dropdownPosition === 'auto' || $select.dropdownPosition === 'up'){
1180             scope.calculateDropdownPos();
1181           }
1182
1183         });
1184
1185         var setDropdownPosUp = function(offset, offsetDropdown){
1186
1187           offset = offset || uisOffset(element);
1188           offsetDropdown = offsetDropdown || uisOffset(dropdown);
1189
1190           dropdown[0].style.position = 'absolute';
1191           dropdown[0].style.top = (offsetDropdown.height * -1) + 'px';
1192           element.addClass(directionUpClassName);
1193
1194         };
1195
1196         var setDropdownPosDown = function(offset, offsetDropdown){
1197
1198           element.removeClass(directionUpClassName);
1199
1200           offset = offset || uisOffset(element);
1201           offsetDropdown = offsetDropdown || uisOffset(dropdown);
1202
1203           dropdown[0].style.position = '';
1204           dropdown[0].style.top = '';
1205
1206         };
1207
1208         scope.calculateDropdownPos = function(){
1209
1210           if ($select.open) {
1211             dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown');
1212             if (dropdown.length === 0) {
1213               return;
1214             }
1215
1216             // Hide the dropdown so there is no flicker until $timeout is done executing.
1217             dropdown[0].style.opacity = 0;
1218
1219             // Delay positioning the dropdown until all choices have been added so its height is correct.
1220             $timeout(function(){
1221
1222               if ($select.dropdownPosition === 'up'){
1223                   //Go UP
1224                   setDropdownPosUp();
1225
1226               }else{ //AUTO
1227
1228                 element.removeClass(directionUpClassName);
1229
1230                 var offset = uisOffset(element);
1231                 var offsetDropdown = uisOffset(dropdown);
1232
1233                 //https://code.google.com/p/chromium/issues/detail?id=342307#c4
1234                 var scrollTop = $document[0].documentElement.scrollTop || $document[0].body.scrollTop; //To make it cross browser (blink, webkit, IE, Firefox).
1235
1236                 // Determine if the direction of the dropdown needs to be changed.
1237                 if (offset.top + offset.height + offsetDropdown.height > scrollTop + $document[0].documentElement.clientHeight) {
1238                   //Go UP
1239                   setDropdownPosUp(offset, offsetDropdown);
1240                 }else{
1241                   //Go DOWN
1242                   setDropdownPosDown(offset, offsetDropdown);
1243                 }
1244
1245               }
1246
1247               // Display the dropdown once it has been positioned.
1248               dropdown[0].style.opacity = 1;
1249             });
1250           } else {
1251               if (dropdown === null || dropdown.length === 0) {
1252                 return;
1253               }
1254
1255               // Reset the position of the dropdown.
1256               dropdown[0].style.position = '';
1257               dropdown[0].style.top = '';
1258               element.removeClass(directionUpClassName);
1259           }
1260         };
1261       };
1262     }
1263   };
1264 }]);
1265
1266 uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) {
1267   return {
1268     restrict: 'EA',
1269     require: '^uiSelect',
1270     replace: true,
1271     transclude: true,
1272     templateUrl: function(tElement) {
1273       // Needed so the uiSelect can detect the transcluded content
1274       tElement.addClass('ui-select-match');
1275
1276       // Gets theme attribute from parent (ui-select)
1277       var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
1278       var multi = tElement.parent().attr('multiple');
1279       return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html');
1280     },
1281     link: function(scope, element, attrs, $select) {
1282       $select.lockChoiceExpression = attrs.uiLockChoice;
1283       attrs.$observe('placeholder', function(placeholder) {
1284         $select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
1285       });
1286
1287       function setAllowClear(allow) {
1288         $select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
1289       }
1290
1291       attrs.$observe('allowClear', setAllowClear);
1292       setAllowClear(attrs.allowClear);
1293
1294       if($select.multiple){
1295         $select.sizeSearchInput();
1296       }
1297
1298     }
1299   };
1300 }]);
1301
1302 uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) {
1303   return {
1304     restrict: 'EA',
1305     require: ['^uiSelect', '^ngModel'],
1306
1307     controller: ['$scope','$timeout', function($scope, $timeout){
1308
1309       var ctrl = this,
1310           $select = $scope.$select,
1311           ngModel;
1312
1313       if (angular.isUndefined($select.selected))
1314         $select.selected = [];
1315
1316       //Wait for link fn to inject it
1317       $scope.$evalAsync(function(){ ngModel = $scope.ngModel; });
1318
1319       ctrl.activeMatchIndex = -1;
1320
1321       ctrl.updateModel = function(){
1322         ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes
1323         ctrl.refreshComponent();
1324       };
1325
1326       ctrl.refreshComponent = function(){
1327         //Remove already selected items
1328         //e.g. When user clicks on a selection, the selected array changes and
1329         //the dropdown should remove that item
1330         $select.refreshItems();
1331         $select.sizeSearchInput();
1332       };
1333
1334       // Remove item from multiple select
1335       ctrl.removeChoice = function(index){
1336
1337         var removedChoice = $select.selected[index];
1338
1339         // if the choice is locked, can't remove it
1340         if(removedChoice._uiSelectChoiceLocked) return;
1341
1342         var locals = {};
1343         locals[$select.parserResult.itemName] = removedChoice;
1344
1345         $select.selected.splice(index, 1);
1346         ctrl.activeMatchIndex = -1;
1347         $select.sizeSearchInput();
1348
1349         // Give some time for scope propagation.
1350         $timeout(function(){
1351           $select.onRemoveCallback($scope, {
1352             $item: removedChoice,
1353             $model: $select.parserResult.modelMapper($scope, locals)
1354           });
1355         });
1356
1357         ctrl.updateModel();
1358
1359       };
1360
1361       ctrl.getPlaceholder = function(){
1362         //Refactor single?
1363         if($select.selected && $select.selected.length) return;
1364         return $select.placeholder;
1365       };
1366
1367
1368     }],
1369     controllerAs: '$selectMultiple',
1370
1371     link: function(scope, element, attrs, ctrls) {
1372
1373       var $select = ctrls[0];
1374       var ngModel = scope.ngModel = ctrls[1];
1375       var $selectMultiple = scope.$selectMultiple;
1376
1377       //$select.selected = raw selected objects (ignoring any property binding)
1378
1379       $select.multiple = true;
1380       $select.removeSelected = true;
1381
1382       //Input that will handle focus
1383       $select.focusInput = $select.searchInput;
1384
1385       //Properly check for empty if set to multiple
1386       ngModel.$isEmpty = function(value) {
1387         return !value || value.length === 0;
1388       };
1389
1390       //From view --> model
1391       ngModel.$parsers.unshift(function () {
1392         var locals = {},
1393             result,
1394             resultMultiple = [];
1395         for (var j = $select.selected.length - 1; j >= 0; j--) {
1396           locals = {};
1397           locals[$select.parserResult.itemName] = $select.selected[j];
1398           result = $select.parserResult.modelMapper(scope, locals);
1399           resultMultiple.unshift(result);
1400         }
1401         return resultMultiple;
1402       });
1403
1404       // From model --> view
1405       ngModel.$formatters.unshift(function (inputValue) {
1406         var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
1407             locals = {},
1408             result;
1409         if (!data) return inputValue;
1410         var resultMultiple = [];
1411         var checkFnMultiple = function(list, value){
1412           if (!list || !list.length) return;
1413           for (var p = list.length - 1; p >= 0; p--) {
1414             locals[$select.parserResult.itemName] = list[p];
1415             result = $select.parserResult.modelMapper(scope, locals);
1416             if($select.parserResult.trackByExp){
1417                 var propsItemNameMatches = /(\w*)\./.exec($select.parserResult.trackByExp);
1418                 var matches = /\.([^\s]+)/.exec($select.parserResult.trackByExp);
1419                 if(propsItemNameMatches && propsItemNameMatches.length > 0 && propsItemNameMatches[1] == $select.parserResult.itemName){
1420                   if(matches && matches.length>0 && result[matches[1]] == value[matches[1]]){
1421                       resultMultiple.unshift(list[p]);
1422                       return true;
1423                   }
1424                 }
1425             }
1426             if (angular.equals(result,value)){
1427               resultMultiple.unshift(list[p]);
1428               return true;
1429             }
1430           }
1431           return false;
1432         };
1433         if (!inputValue) return resultMultiple; //If ngModel was undefined
1434         for (var k = inputValue.length - 1; k >= 0; k--) {
1435           //Check model array of currently selected items
1436           if (!checkFnMultiple($select.selected, inputValue[k])){
1437             //Check model array of all items available
1438             if (!checkFnMultiple(data, inputValue[k])){
1439               //If not found on previous lists, just add it directly to resultMultiple
1440               resultMultiple.unshift(inputValue[k]);
1441             }
1442           }
1443         }
1444         return resultMultiple;
1445       });
1446
1447       //Watch for external model changes
1448       scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) {
1449         if (oldValue != newValue){
1450           ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
1451           $selectMultiple.refreshComponent();
1452         }
1453       });
1454
1455       ngModel.$render = function() {
1456         // Make sure that model value is array
1457         if(!angular.isArray(ngModel.$viewValue)){
1458           // Have tolerance for null or undefined values
1459           if(angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue === null){
1460             $select.selected = [];
1461           } else {
1462             throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue);
1463           }
1464         }
1465         $select.selected = ngModel.$viewValue;
1466         $selectMultiple.refreshComponent();
1467         scope.$evalAsync(); //To force $digest
1468       };
1469
1470       scope.$on('uis:select', function (event, item) {
1471         if($select.selected.length >= $select.limit) {
1472           return;
1473         }
1474         $select.selected.push(item);
1475         $selectMultiple.updateModel();
1476       });
1477
1478       scope.$on('uis:activate', function () {
1479         $selectMultiple.activeMatchIndex = -1;
1480       });
1481
1482       scope.$watch('$select.disabled', function(newValue, oldValue) {
1483         // As the search input field may now become visible, it may be necessary to recompute its size
1484         if (oldValue && !newValue) $select.sizeSearchInput();
1485       });
1486
1487       $select.searchInput.on('keydown', function(e) {
1488         var key = e.which;
1489         scope.$apply(function() {
1490           var processed = false;
1491           // var tagged = false; //Checkme
1492           if(KEY.isHorizontalMovement(key)){
1493             processed = _handleMatchSelection(key);
1494           }
1495           if (processed  && key != KEY.TAB) {
1496             //TODO Check si el tab selecciona aun correctamente
1497             //Crear test
1498             e.preventDefault();
1499             e.stopPropagation();
1500           }
1501         });
1502       });
1503       function _getCaretPosition(el) {
1504         if(angular.isNumber(el.selectionStart)) return el.selectionStart;
1505         // selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise
1506         else return el.value.length;
1507       }
1508       // Handles selected options in "multiple" mode
1509       function _handleMatchSelection(key){
1510         var caretPosition = _getCaretPosition($select.searchInput[0]),
1511             length = $select.selected.length,
1512             // none  = -1,
1513             first = 0,
1514             last  = length-1,
1515             curr  = $selectMultiple.activeMatchIndex,
1516             next  = $selectMultiple.activeMatchIndex+1,
1517             prev  = $selectMultiple.activeMatchIndex-1,
1518             newIndex = curr;
1519
1520         if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false;
1521
1522         $select.close();
1523
1524         function getNewActiveMatchIndex(){
1525           switch(key){
1526             case KEY.LEFT:
1527               // Select previous/first item
1528               if(~$selectMultiple.activeMatchIndex) return prev;
1529               // Select last item
1530               else return last;
1531               break;
1532             case KEY.RIGHT:
1533               // Open drop-down
1534               if(!~$selectMultiple.activeMatchIndex || curr === last){
1535                 $select.activate();
1536                 return false;
1537               }
1538               // Select next/last item
1539               else return next;
1540               break;
1541             case KEY.BACKSPACE:
1542               // Remove selected item and select previous/first
1543               if(~$selectMultiple.activeMatchIndex){
1544                 $selectMultiple.removeChoice(curr);
1545                 return prev;
1546               }
1547               // Select last item
1548               else return last;
1549               break;
1550             case KEY.DELETE:
1551               // Remove selected item and select next item
1552               if(~$selectMultiple.activeMatchIndex){
1553                 $selectMultiple.removeChoice($selectMultiple.activeMatchIndex);
1554                 return curr;
1555               }
1556               else return false;
1557           }
1558         }
1559
1560         newIndex = getNewActiveMatchIndex();
1561
1562         if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1;
1563         else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
1564
1565         return true;
1566       }
1567
1568       $select.searchInput.on('keyup', function(e) {
1569
1570         if ( ! KEY.isVerticalMovement(e.which) ) {
1571           scope.$evalAsync( function () {
1572             $select.activeIndex = $select.taggingLabel === false ? -1 : 0;
1573           });
1574         }
1575         // Push a "create new" item into array if there is a search string
1576         if ( $select.tagging.isActivated && $select.search.length > 0 ) {
1577
1578           // return early with these keys
1579           if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) {
1580             return;
1581           }
1582           // always reset the activeIndex to the first item when tagging
1583           $select.activeIndex = $select.taggingLabel === false ? -1 : 0;
1584           // taggingLabel === false bypasses all of this
1585           if ($select.taggingLabel === false) return;
1586
1587           var items = angular.copy( $select.items );
1588           var stashArr = angular.copy( $select.items );
1589           var newItem;
1590           var item;
1591           var hasTag = false;
1592           var dupeIndex = -1;
1593           var tagItems;
1594           var tagItem;
1595
1596           // case for object tagging via transform `$select.tagging.fct` function
1597           if ( $select.tagging.fct !== undefined) {
1598             tagItems = $select.$filter('filter')(items,{'isTag': true});
1599             if ( tagItems.length > 0 ) {
1600               tagItem = tagItems[0];
1601             }
1602             // remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous
1603             if ( items.length > 0 && tagItem ) {
1604               hasTag = true;
1605               items = items.slice(1,items.length);
1606               stashArr = stashArr.slice(1,stashArr.length);
1607             }
1608             newItem = $select.tagging.fct($select.search);
1609             // verify the new tag doesn't match the value of a possible selection choice or an already selected item.
1610             if (
1611               stashArr.some(function (origItem) {
1612                  return angular.equals(origItem, $select.tagging.fct($select.search));
1613               }) ||
1614               $select.selected.some(function (origItem) {
1615                 return angular.equals(origItem, newItem);
1616               })
1617             ) {
1618               scope.$evalAsync(function () {
1619                 $select.activeIndex = 0;
1620                 $select.items = items;
1621               });
1622               return;
1623             }
1624             newItem.isTag = true;
1625           // handle newItem string and stripping dupes in tagging string context
1626           } else {
1627             // find any tagging items already in the $select.items array and store them
1628             tagItems = $select.$filter('filter')(items,function (item) {
1629               return item.match($select.taggingLabel);
1630             });
1631             if ( tagItems.length > 0 ) {
1632               tagItem = tagItems[0];
1633             }
1634             item = items[0];
1635             // remove existing tag item if found (should only ever be one tag item)
1636             if ( item !== undefined && items.length > 0 && tagItem ) {
1637               hasTag = true;
1638               items = items.slice(1,items.length);
1639               stashArr = stashArr.slice(1,stashArr.length);
1640             }
1641             newItem = $select.search+' '+$select.taggingLabel;
1642             if ( _findApproxDupe($select.selected, $select.search) > -1 ) {
1643               return;
1644             }
1645             // verify the the tag doesn't match the value of an existing item from
1646             // the searched data set or the items already selected
1647             if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) {
1648               // if there is a tag from prev iteration, strip it / queue the change
1649               // and return early
1650               if ( hasTag ) {
1651                 items = stashArr;
1652                 scope.$evalAsync( function () {
1653                   $select.activeIndex = 0;
1654                   $select.items = items;
1655                 });
1656               }
1657               return;
1658             }
1659             if ( _findCaseInsensitiveDupe(stashArr) ) {
1660               // if there is a tag from prev iteration, strip it
1661               if ( hasTag ) {
1662                 $select.items = stashArr.slice(1,stashArr.length);
1663               }
1664               return;
1665             }
1666           }
1667           if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem);
1668           // dupe found, shave the first item
1669           if ( dupeIndex > -1 ) {
1670             items = items.slice(dupeIndex+1,items.length-1);
1671           } else {
1672             items = [];
1673             items.push(newItem);
1674             items = items.concat(stashArr);
1675           }
1676           scope.$evalAsync( function () {
1677             $select.activeIndex = 0;
1678             $select.items = items;
1679           });
1680         }
1681       });
1682       function _findCaseInsensitiveDupe(arr) {
1683         if ( arr === undefined || $select.search === undefined ) {
1684           return false;
1685         }
1686         var hasDupe = arr.filter( function (origItem) {
1687           if ( $select.search.toUpperCase() === undefined || origItem === undefined ) {
1688             return false;
1689           }
1690           return origItem.toUpperCase() === $select.search.toUpperCase();
1691         }).length > 0;
1692
1693         return hasDupe;
1694       }
1695       function _findApproxDupe(haystack, needle) {
1696         var dupeIndex = -1;
1697         if(angular.isArray(haystack)) {
1698           var tempArr = angular.copy(haystack);
1699           for (var i = 0; i <tempArr.length; i++) {
1700             // handle the simple string version of tagging
1701             if ( $select.tagging.fct === undefined ) {
1702               // search the array for the match
1703               if ( tempArr[i]+' '+$select.taggingLabel === needle ) {
1704               dupeIndex = i;
1705               }
1706             // handle the object tagging implementation
1707             } else {
1708               var mockObj = tempArr[i];
1709               if (angular.isObject(mockObj)) {
1710                 mockObj.isTag = true;
1711               }
1712               if ( angular.equals(mockObj, needle) ) {
1713                 dupeIndex = i;
1714               }
1715             }
1716           }
1717         }
1718         return dupeIndex;
1719       }
1720
1721       $select.searchInput.on('blur', function() {
1722         $timeout(function() {
1723           $selectMultiple.activeMatchIndex = -1;
1724         });
1725       });
1726
1727     }
1728   };
1729 }]);
1730
1731 uis.directive('uiSelectSingle', ['$timeout','$compile', function($timeout, $compile) {
1732   return {
1733     restrict: 'EA',
1734     require: ['^uiSelect', '^ngModel'],
1735     link: function(scope, element, attrs, ctrls) {
1736
1737       var $select = ctrls[0];
1738       var ngModel = ctrls[1];
1739
1740       //From view --> model
1741       ngModel.$parsers.unshift(function (inputValue) {
1742         var locals = {},
1743             result;
1744         locals[$select.parserResult.itemName] = inputValue;
1745         result = $select.parserResult.modelMapper(scope, locals);
1746         return result;
1747       });
1748
1749       //From model --> view
1750       ngModel.$formatters.unshift(function (inputValue) {
1751         var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
1752             locals = {},
1753             result;
1754         if (data){
1755           var checkFnSingle = function(d){
1756             locals[$select.parserResult.itemName] = d;
1757             result = $select.parserResult.modelMapper(scope, locals);
1758             return result == inputValue;
1759           };
1760           //If possible pass same object stored in $select.selected
1761           if ($select.selected && checkFnSingle($select.selected)) {
1762             return $select.selected;
1763           }
1764           for (var i = data.length - 1; i >= 0; i--) {
1765             if (checkFnSingle(data[i])) return data[i];
1766           }
1767         }
1768         return inputValue;
1769       });
1770
1771       //Update viewValue if model change
1772       scope.$watch('$select.selected', function(newValue) {
1773         if (ngModel.$viewValue !== newValue) {
1774           ngModel.$setViewValue(newValue);
1775         }
1776       });
1777
1778       ngModel.$render = function() {
1779         $select.selected = ngModel.$viewValue;
1780       };
1781
1782       scope.$on('uis:select', function (event, item) {
1783         $select.selected = item;
1784       });
1785
1786       scope.$on('uis:close', function (event, skipFocusser) {
1787         $timeout(function(){
1788           $select.focusser.prop('disabled', false);
1789           if (!skipFocusser) $select.focusser[0].focus();
1790         },0,false);
1791       });
1792
1793       scope.$on('uis:activate', function () {
1794         focusser.prop('disabled', true); //Will reactivate it on .close()
1795       });
1796
1797       //Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954
1798       var focusser = angular.element("<input ng-disabled='$select.disabled' class='ui-select-focusser ui-select-offscreen' type='text' id='{{ $select.focusserId }}' aria-label='{{ $select.focusserTitle }}' aria-haspopup='true' role='button' />");
1799       $compile(focusser)(scope);
1800       $select.focusser = focusser;
1801
1802       //Input that will handle focus
1803       $select.focusInput = focusser;
1804
1805       element.parent().append(focusser);
1806       focusser.bind("focus", function(){
1807         scope.$evalAsync(function(){
1808           $select.focus = true;
1809         });
1810       });
1811       focusser.bind("blur", function(){
1812         scope.$evalAsync(function(){
1813           $select.focus = false;
1814         });
1815       });
1816       focusser.bind("keydown", function(e){
1817
1818         if (e.which === KEY.BACKSPACE) {
1819           e.preventDefault();
1820           e.stopPropagation();
1821           $select.select(undefined);
1822           scope.$apply();
1823           return;
1824         }
1825
1826         if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
1827           return;
1828         }
1829
1830         if (e.which == KEY.DOWN  || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE){
1831           e.preventDefault();
1832           e.stopPropagation();
1833           $select.activate();
1834         }
1835
1836         scope.$digest();
1837       });
1838
1839       focusser.bind("keyup input", function(e){
1840
1841         if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) {
1842           return;
1843         }
1844
1845         $select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input
1846         focusser.val('');
1847         scope.$digest();
1848
1849       });
1850
1851
1852     }
1853   };
1854 }]);
1855 // Make multiple matches sortable
1856 uis.directive('uiSelectSort', ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function($timeout, uiSelectConfig, uiSelectMinErr) {
1857   return {
1858     require: '^^uiSelect',
1859     link: function(scope, element, attrs, $select) {
1860       if (scope[attrs.uiSelectSort] === null) {
1861         throw uiSelectMinErr('sort', 'Expected a list to sort');
1862       }
1863
1864       var options = angular.extend({
1865           axis: 'horizontal'
1866         },
1867         scope.$eval(attrs.uiSelectSortOptions));
1868
1869       var axis = options.axis;
1870       var draggingClassName = 'dragging';
1871       var droppingClassName = 'dropping';
1872       var droppingBeforeClassName = 'dropping-before';
1873       var droppingAfterClassName = 'dropping-after';
1874
1875       scope.$watch(function(){
1876         return $select.sortable;
1877       }, function(newValue){
1878         if (newValue) {
1879           element.attr('draggable', true);
1880         } else {
1881           element.removeAttr('draggable');
1882         }
1883       });
1884
1885       element.on('dragstart', function(event) {
1886         element.addClass(draggingClassName);
1887
1888         (event.dataTransfer || event.originalEvent.dataTransfer).setData('text', scope.$index.toString());
1889       });
1890
1891       element.on('dragend', function() {
1892         element.removeClass(draggingClassName);
1893       });
1894
1895       var move = function(from, to) {
1896         /*jshint validthis: true */
1897         this.splice(to, 0, this.splice(from, 1)[0]);
1898       };
1899
1900       var dragOverHandler = function(event) {
1901         event.preventDefault();
1902
1903         var offset = axis === 'vertical' ? event.offsetY || event.layerY || (event.originalEvent ? event.originalEvent.offsetY : 0) : event.offsetX || event.layerX || (event.originalEvent ? event.originalEvent.offsetX : 0);
1904
1905         if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) {
1906           element.removeClass(droppingAfterClassName);
1907           element.addClass(droppingBeforeClassName);
1908
1909         } else {
1910           element.removeClass(droppingBeforeClassName);
1911           element.addClass(droppingAfterClassName);
1912         }
1913       };
1914
1915       var dropTimeout;
1916
1917       var dropHandler = function(event) {
1918         event.preventDefault();
1919
1920         var droppedItemIndex = parseInt((event.dataTransfer || event.originalEvent.dataTransfer).getData('text'), 10);
1921
1922         // prevent event firing multiple times in firefox
1923         $timeout.cancel(dropTimeout);
1924         dropTimeout = $timeout(function() {
1925           _dropHandler(droppedItemIndex);
1926         }, 20);
1927       };
1928
1929       var _dropHandler = function(droppedItemIndex) {
1930         var theList = scope.$eval(attrs.uiSelectSort);
1931         var itemToMove = theList[droppedItemIndex];
1932         var newIndex = null;
1933
1934         if (element.hasClass(droppingBeforeClassName)) {
1935           if (droppedItemIndex < scope.$index) {
1936             newIndex = scope.$index - 1;
1937           } else {
1938             newIndex = scope.$index;
1939           }
1940         } else {
1941           if (droppedItemIndex < scope.$index) {
1942             newIndex = scope.$index;
1943           } else {
1944             newIndex = scope.$index + 1;
1945           }
1946         }
1947
1948         move.apply(theList, [droppedItemIndex, newIndex]);
1949
1950         scope.$apply(function() {
1951           scope.$emit('uiSelectSort:change', {
1952             array: theList,
1953             item: itemToMove,
1954             from: droppedItemIndex,
1955             to: newIndex
1956           });
1957         });
1958
1959         element.removeClass(droppingClassName);
1960         element.removeClass(droppingBeforeClassName);
1961         element.removeClass(droppingAfterClassName);
1962
1963         element.off('drop', dropHandler);
1964       };
1965
1966       element.on('dragenter', function() {
1967         if (element.hasClass(draggingClassName)) {
1968           return;
1969         }
1970
1971         element.addClass(droppingClassName);
1972
1973         element.on('dragover', dragOverHandler);
1974         element.on('drop', dropHandler);
1975       });
1976
1977       element.on('dragleave', function(event) {
1978         if (event.target != element) {
1979           return;
1980         }
1981         element.removeClass(droppingClassName);
1982         element.removeClass(droppingBeforeClassName);
1983         element.removeClass(droppingAfterClassName);
1984
1985         element.off('dragover', dragOverHandler);
1986         element.off('drop', dropHandler);
1987       });
1988     }
1989   };
1990 }]);
1991
1992 /**
1993  * Parses "repeat" attribute.
1994  *
1995  * Taken from AngularJS ngRepeat source code
1996  * See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L211
1997  *
1998  * Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat:
1999  * https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697
2000  */
2001
2002 uis.service('uisRepeatParser', ['uiSelectMinErr','$parse', function(uiSelectMinErr, $parse) {
2003   var self = this;
2004
2005   /**
2006    * Example:
2007    * expression = "address in addresses | filter: {street: $select.search} track by $index"
2008    * itemName = "address",
2009    * source = "addresses | filter: {street: $select.search}",
2010    * trackByExp = "$index",
2011    */
2012   self.parse = function(expression) {
2013
2014
2015     var match;
2016     //var isObjectCollection = /\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)/.test(expression);
2017     // If an array is used as collection
2018
2019     // if (isObjectCollection){
2020     // 000000000000000000000000000000111111111000000000000000222222222222220033333333333333333333330000444444444444444444000000000000000055555555555000000000000000000000066666666600000000
2021     match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(\s*[\s\S]+?)?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
2022
2023     // 1 Alias
2024     // 2 Item
2025     // 3 Key on (key,value)
2026     // 4 Value on (key,value)
2027     // 5 Source expression (including filters)
2028     // 6 Track by
2029
2030     if (!match) {
2031       throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
2032               expression);
2033     }
2034     
2035     var source = match[5], 
2036         filters = '';
2037
2038     // When using (key,value) ui-select requires filters to be extracted, since the object
2039     // is converted to an array for $select.items 
2040     // (in which case the filters need to be reapplied)
2041     if (match[3]) {\r
2042       // Remove any enclosing parenthesis\r
2043       source = match[5].replace(/(^\()|(\)$)/g, '');\r
2044       // match all after | but not after ||\r
2045       var filterMatch = match[5].match(/^\s*(?:[\s\S]+?)(?:[^\|]|\|\|)+([\s\S]*)\s*$/);\r
2046       if(filterMatch && filterMatch[1].trim()) {\r
2047         filters = filterMatch[1];\r
2048         source = source.replace(filters, '');\r
2049       }      \r
2050     }
2051
2052     return {
2053       itemName: match[4] || match[2], // (lhs) Left-hand side,
2054       keyName: match[3], //for (key, value) syntax
2055       source: $parse(source),
2056       filters: filters,
2057       trackByExp: match[6],
2058       modelMapper: $parse(match[1] || match[4] || match[2]),
2059       repeatExpression: function (grouped) {
2060         var expression = this.itemName + ' in ' + (grouped ? '$group.items' : '$select.items');
2061         if (this.trackByExp) {
2062           expression += ' track by ' + this.trackByExp;
2063         }
2064         return expression;
2065       } 
2066     };
2067
2068   };
2069
2070   self.getGroupNgRepeatExpression = function() {
2071     return '$group in $select.groups';
2072   };
2073
2074 }]);
2075
2076 }());
2077 angular.module("ui.select").run(["$templateCache", function($templateCache) {$templateCache.put("bootstrap/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content ui-select-dropdown dropdown-menu\" role=\"listbox\" ng-show=\"$select.open\"><li class=\"ui-select-choices-group\" id=\"ui-select-choices-{{ $select.generatedId }}\"><div class=\"divider\" ng-show=\"$select.isGrouped && $index > 0\"></div><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label dropdown-header\" ng-bind=\"$group.name\"></div><div id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\" role=\"option\"><a href=\"\" class=\"ui-select-choices-row-inner\"></a></div></li></ul>");
2078 $templateCache.put("bootstrap/match-multiple.tpl.html","<span class=\"ui-select-match\"><span ng-repeat=\"$item in $select.selected\"><span class=\"ui-select-match-item btn btn-default btn-xs\" tabindex=\"-1\" type=\"button\" ng-disabled=\"$select.disabled\" ng-click=\"$selectMultiple.activeMatchIndex = $index;\" ng-class=\"{\'btn-primary\':$selectMultiple.activeMatchIndex === $index, \'select-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span class=\"close ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$selectMultiple.removeChoice($index)\">&nbsp;&times;</span> <span uis-transclude-append=\"\"></span></span></span></span>");
2079 $templateCache.put("bootstrap/match.tpl.html","<div class=\"ui-select-match\" ng-hide=\"$select.open\" ng-disabled=\"$select.disabled\" ng-class=\"{\'btn-default-focus\':$select.focus}\"><span tabindex=\"-1\" class=\"btn btn-default form-control ui-select-toggle\" aria-label=\"{{ $select.baseTitle }} activate\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" style=\"outline: 0;\"><span ng-show=\"$select.isEmpty()\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"ui-select-match-text pull-left\" ng-class=\"{\'ui-select-allow-clear\': $select.allowClear && !$select.isEmpty()}\" ng-transclude=\"\"></span> <i class=\"caret pull-right\" ng-click=\"$select.toggle($event)\"></i> <a ng-show=\"$select.allowClear && !$select.isEmpty()\" aria-label=\"{{ $select.baseTitle }} clear\" style=\"margin-right: 10px\" ng-click=\"$select.clear($event)\" class=\"btn btn-xs btn-link pull-right\"><i class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"></i></a></span></div>");
2080 $templateCache.put("bootstrap/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple ui-select-bootstrap dropdown form-control\" ng-class=\"{open: $select.open}\"><div><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\" role=\"combobox\" aria-label=\"{{ $select.baseTitle }}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div></div>");
2081 $templateCache.put("bootstrap/select.tpl.html","<div class=\"ui-select-container ui-select-bootstrap dropdown\" ng-class=\"{open: $select.open}\"><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"off\" tabindex=\"-1\" aria-expanded=\"true\" aria-label=\"{{ $select.baseTitle }}\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"form-control ui-select-search\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-show=\"$select.searchEnabled && $select.open\"><div class=\"ui-select-choices\"></div></div>");
2082 $templateCache.put("select2/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content select2-results\"><li class=\"ui-select-choices-group\" ng-class=\"{\'select2-result-with-children\': $select.choiceGrouped($group) }\"><div ng-show=\"$select.choiceGrouped($group)\" class=\"ui-select-choices-group-label select2-result-label\" ng-bind=\"$group.name\"></div><ul role=\"listbox\" id=\"ui-select-choices-{{ $select.generatedId }}\" ng-class=\"{\'select2-result-sub\': $select.choiceGrouped($group), \'select2-result-single\': !$select.choiceGrouped($group) }\"><li role=\"option\" id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{\'select2-highlighted\': $select.isActive(this), \'select2-disabled\': $select.isDisabled(this)}\"><div class=\"select2-result-label ui-select-choices-row-inner\"></div></li></ul></li></ul>");
2083 $templateCache.put("select2/match-multiple.tpl.html","<span class=\"ui-select-match\"><li class=\"ui-select-match-item select2-search-choice\" ng-repeat=\"$item in $select.selected\" ng-class=\"{\'select2-search-choice-focus\':$selectMultiple.activeMatchIndex === $index, \'select2-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span uis-transclude-append=\"\"></span> <a href=\"javascript:;\" class=\"ui-select-match-close select2-search-choice-close\" ng-click=\"$selectMultiple.removeChoice($index)\" tabindex=\"-1\"></a></li></span>");
2084 $templateCache.put("select2/match.tpl.html","<a class=\"select2-choice ui-select-match\" ng-class=\"{\'select2-default\': $select.isEmpty()}\" ng-click=\"$select.toggle($event)\" aria-label=\"{{ $select.baseTitle }} select\"><span ng-show=\"$select.isEmpty()\" class=\"select2-chosen\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"select2-chosen\" ng-transclude=\"\"></span> <abbr ng-if=\"$select.allowClear && !$select.isEmpty()\" class=\"select2-search-choice-close\" ng-click=\"$select.clear($event)\"></abbr> <span class=\"select2-arrow ui-select-toggle\"><b></b></span></a>");
2085 $templateCache.put("select2/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple select2 select2-container select2-container-multi\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled}\"><ul class=\"select2-choices\"><span class=\"ui-select-match\"></span><li class=\"select2-search-field\"><input type=\"text\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"select2-input ui-select-search\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-model=\"$select.search\" ng-click=\"$select.activate()\" style=\"width: 34px;\" ondrop=\"return false;\"></li></ul><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"ui-select-choices\"></div></div></div>");
2086 $templateCache.put("select2/select.tpl.html","<div class=\"ui-select-container select2 select2-container\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled, \'select2-container-active\': $select.focus, \'select2-allowclear\': $select.allowClear && !$select.isEmpty()}\"><div class=\"ui-select-match\"></div><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"select2-search\" ng-show=\"$select.searchEnabled\"><input type=\"text\" autocomplete=\"off\" autocorrect=\"false\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"ui-select-search select2-input\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div></div></div>");
2087 $templateCache.put("selectize/choices.tpl.html","<div ng-show=\"$select.open\" class=\"ui-select-choices ui-select-dropdown selectize-dropdown single\"><div class=\"ui-select-choices-content selectize-dropdown-content\"><div class=\"ui-select-choices-group optgroup\" role=\"listbox\"><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label optgroup-header\" ng-bind=\"$group.name\"></div><div role=\"option\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\"><div class=\"option ui-select-choices-row-inner\" data-selectable=\"\"></div></div></div></div></div>");
2088 $templateCache.put("selectize/match.tpl.html","<div ng-hide=\"($select.open || $select.isEmpty())\" class=\"ui-select-match\" ng-transclude=\"\"></div>");
2089 $templateCache.put("selectize/select.tpl.html","<div class=\"ui-select-container selectize-control single\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.open && !$select.searchEnabled ? $select.toggle($event) : $select.activate()\"><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search ui-select-toggle\" ng-click=\"$select.toggle($event)\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-hide=\"!$select.searchEnabled || ($select.selected && !$select.open)\" ng-disabled=\"$select.disabled\" aria-label=\"{{ $select.baseTitle }}\"></div><div class=\"ui-select-choices\"></div></div>");}]);