var angular = require('angular');
require('jsUtil');
require('../modules');

var module = angular.module('commons.directives.sinosearchmodal');

module.directive('sinoSearchModal', function() {
  return {
    restrict: 'C',
    link: function(scope, element) {
      scope.search = {
        text: ''
      };
      scope.searching = false;
      scope.searchopen = false;
      scope.everytimeOpen = false;

      var search = element[0].querySelector('input[type=search]');
      element.bind('webkitTransitionEnd transitionend', function() {
        if(scope.everytimeOpen) {
          return;
        }
        if (scope.searchopen) {
          scope.everytimeOpen = true;
          search.focus();
          if(_.isObjectExist('cordova.plugins.Keyboard', window)) {
            window.cordova.plugins.Keyboard.show();
          }
        }
      });

      scope.closeKeyBoard = function() {
        if(_.isObjectExist('cordova.plugins.Keyboard', window)) {
          window.cordova.plugins.Keyboard.close();
        }
      };

      scope.openSearch = function() {
        scope.searching = true;
        scope.searchopen = true;
        scope.search.text = '';
      };

      scope.onEndEvent = function() {
        scope.searchopen = scope.searching;
      };

      scope.closeSearch = function() {
        scope.closeKeyBoard();
        scope.searchopen = false;
        scope.searching = false;
        scope.everytimeOpen = false;
      };
    }
  };
});
