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

// set 'side toolbar' & 'groups' popup position
function setToolbarPos() {
    var toolbar = $('#side-toolbar');

    // set toolbar pos
    toolbar.css({'top': ($(window).height() - toolbar.outerHeight())/2});

    // set 'groups' popup position
    $('#to-group').css({'top': parseInt(toolbar.css('top')) + 59});
}
$(window).load(function() {
    var to_top = $('<ul class="side-toolbar hide" style="margin-top:3px;"><li class="item" title="{% trans "Back to top" %}"><img src="{{MEDIA_URL}}img/top.png" alt="{% trans "top" %}" /></li></ul>');
    to_top.click(function() {
        $(window).scrollTop(0);
    }).appendTo($('#side-toolbar'));
    $(window).scroll(function() {
        if ($(window).scrollTop() > 0) {
            to_top.show();
        } else {
            to_top.hide();
        }
    });
    setToolbarPos();
}).resize(setToolbarPos);


{% if groups %}
function getAndHandleDiscussions(data_html) {
    $('#discussions-to-grp').html(data_html).css({'max-height': parseInt($(window).height() * 0.8 - $('#discuss-to-group-form').outerHeight())}).removeClass('hide'); // 'parseInt' to fix '.msg-main top border missing when the ul's max-height is xxx.5px'
    var popup = $('#discuss-to-group');
    popup.css({'top':($(window).height() - popup.outerHeight())/2});
    {% include 'group/msg_js.html' %}
}
$('#discuss').click(function() {
    var popup = $('#discuss-to-group'),
        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
        $('.att-name', form).html($('#cur-dir-name').html());
    }   

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

// click 'close' to close discuss popup
$('#discuss-to-group .close').click(function () {
    $('#discuss-to-group').addClass('hide');
});

$(document).click(function(e) {
    var target = e.target || event.srcElement;
    if (!$('#discuss, #discuss-to-group').is(target) && !($('#discuss, #discuss-to-group').find('*').is(target))) {
        $('#discuss-to-group').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['error']) {
                feedback(data['error'], 'error');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            var err_str = ''; 
            if (jqXHR.responseText) {
                err_str = $.parseJSON(jqXHR.responseText).error;
            } else {
                err_str = "{% trans "Failed. Please check the network." %}";
            }   
            apply_form_error(form_id, err_str); 
        }   
    });
    return false;
});

$('#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
    $('#to-group').toggleClass('hide');
    {% endif %}
});
$(document).click(function(e) {
    var target = e.target || event.srcElement;
    if (!$('#click-into-group, #to-group').is(target) && !($('#click-into-group, #to-group').find('*').is(target))) {
        $('#to-group').addClass('hide');
    }   
});
{% endif %}
