/**
 * 
 * jQuery P&G Menu Plugin
 * Copyright(c) 2008, VSA Partners, Inc.
 * http://www.vsapartners.com 
 * 
 * @author Ry Racherbaumer (rracherbaumer@vsapartners.com)
 * @version 0.1
 * 
 */

//
// create closure
//
(function($) {
	//
	// plugin definition
	//
 	$.fn.pgmenu = function(options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.pgmenu.defaults, options);
		// iterate and reformat each matched element
		return this.each(function() {
			// get this element
			var $this = $(this);
			var $li = $('li', $this);
			var $current = $('li.current', $this);
			var nocurrent = false;
			// see if a current item is selected
			if ($current.length > 0) {
				var $currenta = $('a', $current);
				// lose the bg image
				$current.css('background-image', 'none');
				// create the hover element, add its class, then append it to bound element
				var hoverEl = $('<div/>').addClass(opts.hoverClass).css({
					left: $currenta.position().left,
					width: $currenta.width() + 8
				}).appendTo($this);
			} else {
				// create the hover element, add its class, hide it, then append it to bound element
				var hoverEl = $('<div/>').addClass(opts.hoverClass).css({
					left: 0,
					width: 0,
					opacity: 0
				}).appendTo($this);
				nocurrent = true;
			}
			// bind mouseover event to listitem
			$li.not('.current').bind('mouseenter', function() {
				var me = $('a', this);
				hoverEl.stop();
				// if there's no current element and the hoverEl is hidden
				// don't animate, just position and show hoverEl
				if (nocurrent === true && hoverEl.css('opacity') == 0) {
					hoverEl.css({
						opacity: 1,
						left: me.position().left,
						width: me.width()+8
					});
				} else {
					hoverEl.animate({
						opacity: 1,
						left: me.position().left,
						width: me.width()+8
					}, opts.delay, opts.easing);
				}				
			});
			// bind mouseout event to listitem
			$li.not('.current').bind('mouseleave', function() {
				hoverEl.stop();
				// if there's no current element, fade out the hoverEl
				if (nocurrent === true) {
					hoverEl.animate({
						opacity:0
					}, 500);
				} else {
					hoverEl.animate({
						left:$currenta.position().left,
						width:$currenta.width()+8
					}, opts.delay, opts.easing);
				}						
			});
		});
	};
	//
	// plugin defaults
	//
	$.fn.pgmenu.defaults = {
		hoverClass: 'hoverElement',
		easing: null,
		delay: 500
	};
//
// end of closure
//
})(jQuery);