var Section = (function() { return {
    
    setup: function() {
        this.allSections    = $('section');
        this.currentSection = $('#stage');
        
        this.changeSection();
    },

    position:       0,
    variance:       40,
    increment:      100,
    topHeight:      590,
    currentSection: $(),
    allSections:    $(),
    
    whichSection: function() {
        return currentSection;
    },
    
    changeSection: function() {
        // Every n pixels, test if we're still in the same section.)
        if ($(window).scrollTop() > this.position + this.increment ||
            $(window).scrollTop() < this.position - this.increment) {
            
            if (!this.currentSection.position().top <= $(window).scrollTop() + this.variance) {
                this.highlightSection();
            }
        }
    },
    
    highlightSection: function() {
        // We need to keep the object's context inside the each() loop.
        var t = this;
        
        // If we are in a different section, we need to figure out where we are.
        this.allSections.each(function() {
            var that = $(this);
            var id   = that.attr('id');
            
            // Reset the position so that we know when to test again.
            this.position = $(window).scrollTop();
            
            if ($(window).scrollTop() < t.topHeight) {
                // If our scroll top is less than the height of the top of a project,
                // then we are not in a content section and we shouldn't highlight a section.
                $('.current').removeClass('current');

            } else if ($('#projects').position().top < $(window).scrollTop() + t.variance) {
                // If we are in the Projects section, then we are not in a content section
                // and we shouldn't highlight a section.
                $('.current').removeClass('current');

            } else if (that.position().top < $(window).scrollTop() + t.variance) {
                // We have found the section and now we need to highlight it.
                $('.current').removeClass('current');
                $('#topbar li[data-section=' + id + ']').addClass('current');
                t.currentSection = that;
            }
        });
    }
};})();

