Most of the errors you have there are trivial and caused by a lack of basic knowledge of scripting. You need to completely redo that whole function instead of copy/pasting stuff. After you redo the function, if you still have errors, try to read what the error says and try to fix it. It would probably help if you used consistent indentation too.