namespace ti_common {

    interface IMyAttr extends ng.IAttributes {
        ticClickElsewhere;
    }

    class ClickElsewhere implements ng.IDirective {
        constructor(private $window, private $parse, private $timeout) { }

        public restrict = 'A';

        link = (scope: ng.IScope, element: JQuery, attrs: IMyAttr) => {
            let clickOutHandler = this.$parse(attrs.ticClickElsewhere);

            angular.element(this.$window).on('click', (event) => {
                if (!element[0].contains(event.target)) {
                    clickOutHandler(scope, { $event: event });
                    scope.$apply();
                }
            });
            
        };

        public static Factory() {
            let directive = ($window, $parse, $timeout) => {
                return new ClickElsewhere($window, $parse, $timeout);
            };
            directive.$inject = ['$window', '$parse', '$timeout'];
            return directive;
        }
    };

    angular.module('ti_common').directive('ticClickElsewhere', ClickElsewhere.Factory());
}
