// Depends on lowpro and prototype

// this adjusts the positioning onload
Event.onReady(function() {
  	$$('li.nav-item').each(function(el){

		var itemSize = 22;
		var offset = 2;
		if (el.down('div') != null) {

			var numItems = el.down('div').down('ul').childElements('li').size();
			var height = (numItems * itemSize)+offset;
			el.down('div').setStyle({top:-height+'px',height:height+'px'});
		}
	});


});

// behaviours for the menu items
Event.addBehavior({
	'li.nav-item:mouseover' : function(event) {
		if (this.down('div') != null) {
			if(this.down('div').getStyle('display')=='none'){
				this.down('div').show();
			}
			// take a peep at the siblings and make sure they are down where they belong
			this.siblings().each(function(el){
		  		if (el != null && el.down('div') != null) {
					if(el.down('div').getStyle('display')=='block') {
						el.down('div').hide()
					}
		  		}
			});
		}
   },

	'li.nav-item:mouseout' : function(event){
		// if we're rolling out of the menu item and not into the submenu, put it away
		if( this.down('div') != null
			&& !Position.within(this,Event.pointerX(event),Event.pointerY(event))
			&& !Position.within(this.down('div'), Event.pointerX(event), Event.pointerY(event))){
					if(this.getStyle('display')=='block'){
						if (this.down('div') != null) {
							this.down('div').hide();
						}
					}
		}
	},

   'div.submenu:mouseout' : function(event){
		// rolling out of the submenu (and not back into the parent li)
		if(!Position.within(this,Event.pointerX(event),Event.pointerY(event)) && !Position.within(this.up('li'), Event.pointerX(event), Event.pointerY(event))){
				if(this.getStyle('display')=='block'){
					this.hide();
				}
		}
	}
});

