var GLOBALS  = {
					maxBoxStageWidth:	780,
					maxBoxStageHeight:	69,
					navIsVisible:		false,
					tmp:	{
								yMousePos:	0,
								maxLeft: 	0,
								maxBottom: 	0,
								minLeft:	0	
							}
				};
$(document).ready(function(){
	$('.mainlinkmenu').bind('mouseover',function(e){
		GLOBALS.tmp.yMousePos = e.pageY;
		GLOBALS.navIsVisible = true;
		$('#subnavcontainer').css({left:"auto"});
		var thisUl = $('ul',$(this).parent());
		var i			=1;
		var tempUl 		= '';
		var fullList 	= '';
		var printed		= false;
		$('li', $(thisUl)).each(function(){
				if (i%4 != 0){			
					tempUl += '<li>'+$(this).html()+'</li>';
					printed = false;
				}else{
					if (i>=3){
						tempUl += '<li>'+$(this).html()+'</li>';
						fullList += '<ul>'+tempUl+'</ul>';
						tempUl = '';
						printed = true;
					}
				}
				i++;
		});
		if (!printed){
			fullList += '<ul>'+tempUl+'</ul>';
			tempUl = '';
			printed = true;
		}
		$('#subnavcontainer').html(fullList);
		var spaceleft = $(this).offset().left;
		if ( (spaceleft+$('#subnavcontainer').width())>GLOBALS.maxBoxStageWidth){
			spaceleft -= (spaceleft+$('#subnavcontainer').width()-GLOBALS.maxBoxStageWidth);
		}
		$('#subnavcontainer').css({position:"absolute", left:spaceleft+"px"});
		$('#subnavcontainer').css({display:'block'});
		GLOBALS.tmp.maxLeft = spaceleft+$('#subnavcontainer').width();
		GLOBALS.tmp.maxBottom = GLOBALS.maxBoxStageHeight+$('#subnavcontainer').offset().top;
		GLOBALS.tmp.minLeft = spaceleft;
		$('#pos').html(GLOBALS.tmp.maxLeft + ' ' +GLOBALS.tmp.maxBottom + ' '+GLOBALS.tmp.minLeft + ' ');
	});
	
	
	$('#container').bind('mousemove',function(e){
		if (GLOBALS.navIsVisible){
			if(e.pageX>GLOBALS.tmp.maxLeft || e.pageX<GLOBALS.tmp.minLeft || e.pageY>GLOBALS.tmp.maxBottom){
				$('#subnavcontainer').html('');
				GLOBALS.navIsVisible = false;
			}
		}
	});
	
	
});