// JavaScript Document
const subMenuShowingClass = 'subMenuShowing';

function ToggleImage(img, isMainMenuItem) {
	// use the correct suffixes.
	var onSuffix;
	var offSuffix;
	if (isMainMenuItem) {
		onSuffix = 'On.jpg';
		offSuffix = 'Off.jpg';
	} else {
		onSuffix = '_on.png';
		offSuffix = '_off.png';
	}
	
	if (!$(img).hasClass(subMenuShowingClass)) {
		// determine if the src image is "On" or "Off".
		var src = $(img).attr('src');
		var isOn = (src.indexOf(onSuffix, 0) >= 0);
		
		// determine the new src attribute for the image (swap the On/Off state).
		var newSrc = (isOn ? src.replace(onSuffix, offSuffix) : src.replace(offSuffix, onSuffix));
		$(img).attr('src', newSrc);
	}
}

$(function() {
	// menu image swapping.
	$('#topNav img.menuItem').hover(function() {
		ToggleImage(this, true);
	});
	
	$('#topNav img.subMenuItem').hover(function() {
		ToggleImage(this, false);
	});
	
	// sub-menu display.
	$('#topNav img.hasSubMenu').mouseenter(function() {
		// Add a class on the parent menu item that indicates its sub-menu is showing.
		$(this).addClass(subMenuShowingClass);
		
		// get the id of the image with a sub-menu, and determine the id of the sub-menu to display/hide.
		var menuId = $(this).attr('id');
		var subMenuId = "sub-" + menuId;
		
		// show the sub-menu.
		$('#' + subMenuId).fadeIn('slow');
	});
	
	// sub-menu hide.
	$('#topNav .subMenu').mouseleave(function() {
		// hide the sub-menu.
		$(this).fadeOut('slow');
		
		// get the id of this sub-menu element, and determine the id of the parent menu item.
		var subMenuId = $(this).attr('id');
		var parentMenuId = subMenuId.replace('sub-', '');
		
		// remove the class on the parent menu item that indicates its sub-menu is showing.
		var parentMenuImg = $('#' + parentMenuId)
		parentMenuImg.removeClass(subMenuShowingClass);
		
		ToggleImage(parentMenuImg, true);
	});
});
