This function has a whole block of implicitly declared global variables. You need to declare the variables with "var".