$(function() {

		var flyOut = $("#flyOut");
		var checkSubMenuTimer;
		var checkTimerLength = 50;

		var overFlyOut = false;
		var overMenu = false;
		var overSub = false;			
		
		var currentSection;
		var currentItem;
    	var curTarg;


    //////////////////////////////
    //
	//  START HOVER EVENTS
	//    


		// Hover over menu items
    	var menuConfig = {    
     		sensitivity:1, // number = sensitivity threshold (must be 1 or higher)    
     		interval: 1, // number = milliseconds for onMouseOver polling interval    
     		over: sectionOn, // function = onMouseOver callback (REQUIRED)    
     		timeout: 100, // number = milliseconds delay before onMouseOut    
     		out: sectionOff // function = onMouseOut callback (REQUIRED)    
		};
		
		$(".menu .menu-content").hoverIntent( menuConfig );

		var curSection;
		function sectionOn(event) { 
			currentSection = $(this);
	      	openSection($(this), false);
      	}
      	
      	function sectionOff(event) { 
	      	var mouseInside = currentSection;
      		if (mouseInside == false){
      			overMenu = false;
      			closeSection(currentSection);	 
      			rollOff(currentSection); 
      		}
      		setTimeout(checkSubMenu,checkTimerLength,1);
      	}
      	
      	function testMouseInside(targ){
      		if (targ){
		      	var pos = targ.offset();
	      		var posRight = pos.left + targ.width();
	      		var posBottom = pos.left + targ.width();
	      		
	      		var mouseInside = false;
	      		
	      		if (cursorX > pos.left && cursorX < posRight){
	      			if (cursorY > pos.top && cursorY < posBottom){
	      				mouseInside = true;
	      			}
	      		}
	      		return mouseInside;
      		} else {
      			//console.log(targ);
      		}
      	}

		
		// Hover over gray flyout
		
		flyOut.hover(
      		function (event) {
      			overFlyOut = true;
      		}, 
      		function (event) {
      			overFlyOut = false;
      			//closeSection(curSection);
      			sectionOff(event);
      		}
    	);
    	
    		
    	// Hover over menu items
    	var config = {    
     		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
     		interval: 5, // number = milliseconds for onMouseOver polling interval    
     		over: subSubOn, // function = onMouseOver callback (REQUIRED)    
     		timeout: 300, // number = milliseconds delay before onMouseOut    
     		out: subSubOff // function = onMouseOut callback (REQUIRED)    
		};
		
		$(".menuLevel1 ul li").hoverIntent( config );
		function subSubOn(event) {
      			overSub = true;
				//log($(this));
				showMenu($(this), event);
      	}
      	function subSubOff (event) {
      			overSub = false;
      			checkSubMenu();
      	}


    	
	//  END HOVER EVENTS
	//
    //////////////////////////////



		function rollOff(targ){
			currentSection = targ;
			checkSubMenuTimer = setTimeout(checkSubMenu,checkTimerLength,1);
		}
		function checkSubMenu(){
			
			if (overFlyOut == false && testMouseInside(currentSection) == false ){
				// TODO TEST MOUSE INSIDE
				//if (!overMenu){
					hideMenu(flyOut, null);
					closeSection(currentSection);
				//}
			} else {
				clearTimeout(checkSubMenuTimer);
				checkSubMenuTimer = setTimeout(checkSubMenu,checkTimerLength,1);
			}
		}
		

		
		function closeSection(targ){
			var selectedEffect = "clip";
			var options = {};
			var partialOpen = false;
			
			if( $(targ).hasClass("currentSection") ){
				partialOpen = true;
			}
			var openObject = $(".menuLevel1");
				
				if ( partialOpen == true ){
					//$(targ).stop().animate({ height: "60px", top: "40px"}, {duration: 500, easing:'easeInOutQuart'} );	      		
				} else {
					$(targ).stop().animate({ height: "40px", top: "60px"}, {duration: 500, easing:'easeInOutQuart'} );	      		
				}
	      		targ.removeClass('is_open');
		};
		
		
		function openSection(targ, quick){

			var selectedEffect = "clip";
			var options = {};
			
			var openObject = $(".menuLevel1");
			
			// Find the new opening amounts
			var openHeight = 50 + targ.children(".menuLevel1").height();
			var openTop = 108 - openHeight;
      		
      		//alert('openHeight '+openHeight);
      						

			
			if (!quick) {
				openHeight = openHeight + "px";
				openTop = openTop + "px";
				
				$(targ).stop().animate({ 
	        		height: openHeight,
	        		top: openTop
	      		}, 450 );
      		} else {
      			//openHeight = Number(openHeight);
      			if (openHeight > 180){
      				openHeight = 122;
      				openTop = 113 - openHeight;
      			}
      			openHeight = openHeight + "px";
				openTop = openTop + "px";
			
				$(targ).css('height',openHeight);
				$(targ).css('top',openTop);
      		}
			targ.addClass('is_open');
		};
		
		function showMenu(targ, event){
			var menuContent = "<ul>"+targ.children("ul").html()+"</ul>";//$("#nav-gallery");
			var menuDisplay = $("#flyOut");
			var oldContent = menuDisplay.children("ul");
			oldContent.replaceWith(menuContent);
			
			flyOut.css( { "display": "block" } );
			
			//var pos = $(targ).offset();
			//var newX = pos.left + $(targ).width();
			
			var targContent = targ.children(".category-link").width();
			
			var pos = $(targ).offset();
			var maxX = pos.left + targContent - 10;
			var newX = pos.left + 65;
			
			if (maxX > newX + 50){ newX = maxX };
			
			var curX = menuDisplay.offset().left;
			var difX = Math.abs(curX - newX);
			
			
			// Add Unit Type
			var newX = newX + "px";			
			
			// If it is a big jump then short circuit the animation on X
			if (difX > 150){
				menuDisplay.css( { "left": newX } );
				menuDisplay.css( { "top": pos.top } );
			}
			
			//menuDisplay.css( { "left": newX } );
			menuDisplay.stop().animate({ 
        		opacity: "1",
        		left: newX,
        		top: pos.top
      		}, 450 );
			
		}

		function menuKill(){
			//flyOut
			log("??? MENU DEAD ???");
			flyOut.css( { "display": "none" } );
		}
		
		function hideMenu(targ, event){
			var menuDisplay = $("#flyOut");
			menuDisplay.stop().animate({ opacity: "0"}, 450, function(){ menuKill(); } );
		}
		
		function initMenu(){
			//alert("curSection: "+curSection);
			curSection = $(".currentSection");
			//alert( curSection.attr('id') );
			if (curSection){
				openSection(curSection, true);
			}
		}

		initMenu();
		
	});
