Refactor some big ugly js code