Fixes a lot of scope-errors and uses safer comparisons of variables.

Ran the code thru JSHint and corrected some validation errors