javascript loops and bug fixes