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

var share_list = [], contacts = [], contact_email;    
{% for contact in contacts %}
contact_email = '{{ contact.contact_email }}';
share_list.push({value: contact_email, label: contact_email});
contacts.push({value:contact_email, avatar:'{% avatar contact.contact_email 16 %}'});
{% endfor %}

function showSharePopup(op, name, aj_urls, type, cur_path) {
    var path;
    if (op.attr('id') == 'share-cur-dir') {
        path = cur_path.substr(0, cur_path.length - 1); // rm the last '/' as seafile_api treats '/xx' and '/xx/' as different
    } else {
        path = cur_path + name;
    }
    $('#file-share').modal({appendTo: "#main",'focus':false, containerCss:{"padding":0}});

    var hd = $('#file-share .hd');
    hd.html(hd.html().replace('%(name)s', '<span class="op-target">' + trimFilename(name, 30) + '</span>'));

    if (type == 'd') {
        $('#private-share-tab, #private-share').remove();
    } else {
        $('#syncable-share-tab, #syncable-share, #upload-link-share-tab, #upload-link-share').remove();
    }
    $("#file-share-tabs").tabs();

    // share link
    if (op.data('link')) {
        $('#gen-link-btn').addClass('hide');
        $('#share-link-body').removeClass('hide');
        var link = op.data('link');
        $('#shared-link-text, #link-send-form input[name="file_shared_link"]').val(link);
        $('#main').append('<p id="linkwidth" class="hide">' + link + '</p>');
        $('#shared-link-text').css({'width':$('#linkwidth').width() + 25});
        $('#linkwidth').remove();
    } else {
        $('#gen-link-btn').removeClass('hide');
        $('#share-link-body').addClass('hide');
    }
    $('#gen-link-btn').data('url', aj_urls['link']).data('obj', op);
    $('#rm-shared-link').data('obj', op);

    // share upload link
    $('#upload-link-share-tab .a').click(function() {
        if (op.data('upload-link')) {
            $('#gen-upload-link-btn').addClass('hide');
            $('#share-upload-link-body').removeClass('hide');
            var link = op.data('upload-link');
            $('#shared-upload-link-text, #upload-link-send-form input[name="shared_upload_link"]').val(link);
            $('#main').append('<p id="linkwidth" class="hide">' + link + '</p>');
            $('#shared-upload-link-text').css({'width':$('#linkwidth').width() + 25});
            $('#linkwidth').remove();
        } else {
            $('#gen-upload-link-btn').removeClass('hide');
            $('#share-upload-link-body').addClass('hide');
        }
        $('#gen-upload-link-btn').data('url', aj_urls['upload-link']).data('obj', op);
        $('#rm-shared-upload-link').data('obj', op);
    });

    // 'private share' for file
    $('#private-share-tab a').click(function() {
        var form = $('#private-share-form');
        $("input[name=s_type]", form).val(type);
        $("input[name=path]", form).val(path);

        var opts = '', email, avatar;
        for (var i = 0, len = contacts.length; i < len; i++) {
            email = contacts[i].value;
            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>';
        }
        $('[name="emails"]', form).html(opts).select2({
            placeholder: "{% trans "Select contacts" %}",
            formatResult: format,
            formatSelection: format,
            escapeMarkup: function(m) { return m; }
        });
    });

    // syncable share for dir
    $('#syncable-share-tab a').click(function() {
        var form = $("#repo-share-form");
        form.removeClass('hide').css({'width':'auto', 'padding-top':0});
        $("h3", form).remove();
        $('.checkbox-label', form).css({'margin-right':'3px'}); // make it not show on top of the scrollbar when hover
        form.data('dir-path', path).attr('data-name', name);
        $("#repo-share-tabs").tabs();
        $('#repo-share-tabs .ui-tabs-nav').removeClass('tab-popup-tabs-nav').addClass('tab-tabs-nav').css({'padding-left': '1.4em'});
        $(window).resize(); // to reposition the popup, as this panel is 'taller'
    });

    $('#simplemodal-container').css({'height':'auto', 'width':'auto'});
}

