js refactor
hopefully code is somewhat clearer...