$(function(){$('nav#primary > ul > li.dropdown').subnav();});

// Easing
jQuery.extend( jQuery.easing,{
	easeInOutExpo: function (x, t, b, c, d){
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	}
});

$.fn.subnav = function(subsub){
	if( $.browser.msie && $.browser.version < 9 ){
		var capable = false;
	}else{
		var capable = true;
	}
	return this.each(function(){
		var snav = false;
		var hnav = false;
		var $dropdown;
		var ddClass = '';
		capable == true ? ( subsub == true ? ddClass = 'dropdown subsub capable' : ddClass = 'dropdown capable' ) : ( subsub == true ? ddClass = 'dropdown subsub' : ddClass = 'dropdown' );
		$dropdown = $('<div/>',{
			'class': ddClass,
			html: '<ul>' + $(this).children('ul').html() + '</ul>',
			mouseleave: function(){
				hnav = false;
				setTimeout(cleanup, 100);
			},
			mouseenter: function(){
				hnav = true;
			}
		}).appendTo('body');
		if( !subsub ) $dropdown.find('.dropdown').subnav(true).children('ul').remove();
		$(this).mouseenter(function(e){
			hnav = true;
			if( snav == false ){
				if( subsub ){
					var x = $(this).offset().left + 210;
					var y = $(this).offset().top;
				}else{
					var x = $(this).offset().left;
					var y = $(this).offset().top + 30;
				}
				$dropdown.css({top:y,left:x}).show();
				var h = $dropdown.find('ul').height();
				if(capable){
					$dropdown.stop([]).css({opacity:0}).animate({height:h,opacity:1},500,'easeInOutExpo');
				}else{
					$dropdown.css({height:h});
				}
				snav = true;
				$dropdown.find('li.dropdown').mouseover(function(){
					$dropdown.siblings('.dropdown').hover(function(){
						hnav = true;
					},function(){
						hnav = false;
						setTimeout(cleanup, 100);
					});
				});
			}else{
				$dropdown.stop([]).animate({height:$dropdown.find('ul').height(),opacity:1},400,'easeInOutExpo');
			}
		});
		$(this).mouseleave(function(){
			hnav = false;
			setTimeout(cleanup, 200);
		});
		function cleanup(){
			if( hnav == false ){
				if( capable ){
					$dropdown.stop([]).animate({height:0,opacity:0},500,'easeInOutExpo',function(){
						$(this).hide();
						snav = false;
					});
				}else{
					$dropdown.hide();
					snav = false;
				}
			}
		}
	});
};
