Refactored some stuff and applied javascript best practices

I made this script more compliant to javascript best pratices.

Changes made:
* Put the script in a closure
* Added the "use strict" declaration.
* Avoided code repetitions

I hope it will be appreciated