Moved JS variables to inside function scope; added comments