{% extends 'base.html' %}
{% load i18n template_tools widget_tweaks %}

{% block head %}
    {{ block.super }}

    {% include "cms/includes/orderable-inline-head.html" %}
    <script type="text/javascript">
        // `inlines.js` expects a `django` object with a `jQuery` key.
        window.django = {jQuery: $};
    </script>
    <script type="text/javascript" src="{{ STATIC_URL }}common/js/inlines.js"></script>
{% endblock %}

{% block subtitle %}
    {% if object.pk %}
	    {% trans 'Edit question' %}
    {% else %}
        {% trans 'New question' %}
    {% endif %}
{% endblock %}

{% block actions %}
    <a href="{{ questionnaire.get_detail_url }}" class="btn btn-default">
        {% trans 'Back to the list of questions' %}
    </a>
{% endblock %}

{% block main %}
    <form action="{% if object.pk %}{{ object.get_edit_url }}{% else %}{{ create_url }}{% endif %}"
          method="post" enctype="multipart/form-data" id="questionnaire-question-form">{% csrf_token %}
        {{ choices_formset.management_form }}
        <div class="panel panel-default">
            <div class="panel-body">
                {% if form.errors or choices_formset.errors %}
                    <div class="alert alert-danger">
                        {% trans 'Please correct errors below.' %}
                        {% if form.non_field_errors %}
                            {{ form.non_field_errors }}
                        {% endif %}
                    </div>
                {% endif %}
                {% include 'cms/extras/form.html' with display='block' %}
                <h4>{% trans 'Choices' %}</h4>
                {% if choices_formset.non_field_errors %}
                    <div class="alert alert-danger">
                        {{ choices_formset.non_field_errors }}
                    </div>
                {% endif %}
                <div class="questionnaire-question-choices orderable-inline">
                    {% for choice_form in choices_formset %}
                        {% reducespaces %}
                        <div class="
                                orderable-entry
                                inline-choice
                                form-inline
                                {% if forloop.last %}empty-form last-related{% endif %}"
                             id="{{ choices_formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
                            {% endreducespaces %}
                            <div class="choice-item">
                                <span class="inline_label"></span>
                                {% for field in choice_form.hidden_fields %}
                                    {{ field }}
                                {% endfor %}
                                {% if questionnaire.is_scoring %}
                                    <div class="btn btn-default btn-valid">
                                        {% render_field choice_form.is_valid %}
                                        <i class="fa fa-check"></i>
                                    </div>
                                {% endif %}
                                <span class="form-group {% if choice_form.label.errors %}has-error{% endif %}">
                                    {% render_field choice_form.label class+='form-control' style="width:950px" placeholder=choice_form.label.label autocomplete="off" %}
                                </span>
                                {% if choice_form.instance and choice_form.instance.pk %}
                                    <span class="delete btn btn-sm btn-danger">
                                        {{ choice_form.DELETE.label }} {{ choice_form.DELETE }}
                                    </span>
                                {% endif %}
                            </div>
                            {% for field in choice_form.visible_fields %}{% if field.name != 'DELETE' %}
                                {% if field.errors %}
                                    <div class="alert alert-danger">
                                        {{ field.label }}: {{ field.errors }}
                                    </div>
                                {% endif %}
                            {% endif %}{% endfor %}
                        </div>
                    {% endfor %}
                </div>
            </div>
            <div class="panel-footer clearfix">
                <a class="btn btn-default pull-left" href="{{ questionnaire.get_detail_url }}">{% trans 'Cancel' %}</a>
                <div class="pull-right">
                    <input class="btn btn-primary" type="submit" value="{% trans 'Confirm' %}" />
                    {% include 'questionnaires/_question_add_another.html' %}
                </div>
            </div>
        </div>
    </form>
    <script type="text/javascript">
        $(document).ready(function () {
            // Handle the click on the "is valid" button
            var handleIsCorrect = function($button) {
                var isChecked = $button.children('input').is(':checked');
                $button.toggleClass('btn-success', !isChecked);
                $button.children('input').prop('checked', !isChecked);
                
                handleIsMultipleChoices()
            };
        
            var handleIsMultipleChoices = function() {
                // Handle automatically if the "is_multiple_choices" field should be checked or not,
                // accordingly to the number of choices checked as "valid" ones
                var $isMultipleChoices = $('#id_is_multiple_choices'),
                    $validChoices = $('.inline-choice').not('.soft-deleted').find('input[type="checkbox"]:checked');
                
                if ($validChoices.length > 1) {
                    $isMultipleChoices.prop('checked', true)
                } else {
                    $isMultipleChoices.prop('checked', false)
                }
            };
        
            $('.inline-choice').stackedFormset({
                prefix: '{{ choices_formset.prefix }}',
                softDeletion: true,  // Handles the deletion of existing choices, and dynamically
                // created ones the same way.
                addCssClass: 'add-row', // To make the "Add another answer" link looks like a button.
                addText: '{% trans 'New choice' %}', // Text of the "Add another answer" button.
                deleteText: "<i class='fa fa-remove'></i>"
            });
        
            // Manually add the classes to transform the "Add another answer" into a button
            $('.add-row').children('a').addClass('btn btn btn-primary');
            
            // If a choice got soft deleted, we need to update the multiple choice option as well
            {% if questionnaire.is_scoring %}
                $(document).on('click', '.inline-deletelink', function(){
                    handleIsMultipleChoices();
                });
            {% endif %}

            // Click on the button element
            $('.questionnaire-question-choices').on('click', '.btn-valid', function(){
                handleIsCorrect($(this));
            });

            // Change event on the checkbox element
            $('.questionnaire-question-choices').on('change', '.btn input[type="checkbox"]', function(){
                handleIsCorrect($(this).parent('.btn'));
            });

            $('.questionnaire-question-choices .btn-valid').each(function(){
                if ($(this).children('input').is(':checked')) {
                    $(this).addClass('btn-success')
                }
            });
        });
    </script>
{% endblock %}
