{% extends "modal_base.html" %}
{% load i18n template_tools widget_tweaks %}

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

{% block body %}
    {% 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>
    <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="modal-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="choice-valid">
                                    {% render_field choice_form.is_valid %}
                                    {% trans 'Right answer' %}
                                </div>
                            {% endif %}
                            <span class="form-group {% if choice_form.label.errors %}has-error{% endif %}" >
                                {% render_field choice_form.label class+='form-control' style="width:100%" 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="modal-footer clearfix">
            <a class="btn my-btn btn-default pull-left" data-dismiss="modal">{% trans 'Cancel' %}</a>
            <div class="pull-right">
                <input class="btn my-btn my-btn-purple" type="submit" value="{% trans 'Confirm' %}" />
                {% include 'questionnaires/_question_add_another.html' %}
            </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('choice-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-trash'></i>"
            });

            // Manually add the classes to transform the "Add another answer" into a button
            $('.add-row').children('a').addClass('btn btn my-btn btn-default my-btn-default-red');

            // 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', '.choice-valid', function(){
                handleIsCorrect($(this));
            });

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

            $('.questionnaire-question-choices .choice-valid').each(function(){
                if ($(this).children('input').is(':checked')) {
                    $(this).addClass('choice-success')
                }
            });

            $('#questionnaire-question-form').ajaxForm({
                beforeSubmit:function() {
                    $('input[type="submit"], button').attr('disabled', 'disabled');
                },
                success: function(htmlResponse, statusText, xhr, $form){
                    var $htmlResponse = $(htmlResponse);

                    if ($htmlResponse.closest('#questionnaire-question-form').length) {
                        $('#dialog-box-modal .modal-content').html($htmlResponse);
                        $('input[type="submit"], button').attr('disabled', false);
                    } else {
                        var addAnother = $form.data('add_another');

                        $('body').html($htmlResponse);
                        $('.dropdown-toggle').dropdown();

                        if (addAnother) {
                            $('#question-create').modal('show');
                        }
                    }
                }
            });
        });
    </script>
{% endblock %}
