$(function(){

    var config = {    
         sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
         interval: 0,  // number = milliseconds for onMouseOver polling interval    
         over: doOpen,   // function = onMouseOver callback (REQUIRED)    
         timeout: 500,   // number = milliseconds delay before onMouseOut    
         out: doClose    // function = onMouseOut callback (REQUIRED)    
    },
	openEl = null,
	topLevelItems = $("ul.dropdown > li"),
	cachedHeights = [];
    
	function isChildOfOpenEl(el) {
		if (openEl == null)
			return false;
		
		var isChild = false;
		$(el).parents().each(function(){
			if (this == openEl)
				isChild = true;
		});
		return isChild;
	}
	
	function closeOpenEl(thisEl) {
		if (openEl == null || openEl == thisEl)
			return;
		doClose(openEl);
	}
	
    function doOpen() {
		var isChild = isChildOfOpenEl(this);
		if (!isChild) { // short circuit
			closeOpenEl(this);
			openEl = this;
		}
		
		$(this).addClass("hover");
		if (!$(this).hasClass('hasDropDown'))
			return;
		
		var subMenu = $('ul:first',this);
		
        subMenu.css(
			{
				'visibility': 'visible',
				'display': 'block',
				'height': '0px',
				'opacity': 1
			}
		).animate(
			{
				'height': cachedHeights[topLevelItems.index(this)] + 'px'
			},
			{
				duration: 200,
				easing: 'linear'
			}
		);
    }
 
    function doClose(element) {
		var el = (element.nodeType == null) ? this : element, // determine if this is a DOM node
			subMenu = $('ul:first',el);
		
		if (!$(el).hasClass('hasDropDown')) {
			$(el).removeClass('hover');
			return;
		}
		
        subMenu.animate(
			{
				'height': '0px'
			},
			{
				duration: 100,
				easing: 'linear',
				complete: function() {
					var height = cachedHeights[topLevelItems.index(el)];
					$(this).css('height', height + 'px');
					$(this).css('visibility', 'hidden');
					$(this).parent().removeClass("hover");
				}
			}
		);
    }

	// initialization
	topLevelItems.each(function(){
		cachedHeights.push($('ul:first', this).height());
	});
	$("ul.dropdown li").hoverIntent(config);
    $("ul.dropdown li ul li:has(ul)").find("a:first").append(" &raquo; ");

});
