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

var share_list = [], contacts = [];
$(function () {
    $.ajax({
        url:'{% url 'get_contacts' %}',
        cache: false,
        dataType: 'json',
        success: function(data) {
            var contact_list = data['contacts'], contact_email;
            for (var i = 0, len = contact_list.length; i < len; i++) {
                contact_email = contact_list[i].email;
                share_list.push({value: contact_email, label: contact_email});
                contacts.push({value:contact_email, avatar:contact_list[i].avatar});
            }
        }
    });
});

function showSharePopup(op, name, aj_data, 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;
    }

    var form = $('#file-share');

    {% if ENABLE_SUB_LIBRARY and not repo.is_virtual and is_repo_owner %}
    var grp_options_ct = $('#share-grp-options');
    if (!$.trim(grp_options_ct.html())) {
        var grp_options = '<ul class="option-list">';
        {% for group in request.user.joined_groups %}
        grp_options += '<li> <label class="checkbox-label"> <span class="checkbox"><input type="checkbox" name="grp" value="{{ group.group_name }}" class="checkbox-orig"/></span> {{group.avatar|safe}} <span class="checkbox-option">' + "{{ group.group_name }}" + '</span> </label> </li>';
        {% endfor %}
        grp_options += '</ul>';
        grp_options_ct.html(grp_options);
    }
    var contact_options_ct = $('#share-contact-options');
    if (!$.trim(contact_options_ct.html())) {
        var contact_options = '<ul class="option-list">';
        for (var i = 0, len = contacts.length; i < len; i++) {
            contact_email = contacts[i].value;
            contact_options += ' <li> <label class="checkbox-label"> <span class="checkbox"><input type="checkbox" name="contact" value="' + contact_email + '" class="checkbox-orig" /></span>' + contacts[i].avatar + ' <span class="checkbox-option">' + contact_email + '</span> </label> </li>';
        }
        contact_options += '</ul>';
        contact_options_ct.html(contact_options);
    }

    $('.checkbox-orig', $('#share-grp-options, #share-contact-options')).click(function() {
        $(this).parent().toggleClass('checkbox-checked');
    });
    $(".checkbox-label", $('#share-grp-options, #share-contact-options')).hover(
        function() {
            $(this).addClass('hl');
        },
        function() {
            $(this).removeClass('hl');
        }
    );
    {% endif %}

    form.modal({appendTo: "#main",'focus':false, containerCss:{"padding":0}});

    var hd = $('#file-share .hd');
    hd.html(hd.html().replace('%(name)s', '<span class="op-target">' + HTMLescape(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.attr('data-link')) {
        $('#gen-link-btn, #link-options').addClass('hide');
        $('#share-link-body').removeClass('hide');
        var link = op.attr('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, #link-options').removeClass('hide');
        $('#share-link-body').addClass('hide');
    }
    $('#gen-link-btn').data('aj_data', aj_data).data('obj', op);
    $('#rm-shared-link').data('obj', op);
    $('input[name="file_shared_name"]').val(name);
    $('input[name="file_shared_type"]').val(type);

    {% if user_perm == 'rw' %}
    // share upload link
    $('#upload-link-share-tab .a').click(function() {
        if (op.attr('data-upload-link')) {
            $('#gen-upload-link-btn, #upload-link-options').addClass('hide');
            $('#share-upload-link-body').removeClass('hide');
            var link = op.attr('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, #upload-link-options').removeClass('hide');
            $('#share-upload-link-body').addClass('hide');
        }
        $('#gen-upload-link-btn').data('aj_data', aj_data).data('obj', op);
        $('#rm-shared-upload-link').data('obj', op);
    });
    {% endif %}

    // '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; }
        });
    });

    {% if ENABLE_SUB_LIBRARY and not repo.is_virtual and is_repo_owner %}
    // 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);
        $("#repo-share-tabs").tabs();
        $('#repo-share-tabs .ui-tabs-nav').css({'padding-left': '1.4em'});
    });
    {% endif %}

    $('#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'))});
    var text = $('#download-extra-msg-text');
    text.css({'width': $('#link-share').width() - parseInt(text.css('padding-left')) - parseInt(text.css('padding-right')) - parseInt(text.css('border-left-width')) - parseInt(text.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('input[name="email"]').val()),
        submit_btn = form.children('input[type="submit"]'),
        extra_msg = form.children('textarea[name="extra_msg"]').val(),
        file_shared_name = form.children('input[name="file_shared_name"]').val(),
        file_shared_type = form.children('input[name="file_shared_type"]').val();

    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,
                extra_msg: extra_msg,
                file_shared_name: file_shared_name,
                file_shared_type: file_shared_type
              },
        success: function(data) {
            $.modal.close();
            var msg = "{% trans "Successfully sent to {placeholder}" %}"
                .replace('{placeholder}', data['send_success'].join(', '));
            feedback(msg, "success");
            if (data['send_failed'].length > 0) {
                msg += '<br />' + "{% trans "Failed to send to {placeholder}" %}"
                    .replace('{placeholder}', data['send_failed'].join(', '));
                feedback(msg, 'info');
            }
        },
        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'),
        form = $('#link-options'),
        form_id = form.attr('id'),
        use_passwd = $('#link-passwd-switch').attr('checked'),
        set_expiration = $('#link-expire-switch').attr('checked'),
        passwd, passwd_again, expire_days, post_data;

    if (use_passwd) {
        passwd = $('input[name="passwd"]', form).val();
        passwd_again = $('input[name="passwd_again"]', form).val();

        if (!$.trim(passwd)) {
            apply_form_error(form_id, "{% trans "Please enter password" %}");
            return false;
        }
        if ($.trim(passwd).length < {{share_link_password_min_length}}) {
            apply_form_error(form_id, "{% trans "Password is too short" %}");
            return false;
        }
        if (!$.trim(passwd_again)) {
            apply_form_error(form_id, "{% trans "Please enter the password again" %}");
            return false;
        }
        if ($.trim(passwd) != $.trim(passwd_again)) {
            apply_form_error(form_id, "{% trans "Passwords don't match" %}");
            return false;
        }
        post_data = {'use_passwd': 1, 'passwd': passwd};
    } else {
        post_data = {'use_passwd': 0};
    }

    if (set_expiration) {
        expire_days = $('input[name="expire-days"]', form).val();
        if (!$.trim(expire_days)) {
            apply_form_error(form_id, "{% trans "Please enter days" %}");
            return false;
        }
        if (Math.floor(expire_days) == expire_days && $.isNumeric(expire_days)) {
            post_data["expire_days"] = expire_days;
        } else {
            apply_form_error(form_id, "{% trans "Please enter valid days" %}");
            return false;
        }
    }

    $.ajax({
            url: '{% url 'ajax_get_download_link' %}',
            type: 'POST',
            dataType: 'json',
            beforeSend: prepareCSRFToken,
            data: $.extend(post_data, $(this).data('aj_data')),
            success: function(data) {
                var link = data['download_link'];
                // hide gen-link button, and show link
                gen_link_btn.addClass('hide');

                $('#link-options, #link-options .error').addClass('hide');
                $('#link-passwd, #link-expire').hide(); // slideDown use 'show()'
                $('#link-passwd-switch, #link-expire-switch').attr('checked', false).parent().removeClass('checkbox-checked');
                $('[type="password"], [name="expire-days"]', form).val('').attr('disabled', false).removeClass('input-disabled');

                $('#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.attr({'data-link': link, 'data-token':data['token']});
            },
            error:ajaxErrorHandler
    });
    return false;
});

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

    $.ajax({
        url: '{% url 'ajax_remove_shared_link' %}',
        type: 'POST',
        data: {'t': token},
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        success: function(data) {
            $('#share-link-body').addClass('hide');
            $('#link-options, #gen-link-btn').removeClass('hide');
            obj.attr({'data-link':'', 'data-token':''});
        },
        error: ajaxErrorHandler
    });
});

