Refactored javascript code so it will be easy to maintain in sync with t...

@alexey-rise please review. Cheers!