Refactored to use jquery and optimized some of the code.