{% 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 %}
<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|id_or_email %}" 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="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/>
        <div id="msg-file-share">
            <button type="button" id="msg-file-share-btn"><span class="icon-plus-sign-alt"></span> {% trans "Add files" %}</button>
            <div id="msg-file-tree" class="hide"></div>
            <span class="icon-remove hide"></span>
        </div>
        <p class="error hide"></p>
        <input type="submit" value="{% trans "Submit"%}" />
        <input type="button" value="{% trans "Cancel"%}" class="cancel" />
    </form>
</div>

{% endblock %}

{% block extra_script %}{{block.super}}
<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() {
            popup.html('<p class="error">' + "{% trans "Failed to get your contacts for sending a message." %}" + '</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');
    if (!popup.hasClass('hide') && !popup.is(target) && !popup.find('*').is(target) && !popup_switch.is(target)) {
        popup.addClass('hide');
    }    
});
$('#msg-file-share-btn').click(function() {
    var msg_file_share = $('#msg-file-share'),
        btn = $(this);
    $.ajax({
        'url': '{% url 'get_my_unenc_repos' %}',
        'cache': false,
        'dataType': 'json',
        'success': function(data) {
            btn.addClass('hide');
            var file_tree = new FileTree();
            var repos = file_tree.format_repo_data(data);
            if (repos.length > 0) {
                file_tree.renderFileTree($('#msg-file-tree').css({'max-height':$(window).height() - $('#title-panel').offset().top - $('#title-panel').height() - $('#send-msg-popup').outerHeight(), 'overflow':'auto'}).data('site_root', '{{SITE_ROOT}}'), repos, {'two_state': true});
                $('#msg-file-tree').fadeIn(600);
                msg_file_share.find('.icon-remove').removeClass('hide');
            } else {
                msg_file_share.html('<p class="error">' + "{% trans "You don't have any library at present" %}" + '</p>');
            }
        },
        'error': function(jqXHR, textStatus, errorThrown) {
            if (!jqXHR.responseText) {
                msg_file_share.html('<p class="error">' + "{% trans "Failed. Please check the network." %}" + '</p>');
            }
        }
    });
});
$('#msg-file-share .icon-remove').click(function() {
        $(this).addClass('hide');
        $('#msg-file-tree').fadeOut(200);
        $('#msg-file-share-btn').removeClass('hide');
});
$('#send-msg-form .cancel').click(function() {
        $('#send-msg-popup').addClass('hide');
        $('#add-msg').removeClass('add-msg-hl');
});

$('#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();

    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);

    var selected = [];
    $('[name="selected"][checked="checked"]', form).each(function() {
        var val =  $(this).val();
        if (val.charAt(val.length - 1) != '/') { // only submit file
            selected.push($(this).val());
        }
    });

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        data: { 'mass_msg': msg, 'mass_email': emails, 'selected': selected },
        traditional: true,
        success: function(data) {
            msg_input.val('');
            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 %}
