Refactor js structure

This is a work in progress (almost done) to simplify the JS and better encapsulate responsibilities