JS fixes and refactoring