var Menu = function(items, current) {
	this.node = document.createElement("div");
	this.nodeImg = document.createElement("img");
	this.nodePopup = document.createElement("div");
	this.current = current;
	this.hideTimeout = null;
	this.init(items);
};

Menu.prototype.createItems = function(items) {
	var ul = document.createElement("ul");
	for (key in items) {
		var item = items[key];
		if ("type" in item && item.type == "part") {
			var li = document.createElement("li");
			li.appendChild(document.createTextNode(item.title));
			li.className = "part";
			ul.appendChild(li);
			var partUl = document.createElement("ul");
			ul.appendChild(partUl);
			partUl.appendChild(this.createItems(item.menu));
		}
		else {
			ul.appendChild(new MenuItem(item, this.current == key).node);
		}
	}
	return ul;
};

Menu.prototype.addItem = function(node) {
	this.nodePopup.appendChild(node);
};

Menu.prototype.init = function(items) {
	var self = this;
	this.node.className = "menu";
	
	this.node.appendChild(this.nodeImg);
	this.nodeImg.src = "img/icons/menu_32.png";
	this.nodeImg.onclick = function() { self.onclick() };
	this.nodeImg.onmouseenter = function() { self.onmouseenter() };
	this.nodePopup.onmouseover = function() { self.onmouseover() };
	this.nodePopup.onmousemove = function() { self.onmouseover() };

	this.setVisibility(false);
	this.node.appendChild(this.nodePopup);
	this.nodePopup.className = "popup";
	this.addItem(this.createItems(items));
};

Menu.prototype.onclick = function() {
	this.swVisibility();
};

Menu.prototype.onmouseenter = function() {
	this.setVisibility(true);
	this.startHideTimeout();
};

Menu.prototype.startHideTimeout = function() {
	var self = this;

	if (this.hideTimeout) {
		clearTimeout(this.hideTimeout);
		this.hideTimeout = null;
	}

	this.hideTimeout = setTimeout(function() {
		self.setVisibility(false);
	}, 10000);
};

Menu.prototype.onmouseover = function() {
	this.startHideTimeout();
};

Menu.prototype.setVisibility = function(value) {
	this.nodePopup.style.display = value ? "" : "none";
};

Menu.prototype.getVisibility = function() {
	return this.nodePopup.style.display == "" ? true : false;
};

Menu.prototype.swVisibility = function() {
	this.setVisibility(!this.getVisibility());
};

var MenuItem = function(arr, current) {
	this.node = document.createElement("li");
	this.init(arr, current);
};

MenuItem.prototype.init = function(arr, current) {
	var a = document.createElement("a");
	if ("icon" in arr) {
		var icon = document.createElement("img");
		icon.src = arr.icon;
		a.appendChild(icon);
	}
	a.appendChild(document.createTextNode(arr.title));
	a.href = arr.path;
	this.node.appendChild(a);

	if (current) this.node.className = "current";
};
