Move functions out of the global scope. Fix a number of JSLint issues