Lots of answers already, but most of them seem to be about alternative solutions. I'll review your code on the details and show you how to refactor your code step by step. (This is a long answer, link to bottom of answerlink to bottom of answer)
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/