/**
 * Gets the cummulative offset from the origin of a particular element by iteratively going through its parents.
 **/
function getCumulativeOffset(element) {
    var left, top;
    left = top = 0;
    if (element != null && element.offsetParent) {
        do {
            left += element.offsetLeft;
            top  += element.offsetTop;
        } while (element = element.offsetParent);
    }
    return {
        x: left,
        y: top
    };
};

/**
 * Gets the scroll position.
 */
function getScrollY() {
    var y = 0;
    if (typeof( window.pageYOffset ) == 'number') { // Netscape
        //x = window.pageXOffset;
        y = window.pageYOffset;
    } else if (document.body && ( document.body.scrollLeft || document.body.scrollTop)) { // DOM
        //x = document.body.scrollLeft;
        y = document.body.scrollTop;
    } else if (document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop)) { // IE6 standards compliant mode
        //x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    }
    return y;
}

var lastPosition = -1;

/**
 * Smoothly scrolls to a position.
 **/
function smoothScrollTo(target) {
    var currentPosition = getScrollY();
    var delta = (target - currentPosition) / 6.0;
    var nextStep = currentPosition + delta;
    
    // Check whether scrolling has been interrupted by the user.
    var halted = false;
    if (nextStep > lastPosition) {
        halted = currentPosition > nextStep || currentPosition < lastPosition;
    } else {
        halted = currentPosition < nextStep || currentPosition > lastPosition;
    }
    
    if (halted) {
        lastPosition = -1;
        return;
    }
    
    window.scrollBy(0, delta);
    
    if (Math.abs(delta) >= 1) {
        setTimeout('smoothScrollTo(' + target + ')', 50);
    } else {
        lastPosition = -1;
        return;
    }
    lastPosition = currentPosition;
}

/**
 * Smoothly scrolls to an element.
 */
function scrollToElement(element) {
    lastPosition = getScrollY();
    smoothScrollTo(getCumulativeOffset(document.getElementById(element)).y);
}


/**
 * Scrolls up to the top.
 */
function scrollToTop() {
    lastPosition = getScrollY();
    smoothScrollTo(0);
}


// Declare variables outside function for efficiency.
var nav = document.getElementById("nav");
var me = document.getElementById("me");
var headerHeight = getCumulativeOffset(nav).y;
if (me != null) var myHeight = getCumulativeOffset(me).y;

/**
 * Apples a CSS class to the navigation bar based on scroll position.
 **/
function onScroll() {
    var scrollY = getScrollY();
    
    nav.className = (scrollY > headerHeight) ? "scrolled" : "top";
    if (me != null) {
        me.className = (scrollY > myHeight) ? "fixed" : "";
    }
}

// Set up event listener.
window.onscroll = onScroll;
window.addEventListener("touchmove", onScroll, false);