/* Auto Highlight Main Menu */

var absoluteUrlPattern = /^([^:\/?#]+):\/\/(([^@\/?#]*)@)?([^:\/?#]*)(:([0123456789]*))?([^?#]*)(\?([^#]*))?(#(.*))?/g;

function parseAbsoluteURL(urlString) {

    var components = {
        "scheme"    :null,
        "userinfo"  :null,
        "hostname"  :null,
        "host"      :null,
        "port"      :null,
        "path"      :null,
        "query"     :null,
        "fragment"  :null
    };
    
    var a = absoluteUrlPattern.exec(urlString);
    absoluteUrlPattern.lastIndex = 0;
    if(!a) return null;
    
    components.scheme   = a[1];
    components.userinfo = a[3];
    components.hostname = a[4];
    components.port     = a[6];
    components.path     = a[7];
    components.query    = a[9];
    components.fragment = a[11];
    
    components.host = components.hostname;
    if(components.port) components.host += ":" + components.port;
    
    // potential TODO -- remove redundant slashes found in the path component
    
    return components;
}

function isSubDirectory(subDir, parentDir) {
    return subDir.indexOf(parentDir) == 0;
}

function highlight(anchor){
	anchor.parentNode.className = "on";
}

$(document).ready(function(){

	var links = document.getElementsByTagName("a");
	var subDirMatch = {"length":null};
	
	// Search for an exact path match
	for(var i = 0; i < links.length; i++) {

		var linkURL = parseAbsoluteURL(links[i].href);
		if(location.host != linkURL.host) continue; //skip external link
		
		if(linkURL.path == location.pathname) {
			highlight(links[i]);
			return;
		}
		
		if(location.pathname == "/" && linkURL.path == "/index.htm"){
			highlight(links[i]);
			return;
		}
		
		if((linkURL.path !="/" || location.pathname == "/index.htm") && isSubDirectory(location.pathname, linkURL.path)) {
			if(linkURL.path.length > subDirMatch.length) { //Match longest sub directory
				subDirMatch.link = links[i];
				subDirMatch.length = linkURL.path.length;
			}
		}
	}

	if(subDirMatch.link) {
		highlight(subDirMatch.link);
		return;
	}
});
