Refactor chat related JS code