var MainMenu = 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( 'div.slider' );
			if ( sub ) {
				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( 'div.slider' );
    var subtxt = item.getElement( 'ul' );
		if ( sub ) {
      item.addClass( 'open' );
			var index = item.get('class');
			if ( !this.realSubHeights[index] ) {
				this.realSubHeights[index] = sub.getStyle('height');
				sub.setStyle( 'height', 0 );
        subtxt.setStyle( 'opacity', 0 );
			}
      var realHeight = this.realSubHeights[index];
      sub.setStyle( 'visibility', 'visible' );
      sub.set('tween', {transition: Fx.Transitions.Sine.easeOut, 'duration': '300'});
      sub.tween( 'height', [sub.getSize().y, realHeight]);
      subtxt.set( 'tween', {'duration': 500} );
      subtxt.tween( 'opacity', [subtxt.getStyle('opacity'), 0.9]);
		}
	},
	
	hide: function ( item )
	{
		var sub = item.getElement( 'div.slider' );
    var subtxt = item.getElement( 'ul' );
		if ( sub ) {
      sub.set('tween', {transition: Fx.Transitions.Sine.easeInOut, 'duration': '300'});
			sub.tween( 'height', [sub.getStyle('height'), 0]);
      subtxt.set( 'tween', {'duration': 100} );
      subtxt.tween( 'opacity', [subtxt.getStyle('opacity'), 0]);
      item.removeClass( 'open' );
		}
	},
	
	onTweenComplete: function ( event, item )
	{
		var sub = item.getElement( 'div.slider' );
		if ( sub.getStyle('height') == '0px' ) sub.setStyle( 'visibility', 'hidden' );
	}
});

var menu = new MainMenu( 'mainMenu' );
