TP.MenuView = Class.create({
	
	current: null,
	hide: null,
	currentFunction: null,

	initialize: function(rootObject){
			
		$(rootObject).select('ul.left-nav li.flyout').each(function(element){
			
			var popout = element.select('div').first();
			
			element.observe('mouseover', function(event){
				// The event in IE fires before CSS shows the div so we have to do this here				
				popout.style.display='block';
				element.addClassName('active');
				
				if(this.current == popout)
					return;
				
				this.current = popout;	
				
				if(this.currentFunction != null) {
					clearTimeout(this.hide);
					this.currentFunction();
				}
				
				this.resize(this.current);
	
			}.bind(this));
			
			element.observe('mouseout', function(){
				this.current = null;
				
				this.currentFunction = function() {
					if(this.current != popout) {
						popout.style.display='none';			
					
						if(this.current != element) {
							element.removeClassName('active');
						}
					}
					this.currentFunction = null;
				}.bind(this);
				
				this.hide = setTimeout(this.currentFunction, 300);

			}.bind(this));
			 

			Event.observe(window, 'scroll', function(){
				this.current = null;
			}.bind(this));

			Event.observe(window, 'resize', function(){
				this.current = null;
			}.bind(this));
			
		}.bind(this));
		
		
		
	},
	
	resize: function(popout) {
		
		if(popout == null)
			return;
		
		var top = TP.findLocation(popout.down()).y;				
		var height = popout.down().offsetHeight;
		var scroll = TP.getScrollPosition();
		var size = TP.getSize();
		var pageBottom = size.height + scroll;
		var elementBottom = top + height;
		
		if(popout.elementTop == null)
			popout.elementTop = top;
		
		if(popout.elementBottom == null)
			popout.elementBottom = elementBottom;
		
		
		if(height > size.height){	
			if ((top - scroll+10) != 0) {
				
				if((elementBottom - pageBottom) < 0) {
					popout.style.top = 0 + "px";
				} 				
				
				popout.style.top = "-" + (popout.elementTop - scroll + 10) + "px";
			}
		} else {
			if((elementBottom - pageBottom) != 0){							
				
				if((elementBottom - pageBottom) < 0) {
					popout.style.top = 0 + "px";
				} 
				
				popout.style.top = "-" + (popout.elementBottom - pageBottom) + "px";
				
			} 
		}		
	}
	
});

Event.observe(window, 'load', function(){
	if($('leftmenu'))
		new TP.MenuView('leftmenu');
});