Properly scope variables in javascript

Also do jshint correction