$(document).ready(function () { //when the document is ready...


    // setting heights dynamically 

    var hTotal = 0;
    var dMargin = 0;

    $.each($('#scrollContainer > div:not(#intro)'), function () {

        var height = Number($(this).height()) || 100;

        hTotal += height;
        $(this).css('height', height);
        if ($(this).attr('id') != "header") {
            // if a background is present, then bind inview class.
            if ($(this).css('background-image') != 'none') {
                addPX($(this), hTotal + dMargin, 0.5)
            };
        };
    })


    var $window = $(window);
    var windowHeight = $window.height(); //get the height of the window

    // addPX($('#intro .highlight'), $('#intro .highlight').height(), 0.6)

    function addPX(element, height, speed) {

        $(element).data('bHeight', height);
        $(element).data('bSpeed', speed);

        if ($('#home').is('*') == false) { /* THIS SHOULD BE FIXED! - Intro gives JS errors */
            $(element).bind('inview', function (event, isInView) {
                if (isInView) {
                    $(this).addClass("inview");
                } else {
                    $(this).removeClass("inview");
                };
            });
        }

    }


    //function that is called for every pixel the user scrolls. Determines the position of the background
    /*arguments: 
    x = horizontal position of background
    windowHeight = height of the viewport
    pos = position of the scrollbar
    adjuster = adjust the position of the background
    inertia = how fast the background moves in relation to scrolling
    */
    function newPos(x, windowHeight, pos, adjuster, inertia) {
        var adjuster = adjuster - 30;
        return x + "% " + (-((windowHeight + pos) - adjuster) * inertia) + "px";
    }

    //function to be called whenever the window is scrolled or resized
    function Move() {
        var pos = $window.scrollTop(); //position of the scrollbar

        $.each($('.inview'), function () {
            $(this).css({ 'backgroundPosition': newPos('50', windowHeight, pos, $(this).data('bHeight'), $(this).data('bSpeed')) });
        });
    }

    $window.resize(function () { //if the user resizes the window...
        Move();
    });
    $window.bind('scroll', function () { //when the user is scrolling...
        Move();
    });

});
