Javascript refactoring