var intNavBarTitleYPos;
var strNavBarTitleOriginalText;
var eleNavBarTitle;
var strNavBarInternalLinks;
var arrNavBarMarkers;
var blnNavBarSetup = false;
var intNavBarHeight;

/*

    Written by Dave Child
    http://www.addedbytes.com
    Identify markers with 'class="navBarMarker"'

    To Do: 
        - Add navbar from here rather than adding it to HTML.
        - Change hash anchor behaviour so it doesn't jump too far.

*/

function prepareNavBar() {

	
	if (blnNavBarSetup == false) {

		// blnNavBarSetup is set to true the first time this is run.
		// Positions of markers are recalculated on page load, as image loading can move markers.
		var arrH1s = document.getElementsByTagName('h1');
		intNavBarTitleYPos = getNavBarMarkerPos(arrH1s[0], true);

		var strThisPage = window.location.href + '#';
		strThisPage = strThisPage.substring(0, strThisPage.indexOf('#'));

		if (intNavBarTitleYPos) {

			// Grab H1 content for titles and add to navbar
			if (arrH1s[0].getAttribute('title')) {
				strNavBarTitleOriginalText = '<a href="/">Home</a> &#187; ' + arrH1s[0].getAttribute('title'); 
			} else {
				strNavBarTitleOriginalText = '<a href="/">Home</a> &#187; ' + arrH1s[0].innerHTML; 
			}

			// Grab all elements that have been identified as page markers
			arrNavBarMarkers = getElementsByClassName('navBarMarker');
			
			strNavBarInternalLinks = '<a href="' + strThisPage + '#top" title="Jump to Top">Top</a>';
			// For each marker, grab its position and title (if set)
			for (i = 0; i < arrNavBarMarkers.length; i++) {
				arrNavBarMarkers[i]['intYPos'] = getNavBarMarkerPos(arrNavBarMarkers[i], false);
				arrNavBarMarkers[i]['intHeight'] = getNavBarMarkerHeight(arrNavBarMarkers[i]);
				if (arrNavBarMarkers[i].getAttribute('title')) {
					arrNavBarMarkers[i]['strText'] = arrNavBarMarkers[i].getAttribute('title');
				} else {
					arrNavBarMarkers[i]['strText'] = arrNavBarMarkers[i].innerHTML;
				}
				if (arrNavBarMarkers[i].getAttribute('id')) {
					arrNavBarMarkers[i]['elementId'] = arrNavBarMarkers[i].getAttribute('id');
				} else { // No id. Create one and add it.
					arrNavBarMarkers[i].setAttribute('id', arrNavBarMarkers[i]['strText'].replace(/[^A-Za-z0-9]/gi, ''));
					arrNavBarMarkers[i]['elementId'] = arrNavBarMarkers[i].getAttribute('id');
				}
				if ((i == (arrNavBarMarkers.length - 1)) || (arrNavBarMarkers.length < 2)) {
					strNavBarInternalLinks = strNavBarInternalLinks + ' or '; 
				} else {
					strNavBarInternalLinks = strNavBarInternalLinks + ', ';
				}
				strNavBarInternalLinks += '<a href="' + strThisPage + '#' + arrNavBarMarkers[i]['elementId'] + '" id="navbarlink' + i + '">' + arrNavBarMarkers[i]['strText'] + '</a>';
			}

			// Assign navbar contents
			document.getElementById('navBarInternalLinks').innerHTML = strNavBarInternalLinks;
			eleNavBarTitle = document.getElementById('navBarTitle');
			eleNavBarTitle.innerHTML = strNavBarTitleOriginalText;
			addScrollEvent(toggleNavBar);
			
			// Manage anchor tags - without this they jump too far.
			addClickEvent(adjustScroll);
			
			toggleNavBar();
			blnNavBarSetup = true;

		}

	}
	
}

