Reorganize JS so functions are always defined prior to use.