'use strict';

angular.module('$strap.directives')

.directive('bsSelect', function($timeout) {

  var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/;

  return {
    restrict: 'A',
    require: '?ngModel',
    link: function postLink(scope, element, attrs, controller) {

      var options = scope.$eval(attrs.bsSelect) || {};

      $timeout(function() {
        element.selectpicker(options);
        element.next().removeClass('ng-scope');
      });
      
      // If we have a controller (i.e. ngModelController) then wire it up
      if(controller) {

        var refresh = function(newValue, oldValue) {
          if (!angular.equals(newValue, oldValue)) {
            element.selectpicker('refresh');
          }
        };

        // Watch for changes to the model value
        scope.$watch(attrs.ngModel, function(newValue, oldValue) {
          refresh(newValue, oldValue);
        });

        // Watch for changes to the options
        scope.$watch(attrs.bsSelect, function(newValue, oldValue) {
          refresh(newValue, oldValue);
        });

      }

    }

  };

});

@@ -942,87 +942,107 @@
 el, 
-function(newValue, oldValue) %7B%0A          refresh(newValue, oldValue);%0A        %7D
+refresh);%0A%0A        // Watch for changes to the options%0A        scope.$watch(attrs.bsSelect, refresh
 );%0A%0A
@@ -1069,39 +1069,37 @@
  changes to the 
-options
+title
 %0A        scope.$
@@ -1108,92 +1108,49 @@
 tch(
-attrs.bsSelect, function(newValue, oldValue) %7B%0A          refresh(newValue, oldValue)
+function() %7B%0A          return attrs.title
 ;%0A  
@@ -1156,16 +1156,25 @@
        %7D
+, refresh
 );%0A%0A    

update the title when the attribute changes