Some code cleaning, mainly moving var declarations to top of the function, changing a couple of var names and fixing some JSHint errors