tidy up and simplify code for readability

No new functionality, but tidied up the code a bit according to jslint and tried to break out things into functions. Should still work, but would test it a bit thorough before foss4g ;)