You need to wrap everything in code tags, it's difficult to follow the code when it's unformatted.
In general I would say don't try and merge different snippets or bits of code you find on the forum, it tends to lead to a Frankencode mess.
You need to understand what each bit of code does, and how it works, then rewrite it into your own project in a way that makes sense. If you don't know what the code does and how it does it then you don't have control over your own project and you'll keep running into these issues.