{% load wagtailcore_tags core_tags gem_tags %}

<form id="reaction-questions__form" action="{% pageurl form_page %}" method="post" class="reaction-questions__form" novalidate>
{% csrf_token %}
  {{ form.media }}
  {% for field in form %}
    {% if field|fieldtype == 'RadioSelect' %}
      <div class="reaction-questions__list">
        {% for value, text in field.field.choices %}
          <div class="reaction-questions__item">
            {% if user_has_chosen %}
              <input name="{{ field.name }}"
              id="{{ value|slugify }}_{{ forloop.counter0 }}"
              type="radio" value="{{ value }}"
              onclick="set_rq_form_choice('{{field.name}}_{{ forloop.counter0 }}')"
              class="{{ value|slugify }}"/>
            {% else %}
              <input name="{{ field.name }}"
              id="{{ value|slugify }}_{{ forloop.counter0 }}"
              type="radio" value="{{ value }}"
              onclick="set_rq_form_choice('{{field.name}}_{{ forloop.counter0 }}')"
              class="{{ value|slugify }}"/>
            {% endif %}
             <label class="reaction-questions__label" for="{{ value|slugify }}_{{ forloop.counter0 }}">
               {{ text|capfirst }}
             </label>
          </div>
        {% endfor %}
      </div>
    {% endif %}

    {% if field.errors %}
      <ul class="error-list">
      {% for error in field.errors %}
        <li class="error-list__item">{{ error }}</li>
      {% endfor %}
      </ul>
    {% endif %}

  {% endfor %}
</form>

<script type="text/javascript">
  /*
    data: {
      frm.serialize() + '&ajax=True'
    },
  */

  function set_rq_form_choice(slug) {
    var frm = $('#reaction-questions__form'),
      label = $(event.target),
      $thisElem = label.next()[0];
    $('.reaction-questions__label').removeClass('active');
    $($thisElem).addClass('active');
    sessionStorage.setItem('rq',$($thisElem).attr('for'));

      console.log(frm.attr('action'));
    $.ajax({
      type: frm.attr('method'),
      url: frm.attr('action'),
      data: {
        csrfmiddlewaretoken: "{{ csrf_token }}",
        choice: slug,
        ajax: "True"
      },
      success: function(data) {
        //send_results(slug);
        console.log(data);
        for (form in data) {
          var responses = data[form];
          var updated = [];
          for (choice in responses) {
            var percent = responses[choice];
            $('#'+choice+'-perc').text(percent).css('width',percent+'%');
            updated.push(choice+'-perc');
          }
          $('.response-percent__bar').each(function(){
            if ($.inArray(this.id, updated) == -1){
              $(this).text(0).css('width','0%');
            }
          })
        }

      }
    });
  };
  $('label[for='+ sessionStorage.getItem('rq') +']').addClass('active');
</script>
