/*
 
  jQuery subnav - Version 1.1

  By: Tim Gieseking
  
  A jQuery plugin for showing/hiding sub navigation.
  
  $('ul.subnav').subnav();
  
*/
;(function($) { 
		
	$.fn.subnav = function(settings) {
		
		settings = $.extend({}, $.fn.subnav.defaults, settings);
	    
		var $subnavli = this.children('li'),
			$subnavlia = $subnavli.children('a'),
			$currentul = this.children('li.current').find('ul:eq(0)'),
			t = '',
			fullwidth = this.parent('#nav-container').outerWidth(true);
									
		if (settings.padleft === true) { 
			$subnavli.each(function() { var $thisul = $(this).find('ul:eq(0)'); if ($thisul.length > 0) { moveleft($thisul); }}); 
		}
		
		$subnavli.not('.current').children('ul').hide();
		
		$subnavli.hover(
			
			function() {
				
				clearTimeout(t);
				
				var $this = $(this),
					$thisul = $this.find('ul:eq(0)');
					/*This is a quick band-aid for the nav bug*/
					$this.addClass('pushLeft')
					
				if (!$thisul.is(':visible'))
				{
					if ($thisul.length > 0 || settings.hideifnochildren == true)
					{
						$subnavli.children('ul').hide();
						$thisul.fadeIn('fast');
					}
				}
			},
			
			function() {
				if (!$(this).hasClass('current'))
				{
					clearTimeout(t);
					t = setTimeout(
						function() {
							$subnavli.children('ul').fadeOut('fast');
							$currentul.fadeIn('fast');
						}, settings.pause);
				}
				
			}
			
		);


		function moveleft($thisul)
		{
		
			var sumW = 0,
				leftpos = 0,
				i = 0,
				parentliwidth = 0,
				$parentli = $thisul.parent(),
				$parentlis = $parentli.add($parentli.siblings('li')),
				idx = $parentlis.index($parentli),
				forcewidth = false;
			
			if ($.browser.msie && $.browser.version <= 7) { forcewidth = true; }
			
			$thisul.children('li').each(function() 
			{  
				var $this = $(this),
					thiswidth = parseInt($this.outerWidth(true)); 
				
				sumW += thiswidth; 
				if (forcewidth === true) { $this.css({width: thiswidth + 'px'}); }
			});
			
			sumW += 10;
						
			$parentlis.each(function() 
			{
				var thiswidth = parseInt($(this).outerWidth(true));
				if (i < idx) { leftpos += thiswidth; }
				i++;
			});
										
			var parentliwidth = parseInt($parentlis.parent('ul').outerWidth(true)),
				emptyspace = fullwidth - parentliwidth,
				newpad = fullwidth - sumW,
				newwidth = fullwidth - newpad,
				maxpad = leftpos;

			//console.log(maxpad + ' - ' + newpad);
			
			if (newpad > 0) 
			{
				if (newpad > maxpad)
				{
					newwidth = newwidth + (newpad - maxpad);
					newpad = maxpad;
				}
				
				$thisul.css({paddingLeft: newpad + 'px', width: newwidth + 'px'});
				
			}
			
			return true;
		};	
	};

	// default options
	$.fn.subnav.defaults = {
		pause:"1500", 
		padleft:true, 
		hideifnochildren:true
	};
	


})(jQuery);
