{% load i18n %}


function showSharePopup(op, name, aj_data, type, cur_path) {
    var path = cur_path + name;

    var form = $('#file-share');
    var modal = form.modal({appendTo: "#main", focus:false});

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

    $("#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);

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

$('#send-link').on('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").on('click', function() {
    $('#link-send-form, #send-link, #rm-shared-link').toggleClass('hide');
});

$("#link-send-form").on('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 = JSON.parse(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').on('click', function() {
    $(this).trigger('select');
});

$('#gen-link-btn').on('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').prop('checked'),
        set_expiration = $('#link-expire-switch').prop('checked'),
        preview_only = $('[name="preview_only"]', form).prop('checked'),
        password, password_again, expire_days,
        post_data = {};

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

        if (!$.trim(password)) {
            apply_form_error(form_id, "{% trans "Please enter password" %}");
            return false;
        }
        if ($.trim(password).length < {{share_link_password_min_length}}) {
            apply_form_error(form_id, "{% trans "Password is too short" %}");
            return false;
        }
        if (!$.trim(password_again)) {
            apply_form_error(form_id, "{% trans "Please enter the password again" %}");
            return false;
        }
        if ($.trim(password) != $.trim(password_again)) {
            apply_form_error(form_id, "{% trans "Passwords don't match" %}");
            return false;
        }
        post_data['password'] =  password;
    }

    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;
        }
    }

    if (preview_only) {
        post_data["permissions"] = JSON.stringify({
            "can_preview": true,
            "can_download": false
        });
    }

    $.ajax({
            url: '{% url 'api-v2.1-share-links' %}',
            type: 'POST',
            dataType: 'json',
            beforeSend: prepareCSRFToken,
            data: $.extend(post_data, $(this).data('aj_data')),
            success: function(data) {
                var link = data['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').prop('checked', false);
                $('[type="password"], [name="expire-days"]', form).val('').attr('disabled', false).removeClass('input-disabled');
                $('[name="preview_only"]', form).prop('checked', false);

                $('#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').on('click', function() {
    var obj = $(this).data('obj'),
        token = obj.attr('data-token');

    $.ajax({
        url: '{{ SITE_ROOT }}api/v2.1/share-links/' + token + '/',
        type: 'DELETE',
        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
    });
});

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

    if ($(this).prop('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').on('click', function () {
    var form = $('#link-options'),
        days_input = $('input[name="expire-days"]', form);
    var link_expire = $('#link-expire');

    if ($(this).prop('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');
    }
});
