// tlhunter 2010-01-21 - Initial Build
//          2010-04-20 - i18n check
// Automatically highlights current page using simplediv structure
$(document).ready(function() {
	var currentPath = window.location.href;
	if (currentPath.match(/\/([a-z]{2})\/([a-z]{3})\/([a-z]{2})\//)) { // ~ na/usa/en
		firstImportantSegment = 3;
	} else if (currentPath.match(/\/([a-z]{2})\/([a-z]{2})\//)) { // ~ na/en
		firstImportantSegment = 2;
	} else {
		firstImportantSegment = 0;
	}
	var domain = document.domain;
	if (domain == "usmdlsdoww200" || domain == "usmdlsdoww840") {
		var metaPath = "http://" + $("meta[name=dow-site-base-internal]").attr("content") + "/";
	} else if (domain.indexOf("-st.") >= 0 || domain.indexOf("preview-") >= 0) {
		var metaPath = "http://preview-" + $("meta[name=dow-site-base]").attr("content") + "/";
	} else {
		var metaPath = "http://" + $("meta[name=dow-site-base]").attr("content") + "/";
	}
	if (metaPath) {
		errorLog("currentPath: " + currentPath, 'info');
		errorLog("metaPath: " + metaPath, 'info');
		if (currentPath.indexOf(metaPath) == 0) {
			subPath = removeTrailingSlash(currentPath.substring(metaPath.length, currentPath.length));
			errorLog("subPath: " + subPath, 'info');
			if (subPath.length > 0) {
				chopPath = removeEmptyArrayElements(currentPath.substr(metaPath.length).split("/"));
				$(".main-nav ul li").each(function() {
					var link = removeEmptyArrayElements($(this).find("a").attr("href").split("/"));
					if (link[firstImportantSegment] == chopPath[firstImportantSegment]) {
						$(this).addClass("main-nav-hnav-table-selected");
						$(this).removeClass("main-nav-hnav-table-unselected");
					}
					errorLog("link: " + link + " chopPath: " + chopPath, 'log');
				});
			} else {
				errorLog("We are at the top of the site", 'info');
			}
		} else {
			errorLog("dow-site-base meta tag is lying to us.", 'error');
		}
	} else {
		errorLog("Site doesn't use dow-site-base meta tag.", 'info');
	}
});

function removeEmptyArrayElements(myArray) {
	for (var i in myArray) {
		if (myArray[i] == '') {
			myArray.splice(i, 1);
		}
	}
	return myArray;
}

function removeTrailingSlash(string) {
	if (string.substring(string.length - 1) == '/') {
		string = string.substring(0, string.length - 1);
	}
	return string;
}

function errorLog(errorMessage, level) {
	if (typeof console == 'object') {
		if (typeof level == 'undefined')
			console.log(errorMessage);
		else if (level == 'log')
			console.log(errorMessage);
		else if (level == 'debug')
			console.debug(errorMessage);
		else if (level == 'error')
			console.error(errorMessage);
		else if (level == 'info')
			console.info(errorMessage);
	}
}
