var EGSMenu = Class.create();
EGSMenu.prototype = {
	menu_items: [],
	initialize: function(container,tagname) {
		tagname=tagname||'a';
		this.items = container.getElementsByTagName(tagname);
		$A(this.items).each(function(link) {
			var item =new EGSMenuItem(link);
			item.setMenu(this);
			this.menu_items.push(item);
		}.bind(this));
	},
	clear: function(ignore) {
		$A(this.menu_items).each(function(item) {
			if(item!=ignore) {
				item._hideSubMenu();
			}
		});
	}
}

var EGSMenuItem = Class.create();
EGSMenuItem.prototype={
	is_active: false,
	persistTime: 200,
	can_hide: false,
	initialize: function(link) {
		this.link=$(link);
		if(this.link.href==window.location+'#') {
			this.link.onclick=function() { return false; };
		}
		var img=this.link.down('img');
		if(img) {
			if(img.hasClassName('active')) {
				this.is_active=true;
				this.swapImage('on');
			}
			this.attachObservers();
			this.loadImage();
		}
	},
	setMenu: function(menu) {
		this.menu = menu;
	},
	attachObservers: function() {
		if(!this.is_active) {
			this.link.observe('mouseover',this.swapImage.bind(this,'on'),false);
			this.link.observe('mouseout',this.swapImage.bind(this,'off'),false);
		}
		if($('sub_'+this.link.id)) {
			this.subMenu =$('sub_'+this.link.id);
			this.link.observe('mouseover',this.showSubMenu.bind(this));
			this.link.observe('mouseout',this.hideSubMenu.bind(this),false);
		}
	},
	loadImage: function() {
		var img=this.link.down('img');
		if(img) {
			var new_img = new Image();
			if(this.is_active) {
				new_img.src = this.link.down('img').src.replace('_on','_off');
			}
			else {
				new_img.src = this.link.down('img').src.replace('_off','_on');
			}
		}
	},
	showSubMenu: function() {
	//	this.menu.clear(this);
		var subMenu = this.subMenu;
		var pos = Position.cumulativeOffset(this.link);
		//subMenu.position='absolute';
		//subMenu.style.left = pos[0]+'px';
		subMenu.observe('mouseover',this.blockHiding.bind(this),false);
		subMenu.observe('mouseout',this.hideSubMenu.bind(this),false);
		subMenu.style.zIndex=50;
		subMenu.show();
	},
	blockHiding: function() {
		this.can_hide=false;
	},
	hideSubMenu: function(link) {
		this.can_hide=true;
		setTimeout(this._hideSubMenu.bind(this),this.persistTime);
	},
	_hideSubMenu: function() {
		if(this.can_hide) {
			this.subMenu.hide();
		}
	},
	swapImage: function(state) {
		var img = $(this.link).down('img');
		if(img) {
			if(state=='on') {
				img.src=img.src.replace('_off','_on');
			}
			else {
				img.src=img.src.replace('_on','_off');
			}
		}
	}
}
