'use strict';

/* Directives */


angular.module('watuu.directives', []).
  directive('audioEvents', ['$rootScope', 'userService', 'playerService', 'globalconfig', function($rootScope, User, $player, globalconfig) {
	  // Set the event listeners for the audio element
	  
      return function($scope, elm, attrs) {

    	// Wrapper method for audio play event
		  $scope.reportWatuuPlayed = function(e) {
			  $rootScope.checkServerTimestamp();
			  $player.reportWatuuPlayed(e, $rootScope.timestamp, $rootScope.current_watuu.guid, User.username, 'firefox', globalconfig.app_version);
		  };
		  
		  // Wrapper method for audio stop event
		  $scope.reportWatuuStopped = function(e) {
			  $rootScope.checkServerTimestamp();
			  $player.reportWatuuStopped(e, $rootScope.timestamp, $rootScope.current_watuu.guid, User.username, 'firefox', globalconfig.app_version);
		  };
		  
		  // Wrapper method for audio finished event
		  $scope.reportWatuuFinished = function(e) {
			  $rootScope.checkServerTimestamp();
			  $player.reportWatuuFinished(e, $rootScope.timestamp, $rootScope.current_watuu.guid, 0, User.username, 'firefox', globalconfig.app_version);
		  }; 
		  
        elm[0].addEventListener('play', $scope.reportWatuuPlayed, false);
        elm[0].addEventListener('pause', $scope.reportWatuuStopped, false);
        elm[0].addEventListener('ended', $scope.reportWatuuFinished, false);

      };
      
  }]).
  /*
  This directive allows us to pass a function in on an enter key to do what we want.
  */
  directive('ngEnter', function () {
      return function (scope, element, attrs) {
          element.bind("keydown keypress", function (event) {
              if(event.which === 13) {
                  scope.$apply(function (){
                      scope.$eval(attrs.ngEnter);
                  });
   
                  event.preventDefault();
              }
          });
      };
  }).
  /*
  Shows a Boostrap 3 modal
  */
  directive('flashDialog', ['userService', function(User) {
      return function (scope, element, attrs) {
    	  // Only show the note if the user was set but not logged in (cos it is a newly registered user)
    	  if(User.username != '' && !User.isLogged)
    		  element.modal({ keyboard: false });
      };
  }]);
