huge JS rewrite