First off, this is not Java...it is JavaScript. They are two totally separate languages. Many people make this mistake.

As for the implementation, I suggest a much simpler approach!