Context
You have a global variable inside a function, that doesn't seem to be global at all. (ie. it doesn't have the value it's supposed to)
Likely solution
Your calling the function (a) where you declared the variable global from another function (b) where you set the variable.
But the variable isn't declared global in (b). So make it global there, and your problems will vanish.
(Tends to happen with callbacks all of the time ;-))