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