$('#send-link').click(function() {
    $(this).addClass('hide');
    $('#rm-shared-link').addClass('hide');
    var input = $('#link-send-input');
    input.css({'width': $('#link-share').width() - parseInt(input.css('padding-left')) - parseInt(input.css('padding-right')) - parseInt(input.css('border-left-width')) - parseInt(input.css('border-right-width'))});
    $('#link-send-form').removeClass('hide');
    addAutocomplete('#link-send-input', '#link-send-form', share_list);
});

$("#link-send-form .cancel").click(function() {
    $('#link-send-form, #send-link, #rm-shared-link').toggleClass('hide');
});

$("#link-send-form").submit(function(event) {
    var form = $(this), 
        file_shared_link = form.children('input[name="file_shared_link"]').val(),
        email = $.trim(form.children('textarea[name="email"]').val()),
        submit_btn = form.children('input[type="submit"]');
    
    if (!email) {
        apply_form_error('link-send-form', '{% trans "Please input at least an email." %}');
        return false;
    }

    disable(submit_btn);
    $('#link-send-form .error').addClass('hide');
    $('#sending').removeClass('hide');

    $.ajax({
        type: "POST",
        url: "{% url 'send_shared_link' %}",
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {file_shared_link: file_shared_link, email: email},
        success: function(data) {
            $.modal.close();
            feedback(data['msg'], "success");
        },
        error: function(xhr, textStatus, errorThrown) {
            $('#sending').addClass('hide');
            enable(submit_btn);
            var err_str = '';
            if (xhr.responseText) {
                var err = jQuery.parseJSON(xhr.responseText);
                if (err.error) {
                    err_str = err.error;
                } else {
                    for (var i in err) {
                        err_str += err[i];
                    }
                }
            } else {
                err_str = '{% trans "Failed. Please check the network." %}';
            }
            apply_form_error('link-send-form', err_str);
        }
    });
   return false;
});

$('#shared-link-text').click(function() {
    $(this).select();
});

$('#gen-link-btn').click(function() {
    var gen_link_btn = $(this),
        obj = gen_link_btn.data('obj');

    $.ajax({
            url: gen_link_btn.data('url'),
            dataType: 'json',
            cache: false,
            success: function(data) {
                var link = data['shared_link'];
                // hide gen-link button, and show link
                gen_link_btn.addClass('hide');
                $('#shared-link-text, #link-send-form input[name="file_shared_link"]').val(link);
                $('#main').append('<p id="linkwidth" class="hide">' + link + '</p>');
                $('#shared-link-text').css({'width':$('#linkwidth').width() + 25});
                $('#linkwidth').remove();
                $('#share-link-body').removeClass('hide');
                obj.data('link', link).data('token', data['token']);
            },
            error: function(xhr, textStatus, errorThrown) {
                if (xhr.responseText) {
                    feedback(jQuery.parseJSON(xhr.responseText).error, 'error');
                } else {
                    feedback("{% trans "Failed. Please check the network." %}", 'error');
                }   
            }
    });
    return false;
});

$('#rm-shared-link').click(function() {
    var obj = $(this).data('obj'),
        token = obj.data('token');

    $.ajax({
        url: '{% url 'remove_shared_link' %}?t=' + token,
        dataType: 'json',
        cache: false,
        success: function(data) {
            $('#share-link-body').addClass('hide');
            $('#gen-link-btn').removeClass('hide');
            obj.data('link', '').data('token', '');
        },
        error: function(xhr, textStatus, errorThrown) {
            if (xhr.responseText) {
                feedback(jQuery.parseJSON(xhr.responseText).error, 'error');
            } else {
                feedback("{% trans "Failed. Please check the network." %}", 'error');
            }   
        }
    });
});

$('#shared-upload-link-text').click(function() {
    $(this).select();
});

