Fix ajax retrieval of template and refactor.

The page now waits for AJAX calls to complete before rendering the page.

Javascript refactoring.