/* Binds hides cp_submenu blocks and binds them to main-nav tabs.
 * Losely based on 'Simple Tabs', See here for the genesis:
 * http://www.sohtanaka.com/web-design/examples/tabs/ 
 */

jQuery(document).ready(function() {
	initCpSubmenus();
});


function initCpSubmenus(){
	
	/* Instantiate the timer var. The timer var is needed 
	   for clearing on the initial mouseover since the
		 alternative (checking if timer is undefined) is not 
		 consistent between browsers. 
	*/
	var cp_closing_timer = setTimeout(function(){ /* nothing */ },0);

	
	// Tab's mouseenter event
	jQuery("#main-menu-links li").mouseenter(function() {
														   
		// Cancell any delayed fade out & 
		// just immediatley hide all submenus 
		clearTimeout(cp_closing_timer);
		jQuery(".block-cp-submenu").hide(); 
		
		// Remove any "submenu-active" class
		jQuery("#main-menu-links li a").removeClass("active-submenu");
		
		// Add "active-submenu" class to our newly selected tab
		jQuery(this).find("a").addClass("active-submenu"); 
		
		
		// Convert the href to the corresponsing submen id
		var linktxt = jQuery(this).find("a").text(); 
		var submenu = convertToSubmenuId(linktxt); 
		
		
		// Fade in the active content  
		jQuery(submenu).show();
		 
		return false;
	});
	
	// Tab's mouseleave event
	jQuery("#main-menu-links li").mouseleave(function() {	   
		cp_closing_timer = setTimeout( function() { 
          jQuery(".block-cp-submenu").fadeOut('slow');
					jQuery("#main-menu-links li a").removeClass("active-submenu");
        },75);
	});
	
	// Submenu's  mouseleave event
	jQuery(".block-cp-submenu").mouseleave(function() {		   
		cp_closing_timer = setTimeout( function() { 
          jQuery(".block-cp-submenu").fadeOut('slow'); 
					jQuery("#main-menu-links li a").removeClass("active-submenu");
        },75);
	});
	
	// Submenu's mouseenter event
	jQuery(".block-cp-submenu").mouseenter(function() {
		// Cancell any delayed fade out since
		// they are engaging the submenu
		clearTimeout(cp_closing_timer);								   
	});
	
}

// Converts a link's text to oue submenu ID format
function convertToSubmenuId(linktxt){ 
	// All lowercase
	linktxt = linktxt.toLowerCase();
	
	// Remove ampersands
	linktxt = replaceAll(linktxt, " &", "");
	linktxt = replaceAll(linktxt, " &amp;", "");
	 
	// Dashify spaces
	linktxt = replaceAll(linktxt, " ", "-");  
	
	// Ad the common appendage we namspaced our classes with 
	return '#cp-submenu-' + linktxt;
}

// Replaces all instances of the given substring.
function replaceAll(str, replaceStr, replaceWithStr){
	var intIndexOfMatch = str.indexOf( replaceStr );
	while (intIndexOfMatch != -1){ 
		str = str.replace( replaceStr, replaceWithStr )
		intIndexOfMatch = str.indexOf( replaceStr );
	} 
	return str;
}

 
;