$('#send-upload-link').click(function() {
    $(this).addClass('hide');
    $('#rm-shared-upload-link').addClass('hide');
    var input = $('#upload-link-send-input');
    input.css({'width': $('#upload-link-share').width() - parseInt(input.css('padding-left')) - parseInt(input.css('padding-right')) - parseInt(input.css('border-left-width')) - parseInt(input.css('border-right-width'))});
    $('#upload-link-send-form').removeClass('hide');
    addAutocomplete('#upload-link-send-input', '#upload-link-send-form', share_list);
});

$("#upload-link-send-form .cancel").click(function() {
    $('#upload-link-send-form, #send-upload-link, #rm-shared-upload-link').toggleClass('hide');
});

$("#upload-link-send-form").submit(function(event) {
    var form = $(this),
        shared_upload_link = form.children('input[name="shared_upload_link"]').val(),
        email = $.trim(form.children('textarea[name="email"]').val()),
        submit_btn = form.children('input[type="submit"]');

    if (!email) {
        apply_form_error('upload-link-send-form', '{% trans "Please input at least an email." %}');
        return false;
    }

    disable(submit_btn);
    $('#upload-link-send-form .error').addClass('hide');
    $('#upload-sending').removeClass('hide');

    $.ajax({
        type: "POST",
        url: "{% url 'send_shared_upload_link' %}",
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {shared_upload_link: shared_upload_link, email: email},
        success: function(data) {
            $.modal.close();
            feedback(data['msg'], "success");
        },
        error: function(xhr, textStatus, errorThrown) {
            $('#upload-sending').addClass('hide');
            enable(submit_btn);
            var err_str = '';
            if (xhr.responseText) {
                var err = jQuery.parseJSON(xhr.responseText);
                if (err.error) {
                    err_str = err.error;
                } else {
                    for (var i in err) {
                        err_str += err[i];
                    }
                }
            } else {
                err_str = '{% trans "Failed. Please check the network." %}';
            }
            apply_form_error('upload-link-send-form', err_str);
        }
    });
   return false;
});

$('#gen-upload-link-btn').click(function() {
    var gen_upload_link_btn = $(this),
    obj = gen_upload_link_btn.data('obj');

    $.ajax({
        url: gen_upload_link_btn.data('url'),
        dataType: 'json',
        cache: false,
        success: function(data) {
            var upload_link = data['shared_upload_link'];
            gen_upload_link_btn.addClass('hide');
            $('#shared-upload-link-text, #upload-link-send-form input[name="shared_upload_link"]').val(upload_link);
            $('#main').append('<p id="linkwidth" class="hide">' + upload_link + '</p>');
            $('#shared-upload-link-text').css({'width':$('#linkwidth').width() + 25});
            $('#linkwidth').remove();
            $('#share-upload-link-body').removeClass('hide');
            obj.data('upload-link', upload_link).data('upload-token', data['token']);
        },
        error: function(xhr, textStatus, errorThrown) {
            if (xhr.responseText) {
                feedback(jQuery.parseJSON(xhr.responseText).error, 'error');
            } else {
                feedback("{% trans "Failed. Please check the network." %}", 'error');
            }
        }
    });
    return false;
});

$('#rm-shared-upload-link').click(function() {
    var obj = $(this).data('obj'),
        token = obj.data('upload-token');

    $.ajax({
        url: '{% url 'remove_shared_upload_link' %}?t=' + token,
        dataType: 'json',
        cache: false,
        success: function(data) {
            $('#share-upload-link-body').addClass('hide');
            $('#gen-upload-link-btn').removeClass('hide');
            obj.data('upload-link', '').data('upload-token', '');
        },
        error: function(xhr, textStatus, errorThrown) {
            if (xhr.responseText) {
                feedback(jQuery.parseJSON(xhr.responseText).error, 'error');
            } else {
                feedback("{% trans "Failed. Please check the network." %}", 'error');
            }
        }
    });
});