{% if user_perm == 'rw' %}
$('#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'))});
    var text = $('#upload-extra-msg-text');
    text.css({'width': $('#upload-link-share').width() - parseInt(text.css('padding-left')) - parseInt(text.css('padding-right')) - parseInt(text.css('border-left-width')) - parseInt(text.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('input[name="email"]').val()),
        submit_btn = form.children('input[type="submit"]'),
        extra_msg = form.children('textarea[name="extra_msg"]').val();

    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,
                extra_msg: extra_msg
              },
        success: function(data) {
            $.modal.close();
            var msg = "{% trans "Successfully sent to {placeholder}" %}"
                .replace('{placeholder}', data['send_success'].join(', '));
            feedback(msg, "success");
            if (data['send_failed'].length > 0) {
                msg += '<br />' + "{% trans "Failed to send to {placeholder}" %}"
                    .replace('{placeholder}', data['send_failed'].join(', '));
                feedback(msg, 'info');
            }
        },
        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'),
        form = $('#upload-link-options'),
        form_id = form.attr('id'),
        passwd_switch = $('#upload-link-passwd-switch'),
        use_passwd = passwd_switch.attr('checked'),
        passwd, passwd_again, post_data;

    if (use_passwd) {
        passwd = $('input[name="passwd"]', form).val();
        passwd_again = $('input[name="passwd_again"]', form).val();

        if (!$.trim(passwd)) {
            apply_form_error(form_id, "{% trans "Please enter password" %}");
            return false;
        }
        if ($.trim(passwd).length < {{share_link_password_min_length}}) {
            apply_form_error(form_id, "{% trans "Password is too short" %}");
            return false;
        }
        if (!$.trim(passwd_again)) {
            apply_form_error(form_id, "{% trans "Please enter the password again" %}");
            return false;
        }
        if ($.trim(passwd) != $.trim(passwd_again)) {
            apply_form_error(form_id, "{% trans "Passwords don't match" %}");
            return false;
        }
        post_data = {'use_passwd': 1, 'passwd': passwd};
    } else {
        post_data = {'use_passwd': 0};
    }

    $.ajax({
        url: '{% url 'ajax_get_upload_link' %}',
        type: 'POST',
        dataType: 'json',
        beforeSend: prepareCSRFToken,
        data: $.extend(post_data, {
            'repo_id': $(this).data('aj_data').repo_id, 
            'p': $(this).data('aj_data').p
        }),
        success: function(data) {
            var upload_link = data['upload_link'];
            gen_upload_link_btn.addClass('hide');

            $('#upload-link-options, #upload-link-options .error').addClass('hide');
            $('#upload-link-passwd').hide();
            $('#upload-link-passwd-switch').attr('checked', false).parent().removeClass('checkbox-checked');
            $('[type="password"]', form).val('').attr('disabled', false).removeClass('input-disabled');

            $('#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.attr({'data-upload-link': upload_link, 'data-upload-token': data['token']});
        },
        error: function(xhr, textStatus, errorThrown) {
            location.reload(true);
        }
    });
    return false;
});

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

    $.ajax({
        url: '{% url 'ajax_remove_shared_upload_link' %}',
        type: 'POST',
        data: {'t': token},
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        success: function(data) {
            $('#share-upload-link-body').addClass('hide');
            $('#upload-link-options, #gen-upload-link-btn').removeClass('hide');
            obj.attr({'data-upload-link': '', 'data-upload-token':''});
        },
        error:ajaxErrorHandler
    });
});

