Refactor js to follow jquery guidelines and use named functions instead of anonymous ones