This whole section should be done in drupal templates and theme functions. All you are doing is adding/removing classes?