'use strict';

/* Directives */

angular.module('ruleEditor.directives', [])
  
  .directive('ngEnter', function () {
    return function (scope, element, attrs) {
      element.bind("keydown keypress", function (event) {
        if (event.which === 13) {  // Return key
          scope.$apply(function (){
            scope.$eval(attrs.ngEnter);
          });
          event.preventDefault();
        }
      });
    };
  })
  
  .directive('focusMe', function() {
    return {
      link: function(scope, element, attrs) {
        scope.$watch(attrs.focusMe, function(value) {
          if (value === true) {
            element[0].focus();
            scope[attrs.focusMe] = false;
          }
        });
      }
    };
  })

  .directive('postagHelp', ['$parse', 'PostagHelper', function($parse, postagHelper) {
    return {
      link: function(scope, element, attrs) {
        var model = $parse(attrs.postagHelp);
        scope.$watch(model, function(value) {
          var languageConfig = postagHelper.tagMapping[scope.language.code];
          var map = languageConfig.tags;
          var matcher = new RegExp("[^" + languageConfig.posTagChars + "]+", "g");
          var highlightTags = value.split(matcher);
          var result = [];
          for (var idx in map) {
            if (map.hasOwnProperty(idx)) {
              var title = map[idx].replace(/.*\((.*)\)/, "$1");
              result.push(
                {
                  tag: idx,
                  name: map[idx].replace(/\(.*\)/, ""),
                  title: title ? title : null,
                  highlight: highlightTags.indexOf(idx) !== -1
                });
            }
          }
          var changed = !angular.equals(result, scope.gui.posTagHelp);
          if (changed) {  // needed optimization so typing doesn't slow down
            scope.gui.posTagHelp = result;
          }
        });
      }
    }
  }])

  .directive('autocomplete', ['Autocompleter', function (autocompleter) {
    
    // See http://stackoverflow.com/questions/12959516/problems-with-jquery-autocomplete-angularjs?rq=1
    // and http://jqueryui.com/resources/demos/autocomplete/multiple.html 
    
    return {
      restrict: "A",
      require: '?ngModel',
      link: function (scope, elem, attr, ngModel) {
        elem.autocomplete({

          minLength: 0,

          source: function (searchTerm, response) {
            var cursorPosition = elem[0].selectionStart;
            var autocompleteResults = autocompleter.search(searchTerm.term, cursorPosition, scope.language.code);
            if (autocompleteResults === null) {
              response();
            } else {
              response($.map(autocompleteResults, function (autocompleteResult) {
                return {
                  value: autocompleteResult
                }
              }));
            }
          },
          
          select: function (event, selectedItem) {
            var newValue = autocompleter.select(event, selectedItem, elem);
            // this doesn't work because it sets the same 'new' value again and again:
            /*elem.on('blur keyup change', function() {
              // see http://docs.angularjs.org/api/ng/type/ngModel.NgModelController
              scope.$apply(function() {
                console.log("SET");
                ngModel.$setViewValue(newValue);
              });
            });*/
            scope.$eval(attr.ngModel + " = '" + newValue + "'");
            scope.$apply();
            event.preventDefault();
            return false;
          },

          focus: function() {
            // prevent value inserted on focus
            return false;
          }
          
        });
      }
    };
  }
  
]);

@@ -819,136 +819,29 @@
     
-return %7B%0A      link: function(scope, element, attrs) %7B%0A        var model = $parse(attrs.postagHelp);%0A        scope.$watch(model,
+var updateHelpView = 
  fun
@@ -838,32 +838,39 @@
 iew =  function(
+scope, 
 value) %7B%0A       
@@ -858,28 +858,24 @@
 e, value) %7B%0A
-    
       var la
@@ -935,20 +935,16 @@
 .code%5D;%0A
-    
       va
@@ -974,28 +974,24 @@
 tags;%0A      
-    
 var matcher 
@@ -1053,28 +1053,24 @@
 %22g%22);%0A      
-    
 var highligh
@@ -1101,28 +1101,24 @@
 her);%0A      
- 
-   
 var result =
@@ -1122,20 +1122,16 @@
 t = %5B%5D;%0A
-    
       fo
@@ -1155,28 +1155,24 @@
 ) %7B%0A        
-   
- 
 if (map.hasO
@@ -1186,28 +1186,24 @@
 rty(idx)) %7B%0A
-    
           va
@@ -1246,28 +1246,24 @@
 %5C)/, %22$1%22);%0A
-    
           re
@@ -1289,18 +1289,10 @@
     
-    %7B%0A    
+%7B%0A
     
@@ -1325,20 +1325,16 @@
         
- 
-   
 name: ma
@@ -1377,20 +1377,16 @@
         
-    
 title: t
@@ -1420,20 +1420,16 @@
         
-  
-  
 highligh
@@ -1473,36 +1473,28 @@
             
-    %7D);%0A    
+%7D);%0A
         %7D%0A  
@@ -1493,34 +1493,26 @@
     %7D%0A      
-    %7D%0A    
+%7D%0A
       var ch
@@ -1568,28 +1568,24 @@
 elp);%0A      
-    
 if (changed)
@@ -1643,28 +1643,24 @@
 own%0A        
-    
 scope.gui.po
@@ -1676,37 +1676,413 @@
 = result;%0A      
+%7D%0A
     %7D
+;%0A    return %7B%0A      link: function(scope, element, attrs) %7B%0A        var model = $parse(attrs.postagHelp);%0A        scope.$watch(model, function(value) %7B%0A          updateHelpView(scope, value);%0A        %7D);%0A        element.bind('focus', function(event) %7B  // also update view when switching between different POS tag fields%0A          updateHelpView(scope, event.target.value);
 %0A        %7D);%0A   

update help view between different POS tag fields