{% comment %}Include needed stuff in ``<head>`` to make an inline formset orderable

This template file is to be included in the ``<head>`` of an html document.

It will add a ``<script>`` tag to allow orderable table to work, and also ``<link>`` and
``<script src=...>`` tags to load external css and js files.

External files loaded are:
- jquery ui css, minified
- jquery ui js, minified

You can skip loading these two files by passing ``no_jqueryui=True`` in the ``include`` tag.

Once this include is added in the template, simply add the ``orderable-inline`` class to a dom
node containing all the orderable entries, add the ``orderable-line`` class to each orderable
entry.

The drag handle will be added for each entry before the node with the ``inline_label`` class.

This include works only with formsets that inherits from
``mtp.apps.common.forms_utils.OrderableInlineFormset``.


Arguments
---------
no_jqueryui
    Default to ``False``, set it to ``True`` to not include tags to load jquery-ui css and js.

Example
-------

    {% block head %}
        {{ block.super }}
        {% include "cms/includes/orderable-inline-head.html" %}
    {% endblock head %}

    {% block main %}
        <div class="orderable-inline">
            {% for formset_form in my_formset %}
                <div class="orderable-entry">
                <h4>
                    <span class="inline_label">
                        {% blocktrans trimmed with choice_number=forloop.counter %}
                            Entry #{{ choice_number }}
                        {% endblocktrans %}
                    </span>
                </h4>
                {{ formset_form.as_table }}
            {% endfor %}
        </div>
    {% endblock main %}


TODO: have a common place in our whole app for jquery-ui

{% endcomment %}

{% load i18n %}

{% if not no_jqueryui %}
    <link rel="stylesheet" href="{{ STATIC_URL }}trainings/js/themes/base/minified/jquery-ui.min.css" type="text/css" media="screen" charset="utf-8" />
    <script type="text/javascript" src="{{ STATIC_URL }}trainings/js/ui/minified/jquery-ui.min.js"></script>
{% endif %}

<script type="text/javascript" charset="utf-8">
(function ($) {
    $(document).ready(function() {

        var activate_inline_orderable = function() {

            var $holder = $(this);

            $holder.find('.orderable-entry').each(function() {
                var $line = $(this);
                var $insertPoint = $line.find('.inline_label');
                var $handle = $insertPoint.prev();
                // Insert the handle if not present
                if (!$handle.length) {
                    $handle = $('<span class="sorthandle"/>');
                    $handle.html("<img src='{{ STATIC_URL }}admin/img/drag_handle.gif' width='11' height='11' title='{% trans 'Drag to reorder' %}' />")
                        .css("cursor", "pointer");
                    $insertPoint.before($handle);
                }
            });

            // Call `sortable` from jquery-ui to activate the ordering by drag and drop.
            $holder.sortable({
                'axis': 'y',
                'cursor': 'crosshair',
                'handle': '.sorthandle',
                'items': '.orderable-entry',
                'forcePlaceholderSize': true,
                'start': function() {
                    // Set a minimal height to the holder to avoid the size height to be reduced when
                    // dragging an item
                    $holder.css("minHeight", $holder.height());
                },
                'stop': function() {
                    // When dragging is done, reset the minimal height to let removal of entries
                    // reduce the holder height
                    $holder.css("minHeight", 0);
                },
                'update': function() {
                    var $forms = $holder.find(".orderable-entry:not(.empty-form)");
                    // Simply replace the content of the ORDER field by its position.
                    // It will be used by the backend to order the entries.
                    var $inputs = $forms.find("input[name$='-ORDER']");
                    $inputs.each(function(index) {
                       $(this).val(index+1);
                    });
                    // Update the numbers in the inline labels (based on code from inlines.js
                    $forms.find(".inline_label").each(function(i) {
                        var $label = $(this);
                        $label.html($label.html().replace(/(#\d+)/g, "#" + (i+1)));
                    });
                } // update

            }); // $holder.sortable

        }; // activate_inline_orderable

        // Activate ordering on each orderable table
        $('.orderable-inline').each(activate_inline_orderable);

    })})($);
</script>
