(function($) {
	
	$.fn.dynaMenu = function() {
		var normalWidths = []; 
		
		$(".dyna-menu-section").each(function(index) {
			var currentSection = $(this);
			var normalWidth = currentSection.css("width").replace("px", "");
			normalWidths[index] = normalWidth;
			var maxWidth = 20;
			
			currentSection.find(".dyna-menu-element").each(function() {
				maxWidth += $(this).outerWidth();
			});
			var step = 6;
			var job;
			
			currentSection.mouseover(function() {

				if (job) {
					window.clearInterval(job);
				}
				
				job = window.setInterval(function() {
					var currentWidth = currentSection.width();
					var remaining = maxWidth - currentWidth;
					
					if (remaining - step <= 0) {
						window.clearInterval(job);
						return;
					}
					
					// find the longest element
					var width = 0;
					var longestElement;
					
					$(".dyna-menu-section").each(function() {
						var section = $(this);
						
						if (currentSection.attr("id") != section.attr("id")) {
							var sectionWidth =  section.width();
							if (sectionWidth > width) {
								longestElement = section;
								width = sectionWidth;
							}
						}
					});
					
					currentSection.css("width", (currentWidth + step) + 'px');
					longestElement.css("width", (width - step) + 'px');
				}, 10)
			});
			currentSection.mouseout(function() {

				if (job) {
					window.clearInterval(job);
				}
				
				job = window.setInterval(function() {
					var currentWidth = currentSection.width();
					var remaining = currentWidth - normalWidth;
					
					if (remaining - step <= 0) {
						window.clearInterval(job);
						return;
					}
					
					// find the shortest element
					var width = 1000;
					var ratio = 1;
					var shortestElement;
					
					$(".dyna-menu-section").each(function(index) {
						var section = $(this);
						
						if (currentSection.attr("id") != section.attr("id")) {
							var sectionWidth =  section.width();
							var normalSessionWidth = normalWidths[index];
							var sessionRatio = sectionWidth / normalSessionWidth;
							if ((sessionRatio < ratio) && (sectionWidth + step <= normalSessionWidth)) {
								shortestElement = section;
								width = sectionWidth;
								ratio = sessionRatio;
							}
						}
					});
					
					currentSection.css("width", (currentWidth - step) + 'px');
					shortestElement.css("width", (width + step) + 'px');
				}, 10);
			});
		});
		
		$(".dyna-menu-element").each(function() {
			var element = $(this);
			element.mouseover(function() {
				element.addClass("active");
			});
			element.mouseout(function() {
				element.removeClass("active");
			});
		})
	};
})(jQuery)
