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

{% block sub_title %}{% trans "Messages" %} - {% endblock %}

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

{% block right_panel %}
<h3 class="hd">{% blocktrans with name=to_email|email2nickname%}Messages with {{name}}{% endblocktrans %}</h3>

<div id="personal-msg-panel" class="msg-panel personal-msg-panel">
    {% if to_email %}
    <form id="personal-message-form" class="msg-form" action="{% url 'message_send' %}?from=user" method="post">{% csrf_token %}
       {% avatar request.user.username 48 %}
        <textarea name="mass_msg" id="message" placeholder="{% trans "Send a message..." %}" class="msg-input"></textarea><br />
        <input type ="hidden" value="{{ to_email }}" name="mass_email" />
        {% for error in form.message.errors %}
        <p class="error">{{ error|escape }}</p>
        {% endfor %}
        <div class="ops hide">
            <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>
        <span class="say"></span>
    </form>
    <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>
        <input type="submit" value="{% trans "Submit" %}" class="submit" />
        <button class="simplemodal-close">{% trans "Cancel"%}</button> 
    </div>
    {% endif %}

    {% if person_msgs %}
    <ul class="msg-list">
    {% for msg in person_msgs.object_list %}
        {% if msg.to_email == request.user.email %}
        <li class="msg msg-received w100" data-id="{{msg.message_id}}">
        <a href="{% url 'user_profile' msg.from_email %}" class="pic fright">{% avatar msg.from_email 48 %}</a>
        {% else %}        
        <li class="msg msg-send w100" data-id="{{msg.message_id}}">
        <a href="{% url 'user_profile' msg.from_email %}" class="pic fleft">{% avatar msg.from_email 48 %}</a> 
        {% endif %}
        <div class="txt">
            <div class="msg-main">
                <div class="msg-hd w100 ovhd">                    
                    {% if msg.from_email == request.user.username %}
                    <span class="msg-del op fright vh">{% trans "Delete" %}</span>
                    {% else %}
                    <span class="re-msg-del op fright vh">{% trans "Delete" %}</span>
                    {% endif %}
                    <a class="author" href="{% url 'user_profile' msg.from_email %}">{{ msg.from_email|email2nickname }}</a>
                    <span class="time">{{ msg.timestamp|translate_seahub_time }}</span>
                </div>
                <p class="msg-con">{{ msg.message|seahub_urlize|find_at|linebreaksbr }}</p>
                <span class="say"></span>
            </div>
        </div>
        </li>
    {% endfor %}
    </ul>
    {% endif %}


    {% if person_msgs.has_other_pages %}
    <div id="paginator">
        {% if person_msgs.has_previous %}
        <a href="?page={{ person_msgs.previous_page_number }}" class="prev">{% trans "Previous" %}</a>
        {% endif %}
        {% for pr in person_msgs.page_range %}
          {% if pr == person_msgs.number %}
          <span class="cur">{{ pr }}</span>
          {% else %}
          <a href="?page={{ pr }}" class="pg">{{ pr }}</a>
          {% endif %}
        {% endfor %}
        {% if person_msgs.has_next %}
        <a href="?page={{ person_msgs.next_page_number }}" class="next">{% trans "Next"%}</a>
        {% endif %}
    </div>
    {% endif %}

    {% if person_msgs.object_list|length > 5 %}
    <a href="#personal-msg-panel" id="msg-upward" class="hide">{% trans "↑Top" %}</a>
    {% endif %}
</div>

{% endblock %}

{% block extra_script %}{{block.super}}
<script type="text/javascript">
{% if person_msgs.object_list|length > 5 %}
// 'back to top'
$(window).scroll(function() {
    var up_icon = $('#msg-upward');
    var msg_panel =  up_icon.parent();
    var msg_panel_offset = msg_panel.offset();
    var msg_panel_bot = msg_panel_offset.top + msg_panel.height(); 
    var win_st = $(window).scrollTop();
    var win_h = $(window).height() + win_st;

    if (win_st > msg_panel_offset.top) {
        up_icon.css({'left': msg_panel_offset.left + msg_panel.width() + 60}).removeClass('hide');
        if (win_h > msg_panel_bot) {
            up_icon.css({'bottom': win_h - msg_panel_bot + 15});
        } else {
            up_icon.css({'bottom': 15});
        }
    } else {
        up_icon.addClass('hide');
    }
});
{% endif %}

var msg_form = $('#personal-message-form');
$('#message').focus(function() {
    $(this).height(75);
    $('.ops', msg_form).removeClass('hide');
});
$('.cancel', msg_form).click(function() {
    $('.ops', msg_form).addClass('hide');
    $('#selected-files').data('files', '').html('');
    $('#message').val('').height(25);
});

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

