Refactored the JS to make it more maintainable.

The inline JS has all been moved out for ease of use.