perhaps we should be using some JS templating library? this code looks pretty difficult to maintain