YAHOO.namespace("kqed");
var KQED = YAHOO.kqed;

KQED.Nav = function() {
	var e = YAHOO.util.Event,
		d = YAHOO.util.Dom,
		primaryNavDivWrapId = "wrap-navigation",
		primaryNavOnClass = "on",
		tertiaryNavBoxId = "tertiary-navigation-box",
		tertiaryNavListClass = "tertiary-navigation-list",
		navPartialMatchClass = "nav-partial-match",
		matchNavLocationClass = "match-nav-location",
		navClasses = [0, "wrap-navigation", "wrap-secondary", "tertiary", "quaternary"],
		youAreHereClasses = [0, "on", "on", "tertiary-youarehere", "quaternary-youarehere"],
		indexJsp = "index.jsp";
	var 
		weAreHere = function(tqNode) {
			var testHref = d.getFirstChild(tqNode).href.toString(), 
				currentLocation = (d.hasClass(tqNode, matchNavLocationClass)) ? 
					(linkBase + navLocation).toString().replace(window.location.hash,"") :
					window.location.toString().replace(window.location.hash,"");

			if (d.hasClass(tqNode, navPartialMatchClass)) {
				// this tertiary allows loose matching
				return (currentLocation.indexOf(testHref) >= 0);
			} else {
				// use strict matching
				testHref = testHref.replace(indexJsp,"");
				currentLocation = currentLocation.replace(indexJsp,"");
				return (currentLocation == testHref);
			}
		},
		nodeIsLevel = function (navLevel, tqNode){
			var isLevel = d.hasClass(tqNode, navClasses[navLevel]);
			return isLevel;
		},
		decorateTertiary = function (navLevel, tqNode){
			d.addClass(tqNode, youAreHereClasses[navLevel]);
		},
		isPartialMatchableHref = function(href) {
			for (var i = 0, found = false;  !found && i < partialMatchableHrefs.length;  i++) {
				found = (partialMatchableHrefs[i] == href)
			}
			return found;
		}
	var navLocation = "", linkBase = "", siteId = "";
	
	return {
		init: function(sNavLocation, sLinkBase, sSiteId) {
			navLocation = sNavLocation;
			linkBase = sLinkBase;
			siteId = sSiteId;
			e.onContentReady(tertiaryNavBoxId, this.decorateTertiaryYouAreHere);
		},
		getLinkBase: function() {
			return linkBase;
		},
		getSiteId: function() {
			return siteId;
		},
		decorateTertiaryYouAreHere: function() {
			var tertNavListNode = d.getElementsByClassName(tertiaryNavListClass, "ul").shift();
			var tertNodes = d.getChildren(tertNavListNode);
			for (var i = 0, needMatch = true ; needMatch && i < tertNodes.length; i++) {
				thisNode = tertNodes[i];
				if (weAreHere(thisNode)) {
					if (nodeIsLevel(3, thisNode)) {
						decorateTertiary(3, thisNode);
						needMatch = false;
					} else if (nodeIsLevel(4, thisNode)) {
						decorateTertiary(4, thisNode);
						needMatch = false;
					};
				};
			};
		},
		undecoratePrimaryYouAreHere: function() {
			// for pages entirely outside nav, set navLocation to /home and run this function to darken 
			var priNavOnNode = d.getElementsByClassName(primaryNavOnClass, "li", primaryNavDivWrapId).shift();
			d.removeClass(priNavOnNode, primaryNavOnClass);
		}
	};
}();


