fixup javascript syntax and reorganize flow