$('#personal-message-form').submit(function() {
    var form = $(this),
        msg_input = $('[name="mass_msg"]', form),
        msg = $.trim(msg_input.val()),
        files_ct = $('#selected-files');
    
    if (!msg) {
        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': '{{to_email}}', 'selected': files_ct.data('files') || [] },
        traditional: true,
        success: function(data) {
            var new_msg = $(data['html']);
            if ($('.msg-list').length == 0) { // the new discussion is the first discussion in this page
                form.after('<ul class="msg-list"></ul>');    
            }
            $('.msg-list').prepend(new_msg);
            bind_del(new_msg);
            new_msg.slideDown(400);
            msg_input.val('');
            files_ct.data('files','').html('').addClass('hide');
            enable(sb_btn);
        },  
        error: function (xhr, textStatus, errorThrown) {
            var err_msg;
            if (xhr.responseText) {
                err_msg = $.parseJSON(xhr.responseText).error[0];
            } else {
                err_msg = "{% trans "Failed. Please check the network." %}";
            }    
            apply_form_error(form.attr('id'), err_msg);
        }
    });
    return false;
});

function bind_del(context) {
$('.msg-del', context).click(function() {
    var msg = $(this).parents('.msg');
    var cfm;
    if (msg.find('.msg-del-confirm').length > 0) {
        cfm = msg.find('.msg-del-confirm');
    } else {
        cfm = '<div class="op-confirm msg-del-confirm hide"><p>{% trans "Really want to delete this discussion?" %}</p><button class="yes">{% trans "Yes" %}</button><button class="no">{% trans "No" %}</button></div>';
        var msg_main = msg.find('.msg-main');
        var msg_hd = msg.find('.msg-hd');
        cfm = msg_main.append(cfm).children(':last');
        cfm.css({'right':msg_main.css('padding-right'), 'top':msg_hd.position().top + msg_hd.height()});
    }
    cfm.removeClass('hide');
    cfm.children('.yes').click(function() {
        cfm.addClass('hide');
        $.ajax({
            url: '{{SITE_ROOT}}user/' + msg.attr('data-id') + '/msgdel/',
            dataType:'json',
            success: function(data) {
                if (data['success']) {
                    msg.remove();
                    feedback("{% trans "Successfully deleted" %}", 'success');
                } else {
                    feedback("{% trans "Failed to delete: " %}" + data['err_msg'], 'error');
                }
            },
            error: function() {
                feedback("{% trans "Failed." %}", 'error');
            }
        });
    });
    cfm.children('.no').click(function() {
        cfm.addClass('hide');
    });
});

$('.re-msg-del', context).click(function() {
    var msg = $(this).parents('.msg');
    var cfm;
    if (msg.find('.msg-del-confirm').length > 0) {
        cfm = msg.find('.msg-del-confirm');
    } else {
        cfm = '<div class="op-confirm msg-del-confirm hide"><p>{% trans "Really want to delete this discussion?" %}</p><button class="yes">{% trans "Yes" %}</button><button class="no">{% trans "No" %}</button></div>';
        var msg_main = msg.find('.msg-main');
        var msg_hd = msg.find('.msg-hd');
        cfm = msg_main.append(cfm).children(':last');
        cfm.css({'right':msg_main.css('padding-right'), 'top':msg_hd.position().top + msg_hd.height()});
    }
    cfm.removeClass('hide');
    cfm.children('.yes').click(function() {
        cfm.addClass('hide');
        $.ajax({
            url: '{{SITE_ROOT}}user/' + msg.attr('data-id') + '/remsgdel/',
            dataType:'json',
            success: function(data) {
                if (data['success']) {
                    msg.remove();
                    feedback("{% trans "Successfully deleted" %}", 'success');
                } else {
                    feedback("{% trans "Failed to delete: " %}" + data['err_msg'], 'error');
                }
            },
            error: function() {
                feedback("{% trans "Failed." %}", 'error');
            }
        });
    });
    cfm.children('.no').click(function() {
        cfm.addClass('hide');
    });
});

$('.msg-main', context).hover(
    function(){
        $(this).find('.op').removeClass('vh');
    },
    function(){
        $(this).find('.op').addClass('vh');
    }
);
$('.msg-main .op', context).hover(
    function() {
        $(this).css({'text-decoration':'underline'});
    },
    function() {
        $(this).css({'text-decoration':'none'});
    }
);
}


bind_del($('.msg'));
</script>

{% endblock %}
