Could you tell where in your code and when this error occurs? Just dumping a ton of code and a fairly vague error message doesn't really help here.
Also try to add some spacing and formatting to your code, and maybe add some documentation here and there as this code is pretty hard to read as it is.
Documenting code is also just good a good practice, even if it is just for fairly simple or trivial code. You don't want to have to figure out what a function does after not looking at it for a couple of months