{% load i18n %}
{% load url from future %}
var Bottom_bar = '<div id="bottom-bar">{% if groups %}<button id="discuss"><span class="icon-comment-alt"></span>{% trans "Discuss" %}</button><button id="click-into-group"><span class="icon-double-angle-right"></span>{% trans "Group" %}</button>{% endif %}</div>';
$('#wrapper').append(Bottom_bar);
$('#main-panel').css('margin-bottom', $('#bottom-bar').outerHeight() + 2);

{% if groups %}
function getAndHandleDiscussions(data_html) {
    $('#discussions-to-grp').html(data_html).css({'max-height': parseInt($(window).height() * 0.9 - $('#bottom-bar').height() - $('#discuss-to-group-caret').height() - $('#discuss-to-group-form').outerHeight())}).removeClass('hide'); // 'parseInt' to fix '.msg-main top border missing when the ul's max-height is xxx.5px'
    {% include 'group/msg_js.html' %}
}
$('#discuss').click(function() {
    var popup = $('#discuss-to-group'),
        caret = $('#discuss-to-group-caret'),
        form = $('#discuss-to-group-form'),
        path = '{{ path }}';

    // for repo.html: when get dir data with ajax
    if ($('#repo-file-list').length > 0) {
        path = cur_path;
        $('[name="path"]', form).val(path);
        // modify attachment dir name
        $('#discuss-to-group-form .att-name').html($('#cur-dir-name').html());
    }   

    if (popup.hasClass('hide')) {
        popup.removeClass('hide');
        caret.removeClass('hide');
        caret.css({'left': $(this).offset().left});
        $.ajax({
            url: form.attr('action'),
            dataType: 'json',
            data: {
                'repo_id': '{{ repo.id }}',
                'path': path
            },
            success: function(data) {
                getAndHandleDiscussions(data['html']);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                var err_str = ''; 
                if (jqXHR.responseText) {
                    err_str = $.parseJSON(jqXHR.responseText).err;
                    feedback(err_str, 'error');
                }
            }   
        });
    } else {
        popup.addClass('hide');
        caret.addClass('hide');
    }
});

$(document).click(function(e) {
    var target = e.target || event.srcElement;
    if (!$('#discuss, #discuss-to-group, #discuss-to-group-caret').is(target) && !($('#discuss-to-group, #discuss-to-group-caret').find('*').is(target))) {
        $('#discuss-to-group, #discuss-to-group-caret').addClass('hide');
    }   
});

$('#discuss-submit').click(function() {
    var form = $('#discuss-to-group-form'),
        form_id = form.attr('id');
    
    if (form.find('.checkbox-checked').length == 0) {
        apply_form_error(form_id, "{% trans "Please select at least 1 group." %}");
        return false;   
    }

    if (!$.trim($('#discuss-to-group-form .input').val())) {
        apply_form_error(form_id, "{% trans "Please input a discussion." %}");
        return false;   
    }
    form.find('.error').addClass('hide');    

    var groups = [];
    form.find('.checkbox-checked .checkbox-orig').each(function() {
        groups.push($(this).val());
    });

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        traditional: true,
        data: {
            'groups': groups,
            'message': $('[name="message"]', form).val(),
            'repo_id': '{{ repo.id }}',
            'path': $('[name="path"]', form).val(),
            'attach_type': $('[name="attach_type"]', form).val()
        },
        success: function(data) {
            if(data['success']) {
                feedback(data['success'], 'success');
                getAndHandleDiscussions(data['html']);
                form.find('.input').val('');
            }
            if(data['err']) {
                feedback(data['err'], 'error');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            var err_str = ''; 
            if (jqXHR.responseText) {
                err_str = $.parseJSON(jqXHR.responseText).err;
            } else {
                err_str = "{% trans "Failed. Please check the network." %}";
            }   
            apply_form_error(form_id, err_str); 
        }   
    });
    return false;
});

$('#main').append('<div id="to-group" class="hide">{{ repo_group_str|escapejs }}</div><div id="to-group-caret" class="hide"><div class="outer-caret"><div class="inner-caret"></div></div></div>');
$('#click-into-group').click(function() {
    {% if groups|length == 1 %}
    // only one group, just turn to group page
    {% for group in groups %}
    location.href= "{% url 'group_info' group.id %}";
    {% endfor %}

    {% else %}
    // more than one group, then let user choose
    if ($('#to-group').hasClass('hide')) {
        $('#to-group, #to-group-caret').removeClass('hide');
        $('#to-group-caret').css('left', $('#click-into-group').offset().left + $('#click-into-group').width()/3);
        if ($('#to-group').offset().left > $('#click-into-group').offset().left) {
            $('#to-group').css('left', $('#click-into-group').offset().left);
        }
    } else {
        $('#to-group, #to-group-caret').addClass('hide');
    }
    {% endif %}
});
$(document).click(function(e) {
    var target = e.target || event.srcElement;
    if (!$('#click-into-group, #to-group, #to-group-caret').is(target) && !($('#to-group, #to-group-caret').find('*').is(target))) {
        $('#to-group, #to-group-caret').addClass('hide');
    }   
});
{% endif %}

$(function() {
    var btn_height = $('#bottom-bar button').outerHeight();
    $('#discuss-to-group-caret, #to-group-caret, #comment-caret').css({'bottom': btn_height + 1});
    $('#file-comment, #to-group, #discuss-to-group').css({'bottom': btn_height + 1 + $('.outer-caret').outerHeight()});
});
