/*!
 * jQuery Hover Navigation
 * http://www.cw-internetdienste.de/
 *
 * Version 0.1
 *
 * Copyright 2010, Christian Weber
 * Free for commercial and
 * non-commercial use. Please shoot
 * me an email if you use it. Would love
 * to see it in action. :)
 *
 * Date: Mon Thu 11 18:18:12 2010 +0100
 */
 
 (function($) {
	$.fn.hoverNavigation = function(options) {
		$.fn.hoverNavigation.defaults = {
			sleep:500,
			mainSleep:2000, /* Standard: 1000 | Gibt Zeit an wie lange Menue ausgeklappt bleibt */
			slideTime:'fast',
			log:false
		};
		$(this).each(function() {
			var config = $.extend(true,$.fn.hoverNavigation.defaults,options);
			var nav = $(this);
			var self = this;
			var current = null;
			var active = false;
			var hover = false;
			var timer = false;
			var subhovered = false;

			nav.children('li.main').hover(
				function() {
					clearTimeout(active);
					clearTimeout(timer);
					hover = $(this);
					timer = setTimeout(function() { self.openMenu(); },config.sleep);
					//self.writeLog('Main in');
				},
				function() {
					clearTimeout(timer);
					subhovered=false;
					//self.writeLog('Main out');
				}
			);
			
			nav.hover(
				function() {
					clearTimeout(active);
					subhovered = true;
					self.writeLog('Sub in');
				},
				function() {
					clearTimeout(timer);
					subhovered =false;
					active = setTimeout(function() { self.closeMenu(); },config.mainSleep);
					self.writeLog('Sub out');
				}
			);
			
			self.closeMenu = function() {
				if(current!=null && subhovered == false) {
					current.slideUp(config.slideTime);
					self.writeLog('Close menu');
				}
			};
			
			self.writeLog = function(txt) {
				if(config.log !== false) {
					$('#'+config.log).html(txt+' ('+subhovered+')<br />'+$('#'+config.log).html());
				}
			};
			
			self.openMenu = function() {
				if(hover.children('ul').length !== 0) {
					if(current!=null && subhovered == false) {
						current.slideUp(config.slideTime,function() {
							current = hover.children('ul');
							hover.children('ul').slideDown(config.slideTime);
						});
					} else {
						current = hover.children('ul');
						hover.children('ul').slideDown(config.slideTime);	
					}
				}
			};
		});
	};
})(jQuery);
