Moved js spaghetti to own script, cleaned up a bit