Major javascript refactoring