{% extends "base.html" %}

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

{% block main_panel %}
<div class="wide-panel" id="upload-link-panel">
    <h3>{% blocktrans %}Upload files to <span class="op-target">{{ dir_name }}</span>{% endblocktrans %}</h3>
    <p>{% trans "shared by:" %} {{username|email2nickname}} {% avatar username 16 %} </p>
    {% if no_quota %}
    <p class="error">{% trans "The owner of this library has run out of space." %}</p>
    {% else %}
    <form id="upload-file-form" enctype="multipart/form-data" method="post" action="">{% csrf_token %}
        <div class="row fileupload-buttonbar">
            <div>
                <span class="fileinput-button vam" id="add-file">
                    <span class="icon-plus"></span>
                    <span>{% trans "Add Files" %}</span>
                    <input type="file" name="file" multiple />
                </span>
                {% if enable_upload_folder %}
                <span class="fileinput-button vam" id="add-folder" style="display:none;">
                    <span class="icon-plus"></span>
                    <span>{% trans "Add folder" %}</span>
                    <input type="file" name="file" multiple directory webkitdirectory />
                </span>
                {% endif %}
                <button type="reset" class="cancel vam" id="cancel-all">
                    <span class="icon-ban-circle"></span>
                    <span>{% trans "Cancel All" %}</span>
                </button>
            </div>
            <ol class="tip">
                <li>{% trans "File Drag & Drop is supported for Chrome, Safari 5.0+, Firefox 4.0+, IE 10.0+" %}</li>
                {% if enable_upload_folder %}
                <li>{% trans "Folder Drag & Drop is supported for Chrome" %}</li>
                {% endif %}
                {% if max_upload_file_size %}
                <li>{% blocktrans with max_file_size=max_upload_file_size|filesizeformat %}File size should be smaller than {{ max_file_size }}{% endblocktrans %}</li>
                {% endif %}
            </ol>
            <div class="fileupload-progress fade">
                <div class="progress progress-success progres-striped active">
                    <div class="bar" style="width:0%"></div>
                </div>
                <div class="progress-extended"></div>
            </div>
            <p class="saving-tip alc hide"><img src="{{MEDIA_URL}}img/loading-icon.gif" alt="" style="margin-right:5px;" class="vam" />{% trans "Saving..." %}</p>
        </div>
        <table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
    </form>
    {% endif %}
</div>
{% endblock %}

{% block extra_script %}
{% if not no_quota %}
{% upload_js %}
<script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.fileupload.min.js"></script>
<!--[if lt IE 8]>
<script type="text/javascript">
    $('#add-file')
    .html('<button type="button">{% trans "Add Files" %}</button><input type="file" name="file" multiple />')
    .css({'border':0, 'padding':0})
    .find('input').height($('#add-file').outerHeight());
    $('#cancel-all .icon-ban-circle').remove();
</script>
<![endif]-->
<script type="text/javascript">
// for file upload
window.locale = { 
    "fileupload": {
        "errors": {
            "maxFileSize": "{% trans "File is too big" %}",
            "minFileSize": "{% trans "File is too small" %}",
            "acceptFileTypes": "{% trans "Filetype not allowed" %}",
            "maxNumberOfFiles": "{% trans "Max number of files exceeded" %}",
            "uploadedBytes": "{% trans "Uploaded bytes exceed file size" %}",
            "emptyResult": "{% trans "Empty file upload result" %}"
        },  
        "error": "{% trans "Error" %}",
        "uploaded": "{% trans "uploaded" %}",
        "canceled": "{% trans "canceled" %}",
        "start": "{% trans "Start" %}",
        "cancel": "{% trans "Cancel" %}",
        "destroy": "{% trans "Delete" %}"
    }   
};

var enable_upload_folder = {% if enable_upload_folder %}true{% else %}false{% endif %};
var enable_resumable_fileupload = {% if enable_resumable_fileupload %}true{% else %}false{% endif %};
var form = $('#upload-file-form');
var saving_tip = $('.saving-tip', form);

