JS refactor and bug fixes