to_delete = []
csrf = $("input[name='csrfmiddlewaretoken']").val()
removed = false

getCoupons = ->
  $.getJSON("/seal/coupon/", (coupons) ->
    for coupon in coupons
      $("table.table tbody").append($("<tr class='admin' id='#{coupon.id}'>").html("<td class='name'>#{coupon.name}</td><td>#{ coupon.description }</td><td>#{ coupon.code }</td><td class='cb'><input type='checkbox' class='checkbox'></td>"))
  )
  .done( ->
    $("input[type='checkbox']").click ->
      to_delete.push($(this).parents('tr').attr('id'))
      removed = true
      $(window).bind 'beforeunload', ->
        return 'You have unsaved changes.'
    $('td input').change ->
      btnDisabled = true
      if $('tr.admin td.cb input[type="checkbox"]').not(':checked').length > 0
        btnDisabled = false
      if btnDisabled
        if not removed
          $(window).unbind 'beforeunload'
      else
        $(window).bind 'beforeunload', ->
          return 'You have unsaved changes.'
  )

getCoupons()

$("button.btn.invites").click (event) ->
  event.preventDefault()
  $.post("/seal/coupon/create/", {
    'name': $("#name").val(),
    'description': $("#description").val(),
    'code': $("#code").val(),
    'csrfmiddlewaretoken': csrf
  }).done( (coupon) ->
    $('form#addUser div.success').show()
    $('form#addUser div.error').hide()
    $("table.table tbody").append($("<tr class='admin' id='#{coupon.id}'>").html("<td class='name'>#{coupon.name}</td><td>#{ coupon.description }</td><td>#{ coupon.code }</td><td class='cb'><input type='checkbox' class='checkbox'></td>"))
    $('td input').change ->
      btnDisabled = true
      if $('tr.admin input').not(':checked').length > 0
        btnDisabled = false
      if $('tr.notAdmin input:checked').length > 0
        btnDisabled = false
    $('td i.fa-remove').click ->
      $(this).parents('tr').remove()
      if $(this).parents('td').hasClass('active')
        users_removed.push($(this).parents('tr').attr('id'))
      else
        invites_removed.push($(this).parents('tr').attr('id'))
      removed = true
      $(window).bind 'beforeunload', ->
        return 'You have unsaved changes.'
    $("input[type='text']").val('')
  )


$("button.btn.update").click (event) ->
  event.preventDefault()
  for id in to_delete
    $.post("/seal/coupon/delete/", {
      'id': id,
      'csrfmiddlewaretoken': csrf
    })
  $('form#updateUsers div.success').remove()
  $('form#updateUsers div.error').remove()
  $('form#updateUsers').prepend('<div class="success"><p>Changes successfully made</p></div>')
  $('tr input[type="checkbox"]:checked').parents('tr').remove()
  removed = false
  $(window).unbind 'beforeunload'


