js refactoring and bugfixing