At a glance, and to be clear this was a quick once-over, I think the general problem might be a JS scope issue. I see some “var” statements in your code components. See here: Variable not defined
Basically, JS scope behaves weirdly. In a code component, you don’t want to use “var”, because then the variable will only be defined for that specific part of the code component (e.g., begin routine), not even the whole trial. If you omit “var”, JS recognizes it as global and you can reference it wherever you want.