/*
Original JavaSript code by Soh Tanaka @ http://www.sohtanaka.com/web-design/mega-drop-downs-w-css-jquery/
Modifications by Gintas Korsakas aka Whooz [ whooz2[at]gmail.com ]
*/
$(document).ready(function() {
	function megaHoverOver(){
		$(this).find(".mm_sub").stop().fadeTo('fast', 1).show();       	
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				$(this).find("ul").each(function() {					
					rowWidth = rowWidth + $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { 
			var biggestRow = 0;	
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});

			$(this).find(".mm_sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
		} else { 			
			$(this).calcSubWidth(); 
			if ( $(this).find(".mm_sub").length > 0 ) {
				
				var o = $(this).find('.mm_sub').offset();     
			    var p = $('#megamenu').offset();
			    var pw = document.getElementById('megamenu').clientWidth;
			    var tw = rowWidth;
				
				if (rowWidth > pw) {
					tw = pw - 19;
					rowWidth = pw - 19;
				}
				
			    var tml = (tw + (o.left - p.left)) - pw;
				$(this).find(".mm_sub").css({'width' : rowWidth}).css({'margin-left':'-' + tml - 19 + 'px'});
			}
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".mm_sub").stop().fadeTo('fast', 0, function() {
		  $(this).css({'margin-left':'0'});
      $(this).hide(); 
	  });
	}

	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 500, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};    

	$("ul#mm_topnav li .mm_sub").css({'opacity':'0'}); 
	$("ul#mm_topnav li").hoverIntent(config);
});
