 template = Handlebars.compile("""
   <div class="char-info">
-    <form>
+    <form data-char-id="{{view.id}}">
       <div class="char-info-display">
         <span>{{{view.moe}}}</span>
         <span>{{view.display}}</span>

      </div>
      <input type="text" name="cns" value="{{exact.cns}}"></input>
      <input type="text" name="comments" value="{{comments}}"></input>
    </form>
  </div>
""")

onReady = ->
  $context = $('#context')

  $.getJSON('/api/chars/all', (data) ->
    for key, datum of data
      view = {}

      # TODO: Select display from multiple sources pua -> uni -> ids
      view.display = datum.display.uni


    for key, datum of data
      html = template(datum)
      $context.append(html)

    $('button').on('click', (event) ->
      $form = $(this).parent()
      id = $form.data('char-id')
      datum = allCharData[id]

      # Tricky deep clone
      datum = JSON.parse(JSON.stringify(datum))

      cns = $form.children('input[name="cns"]').val()
      comments = $form.children('input[name="comments"]').val()

      datum.comments = comments
      datum.exact.cns = cns

      url = "/api/char/#{encodeURIComponent(datum.view.id)}"

      # TODO: Refactoring: Move extra info from `view` to somewhere else
      delete datum.view

      $.ajax {
        url: url
        type: 'PUT'
        data: JSON.stringify(datum)
      }

    )
  )

$(onReady)
