This file needs documentation. It's getting fairly complex, and requires mentally parsing the html to understand what it is doing.