Fixing JS syntax errors caused by T4 template

The T4 template used to append commas (',') in the two foreach loops.
This is invalid syntax for JSON objects. I switched the foreach loops to
for loops and put a condition before writing the commas out.

I also made the template generate better formatted js, but unfortunately
this has caused the T4 template to be harder to read - it seems white
space before conditional T4 blocks is included in the output
unfortunately