
(function($) {

	$.fn.jmenu = function(options) {

		var defaults = {
			timer : 100,
			xOffset: 0,
			yOffset: 0
		};

		var options = $.extend( defaults, options );

		// Le timer qui sera réinitialiser si l'on revient sur le menu
		var timer = 0;

		var hideOtherBranche = function(ele) {
			var child = $(ele).find('ul').get(0);
			//$(ele).parent().find('ul').css('visibility', 'hidden');
			$(ele).parent().find('ul').slideUp('fast');
			//$(child).css('visibility', 'visible');
			$(child).slideDown('fast');
		};

		return this.each(function() {
			$t = $(this);

			$t.find('ul').css('position', 'absolute');
			$t.find('li').css('position', 'relative');

			$t.find('ul ul').each( function() {
				var liElement = $(this).parent().get(0);
				var w = $(liElement).innerWidth();
				$(this).css('left', w + options.xOffset);
				$(this).css('top', options.yOffset);
				$(this).css('margin', 0);
				$(this).css('padding', 0);
			});

			//$t.find('ul').css('visibility', 'hidden');
			$t.find('ul').slideUp('fast');
			$t.find('li').each( function() {
				$(this).mouseenter(function(event) {
					event.stopPropagation();
					hideOtherBranche(this);
					// On stoppe le timer si l'on pénètre dans un élément du menu
					window.clearTimeout(timer);
				});
			});

			// Lorsque l'on quitte le menu on déclenche un timer qui masquera les sous-menus
			$t.mouseleave( function() {
				timer = window.setTimeout( function() {					
					//$t.find('ul').css('visibility', 'hidden');									
					$t.find('ul').slideUp('fast');
				}, options.timer );
			});

			// On stoppe le timer si l'on re-rentre dans le menu
			$t.mouseenter( function() {
				window.clearTimeout(timer);
			});

			// Si l'on pénètre dans un sous menu on stoppe le timer et on force la visibility
			$t.find('ul').each( function() {
				$(this).mouseenter(function(event) {
					event.stopPropagation();
					//$(this).css('visibility', 'visible');	
					$(this).slideDown('fast');	
					window.clearTimeout(timer);
				});
			});

		});

	}

})(jQuery);