$('#upload-link-passwd-switch').click(function () {
    var form = $('#upload-link-options'),
        pwd_input = $('input[type="password"]', form);
    var link_passwd = $('#upload-link-passwd');

    if ($(this).attr('checked')) {
        pwd_input.attr('disabled', false).removeClass('input-disabled');
        link_passwd.slideDown(100);
    } else {
        link_passwd.slideUp(100);
        pwd_input.attr('disabled', true).addClass('input-disabled');
    }
});
{% endif %}

$('#link-passwd-switch').click(function () {
    var form = $('#link-options'),
        pwd_input = $('input[type="password"]', form);
    var link_passwd = $('#link-passwd');

    if ($(this).attr('checked')) {
        pwd_input.attr('disabled', false).removeClass('input-disabled');
        link_passwd.slideDown(100);
    } else {
        link_passwd.slideUp(100);
        pwd_input.attr('disabled', true).addClass('input-disabled');
    }
});

$('#link-expire-switch').click(function () {
    var form = $('#link-options'),
        days_input = $('input[name="expire-days"]', form);
    var link_expire = $('#link-expire'); 

    if ($(this).attr('checked')) {
        link_expire.slideDown(100);
        days_input.attr('disabled', false).removeClass('input-disabled');
    } else {
        link_expire.slideUp(100);
        days_input.attr('disabled', true).addClass('input-disabled');
    }
});
