{% extends "api2/base.html" %}

{% load seahub_tags avatar_tags i18n %}
{% load url from future %}

{% block sub_title %}{{group.group_name}} - {% endblock %}

{% block extra_style %}
{% if not group_msgs.has_next %}
<style type="text/css">
.msg:last-child {
    border-bottom:0;
}
</style>
{% endif %}
{% endblock %}

{% block main_panel %}
    <ul class="msg-list" id="msg-list">
{% if group_msgs %}
    {% include "api2/discussions_body.html" %}
{% else %}
    <div id="placeholder" style="margin-top:20%;">
      <p style="text-align:center">{% trans "No discussions." %}</p>
    </div>
{% endif %}
    </ul>
    {% if group_msgs and group_msgs.has_next %}
    <div id="loading-icon" data-next="{{ group_msgs.next_page_number }}"><img src="{{MEDIA_URL}}img/loading-icon.gif" alt="{% trans 'Loading...' %}" /></div>
    <p id="loading-error" class="error hide"></p>
    {% endif %}
{% endblock %}

{% block extra_script %}
<script type="text/javascript">
function msgClick() {
    window.open($(this).data('url'));
}
$('.msg').click(msgClick);

var g_token = "TOKEN";
function setToken(token) {
    g_token = token;
}
function getToken() {
    return g_token;
}

{% if group_msgs.has_next %}
var g_loading = false;
$(document).scroll(function() {
    var loading_icon = $('#loading-icon');
    if (loading_icon.data('next') && $(window).height() + $(window).scrollTop() == $(document).height() && !g_loading) {
        loading_icon.show();
        g_loading = true;
        $.ajax({
            url:'{% url 'more_discussions' group.id %}?page=' + e(loading_icon.data('next')),
            dataType: 'json',
            cache: false,
            headers:{Authorization:'Token '+g_token},
            success: function(data) {
                loading_icon.data('next', data['next_page']);
                $('.msg-list').append(data['html']);
                $('.msg').unbind().click(msgClick);
                if (!data['next_page']) {
                    loading_icon.hide();
                    $('.msg:last-child').css({'border-bottom':0});
                }
                g_loading = false;
            },
            error: function(jqXHR, textStatus, errorThrown) {
                loading_icon.hide();
                g_loading = false;
                if (!jqXHR.responseText) {
                    $('#loading-error').html("{% trans "Failed. Please check the network." %}").removeClass('hide');  
                }   
            }
        });
    }
});
{% endif %}

function addMessage(html) {
  if (!$('#placeholder').hasClass('hide')) {
    $('#placeholder').addClass('hide');
  }
  var msg_list = $('#msg-list')
  msg_list.prepend(html)
  msg_list.children().eq(0).click(msgClick);
}
</script>
{% endblock %}
