Additional code refactoring to JavaScript

Lots of small refactors across the js files. Tried to DRY up code where possible, and make naming more consistent.