some refactoring to JS. still need to clean up the code