function toggleNavBar() {
    var intScrollYPos = getYPos_navbar();
    if ((intScrollYPos > intNavBarTitleYPos) && (intNavBarTitleYPos > 0)) { 

        // If we've scrolled past the title, show the bar
        document.getElementById('navBar').style.display = 'block';

		if (!intNavBarHeight) {
			intNavBarHeight = document.getElementById('navBar').offsetHeight + 2;
		}

        var blnInSubSection = false;
        // Loop through markers and adjust title
        for (i = 0; i < arrNavBarMarkers.length; i++) {
			 // Markers are offset by intNavBarHeight pixels to account for the bar itself obscuring items
            if ((intScrollYPos > (arrNavBarMarkers[i]['intYPos'] - intNavBarHeight)) && (intScrollYPos < (arrNavBarMarkers[i]['intYPos'] + arrNavBarMarkers[i]['intHeight'] - intNavBarHeight))) {
                adjustNavBarTitle(strNavBarTitleOriginalText + ' &#187; ' + arrNavBarMarkers[i]['strText'], 'navbarlink' + i);
                blnInSubSection = true;
            }
        }

        if (!blnInSubSection) {
            adjustNavBarTitle(strNavBarTitleOriginalText, false);
        }

    } else {
        document.getElementById('navBar').style.display = 'none';
    }
}

function adjustNavBarTitle(strNewTitle, strActiveLinkId) { // Function used to prevent flickering in Firefox.
    if (eleNavBarTitle.innerHTML != strNewTitle) {
        eleNavBarTitle.innerHTML = strNewTitle;

        document.getElementById('navBarInternalLinks').innerHTML = strNavBarInternalLinks;
        eleActiveLink = document.getElementById(strActiveLinkId);
        if (eleActiveLink) {
            // Change the links
            eleActiveLink.style.border = 'none';
            eleActiveLink.style.color = '#cccccc';
            eleActiveLink.style.cursor = 'default';
        }
    }
}

function getYPos_navbar() {
    var intYPos = 0;
    intYPos = document.body ? document.body.scrollTop : intYPos;
    intYPos = document.documentElement ? document.documentElement.scrollTop : intYPos;
    intYPos = window.pageYOffset ? window.pageYOffset : intYPos;
    return intYPos;
}

function getNavBarMarkerPos(eleMarker, blnIncludeHeight) {
    var intMarkerPos = 0;
    if (eleMarker) {
        intMarkerPos = eleMarker.offsetTop;
        var objMarkerParent = eleMarker.offsetParent;
        while (objMarkerParent) {
            intMarkerPos += objMarkerParent.offsetTop;
            objMarkerParent = objMarkerParent.offsetParent;
        }
        if (blnIncludeHeight) {
            intMarkerPos = intMarkerPos + eleMarker.offsetHeight;
        }
    }
    return intMarkerPos;
}

function getNavBarMarkerHeight(eleMarker) {
    return eleMarker.offsetHeight;
}

// This function cobbled together from a variety of sources.
// It detects an anchor tag click and sets a 10ms timeout to 
// scroll the user by the height of the navbar once they have 
// moved down the page. This prevents the navbar covering the 
// anchor they have clicked to. Needs improvement - there must
// be a smarter way to do this!

// http://www.quirksmode.org/js/events_properties.html#target
function adjustScroll(e) { 
	var targ;
	if (!e) {
		var e = window.event;
	}
	if (e.target) {
		targ = e.target;
	} else if (e.srcElement) {
		targ = e.srcElement;
	}
	if (targ.nodeType == 3) { // defeat Safari bug
		targ = targ.parentNode;
	}

	if (targ.hash) {
		var anchor = document.getElementById(targ.hash.substr(1));
		if (anchor) {
			setTimeout("window.scrollBy(0, -(intNavBarHeight - 2))", 10);
		}
	}
}

onDOMLoad(prepareNavBar);
addLoadEvent(prepareNavBar);

if (location.hash) {
	addLoadEvent(function() { setTimeout("window.scrollBy(0, -(intNavBarHeight - 2))", 50) });
}
