Refactored horrid javascript