$(document).ready(function(){
// set width of .mega_content dropdowns in horizontal nav
$("#mega_menu_2 .mega_content, #mega_menu_3 .mega_content").each(function(){
	var curr_number_of_columns = $(this).find("div").length;
	var curr_mega_content_width = (curr_number_of_columns * 195);
	if(curr_number_of_columns == 1){curr_mega_content_width = curr_mega_content_width - 10;}
	curr_mega_content_width = curr_mega_content_width + "px";
	$(this).css("width",curr_mega_content_width);
});

// determine number of links in each menu row

existing_template_position = $("#wrapper").offset();
existing_template_left_margin = existing_template_position.left;
$(".mega").each(function(){
	var curr_mega_content_width = $(this).find(".mega_content").width();
	// if dropdown is greater than half of screen width, then place in center
	if(curr_mega_content_width >= 498 ){
		var desired_left_value = (996 - curr_mega_content_width)/2;
		var existing_position = $(this).offset();
		var existing_left_position = existing_position.left;
		var existing_left_inside_template_position = existing_left_position - existing_template_left_margin;
		var left_position_adjustment = ((existing_left_inside_template_position - desired_left_value) * -1) + "px";
		// dont' center the dropdown if it's too close to the edge
		if($(this).hasClass("mega_right_align") == false && $(this).hasClass("no_auto_center") == false){
			$(this).find(".mega_content").css("left",left_position_adjustment);
		} 
		// desired_left_value > existing_left_inside_template_position
	}
	
	// assign right position to dropdown so that it stays on screen
	if($(this).hasClass("mega_right_align")) {
			// get width of mega_content
			var curr_mega_width = $(this).width();
			if(curr_mega_content_width < 498 || existing_left_inside_template_position > $(this).width()){
				var curr_left_value = -1 * (curr_mega_content_width - curr_mega_width + 8);
				// assign CSS left property to mega content
				$(this).find(".mega_content").css("left",curr_left_value);
			} //if
		} // if
	} //function
); // each


// change class on hover to cause dropdown
$(".mega").hover(function() {
    $this = $(this);
	
	$this.find("a:first").css("color","#000");
    t = setTimeout(function() {
       $this.addClass("hovering");
    }, 500);
    $this.data('timeout', t);
 
}, function() {
    $this = $(this);
    clearTimeout($this.data('timeout'));
		$this.removeClass("hovering");
		$this.find("a:first").css("color","#fff");
		 // if
});

}); // ready
