Move some javascript out of the view and refactor