{% extends "home_base.html" %}
{% load avatar_tags i18n seahub_tags %}

{% block sub_title %}{% trans "Messages" %}{% if total_unread > 0%}({{total_unread}}){%endif%} - {% endblock %}
{% block extra_style %}
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/select2.css?t=1393578720" />
<style type="text/css">
    td { cursor:pointer; }
</style>
{% endblock %}

{% block cur_messages %}tab-cur{% endblock %}

{% block right_panel %}
<div class="hd ovhd">
    <h3 class="fleft">{% trans "Messages" %}</h3>
    <button id="add-msg" class="fright"><span class="icon-pencil"></span>{% trans "New Message" %}</button>
</div>
<table>
    <tr>
        <th width="5%"></th>
        <th width="25%">{% trans "Name"%}</th>
        <th width="50%">{% trans "Message"%}</th>
        <th width="20%">{% trans "Time"%}</th>
    </tr>
    {% if msgs %}
    {% for key,value in msgs %}
    {% with not_read=value.not_read %}
    <tr data-href="{% url 'user_msg_list' key %}" class="{% if not_read > 0 %}bold{% endif %}">
        <td class="alc">{% avatar key 20 %}</td>
        <td>{{ key|email2nickname }}{% if not_read > 0%}({{not_read}}){% endif %}</td>
        <td>{{ value.last_msg|seahub_urlize|truncatewords_html:12 }}</td>
        <td>{{ value.last_time|translate_seahub_time }}</td>
    </tr>
    {% endwith %}
    {% endfor %}
    {% endif %}
</table>

<div id="send-msg-popup" class="hide">
    <img src="{{MEDIA_URL}}img/loading-icon.gif" class="loading-tip" />
    <form id="send-msg-form" action="{% url 'message_send' %}?from=all" method="post" name="send-msg-form" class="msg-form hide">{% csrf_token %}
        <textarea id="mass-msg" name="mass_msg" placeholder="{% trans "message..." %}"></textarea><br/>
        <select id="mass-email" name="mass_email" multiple="multiple"></select><br/>
        <p class="error hide"></p>
        <div class="ops">
            <button type="submit" class="submit">{% trans "Submit" %}</button>
            <button type="button" class="cancel">{% trans "Cancel" %}</button>
            <img src="{{ MEDIA_URL }}img/clip.png" alt="" title="{% trans "Add files" %}" class="add-file fleft" />
            <ul class="hide" id="selected-files"></ul>
        </div>
    </form>
</div>
<div id="add-file-popup" class="file-choose-form hide">
    <h3>{% trans "Choose a file or files:" %}</h3>
    <div class="file-tree-cont" id="file-tree">
        <img src="{{MEDIA_URL}}img/loading-icon.gif" alt="" class="loading-tip" />
    </div>
    <button class="submit">{% trans "Submit" %}</button>
    <button class="simplemodal-close">{% trans "Cancel"%}</button>
</div>

{% endblock %}

{% block extra_script %}{{block.super}}
<script type="text/javascript" src="{{ MEDIA_URL }}js/select2.min.js?t=1393578720"></script>
<script type="text/javascript">
$(function(){       
    $('tr[data-href]').click(function() {
        location.href = $(this).data('href');
    });
});

$('#right-panel').css({'position':'relative'});
$('#add-msg').click(function() {
    var add_msg_btn = $('#add-msg'),
        popup = $('#send-msg-popup');

    if (!popup.hasClass('hide')) {
        popup.addClass('hide');
        return;
    }
    popup.removeClass('hide');
    $.ajax({
        url:'{% url 'get_contacts' %}',
        cache: false,
        dataType: 'json',
        success: function(data) {
            var contacts = data['contacts'],
                opts = '',
                email;
            if (contacts.length > 0) {
                popup.find('.loading-tip').remove();
                $('#send-msg-form').removeClass('hide');

                for(var i = 0, len = contacts.length; i < len; i++) {
                    email = contacts[i].email;
                    opts += '<option value="' + email + '" data-index="' + i + '">' + email + '</option>';
                }
                var format = function(item) {
                    return contacts[$(item.element).data('index')].avatar + '<span class="vam">' + item.text + '</span>';
                }
                $('#mass-email').html(opts).select2({
                    placeholder: "{% trans "send to: click to select contacts" %}",
                    formatResult: format,
                    formatSelection: format,
                    escapeMarkup: function(m) { return m; }
                });
            } else {
                popup.html('<p>' + "{% trans "please add contacts at first" %}" + '</p>');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            var error;
            if (jqXHR.responseText) {
                error = $.parseJSON(jqXHR.responseText).error;
            } else {
                error = "{% trans "Please check the network." %}";
            }
            popup.html('<p class="error alc">' + error + '</p>');
        }
    });
});
$(document).click(function(e) {
    if (e.eventPhase == 2) { // for ff
        return;
    }
    var target = e.target || event.srcElement,
        popup = $('#send-msg-popup'),
        popup_switch = $('#add-msg');
    var add_file_popup = $('#add-file-popup');
/*
    if (!popup.hasClass('hide') && !popup.is(target) && !popup.find('*').is(target) && !popup_switch.is(target) && !add_file_popup.is(target) && !add_file_popup.find('*').is(target)) {
        popup.addClass('hide');
    }    
*/
});

var repos_get_url = '{% url 'get_my_unenc_repos' %}';
{% include 'snippets/add_file_js.html' %}

$('#send-msg-form .cancel').click(function() {
    $('#send-msg-popup').addClass('hide');
    $('#selected-files').data('files','').html('').addClass('hide');
});

$('#send-msg-form').submit(function() {
    var form = $(this),
        form_id = form.attr('id'),
        msg_input = $('[name="mass_msg"]', form),
        msg = $.trim(msg_input.val()),
        emails = $('[name="mass_email"]', form).val(),
        files_ct = $('#selected-files');

    if (!msg) {
        apply_form_error(form_id, "{% trans "message is required" %}");
        return false;
    }
    if (!emails) { // val is null or ['xx',...]
        apply_form_error(form_id, "{% trans "contact is required" %}");
        return false;
    }

    var sb_btn = $('.submit', form);
    disable(sb_btn);

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        data: { 'mass_msg': msg, 'mass_email': emails, 'selected': files_ct.data('files') || [] },
        traditional: true,
        success: function(data) {
            msg_input.val('');
            files_ct.data('files','').html('').addClass('hide');
            enable(sb_btn);
            $('#send-msg-popup').addClass('hide');
            var new_trs = $(data['html']);
            new_trs.each(function() {
                var new_tr = $(this),
                    r = 0;
                $('tr:gt(0)').each(function() {
                    if ($(this).data('href') == new_tr.data('href')) {
                        $(this).replaceWith(new_tr);
                        r = 1;
                    }
                });
                if (!r) {
                    $('tr:first').after(new_tr);             
                }
                new_tr.click(function() {
                    location.href = $(this).data('href');
                });
            });
        },
        error: function (xhr, textStatus, errorThrown) {
            var err_msg;
            if (xhr.responseText) {
                err_msg = $.parseJSON(xhr.responseText).error.join('<br />');
            } else {
                err_msg = "{% trans "Failed. Please check the network." %}";
            }    
            apply_form_error(form_id, err_msg);
        }
    });
    return false;
});

</script>
{% endblock %}
