You need to post the entire code as it is for someone to help you out. Posting in bits and pieces would just make it difficult.
And BTW, that kind of error is normally given when the variable 'w' doesn't refer to any window, i.e. function is called before window is created.