I'd just use some tried and tested code, faster than debugging.....
http://www.javascript-coder.com/…