Refactor to encapsulate in anonymous function and replace some JS with jQuery
Refactor for DRY based on Greg's idea