js code cleaned up and bugs fixed