Used jQuery deferred to load the functions

Separated out the code in individual functions and used jQuery deferred to chain the function calls. Reduced the nesting of async functions.