Refactored some of the javascript to make it more robust.