var GHMenu = new Class(
{
	menuId: '',
	menu: null,
	hideTimeoutMs: 100,
	hideTimeouts: new Hash(),
	realSubHeights: new Hash(),
	
	initialize: function ( menuId )
	{
		this.menuId = menuId;
		window.addEvent( 'domready', this.boot.bind( this ) );
	},

	boot: function ()
	{
		this.menu = $(this.menuId);
		this.addBehaviour();
	},
	
	addBehaviour: function ()
	{
		this.menu.getChildren().each( function ( item ) {
			item.addEvent( 'mouseenter', this.onItemMouseOver.bindWithEvent( this, item ) );
			item.addEvent( 'mouseleave', this.onItemMouseOut.bindWithEvent( this, item ) );
			var sub = item.getElement( 'ul' );
			if ( sub ) {
				sub.set( 'tween', {'duration': 300} );
				var tween = sub.get( 'tween' );
				tween.addEvent( 'complete', this.onTweenComplete.bindWithEvent( this, item ) );
			}
		}.bind( this ) );
	},

	onItemMouseOver: function ( event, item )
	{
		this.show( item );
		
		// Clear the hide timout
		if ( this.hideTimeouts[item.get('class')] ) clearTimeout( this.hideTimeouts[item.get('class')] );
	},
	
	onItemMouseOut: function ( event, item )
	{
		// Set the hide timeout
		this.hideTimeouts[item.get('class')] = setTimeout( function () {
			this.hide( item );
		}.bind( this ), this.hideTimeoutMs );
	},
	
	show: function ( item )
	{
		var sub = item.getElement( 'ul' );
		if ( sub ) {
			var index = item.get('class');
			if ( !this.realSubHeights[index] ) {
				this.realSubHeights[index] = sub.getStyle('height');
				sub.setStyle( 'height', 0 );
				sub.setStyle( 'opacity', 0.85 );
			}
			var realHeight = this.realSubHeights[index];
			sub.setStyle( 'visibility', 'visible' );
			sub.tween( 'height', [sub.getSize().y, realHeight]);
			sub.setStyle( 'z-index', 10 );
		}
	},
	
	hide: function ( item )
	{
		var sub = item.getElement( 'ul' );
		if ( sub ) {
			sub.setStyle( 'z-index', 9 );
			sub.tween( 'height', [sub.getStyle('height'), 0]);
		}
	},
	
	onTweenComplete: function ( event, item )
	{
		var sub = item.getElement( 'ul' );
		if ( sub.getStyle('height') == '0px' ) sub.setStyle( 'visibility', 'hidden' );
	}
});

var menu = new GHMenu( 'mainMenu' ); 
