Restructure js code.

Ready for making more generic