text: /**
   * Contains ui-select "intelligence".
   *
   * The goal is to limit dependency on the DOM whenever possible and
   * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
   */
  uis.controller('uiSelectCtrl',
    ['$scope', '$element', '$timeout', '$filter', '$$uisDebounce', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector', '$window',
    function($scope, $element, $timeout, $filter, $$uisDebounce, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector, $window) {
  
    var ctrl = this;
  
    var EMPTY_SEARCH = '';
  
    ctrl.placeholder = uiSelectConfig.placeholder;
    ctrl.searchEnabled = uiSelectConfig.searchEnabled;
    ctrl.sortable = uiSelectConfig.sortable;
    ctrl.refreshDelay = uiSelectConfig.refreshDelay;
    ctrl.paste = uiSelectConfig.paste;
    ctrl.resetSearchInput = uiSelectConfig.resetSearchInput;
    ctrl.refreshing = false;
    ctrl.spinnerEnabled = uiSelectConfig.spinnerEnabled;
    ctrl.spinnerClass = uiSelectConfig.spinnerClass;
    ctrl.taggingTokenEscape = uiSelectConfig.taggingTokenEscape;
  
    ctrl.removeSelected = uiSelectConfig.removeSelected; //If selected item(s) should be removed from dropdown list
    ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function
    ctrl.skipFocusser = false; //Set to true to avoid returning focus to ctrl when item is selected
    ctrl.tagOnBlur = false;
    ctrl.search = EMPTY_SEARCH;
  
    ctrl.activeIndex = 0; //Dropdown of choices
    ctrl.items = []; //All available choices
  
    ctrl.open = false;
    ctrl.focus = false;
    ctrl.disabled = false;
    ctrl.selected = undefined;
  
    ctrl.dropdownPosition = 'auto';
    ctrl.appendDropdownToBody = uiSelectConfig.appendDropdownToBody;
  
    ctrl.focusser = undefined; //Reference to input element used to handle focus events
    ctrl.multiple = undefined; // Initialized inside uiSelect directive link function
    ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function
    ctrl.tagging = {isActivated: false, fct: undefined};
    ctrl.taggingTokens = {isActivated: false, tokens: undefined};
    ctrl.copying = undefined;
    ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function
    ctrl.clickTriggeredSelect = false;
    ctrl.$filter = $filter;
    ctrl.$element = $element;
  
    // Use $injector to check for $animate and store a reference to it
    ctrl.$animate = (function () {
      try {
        return $injector.get('$animate');
      } catch (err) {
        // $animate does not exist
        return null;
      }
    })();
  
    ctrl.searchInput = $element.querySelectorAll('input.ui-select-search');
    if (ctrl.searchInput.length !== 1) {
      throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length);
    }
  
    ctrl.isEmpty = function() {
      return isNil(ctrl.selected) || ctrl.selected === '' || (ctrl.multiple && ctrl.selected.length === 0);
    };
  
    function _findIndex(collection, predicate, thisArg){
      if (collection.findIndex){
        return collection.findIndex(predicate, thisArg);
      } else {
        var list = Object(collection);
        var length = list.length >>> 0;
        var value;
  
        for (var i = 0; i < length; i++) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return i;
          }
        }
        return -1;
      }
    }
  
    // Most of the time the user does not want to empty the search input when in typeahead mode
    function _resetSearchInput() {
      if (ctrl.resetSearchInput) {
        ctrl.search = EMPTY_SEARCH;
        //reset activeIndex
        if (ctrl.selected && ctrl.items.length && !ctrl.multiple) {
          ctrl.activeIndex = _findIndex(ctrl.items, function(item){
            return angular.equals(this, item);
          }, ctrl.selected);
        }
      }
    }
  
      function _groupsFilter(groups, groupNames) {
        var i, j, result = [];
        for(i = 0; i < groupNames.length ;i++){
          for(j = 0; j < groups.length ;j++){
            if(groups[j].name == [groupNames[i]]){
              result.push(groups[j]);
            }
          }
        }
        return result;
      }
  
    // When the user clicks on ui-select, displays the dropdown list
    ctrl.activate = function(initSearchValue, avoidReset) {
      if (!ctrl.disabled  && !ctrl.open) {
        if(!avoidReset) _resetSearchInput();
  
        $scope.$broadcast('uis:activate');
        ctrl.open = true;
        ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex;
        // ensure that the index is set to zero for tagging variants
        // that where first option is auto-selected
        if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) {
          ctrl.activeIndex = 0;
        }
  
        var container = $element.querySelectorAll('.ui-select-choices-content');
        var searchInput = $element.querySelectorAll('.ui-select-search');
        if (ctrl.$animate && ctrl.$animate.on && ctrl.$animate.enabled(container[0])) {
          var animateHandler = function(elem, phase) {
            if (phase === 'start' && ctrl.items.length === 0) {
              // Only focus input after the animation has finished
              ctrl.$animate.off('removeClass', searchInput[0], animateHandler);
              $timeout(function () {
                ctrl.focusSearchInput(initSearchValue);
              });
            } else if (phase === 'close') {
              // Only focus input after the animation has finished
              ctrl.$animate.off('enter', container[0], animateHandler);
              $timeout(function () {
                ctrl.focusSearchInput(initSearchValue);
              });
            }
          };
  
          if (ctrl.items.length > 0) {
            ctrl.$animate.on('enter', container[0], animateHandler);
          } else {
            ctrl.$animate.on('removeClass', searchInput[0], animateHandler);
          }
        } else {
          $timeout(function () {
            ctrl.focusSearchInput(initSearchValue);
            if(!ctrl.tagging.isActivated && ctrl.items.length > 1) {
              _ensureHighlightVisible();
            }
          });
        }
      }
      else if (ctrl.open && !ctrl.searchEnabled) {
        // Close the selection if we don't have search enabled, and we click on the select again
        ctrl.close();
      }
    };
  
    ctrl.focusSearchInput = function (initSearchValue) {
      ctrl.search = initSearchValue || ctrl.search;
      ctrl.searchInput[0].focus();
    };
  
    ctrl.findGroupByName = function(name) {
      return ctrl.groups && ctrl.groups.filter(function(group) {
        return group.name === name;
      })[0];
    };
  
    ctrl.parseRepeatAttr = function(repeatAttr, groupByExp, groupFilterExp) {
      function updateGroups(items) {
        var groupFn = $scope.$eval(groupByExp);
        ctrl.groups = [];
        angular.forEach(items, function(item) {
          var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn];
          var group = ctrl.findGroupByName(groupName);
          if(group) {
            group.items.push(item);
          }
          else {
            ctrl.groups.push({name: groupName, items: [item]});
          }
        });
        if(groupFilterExp){
          var groupFilterFn = $scope.$eval(groupFilterExp);
          if( angular.isFunction(groupFilterFn)){
            ctrl.groups = groupFilterFn(ctrl.groups);
          } else if(angular.isArray(groupFilterFn)){
            ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn);
          }
        }
        ctrl.items = [];
        ctrl.groups.forEach(function(group) {
          ctrl.items = ctrl.items.concat(group.items);
        });
      }
  
      function setPlainItems(items) {
        ctrl.items = items || [];
      }
  
      ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems;
  
      ctrl.parserResult = RepeatParser.parse(repeatAttr);
  
      ctrl.isGrouped = !!groupByExp;
      ctrl.itemProperty = ctrl.parserResult.itemName;
  
      //If collection is an Object, convert it to Array
  
      var originalSource = ctrl.parserResult.source;
  
      //When an object is used as source, we better create an array and use it as 'source'
      var createArrayFromObject = function(){
        var origSrc = originalSource($scope);
        $scope.$uisSource = Object.keys(origSrc).map(function(v){
          var result = {};
          result[ctrl.parserResult.keyName] = v;
          result.value = origSrc[v];
          return result;
        });
      };
  
      if (ctrl.parserResult.keyName){ // Check for (key,value) syntax
        createArrayFromObject();
        ctrl.parserResult.source = $parse('$uisSource' + ctrl.parserResult.filters);
        $scope.$watch(originalSource, function(newVal, oldVal){
          if (newVal !== oldVal) createArrayFromObject();
        }, true);
      }
  
      ctrl.refreshItems = function (data){
        data = data || ctrl.parserResult.source($scope);
        var selectedItems = ctrl.selected;
        //TODO should implement for single mode removeSelected
        if (ctrl.isEmpty() || (angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.multiple || !ctrl.removeSelected) {
          ctrl.setItemsFn(data);
        }else{
          if ( data !== undefined && data !== null ) {
            var filteredItems = data.filter(function(i) {
              return angular.isArray(selectedItems) ? selectedItems.every(function(selectedItem) {
                return !angular.equals(i, selectedItem);
              }) : !angular.equals(i, selectedItems);
            });
            ctrl.setItemsFn(filteredItems);
          }
        }
        if (ctrl.dropdownPosition === 'auto' || ctrl.dropdownPosition === 'up'){
          $scope.calculateDropdownPos();
        }
        $scope.$broadcast('uis:refresh');
      };
  
      // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259
      $scope.$watchCollection(ctrl.parserResult.source, function(items) {
        if (items === undefined || items === null) {
          // If the user specifies undefined or null => reset the collection
          // Special case: items can be undefined if the user did not initialized the collection on the scope
          // i.e $scope.addresses = [] is missing
          ctrl.items = [];
        } else {
          if (!angular.isArray(items)) {
            throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
          } else {
            //Remove already selected items (ex: while searching)
            //TODO Should add a test
            ctrl.refreshItems(items);
  
            //update the view value with fresh data from items, if there is a valid model value
            if(angular.isDefined(ctrl.ngModel.$modelValue)) {
              ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
            }
          }
        }
      });
  
    };
  
    var _refreshDelayPromise;
  
    /**
     * Typeahead mode: lets the user refresh the collection using his own function.
     *
     * See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
     */
    ctrl.refresh = function(refreshAttr) {
      if (refreshAttr !== undefined) {
        // Debounce
        // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155
        // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177
        if (_refreshDelayPromise) {
          $timeout.cancel(_refreshDelayPromise);
        }
        _refreshDelayPromise = $timeout(function() {
          if ($scope.$select.search.length >= $scope.$select.minimumInputLength) {
            var refreshPromise = $scope.$eval(refreshAttr);
            if (refreshPromise && angular.isFunction(refreshPromise.then) && !ctrl.refreshing) {
              ctrl.refreshing = true;
              refreshPromise.finally(function() {
                ctrl.refreshing = false;
              });
            }
          }
        }, ctrl.refreshDelay);
      }
    };
  
    ctrl.isActive = function(itemScope) {
      if ( !ctrl.open ) {
        return false;
      }
      var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
      var isActive =  itemIndex == ctrl.activeIndex;
  
      if (ctrl.items[itemIndex] && ctrl.items[itemIndex].divider) {
        return false;
      }
  
      if ( !isActive || itemIndex < 0 ) {
        return false;
      }
  
      if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) {
        itemScope.$eval(ctrl.onHighlightCallback);
      }
  
      return isActive;
    };
  
    var _isItemSelected = function (item) {
      return (ctrl.selected && angular.isArray(ctrl.selected) &&
          ctrl.selected.filter(function (selection) { return angular.equals(selection, item); }).length > 0);
    };
  
    var disabledItems = [];
  
    function _updateItemDisabled(item, isDisabled) {
      var disabledItemIndex = disabledItems.indexOf(item);
      if (isDisabled && disabledItemIndex === -1) {
        disabledItems.push(item);
      }
  
      if (!isDisabled && disabledItemIndex > -1) {
        disabledItems.splice(disabledItemIndex, 1);
      }
    }
  
    function _isItemDisabled(item) {
      return disabledItems.indexOf(item) > -1;
    }
  
    ctrl.isDisabled = function(itemScope) {
  
      if (!ctrl.open) return;
  
      var item = itemScope[ctrl.itemProperty];
      var itemIndex = ctrl.items.indexOf(item);
      var isDisabled = false;
  
      if (itemIndex >= 0 && (angular.isDefined(ctrl.disableChoiceExpression) || ctrl.multiple)) {
  
        if (item.isTag) return false;
  
        if (ctrl.multiple) {
          isDisabled = _isItemSelected(item);
        }
  
        if (!isDisabled && angular.isDefined(ctrl.disableChoiceExpression)) {
          isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression));
        }
  
        _updateItemDisabled(item, isDisabled);
      }
  
      return isDisabled;
    };
  
  
    // When the user selects an item with ENTER or clicks the dropdown
    ctrl.select = function(item, skipFocusser, $event) {
      if (isNil(item) || !_isItemDisabled(item)) {
  
        if ( ! ctrl.items && ! ctrl.search && ! ctrl.tagging.isActivated) return;
  
        if (!item || !_isItemDisabled(item)) {
          // if click is made on existing item, prevent from tagging, ctrl.search does not matter
          ctrl.clickTriggeredSelect = false;
          if($event && ($event.type === 'click' || $event.type === 'touchend') && item)
            ctrl.clickTriggeredSelect = true;
  
          if(ctrl.tagging.isActivated && ctrl.clickTriggeredSelect === false) {
            // if taggingLabel is disabled and item is undefined we pull from ctrl.search
            if ( ctrl.taggingLabel === false ) {
              if ( ctrl.activeIndex < 0 ) {
                if (item === undefined) {
                  // when pulling from ctrl.search, deal with tagging tokens
                  item = _replaceAllTaggingTokens(ctrl.search);
                  if (ctrl.tagging.fct) item = ctrl.tagging.fct(item);
                }
                if (!item) {
                  return;
                }
              } else {
                // keyboard nav happened first, user selected from dropdown
                item = ctrl.items[ctrl.activeIndex];
              }
            } else {
              // tagging always operates at index zero, taggingLabel === false pushes
              // the ctrl.search value without having it injected
              if ( ctrl.activeIndex === 0 ) {
                // ctrl.tagging pushes items to ctrl.items, so we only have empty val
                // for `item` if it is a detected duplicate
                if ( item === undefined ) return;
  
                // create new item on the fly if we don't already have one;
                // use tagging function if we have one
                if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) {
                  item = ctrl.tagging.fct(item);
                  if (!item) return;
                // if item type is 'string', apply the tagging label
                } else if ( typeof item === 'string' ) {
                  // trim the trailing space
                  item = item.replace(ctrl.taggingLabel,'').trim();
                }
              }
            }
            // search ctrl.selected for dupes potentially caused by tagging and return early if found
            if (_isItemSelected(item)) {
              ctrl.close(skipFocusser);
              return;
            }
          }
          _resetSearchInput();
          $scope.$broadcast('uis:select', item);
  
          if (ctrl.closeOnSelect) {
            ctrl.close(skipFocusser);
          }
  
          if (!skipFocusser) {
            ctrl.setFocus();
          }
        }
      }
    };
  
    // Closes the dropdown
    ctrl.close = function(skipFocusser, forceClearSearchInput) {
      if (!ctrl.open) return;
      if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched();
      ctrl.open = false;
      if (!ctrl.tagOnBlur || forceClearSearchInput) {
        _resetSearchInput();
      }
      $scope.$broadcast('uis:close', skipFocusser);
  
    };
  
    ctrl.setFocus = function(){
      if (!ctrl.focus) ctrl.focusInput[0].focus();
    };
  
    ctrl.clear = function($event) {
      ctrl.select(null);
      $event.stopPropagation();
      $timeout(function() {
        ctrl.focusser[0].focus();
      }, 0, false);
    };
  
    // Toggle dropdown
    ctrl.toggle = function(e) {
      if (ctrl.open) {
        ctrl.close();
        e.preventDefault();
        e.stopPropagation();
      } else {
        ctrl.activate();
      }
    };
  
    // Set default function for locked choices - avoids unnecessary
    // logic if functionality is not being used
    ctrl.isLocked = function () {
      return false;
    };
  
    $scope.$watch(function () {
      return angular.isDefined(ctrl.lockChoiceExpression) && ctrl.lockChoiceExpression !== "";
    }, _initaliseLockedChoices);
  
    function _initaliseLockedChoices(doInitalise) {
      if(!doInitalise) return;
  
      var lockedItems = [];
  
      function _updateItemLocked(item, isLocked) {
        var lockedItemIndex = lockedItems.indexOf(item);
        if (isLocked && lockedItemIndex === -1) {
          lockedItems.push(item);
          }
  
        if (!isLocked && lockedItemIndex > -1) {
          lockedItems.splice(lockedItemIndex, 1);
        }
      }
  
      function _isItemlocked(item) {
        return lockedItems.indexOf(item) > -1;
      }
  
      ctrl.isLocked = function (itemScope, itemIndex) {
        var isLocked = false,
            item = ctrl.selected[itemIndex];
  
        if(item) {
          if (itemScope) {
            isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression));
            _updateItemLocked(item, isLocked);
          } else {
            isLocked = _isItemlocked(item);
          }
        }
  
        return isLocked;
      };
    }
  
  
    var sizeWatch = null;
    var updaterScheduled = false;
    ctrl.sizeSearchInput = function() {
  
      var input = ctrl.searchInput[0],
          container = ctrl.searchInput.parent().parent()[0],
          minInputWidth = 50,
          calculateContainerWidth = function() {
            // Return the container width only if the search input is visible
            return container.clientWidth * !!input.offsetParent;
          },
          updateIfVisible = function(containerWidth) {
            if (containerWidth === 0) {
              return false;
            }
            var inputWidth = containerWidth - input.offsetLeft - 10;
            if (inputWidth < minInputWidth) inputWidth = containerWidth;
            ctrl.searchInput.css('width', inputWidth+'px');
            return true;
          };
  
      // set width to minimum allowed width plus some padding
      // to fit it on the same line as last tag if possible
      ctrl.searchInput.css('width', (minInputWidth + 10)+'px');
      $timeout(function() { //Give tags time to render correctly
        if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) {
          sizeWatch = $scope.$watch(function() {
            if (!updaterScheduled) {
              updaterScheduled = true;
              $scope.$$postDigest(function() {
                updaterScheduled = false;
                if (updateIfVisible(calculateContainerWidth())) {
                  sizeWatch();
                  sizeWatch = null;
                }
              });
            }
          }, angular.noop);
        }
      });
    };
  
    function _handleDropDownSelection(key, e) {
      var processed = true;
      switch (key) {
        case KEY.DOWN:
          if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
          else if (ctrl.activeIndex < ctrl.items.length - 1) {
            var idx = ++ctrl.activeIndex;
            while(_isItemDisabled(ctrl.items[idx]) && idx < ctrl.items.length) {
              ctrl.activeIndex = ++idx;
            }
          }
          break;
        case KEY.UP:
          var minActiveIndex = (ctrl.search.length === 0 && ctrl.tagging.isActivated) ? -1 : 0;
          if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
          else if (ctrl.activeIndex > minActiveIndex) {
            var idxmin = --ctrl.activeIndex;
            while(_isItemDisabled(ctrl.items[idxmin]) && idxmin > minActiveIndex) {
              ctrl.activeIndex = --idxmin;
            }
          }
          break;
        case KEY.TAB:
          if (!ctrl.multiple || ctrl.open) {
            ctrl.select(ctrl.items[ctrl.activeIndex], true);
            e.preventDefault();
            e.stopPropagation();
          }
          break;
        case KEY.ENTER:
          if(ctrl.open && (ctrl.tagging.isActivated || ctrl.activeIndex >= 0)){
            ctrl.select(ctrl.items[ctrl.activeIndex], ctrl.skipFocusser); // Make sure at least one dropdown item is highlighted before adding if not in tagging mode
          } else {
            ctrl.activate(false, true); //In case its the search input in 'multiple' mode
          }
          break;
        case KEY.ESC:
          ctrl.close();
          break;
        default:
          processed = false;
      }
      return processed;
    }
  
    function _replaceTaggingTokens(search, token) {
      if (token.length > 1) return search; // do not replace token if it is a special key
  
      var tokenRegex = new RegExp(token + '$');
      if ( ctrl.taggingTokenEscape ) {
        // replace escaped tagging tokens with just the token
        // and remove tagging token if it's the last character in string
        var chunks = search.split(ctrl.taggingTokenEscape + token);
        chunks.push(chunks.pop().replace(tokenRegex, ''));
        search = chunks.join(token).trim();
      } else {
        // remove tagging token if it's the last character
        search = search.replace(tokenRegex, '').trim();
      }
      return search;
    }
  
    function _replaceAllTaggingTokens(search) {
      if (ctrl.taggingTokens.isActivated) {
        for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
          var token = ctrl.taggingTokens.tokens[i];
          search = _replaceTaggingTokens(search, token);
        }
      }
      return search;
    }
  
    // Bind to keyboard shortcuts
    ctrl.searchInput.on('keydown', function(e) {
  
      var key = e.which;
  
      if (~[KEY.ENTER,KEY.ESC].indexOf(key)){
        e.preventDefault();
        e.stopPropagation();
      }
  
      // if(~[KEY.ESC,KEY.TAB].indexOf(key)){
      //   //TODO: SEGURO?
      //   ctrl.close();
      // }
  
      $scope.$apply(function() {
  
        var tagged = false;
  
        if (ctrl.items.length > 0 || ctrl.tagging.isActivated) {
          if(!_handleDropDownSelection(key, e) && !ctrl.searchEnabled) {
            e.preventDefault();
            e.stopPropagation();
          }
          if ( ctrl.taggingTokens.isActivated ) {
            for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
              if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) {
                // make sure there is a new value to push via tagging
                // do not tag if tagging token is preceeded by escape sequence
                if ( ctrl.search.length > 0 && !ctrl.search.endsWith(ctrl.taggingTokenEscape) ) {
                  tagged = true;
                }
              }
            }
            if ( tagged ) {
              $timeout(function() {
                ctrl.searchInput.triggerHandler('tagged');
                var newItem = _replaceTaggingTokens(ctrl.search, KEY.MAP[e.keyCode]);
                if ( ctrl.tagging.fct ) {
                  newItem = ctrl.tagging.fct( newItem );
                }
                if (newItem) ctrl.select(newItem, true);
              });
            }
          }
        }
  
      });
  
      if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){
        _ensureHighlightVisible();
      }
  
      if (key === KEY.ENTER || key === KEY.ESC) {
        e.preventDefault();
        e.stopPropagation();
      }
  
    });
  
    ctrl.searchInput.on('paste', function (e) {
      var data;
  
      if (window.clipboardData && window.clipboardData.getData) { // IE
        data = window.clipboardData.getData('Text');
      } else {
        data = (e.originalEvent || e).clipboardData.getData('text/plain');
      }
  
      // Prepend the current input field text to the paste buffer.
      data = ctrl.search + data;
  
      if (data && data.length > 0) {
        if (ctrl.paste) {
          var pastedItems = ctrl.paste(data);
          // broadcast selected items if paste function returns them
          if (pastedItems && pastedItems.length) {
            $scope.$broadcast('uis:select-multiple', pastedItems);
          }
          ctrl.search = EMPTY_SEARCH;
          e.preventDefault();
          e.stopPropagation();
        } else if (ctrl.taggingTokens.isActivated) {
          // If tagging try to split by tokens and add items
          var items = [];
          for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {  // split by first token that is contained in data
            var separator = KEY.toSeparator(ctrl.taggingTokens.tokens[i]) || ctrl.taggingTokens.tokens[i];
            if (data.indexOf(separator) > -1) {
              items = data.split(separator);
              break;  // only split by one token
            }
          }
          if (items.length === 0) {
            items = [data];
          }
          var oldsearch = ctrl.search;
          angular.forEach(items, function (item) {
            var newItem = ctrl.tagging.fct ? ctrl.tagging.fct(item) : item;
            if (newItem) {
              ctrl.select(newItem, true);
            }
          });
          ctrl.search = oldsearch || EMPTY_SEARCH;
          e.preventDefault();
          e.stopPropagation();
        }
      }
    });
  
    // Allow tagging on blur
    ctrl.searchInput.on('blur', function($event) {
      if (ctrl.tagging.isActivated && ctrl.tagOnBlur && ctrl.search) {
  
        // do not tag on blur if focus is going to choices dropdown
        var relatedTarget = $event.relatedTarget || $event.explicitOriginalTarget || document.activeElement;
        if (ctrl.uiSelectChoices[0].contains(relatedTarget)) return;
  
        $timeout(function() {
          ctrl.searchInput.triggerHandler('tagged');
          var newItem = _replaceAllTaggingTokens(ctrl.search);
          if ( ctrl.tagging.fct ) {
            newItem = ctrl.tagging.fct( newItem );
          }
          if (newItem) ctrl.select(newItem, true);
        });
      }
    });
  
    ctrl.searchInput.on('tagged', function() {
      $timeout(function() {
        _resetSearchInput();
      });
    });
  
    // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431
    function _ensureHighlightVisible() {
      var container = ctrl.uiSelectChoices;
      var choices = container.querySelectorAll('.ui-select-choices-row');
      if (choices.length < 1) {
        throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length);
      }
  
      if (ctrl.activeIndex < 0) {
        return;
      }
  
      var highlighted = choices[ctrl.activeIndex];
      var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
      var height = container[0].offsetHeight;
  
      if (posY > height) {
        container[0].scrollTop += posY - height;
      } else if (posY < highlighted.clientHeight) {
        if (ctrl.isGrouped && ctrl.activeIndex === 0)
          container[0].scrollTop = 0; //To make group header visible when going all the way up
        else
          container[0].scrollTop -= highlighted.clientHeight - posY;
      }
    }
  
    var onResize = $$uisDebounce(function() {
      ctrl.sizeSearchInput();
    }, 50);
  
    angular.element($window).bind('resize', onResize);
  
    $scope.$on('$destroy', function() {
      ctrl.searchInput.off('keyup keydown tagged blur paste');
      angular.element($window).off('resize', onResize);
    });
  
    $scope.$watch('$select.activeIndex', function(activeIndex) {
      if (activeIndex)
        $element.find('input').attr(
          'aria-activedescendant',
          'ui-select-choices-row-' + ctrl.generatedId + '-' + activeIndex);
    });
  
    $scope.$watch('$select.open', function(open) {
      if (!open)
        $element.find('input').removeAttr('aria-activedescendant');
    });
  }]);
  