// Initialize the jQuery File Upload widget:
form.fileupload({
    // customize it for 'done'
    getFilesFromResponse: function (data) {
        if (data.result) {
            return data.result;
        }
    },
    autoUpload: true,
    {% if max_upload_file_size %}
    maxFileSize: {{ max_upload_file_size }}, // in bytes
    {% endif %}
    maxNumberOfFiles: 500,
    sequentialUploads: true
})
.bind('fileuploadadd', function(e, data) {
    form.fileupload('option', {
        'formData': {
            'parent_dir': "{{path|escapejs}}"
        },
        'maxChunkSize': undefined,
        'uploadedBytes': undefined
    });
    if (!enable_upload_folder) {
        return;
    }
    // when add folder, a subdirectory will be shown as '.'. rm it.
    var file = data.files[0];
    if (file.name == '.') {
        data.files.shift();
        return;
    }
    if (file.webkitRelativePath) { // for 'upload folder'
        file.relative_path = file.webkitRelativePath;
    }
    if (file.relativePath) { // for 'folder drag & drop'
        file.relative_path = file.relativePath + file.name;
    }
})
.bind('fileuploadsubmit', function(e, data) {
    if (data.files.length == 0) {
        return false;
    }
    var file = data.files[0];
    // get url(token) for every file
    if (!file.error) {
        $.ajax({
            url: '{% url 'get_file_upload_url_ul' uploadlink.token %}?r={{uploadlink.repo_id }}',
            cache: false,
            dataType: 'json',
            success: function(ret) {
                if (enable_upload_folder && file.relative_path) { // 'add folder'
                    var file_path = file.relative_path,
                        r_path = file_path.substring(0, file_path.lastIndexOf('/') + 1),
                        formData = form.fileupload('option', 'formData');
                    formData.relative_path = r_path;
                    form.fileupload('option', {
                        'formData': formData
                    });
                    data.url = ret['url'];
                    data.jqXHR = form.fileupload('send', data);

                } else {
                    var block_size = 1024 * 1024;
                    if (enable_resumable_fileupload &&
                            file.size && file.size > block_size) {
                        form.fileupload('option', 'maxChunkSize', block_size);
                        $.ajax({
                            url: '{% url 'get_file_uploaded_bytes' uploadlink.repo_id %}',
                            data: {
                                'parent_dir': "{{path|escapejs}}",
                                'file_name': file.name
                            },
                            cache: false,
                            dataType: 'json',
                            success: function(file_uploaded_data) {
                                form.fileupload('option', 'uploadedBytes', file_uploaded_data.uploadedBytes);
                                data.url = ret['url'];
                                data.jqXHR = form.fileupload('send', data);
                            }
                        });

                    } else {
                        data.url = ret['url'];
                        data.jqXHR = form.fileupload('send', data);
                    }
                }

            },
            error: function() {
                file.error = "{% trans "Failed to get upload url" %}";
            }
        });
        return false;
    }
})
.bind('fileuploadprogressall', function (e, data) {
    if (data.loaded > 0 && data.loaded == data.total) {
        saving_tip.show();
    }
})
.bind('fileuploaddone', function(evt, data) {
    if (data.textStatus == 'success') {
        var file = data.result[0];
        var file_path = data.files[0].relative_path;
        file.uploaded = true;
        if (file_path) {
            file.relative_path = file_path.substring(0, file_path.lastIndexOf('/') + 1) + file.name;
        }

        var uploaded_done_link = "{% url "upload_file_done" %}" + "?fn=" + e(file.name) + "&repo_id=" + e("{{repo.id}}");
        var path = "{{path|escapejs}}";
        if (file_path) {
            uploaded_done_link += '&p=' + e(path + file_path.substr(0, file_path.lastIndexOf('/') + 1));
        } else {
            uploaded_done_link += '&p=' + e(path);
        }
        $.get(uploaded_done_link);
    }
})
.bind('fileuploadcompleted fileuploadfailed', function() {
    if ($('.files .cancel', form).length == 0) {
        saving_tip.hide();
    }
});

{% if enable_upload_folder %}
if ('webkitdirectory' in $('input[type="file"]', $('#add-file'))[0]) {
    $('#add-folder').show();
    $('#add-file, #add-folder').click(function() {
        form.fileupload(
            'option',
            'fileInput',
            $('input[type="file"]', $(this))
        );
    });
}
{% endif %}

// Enable iframe cross-domain access via redirect option:
form.fileupload(
    'option',
    'redirect',
    window.location.href.replace(location.pathname, '{{MEDIA_URL}}cors/result.html?%s')
);
</script>
{% endif %}
{% endblock %}
