/**
 * Created by shadeeka on 11/30/15.
 */
angular.module('app.directives')
// =========================================================================
// ng-repeat last item event
// =========================================================================

  .directive('onLastRepeat', function() {
  return function(scope, element, attrs) {
    if (scope.$last) setTimeout(function(){
      scope.$emit('onRepeatLast', element, attrs);
    }, 1);
  };
})
 // =========================================================================
// bind ng-click event to touch start event
// =========================================================================

  .directive("ngMobileClick", [function () {
    return function (scope, elem, attrs) {
      elem.bind("touchstart click", function (e) {
        e.preventDefault();
        e.stopPropagation();

        scope.$apply(attrs["ngMobileClick"]);
      });
    }
  }])
  .directive("ngFactClick", [function () {
    return function (scope, elem, attrs) {
      elem.bind("touchstart click", function (e) {
        e.preventDefault();
        scope.$apply(attrs["ngFactClick"]);
      });
    }
  }])
// =========================================================================
// input focus directive
// =========================================================================

  .directive('inputFocus', function () {

    var FOCUS_CLASS = 'nf-active';
    return {
      restrict: 'A',
      priority: 1,
      link: function (scope, element, attrs, ctrl) {
        element.bind('focus',function () {
          element.parent().children("label").addClass(FOCUS_CLASS);
        }).bind('blur', function () {
          if(element[0].value =="")
            element.parent().children("label").removeClass(FOCUS_CLASS);
        });
      }
    };
  })

// =========================================================================
// input capitalized letters directive
// =========================================================================

  .directive('capitalize', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
          if (inputValue == undefined) inputValue = '';
          var capitalized = inputValue.toUpperCase();
          if (capitalized !== inputValue) {
            modelCtrl.$setViewValue(capitalized);
            modelCtrl.$render();
          }
          return capitalized;
        }
        modelCtrl.$parsers.push(capitalize);
        capitalize(scope[attrs.ngModel]); // capitalize initial value
      }
    }});
