$(function() {	
	// Put nav background on top of the current item
	var pos = 0;
	var left = 0;
	if ($('#nav').children('.current-menu-item').length === 0) {
		if ($('#nav').children('.current-menu-parent').length === 0) {
			pos = $('#nav li').eq(0).position();
			left = parseInt(pos.left) - 84 + $('#nav li').eq(0).width()/2;
			$('#nav').css({backgroundPosition: left });
		} else {
			pos = $('#nav').children('.current-menu-parent').position();
			left = parseInt(pos.left) - 84 + $('#nav').children('.current-menu-parent').width()/2;
			$('#nav').css({backgroundPosition: left });
		}
	} else {
		pos = $('#nav').children('.current-menu-item').position();
		left = parseInt(pos.left) - 84 + $('#nav').children('.current-menu-item').width()/2;
		$('#nav').css({backgroundPosition: left });
	}
	
	// Navigation
	$('#navigation ul li').hover(
		function () {
			var width = $(this).width();
			
			$(this).find('ul').show();
			$(this).find('ul ul').hide();
			
			// fix width to widest child
			$(this).find('ul li a').each(
				function () {
					if ($(this).width() > width) {
						width = $(this).width();
					}
				}
			);
			$(this).find('ul, ul li, ul li a').width(width + 20);
			
		},
		function () {
			$(this).find('ul').hide();
		}
	);
	$('#navigation ul ul li').hover(
		function () {
			var width = $(this).width();
			
			$(this).find('ul').show();
			
			// fix width to widest child
			$(this).find('ul li a').each(
				function () {
					if ($(this).width() > width) {
						width = $(this).width();
					}
				}
			);
			$(this).find('ul, ul li, ul li a').width(width + 20);
			
			var margin = width + 1;
			$(this).find('ul li').css({margin: '0 0 0 '+margin+'px'});
		},
		function () {
			$(this).find('ul').hide();
		}
	);
	
	// Add subnav hover
	$('#navigation ul li ul li').hover(
		function () {
			$(this).css({background: 'top left repeat-x url(/wp-content/themes/shredding/img/subnav-bg-hover.png)'});
		},
		function () {
			$(this).css({background: 'top left repeat-x url(/wp-content/themes/shredding/img/subnav-bg.png)'});
		}
	);
});
