jQuery(document).ready(function($){
	var $main = $("#menu > li")
	var $firstUL = $main.children("ul")
	var $secondUL = $firstUL.children("li").children("ul")
	var $current = $main.filter(".current").children("ul")
	$firstUL.each(function(){
		var $firstChildren = $(this).children("li")
		var $childrenCount = $firstChildren.length
		var $width = 0
		if ($childrenCount == 2){
			$firstChildren.each(function(){
				$width += $(this).outerWidth()
				$(this).css({ width: $(this).outerWidth() + 240 + 'px' })
			})
			$(this).css({ "width": ( $width + 480 ) + "px", "margin-left": "-" + ( ($width + 480) / 2 ) + "px" })
		} else if ($childrenCount == 3){
			$firstChildren.each(function(){
				$width += $(this).outerWidth()
				$(this).css({ width: $(this).outerWidth() + 160 + 'px' })
			})
			$(this).css({ "width": ( $width + 480 ) + "px", "margin-left": "-" + ( ($width + 480) / 2 ) + "px" })
		} else if ($childrenCount == 4){
			$firstChildren.each(function(){
				$width += $(this).outerWidth()
				$(this).css({ width: $(this).outerWidth() + 80 + 'px' })
			})
			$(this).css({ "width": ( $width + 320 ) + "px", "margin-left": "-" + ( ($width + 320) / 2 ) + "px" })
		}
	})
	$secondUL.each(function(){
		var $thisWidth = $(this).outerWidth()
		var $parentWidth = $(this).parent().outerWidth()
		$(this).css({ "left": ( $parentWidth / 2 )  + "px" })
		$(this).css({ "margin-left": "-" + ( $thisWidth / 2 )  + "px" })
	})
	$main.hoverIntent({
		sensitivity: 3,
		interval: 100,
		over: showMain,
		timeout: 100,
		out: hideMain
	})
	$firstUL.children("li").hoverIntent({
		sensitivity: 3,
		interval: 150,
		over: showSub,
		timeout: 150,
		out: hideSub
	})
	$secondUL.hide();
	$firstUL.hide();
	if($main.is(".current")) {
		$current.show();
	}
})

function showMain() {
	this.isCurrent = $(this).is(".current")
	if (!this.isCurrent) {
		$(this).siblings(".current").children("ul").stop(true, true).fadeOut(250)
		$(this).find("ul").eq(0).stop(true, true).fadeIn(500)
	}
}
function hideMain() {
	this.isCurrent = $(this).is(".current")
	if (!this.isCurrent) {
		$(this).find("ul").eq(0).stop(true, true).fadeOut(250)
		$(this).siblings(".current").children("ul").stop(true, true).fadeIn(500)
	}
}

function showSub() {
	$(this).find("ul").eq(0).stop(true, true).fadeIn(250)
}
function hideSub() {
	$(this).find("ul").eq(0).stop(true, true).fadeOut(250)
}
