refactoring javascript, split cascading callbacks into functions