Refactored javascript code and added comments