Minor comment, but throughout the JS there is an inconsistent use of spaces around ifs and functions. The preferred syntax is:

    if (expression) {
    }

    function() { }