( function( $ ) {

$( document ).ready( function() {

	// collapse non-selected, non-parent menu items by default
	$( '#ultimenu li:not(.current_page_ancestor,.current_page_item) ul' ).hide();

	// set timout to expand submenus when mouse enters parent
	$( '#ultimenu li.page_item:not(.current_page_ancestor,.current_page_item)' ).mouseenter( function() {
		var o = $( this );
		this.ultimenu_timeout = window.setTimeout( function() {
			o.children( 'ul' ).each( function() {
				$( this ).slideDown( 'fast' );
				// only add parent's "open" state if we open something!
				o.addClass( 'ultimenu_open' );
			} );
		}, 150 );
	} );

	// clear timeout (to prevent any exanding) when mouse leaves parent
	$( '#ultimenu li.page_item:not(.current_page_ancestor,.current_page_item)' ).mouseleave( function() {
		if( this.ultimenu_timeout != null ) {
			window.clearTimeout( this.ultimenu_timeout );
			this.ultimenu_timeout = null;
		}
	} );

	// collapse all submenus when mouse leaves side bar (menu's parent). No need
	// to clear timeouts here, that'll be handled by leaving the parent.
	$( '#ultimenu' ).parent().mouseleave( function() {
		$( '#ultimenu li:not(.current_page_ancestor,.current_page_item) ul', this ).slideUp( 'normal' );
		$( '.ultimenu_open' ).removeClass( 'ultimenu_open' );
	} );

} );

} )( jQuery );
