javascript fully functional - code is in need of clean-up to remove the global variabales