/* *
   * Mega-Menu jQuery
   * This is an altered and expanded version of the jQuery menu found
   * at http://www.sohtanaka.com/web-design/mega-drop-downs-w-css-jquery/ 
   * 
   */

// MEGA-MENU COLUMNS
$(function(){

	var colNum = 10;

	function columnize() {	
		// For each .level2 ul
		$('ul.level2').each(function(i){
			// If there are more than 10 li's inside
			if ($(this).children('li').length > colNum) {
				// Create a new ul after the original		
				$(this).after('<ul class="level2" id="slice' + i + '"></ul>')
					
				// Cut all li's after the first 10 and append to the new ul
				$(this).children('li').slice(colNum).appendTo('#slice' + i);
				
				// Call the function again
				columnize();
			}
		});
	}
	columnize();
});

//On Hover Over
function megaHoverOver(e){
  $(this).find(".sub").stop().fadeTo(50, 1).show(); //Find sub and fade it in
  (function($) {
    //Function to calculate total width of all ul's
    jQuery.fn.calcSubWidth = function() {
			// If this is a mega-menu
  		if ($(this).parents('.m-menu').length > 0) {
    	 	rowWidth = 0;
      	
      	//Calculate row
      	if ($(this).find(".sub > ul.level2").length < 3) {
	        $(this).find(".sub > ul.level2").each(function() { //for each ulâ€¦
	            rowWidth += $(this).width(); //Add each ul's width together
	        });
        }
        else {
        	$(this).find(".sub > ul.level2").each(function() { //for each ulâ€¦
	            rowWidth = $(this).width() * 3; //Add each ul's width together
	        });
        }
      }
      // Else if we just want a regular drop down
      else {
      	rowWidth = 'auto';
      }
    };
  })(jQuery);

  if ( $(this).find(".row").length > 0 ) { //If row existsâ€¦

  	var biggestRow = 0;	

    $(this).find(".row").each(function() {	//for each rowâ€¦
    	$(this).calcSubWidth(); //Call function to calculate width of all ul's
      //Find biggest row
      if(rowWidth > biggestRow) {
      	biggestRow = rowWidth;
      }
    });

    $(this).find(".sub").css({'width' :biggestRow}); //Set width
    $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin
	} 
	else { //If row does not existâ€¦
	  $(this).calcSubWidth();  //Call function to calculate width of all ul's
    $(this).find(".sub").css({'width' : rowWidth}); //Set Width
	}        
}	

//On Hover Out
function megaHoverOut(){
  $(this).find(".sub").stop().hide(); // hide it
}
