Cleaned up and rearranged much of the javascript code.