// 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');
				
					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+1] == chopPath[firstImportantSegment]) {
							$(this).addClass("main-nav-hnav-table-selected");
							$(this).removeClass("main-nav-hnav-table-unselected");
						}
						errorLog("link: " + link + " chopPath: " + chopPath, 'log');
						errorLog("link: " + link[firstImportantSegment] + " chopPath: " + chopPath[firstImportantSegment], 'log');
					});
				
			} 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;
}
