the AS3 version converted to JS
cleaned up