var _editor_url = "/cma";

function MenuZone() {}

MenuZone.loadStyle = function(style) {
	var url = _editor_url || "/css/";
	url += style;
	document.write("<style type='text/css'>@import url(" + url + ");</style>");
};

// event handling

MenuZone._addEvent = function(el, evname, func) {
	if (MenuZone.is_ie) {
		el.attachEvent("on" + evname, func);
	} else {
		el.addEventListener(evname, func, true);
	}
};

MenuZone._addEvents = function(el, evs, func) {
	for (var i in evs) {
		MenuZone._addEvent(el, evs[i], func);
	}
};

MenuZone._removeEvent = function(el, evname, func) {
	if (MenuZone.is_ie) {
		el.detachEvent("on" + evname, func);
	} else {
		el.removeEventListener(evname, func, true);
	}
};

MenuZone._removeEvents = function(el, evs, func) {
	for (var i in evs) {
		MenuZone._removeEvent(el, evs[i], func);
	}
};

MenuZone._stopEvent = function(ev) {
	if (MenuZone.is_ie) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
	}
};

// Browser detection

MenuZone.agt = navigator.userAgent.toLowerCase();
MenuZone.is_ie	   = ((MenuZone.agt.indexOf("msie") != -1) && (MenuZone.agt.indexOf("opera") == -1));
MenuZone.is_gecko  = (navigator.product == "Gecko");

MenuZone.loadStyle("context_menu.css");

function ContextMenu(editor,rightClick) {
	this.editor = editor;
	this.rightClick = rightClick;
	
	//var statusbar = document.createElement("div");
	//statusbar.className = "statusBar";
	//this.editor.appendChild(statusbar);
	//div = document.createElement("span");
	//div.className = "statusBarTree";
	//div.innerHTML = "Path" + ": ";
	//this.editor._statusBarTree = div;

}

ContextMenu.prototype.onGenerate = function() {
	var self = this;
	var doc = this.editordoc = this.editor;
	if( this.rightClick ) {
		MenuZone._addEvents(doc, ["contextmenu"],
				    function (event) {
					    return self.popupMenu(event);
				    });
	}
	else {
		MenuZone._addEvents(doc, ["click"],
				    function (event) {
					    return self.popupMenu(event);
				    });
	}
	this.currentMenu = null;
};

