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

Also convert tabs to spaces. Note: I haven't even run the code, I don't have the device. Please test before merging :).