Refactor javascript

Finally got to refactor some of the javascript. @stevecass if you can take a quick glance and let me know if there's something that looks off.