if (!window.Richfaces) window.Richfaces = {};
Richfaces.ContextMenu = Class.create();

Richfaces.ContextMenu.prototype = {
	
	initialize: function(id, evaluator, options) {
		this.options = options || {};
		this.id = id;
		this.evaluator = evaluator;
		$(id).component = this;
		this.doShow = this.show;
		this.doHide = this.hide;
	},
	
	attachToParent : function(id, event, context) {
		var element = $(id);
		if (!element) {
			element = $(this.id);
			if (element) {
				element = element.parentNode;
			}
		}
		
		if (element) {
			this.applyDecoration(element);
		}
		
		//Strip 'on' here 
		var evnName = event.substr(2);
		var listener = this.show.bindAsEventListener(this, context);
		
		Event.observe(element, evnName, listener);
	},
	
	hide: function() {
		//Stub here
		RichFaces.Menu.Layers.shutdown();
	},
	
	show: function(event, context) {
		this.construct(context);
		event.parameters = context;
		new RichFaces.Menu.DelayedContextMenu(this.id + "_menu", event).show();
		//Event.stop(event||window.event);
	},
	
	construct: function(context) {
		if (this.isNewContext(context)) {
			this.destroy();
		}
		var div = document.createElement("div");
		div.id = this.id + ":_auto_created";
		$(this.id).appendChild(div);
		var html = this.evaluator.invoke('getContent', context||window).join('');
		new Insertion.Top(div, html);
		
	},
	
	destroy: function() {
		var div = $(this.id + ":_auto_created");
		Richfaces.infernalCachePurge(div);
		if (div) {
			div.parentNode.removeChild(div);
		}
		
	},
	
	isNewContext: function(context) {
		//TODO: Check whether contexts are the same and therefore
		// do not destroy menu 
		//var oldContext = this.context || {};
		return true;
	},
	
	applyDecoration : function(element) {
		
		$(element).addClassName("rich-cm-attached");
		
		/*var f = this.options.applyDecorations;
		if (f) {
			f(element);
		}*/
	}
};

Richfaces.disableDefaultHandler = function(event) {
	if (event.startsWith('on')) {
		event = event.substr(2);
	}
	Event.observe(document, event, Event.stop);
};

Richfaces.enableDefaultHandler = function(event) {
	if (event.startsWith('on')) {
	event = event.substr(2);
	}
	Event.stopObserving(document, event, Event.stop);
};


Richfaces.infernalCachePurge = function(root) {
	if (root) {
		if (root._eventID) {
			Event.stopObserving(root);
		}
		var child = root.firstChild;
		while(child) {
			Richfaces.infernalCachePurge(child);
			child = child.nextSibling;
		}
	}
};