Refactored very spooky JavaScript