angular.module("robware").directive('contextMenu', function() {
	return {
		restrict: 'E',
		templateUrl: '/scripts/directives/templates/contextMenu.html',
		scope: {
			actions: '=',
			isChild: '=?'
		},
		link: function(scope, element) {
			scope.isFunction = angular.isFunction;
			scope.show=false;
			scope.selectedElement=null;
			scope.subMenuShowKey="";

			scope.changeSubMenuShowKey=function(name){
				scope.subMenuShowKey=name;
			};

			function show(x, y, target){
				scope.changeSubMenuShowKey("");
				scope.menuX=x+"px";
				scope.menuY=y+"px";
				scope.selectedElement=target;
				scope.show=true;
			};

			function hide(){
				scope.show=false;
			}

			scope.performAction=function(func){
				if (!angular.isFunction(func))
					return;
				func($(scope.selectedElement).scope());
				hide();
			};

			$(document).on("click", function(e){
				hide();
				scope.$apply();
			});

			var parent=element.parent()[0];

			if (scope.isChild){
				show(parent.clientWidth,parent.clientTop);
			}else
				$(parent).css("position","relative");
				element.parent().on("contextmenu", function(e){
					var offset=$(element).offset();
					show(e.pageX-offset.left, e.pageY-offset.top, e.target);
					scope.$apply();
					e.preventDefault();
				});
		}
	};
});

