Script error when running in gateway

Take a look at this thread: Wiki - how to post code on this forum
edit: And remember that you can edit your post, just click on the little pen icon:
image

Your code is unreadable as it is.

But in any case, don't put it in a gateway event script, put it in your library and call it from the event.