var DDMenu = Class.create({
	options : {
		mouseOutDelay:  500
	},
	initialize: function( element , options ){
		this.element = $(element);
		this.options = $H(this.options).merge( options );
		element.observe( "mouseover" , this.onMouseOver.bindAsEventListener( this ) );
		Event.observe( window , "mouseover" , this.onWindowMouseOver.bindAsEventListener( this ) );
		this._hideDelayed( this.element , 0 );
	},
	onMouseOver: function( e ){

		var target , depth , children , top , left , width , height;

		//Cancel any timeout
		if( this.hideDelayedTimeout ){
			clearTimeout( this.hideDelayedTimeout ); 
		}
		//Get the target			
		target = Event.element(e);

		//Check that the target is an <a>
		if( target.tagName != "A" ) return;
		
		//Hide All Childrens
		this._hideDelayed( target.up("ul") , 0 );

		//Check if it has children
		children = this._children( target );
		if( !children ) return;

		//Get the depth level
		depth  = this._depthLevel( target );

		//Show Children
		if( depth == 1 ){ 

			//Show directly under
			var offsetParent = target.cumulativeOffset();
			var dimParent    = target.getDimensions();
			var dimChild     = children.getDimensions();

			top    = (offsetParent.top + dimParent.height )+ "px";
			left   = (offsetParent.left ) + "px";
			width  = "auto";
			children.setStyle( { "top": top , "left": left , "width": width  , "height": "auto" , "overflow": "visible" , "position": "absolute" } );
			children.show();
		
		}else{ //Show menu to the side
			console.log("DEPTH");
		}

	},
	onWindowMouseOver: function( e ){

		var target , children , delay;

		//Get Target
		target = Event.element(e);

		//Ignore Mouse Moves Outside the menu
		if( !target.descendantOf( this.element ) ){
			//Wait some time and hide the menu
			this._hideDelayed( this.element , this.options.get("mouseOutDelay") );
		}

		Event.stop(e);

	},
	_hideDelayed: function( parent , delay ){
		var callback

		callback = function(){

			var children , x , c;

			children = parent.select("ul");
			c        = children.length;
			for( x = 0 ; x < c ; x++ )
				children[x].hide();
			
			//Clear interval id
			this.hideDelayedTimeout = false;

		};

		if( delay == 0 )
		   callback.call();
		else
		   this.hideDelayedTimeout = setTimeout( callback.bind( this ) , delay - 0 );

	},
	_depthLevel: function( el ){

		var depth , node;

		depth = 0;
		node  = el;
		while( node && node != this.element ){
			if( node.tagName == "LI" ) depth++;
			node = node.parentNode;
		}

		return depth;

	},
	_children: function( el ){
		var li , ul;
		li = el.up("li");
		ul = li.down("ul");
		return ul;
	}
});

document.observe("dom:loaded" , function(){
	var menus , x , c;
	menus = $$(".ddmenu");
	c = menus.length;
	for( x = 0 ; x < c; x++ )
		new DDMenu( menus[x] );
});

