Refactored JS, debugged