{% load i18n i18n_utils %}

{% get_current_language as LANGUAGE_CURRENT_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info for LANGUAGE_CURRENT_CODE as language_current %}
{% get_language_info_list for LANGUAGES as languages %}

<form id="set_lang" action="{% url 'set_language' %}" method="post" class="form-inline">
    {% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}" />
    <input name="language" type="hidden" value="" />
    <div class="dropdown">
        <button class="btn btn-default dropdown-toggle {% if not languages %}disabled{% endif %}" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
            <img class="flag" src="{{ STATIC_URL }}common/flags/{{ LANGUAGE_CURRENT_CODE }}.png" /> {{ language_current.name_local|title }}
            {% if languages %}<span class="caret"></span>{% endif %}
        </button>
        {% if languages %}
            <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1">
                {% for language in languages %}
                    <li {% if language.code == LANGUAGE_CURRENT_CODE %}class="disabled"{% else %}data-lang="{{ language.code }}"{% endif %} role="presentation"><a role="menuitem" tabindex="-1" href="#"><img class="flag" src="{{ STATIC_URL }}common/flags/{{ language.code }}.png" /> {{ language.name_local|title }}</a></li>
                {% endfor %}
            </ul>
        {% endif %}
    </div>
</form>

<script type="text/javascript">
    (function($) {
        $(function() {
            $('li[data-lang]')
            .click(function() {
                var language_code = $(this).data('lang')
                $('input[name=language]').attr('value', language_code);
                $('#set_lang').submit();
            });
        });
    })(jQuery);
</script>
