used jquery deferreds to refactor the code.