/**
 * Sliding menu plugin
 * makes an animated div slide along the bottom of the menu and position directly below 
 * the item A tag, it adjusts its width accordingly.
 * 
 * @author Grant Ockwell
 */
 
 (function($) {
	var animationTimer = null;
	
	$.fn.extend({
		
		slideMenu: function() {
		
			$(function() {
			
				$('#menu-slide').hide();

				// there is a selected element, slider must goto it
				if ($('a.selected').length > 0) {
					
					// animate the slider to the current selected element
					var gotoSelectedElement = function(element) {
						$('#menu-slide').animate({
							left: $('a.selected').parent().position().left,
							width: $('a.selected').parent().outerWidth()
						}, 500);
					};
					
					// buffer it by a few milli secconds 
					setTimeout(gotoSelectedElement, 500);
					
				} else {
					// because there is no selected element for it to goto we just fade it out on mouse out
					$('#menu').mouseleave(function() {
						animationTimer = setTimeout("$('#menu-slide').fadeOut('slow')", 200);
					});
				}
				
				
			});
		
			return this.each(function() 
			{
				// get the top level li's
				$(this).find('ul:first>li').mouseover(function() 
				{
					if (animationTimer) { 
						clearTimeout(animationTimer); 
					}

					$('#menu-slide').clearQueue();
					
					if ($('#menu-slide:hidden').length == 1) {
						$('#menu-slide').fadeIn();
					}

					//if ($('#menu-slide:animated').length == 0) {
						$('#menu-slide').animate({
							left: $(this).position().left,
							width: $(this).outerWidth()
						}, 450);
					//} 
					
				}).mouseout(function() 
				{
					var runAnimation = function() {
						$('#menu-slide').animate({
							left: $('a.selected:first').parent().position().left, 
							width: $('a.selected:first').parent().outerWidth()
						} , 450);
					};
					
					// make sure we've got someware to return to, if not the mouseleave fadeout works to hide the slider
					if ($('a.selected').length > 0) {
						animationTimer = setTimeout(runAnimation, 200);
					} 
				});
			});
		}
	});
})(jQuery);
 
