HD.Menu = function( link, menu, parent ){
	//this.ChildMenus = array();
	this.CurrentChild = null;
	this.Menu = menu;
	this.Parent = parent;
	this.Timeout = null;

	if( link && menu ){
		var over = objectiveReference( this.ShowMenu, this );
		HD.Event.OnMouseOver( link, over );
		HD.Event.OnMouseOver( menu, over );

		var out = objectiveReference( this.SetTimeout, this );
		HD.Event.OnMouseOut(  link, out );
		HD.Event.OnMouseOut(  menu, out );

		this.ConnectChildMenus();
	}
}

HD.Menu.prototype.ConnectChildMenus = function(){
	var links = [];
	for( var i = 0; i < this.Menu.childNodes.length; i++ ){
		var node = this.Menu.childNodes[ i ];
		if( node.nodeName == 'A' )
			links.push( node );
	}

	for( var i = 0; i < links.length; i++ ){
		var link = links[ i ];
		var div = link.nextSibling;
		if( !div )
			continue;

		if( div.nodeName != 'DIV' )
			div = div.nextSibling;

		if( !div || div.nodeName != 'DIV' )
			continue;

		new HD.Menu( link, div, this );
	}
}

HD.Menu.prototype.ClearTimeout = function(){
	if( this.Timeout ){
		clearTimeout( this.Timeout );
		this.Timeout = null;
	}

	if( this.Parent ){
		this.Parent.ClearTimeout();
	}
}

HD.Menu.prototype.OnTimeout = function(){
	this.Timeout = null;
	this.HideMenu();
}

HD.Menu.prototype.SetTimeout = function( e ){
	//prevent dups
	this.ClearTimeout();
	
	var fn = objectiveReference( this.OnTimeout, this );
	this.Timeout = setTimeout( fn, 200 );

	if( this.Parent ){
		this.Parent.SetTimeout();
	}
}

HD.Menu.prototype.HideMenu = function(){
	if( this.CurrentChild ){
		this.CurrentChild.HideMenu();
	}

	if( this.Menu ){
		this.Menu.style.display = 'none';
	}
}

HD.Menu.prototype.ShowMenu = function( e ){
	if( this.Parent ){
		if( this.Parent.CurrentChild &&
			this.Parent.CurrentChild != this )
			this.Parent.CurrentChild.HideMenu();

		this.Parent.CurrentChild = this;
	}

	this.ClearTimeout();	
	this.Menu.style.display = 'block';
}

HD.Menu.Create = function( navEl ){
	var cells = navEl.getElementsByTagName( 'td' );
	var topLinks = [];
	for( var i = 0; i < cells.length; i++ ){
		var cell = cells[ i ];
		for( var j = 0; j < cell.childNodes.length; j++ ){
			var node = cell.childNodes[ j ];
			if( node.nodeName == 'A' )
				topLinks .push( node );
		}
	}

	var parent = new HD.Menu();
	for( var i = 0; i < topLinks.length; i++ ){
		var link = topLinks[ i ];
		var div = link.nextSibling;
		if( !div )
			continue;

		if( div.nodeName != 'DIV' )
			div = div.nextSibling;

		if( !div || div.nodeName != 'DIV' )
			continue;

		new HD.Menu( link, div, parent );
	}
	return parent;
}