JavaScript tune up, logic improvements