fixed JS bugs and moved JS to each loop where appropriate