Fixed javascript function scope issue