ContextMenu.prototype.popupMenu = function(ev) {
	var self = this;
	var i18n = ContextMenu.I18N;
	if (this.currentMenu)
		this.currentMenu.parentNode.removeChild(this.currentMenu);
	function getPos(el) {
		var r = { x: el.offsetLeft, y: el.offsetTop };
		if (el.offsetParent) {
			var tmp = getPos(el.offsetParent);
			r.x += tmp.x;
			r.y += tmp.y;
		}
		return r;
	};
	function documentClick(ev) {
		ev || (ev = window.event);
		if (!self.currentMenu) {
			alert(i18n["How did you get here? (Please report!)"]);
			return false;
		}
		var el = MenuZone.is_ie ? ev.srcElement : ev.target;
		for (; el != null && el != self.currentMenu; el = el.parentNode);
		if (el == null)
			self.closeMenu();
		//MenuZone._stopEvent(ev);
		//return false;
	};
	var keys = [];
	function keyPress(ev) {
		ev || (ev = window.event);
		MenuZone._stopEvent(ev);
		if (ev.keyCode == 27) {
			self.closeMenu();
			return false;
		}
		var key = String.fromCharCode(MenuZone.is_ie ? ev.keyCode : ev.charCode).toLowerCase();
		for (var i = keys.length; --i >= 0;) {
			var k = keys[i];
			if (k[0].toLowerCase() == key)
				k[1].__msh.activate();
		}
	};
	self.closeMenu = function() {
		self.currentMenu.parentNode.removeChild(self.currentMenu);
		self.currentMenu = null;
		MenuZone._removeEvent(document, "mousedown", documentClick);
		MenuZone._removeEvent(self.editordoc, "mousedown", documentClick);
		if (keys.length > 0)
			MenuZone._removeEvent(self.editordoc, "keypress", keyPress);
		if (MenuZone.is_ie)
			self.iePopup.hide();
	};
	
	var target = MenuZone.is_ie ? ev.srcElement : ev.target;
	var ifpos = getPos(self.editor);
	var x = ev.clientX + ifpos.x;
	var y = ev.clientY + ifpos.y;
	if( MenuZone.is_gecko ) { x = x - 10; y = y - 10; } // context menu position hack

	var div;
	var doc;
	if (!MenuZone.is_ie) {
		doc = document;
	} else {
		// IE stinks
		var popup = this.iePopup = window.createPopup();
		doc = popup.document;
		doc.open();	
		doc.write("<html><head><style type='text/css'>@import url(" + _editor_url + "/css/context_menu.css); html, body { padding: 0px; margin: 0px; overflow: hidden; border: 0px; }</style></head><body unselectable='yes'></body></html>");
		doc.close();
	}
	div = doc.createElement("div");
	if (MenuZone.is_ie)
		div.unselectable = "on";
	div.oncontextmenu = function() { return false; };
	div.className = "context-menu";
	if (!MenuZone.is_ie)
		div.style.left = div.style.top = "0px";
	doc.body.appendChild(div);

	var table = doc.createElement("table");
	div.appendChild(table);
	table.cellSpacing = 0;
	table.cellPadding = 0;
	var parent = doc.createElement("tbody");
	table.appendChild(parent);

	var options = this.getContextMenu(target);
	if(! options ) return;

	for (var i = 0; i < options.length; ++i) {
		var option = options[i];
		var item = doc.createElement("tr");
		parent.appendChild(item);
		if (MenuZone.is_ie)
			item.unselectable = "on";
		else item.onmousedown = function(ev) {
			MenuZone._stopEvent(ev);
			return false;
		};
		if (!option) {
			item.className = "separator";
			var td = doc.createElement("td");
			td.className = "icon";
			var IE_IS_A_FUCKING_SHIT = '>';
			if (MenuZone.is_ie) {
				td.unselectable = "on";
				IE_IS_A_FUCKING_SHIT = " unselectable='on' style='height=1px'>&nbsp;";
			}
			td.innerHTML = "<div" + IE_IS_A_FUCKING_SHIT + "</div>";
			var td1 = td.cloneNode(true);
			td1.className = "cmlabel";
			item.appendChild(td);
			item.appendChild(td1);
		} else {
			var label = option[0];
			item.className = "item";
			item.__msh = {
				item: item,
				label: label,
				action: option[1],
				tooltip: option[2] || null,
				icon: option[3] || null,
				activate: function() {
					self.closeMenu();
					//self.editor.focusEditor();
					this.action();
				}
			};

			if (typeof(label) == "undefined"){
				parent.removeChild(item);
				continue;
			}
			label = label.replace(/_([a-zA-Z0-9])/, "<u>$1</u>");			
			if (label != option[0])
				keys.push([ RegExp.$1, item ]);
//			if (typeof(label) == "undefined")	{
//				parent.removeChild(item);
//				continue;
//			}

			label = label.replace(/__/, "_");
			var td1 = doc.createElement("td");
			if (MenuZone.is_ie)
				td1.unselectable = "on";
			item.appendChild(td1);
			td1.className = "icon";
			if (item.__msh.icon)
				td1.innerHTML = "<img align='middle' src='" + item.__msh.icon + "' />";
			var td2 = doc.createElement("td");
			if (MenuZone.is_ie)
				td2.unselectable = "on";
			item.appendChild(td2);
			td2.className = "cmlabel";
			td2.innerHTML = label;
			item.onmouseover = function() {
				this.className += " hover";
				//self.editor._statusBarTree.innerHTML = this.__msh.tooltip || '&nbsp;';
			};
			item.onmouseout = function() { this.className = "item"; };
			item.oncontextmenu = function(ev) {
				this.__msh.activate();
				if (!MenuZone.is_ie)
					MenuZone._stopEvent(ev);
				return false;
			};
			item.onmouseup = function(ev) {
				var timeStamp = (new Date()).getTime();
				if (timeStamp - self.timeStamp > 500)
					this.__msh.activate();
				if (!MenuZone.is_ie)
					MenuZone._stopEvent(ev);
				return false;
			};
			//if (typeof option[2] == "string")
			//item.title = option[2];
		}
	}

	if (!MenuZone.is_ie) {
		var dx = x + div.offsetWidth - window.innerWidth + 4;
		var dy = y + div.offsetHeight - window.innerHeight + 4;
		if (dx > 0) x -= dx;
		if (dy > 0) y -= dy;
		div.style.left = x + "px";
		div.style.top = y + "px";
	} else {
		// determine the size
		var foobar = document.createElement("div");
		foobar.className = "context-menu";
		foobar.innerHTML = div.innerHTML;
		document.body.appendChild(foobar);
		var w = foobar.offsetWidth;
		var h = foobar.offsetHeight;
		document.body.removeChild(foobar);
		this.iePopup.show(ev.screenX, ev.screenY, w, h);
	}

	this.currentMenu = div;
	this.timeStamp = (new Date()).getTime();

	MenuZone._addEvent(document, "mousedown", documentClick);
	MenuZone._addEvent(this.editordoc, "mousedown", documentClick);
	if (keys.length > 0)
		MenuZone._addEvent(this.editordoc, "keypress", keyPress);

	MenuZone._stopEvent(ev);
	return false;
};
