$(document).ready(function(){
        var is_dropdown = function(li){
            return li.children('div').hasClass('drop-menu');
        }
	
	var dropdown_toggle = function(li,show){
		if(show){
			$('#nav-menu li.active div').hide();
			$('#nav-menu li').each(function(){
				if($(this).hasClass('active')){
					$(this).removeClass('active');
				}
			});		
			li.addClass('active');
			li.children('div').show();
//			update_div_width(li.children('div'));
//			dropmenu_position(li.children('a'), li.children('div'));
		}else{
			$('#nav-menu li.active').children('div.drop-menu').hide();
			$('#nav-menu li.active').removeClass('active');
		}
	}
	
	var HInavShow = function(){
		if(using_hover() && is_dropdown($(this))){
			dropdown_toggle($(this),true);
		}
	}
	var HInavHide = function(){
		if(using_hover() && is_dropdown($(this))){
			dropdown_toggle($(this),false);
		}
	}
	
	var using_hover = function(){
		return ($('#nav-menu').hasClass('fhover'));
	}
	
	var click_within = function(x,y,o){
		pos = o.position();
		w = o.width();
		h = o.height();
		
		if(x >= pos.left && x<= (pos.left+w) && y>=pos.top && y<= (pos.top+h)){
			return true;
		}
		return false;
	}
	
	var dropmenu_position = function(a,div){
		div.css('top', a.position().top + a.height() + 7);		
		div.css('left', a.position().left - div.outerWidth() + a.outerWidth() + 1);
	}
	
	var update_div_width = function(div){
		w = 0;
		div.children('ul').each(function(){
			w += $(this).outerWidth()+2;
		});
		div.width(w);
	}
	
	$(document).click(function(event){
		x = event.clientX;
		y = event.clientY;
		if($('#nav-menu li.active').size()>0 && !click_within(x,y,$('#nav-menu li.active'))){
			dropdown_toggle($('#nav-menu li.active'), false);
		}		
	});
	
	$("#nav-menu li").hoverIntent({
		sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
		interval: 100,   // number = milliseconds of polling interval
		over: HInavShow,  // function = onMouseOver callback (required)
		timeout: 50,   // number = milliseconds delay before onMouseOut function call
		out: HInavHide    // function = onMouseOut callback (required)
	});
});
