<div id="uploadBox">
    {# jQuery tab wrapper #}
    <div class="upload-tabs">
        {# tab nav bar #}
        <ul>
            <li>
                <a href="#tab-upload">
                    {{ 'Upload' | trans }}
                </a>
            </li>
            <li>
                {# template prod/upload/lazaret.html.twig loaded via ajax #}
                <a class="lazaret-target" href="{{ path('lazaret_elements') }}">
                    {# <span>&nbsp;</span> element is required for the jQuery loading spinner appears && disappears properly #}
                    {{ 'Quarantine' | trans }}<span>&nbsp;</span>
                </a>
            </li>
        </ul>
        {# upload tab content #}

        <div id="tab-upload">
            {% if collections|length > 0 %}
                <form id="fileupload" enctype="multipart/form-data" method="POST" action="{{ path('upload_form') }}">

                    <div id="uploadBoxLeft" class="well">

                        {# action bar #}
                        <table id="addFileList">
                            <tr>
                                <td class='uploader-button'>
                                    <span class="btn fileinput-button input-medium">
                                        <span>{{ 'Select files...' | trans }}</span>
                                        <input type="file" name="files[]" multiple>
                                    </span>
                                        <br />
                                    <span class="comment">
                                        ({% trans with {'%maxFileSizeReadable%' : maxFileSizeReadable} %}maximum : %maxFileSizeReadable%{% endtrans %})
                                    </span>
                                </td>
                                {#<td class='uploader-icon'>#}
                                {#<img src='/assets/common/images/icons/html5-logo.png' width="32px" heigh="32px"  title="{{ 'You are using the HTML5 uploader.' | trans }}"/>#}
                                {#</td>#}
                                {#<td class="uploader-info">#}
                                {#<p>#}
                                {#{{ 'You are using the HTML5 uploader.' | trans }}#}
                                {#{% if not app['browser'].supportFileAPI() %}#}
                                {#{{ 'Your browser does not support all HTML5 features properly.' | trans }}#}
                                {#{% endif %}#}
                                {#</p>#}
                                <a style="display: none" id="UPLOAD_FLASH_LINK" href="{{ path('upload_flash_form') }}"
                                   class="dialog full-dialog">{{ 'Use the Flash uploader' | trans }}</a>
                                {#</td>#}
                            </tr>
                        </table>

                        {# settings box #}
                        <div class='settings-box'>
                            <h5>{{ 'upload:: Destination (collection) :' | trans }} :</h5>
                            {# collections list #}
                            {% if collections|length > 0 %}
                                {% set last_used_collection = app['settings'].getUserSetting(app.getAuthenticatedUser(), 'upload_last_used_collection') %}
                                <select onchange="setPref('upload_last_used_collection', $(this).val());" name="base_id" class="span3" style="margin-left: 10px;">
                                {% for  sbasId, availableCollections in collections %}
                                    <optgroup label="{{ availableCollections['databox'].get_label(app['locale']) }}" class="select-label">
                                    {% for collection in availableCollections['databox_collections'] %}
                                        <option {% if last_used_collection == collection.get_base_id() %} selected="selected" {% endif %} value="{{ collection.get_base_id() }}" class="select-row">{{ collection.get_label(app['locale']) }}</option>
                                    {% endfor %}
                                    </optgroup>
                                {% endfor %}
                                </select>
                                {# collections status #}
                                {% for availableCollections in collections %}
                                    {% for collection in availableCollections['databox_collections'] %}
                                        <div id="status-{{ collection.get_base_id() }}" class='collection-status' style='{{ loop.parent.loop.first and loop.first ? "display:block" :"display:none" }}'>
                                            <h5>{{ 'upload:: Status :' | trans }} :</h5>
                                            <table class="status-tab">
                                                <tbody>
                                                {% for bit, status in availableCollections['databox'].getStatusStructure() %}
                                                    <tr>
                                                        <td class="status-tab-left">
                                                            {% if status['img_off'] is not empty %}
                                                                <img src="{{ status['img_off'] }}" width="16" height="16" />
                                                            {% endif %}
                                                            <span>{{ status['labels_off_i18n'][app['locale']]|default('off') }}</span>
                                                            <input type="radio" name="status[{{ collection.get_base_id() }}][{{ bit }}]" value="0" checked="checked"/>
                                                        </td>
                                                        <td class="status-tab-right">
                                                            <input type="radio" name="status[{{ collection.get_base_id() }}][{{ bit }}]" value="1" />
                                                            <span for="labelon">{{ status['labels_on_i18n'][app['locale']]|default('on') }}</span>
                                                            {% if status['img_on'] is not empty %}
                                                                <img src="{{ status['img_on'] }}" width="16" height="16" />
                                                            {% endif %}
                                                        </td>
                                                    </tr>
                                                {% endfor %}
                                                </tbody>
                                            </table>
                                        </div>
                                    {% endfor %}
                                {% endfor %}
                            {% else %}
                                {{ 'You can not upload files' | trans }}
                            {% endif %}
                        </div>

                        {# upload box #}
                        <div class='upload-box' style="display: none;">
                            {% set quantity = '<span class="number-files">0</span>' %}
                            <h5>{% trans with {'%quantity%' : quantity} %}%quantity% selected files{% endtrans %}</h5>
                            <button type="button" class="clear-queue btn input-medium" style="margin-bottom: 10px;">{{ 'Clear list' | trans }}</button>
                            <button type="button" class="upload-submitter btn input-medium" style="margin-bottom: 10px;">{{ 'Send' | trans }}</button>
                            <div class="clear"></div>
                            <div class='upload-box-addedfiles'></div>
                            <div class="clear"></div>
                        </div>
                    </div>

                    <div id="uploadBoxRight" class="well">
                        <div>
                            <h5 style="margin-top: 10px;">{{ 'Transmited files' | trans }} :
                                <span class='bitrate-box'></span>
                                <span class="transmit-box pull-right" style="display: none;">
                                    <span class="number-files-transmited">0</span>
                                    <span>/</span>
                                    <span class="number-files-to-transmit"></span>
                                </span>
                            </h5>
                            <button id="cancel-all" class="btn" type="button" disabled="disabled">
                                {{ "Cancel all" | trans }}
                            </button>
                        </div>
                        <div class="progress progress-striped active">
                            <div class="progress-bar-total bar" style="width: 0%;"></div>
                        </div>

                        {# download box #}
                        <div class="download-box"></div>
                    </div>

                </form>
                <div>
                    <select name="upload_type" id="upload_type" class="input-large" style="width: 200px; float:right">
                        <option value="html" selected>{{ 'Use the HTML5 uploader' | trans }}</option>
                        <option value="flash">{{ 'Use the Flash uploader' | trans }}</option>
                    </select>
                </div>
            {% else %}
                {{ 'You can not upload files' | trans }}
            {% endif %}
         </div>
    </div>
</div>

{% include "prod/templates/upload.html.twig" %}

<script>


$(document).ready(function () {
    var filesList = $dialog.options.filesList || [];
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    if (iev >= 10) {
        $("#UPLOAD_FLASH_LINK").hide();
        $('#upload_type option[value="flash"]').remove();
    }
    //Upload management
    var UploaderManager = new p4.UploaderManager({
        container: $('#uploadBox'),
        uploadBox: $('#uploadBox .upload-box-addedfiles'),
        settingsBox: $('#uploadBox .settings-box'),
        downloadBox: $('#uploadBox .download-box')
    });

    var totalElement;
    var maxFileSize = {{ maxFileSize }};

    UploaderManager.Preview.setOptions({
        maxWidth: 130,
        maxHeight: 120
    });

    $('#upload_type').on('change', function () {
        if ($(this).val() === 'flash') {
            $("#UPLOAD_FLASH_LINK").trigger("click");
        }
    });

    //Init jquery tabs
    $(".upload-tabs", UploaderManager.getContainer()).tabs({
        beforeLoad: function( event, ui ) {
            ui.jqXHR.success(function( xhr, status, index, anchor ) {
                var lazaretBox = $("#lazaretBox");

                $('.userTips', lazaretBox).tooltip();
            });
            ui.jqXHR.error(function( xhr, status, index, anchor ) {
                //display error message if ajax failed
                $( anchor.hash ).html(language.error);
            });

            ui.tab.find('span').html(' <img src="/assets/common/images/icons/loader404040.gif"/>');
        },
        load: function(event, ui)
        {
          ui.tab.find('span').empty();
          $('.btn.page-lazaret', UploaderManager.getContainer()).bind('click', function () {
              $('.lazaret-target').attr('href', $('a', $(this)).attr('href'));
              $(".upload-tabs", UploaderManager.getContainer()).tabs('load', 1);
              $('#lazaretBox').empty();

              return false;
          });
        },
        create : function () {
            $('#tab-upload').css('overflow', 'hidden');
        },
        heightStyle: "fill"
    });

    //Show the good collection status box
    $('select[name="base_id"]', UploaderManager.getSettingsBox()).bind('change', function(){
        var selectedCollId = $(this).find('option:selected').val();

        $('#uploadBox .settings-box .collection-status').hide();

        $('#uploadBox #status-' + selectedCollId).show();
    });

    UploaderManager.getContainer().on("file-added", function(){
        $(".number-files").html(UploaderManager.countData());
    });

    UploaderManager.getContainer().on("file-removed", function(){
        $(".number-files").html(UploaderManager.countData());
    });

    UploaderManager.getContainer().on("file-transmited", function(){
        var domEl = $(".number-files-transmited");
        domEl.html(parseInt(domEl.html()) + 1);
    });

    UploaderManager.getContainer().on("uploaded-file-removed", function(){
        var domEl = $(".number-files-to-transmit");
        domEl.html(parseInt(domEl.html()) - 1);
    });

    //Remove all element from upload box
    $("button.clear-queue", UploaderManager.getContainer()).bind("click", function(){
        UploaderManager.clearUploadBox();
        $('ul', $(this).closest('.upload-box')).empty();
        UploaderManager.getContainer().trigger("file-removed");
    });

    //Cancel all upload
    $("#cancel-all").bind("click", function(){
        //Remove all cancel
        $('button.remove-element', UploaderManager.getDownloadBox()).each(function(i, el){
            $(el).trigger("click");
        });

        progressbarAll.width('0%');
    });

    //Remove an element from the upload box
    $(UploaderManager.getUploadBox()).on('click', 'button.remove-element', function(){
        var container = $(this).closest("li");
        var uploadIndex = container.find("input[name=uploadIndex]").val();
        UploaderManager.removeData(uploadIndex);
        container.remove();
        UploaderManager.getContainer().trigger("file-removed");
    });

    //Get all elements in the upload box & trigger the submit event
    $("button.upload-submitter", UploaderManager.getContainer()).bind("click", function(){
        //Fetch all valid elements
        var documents = UploaderManager.getUploadBox().find('li.upload-valid');

        totalElement = documents.length;

        if(totalElement > 0) {
            $(".number-files").html("");
            $(".number-files-to-transmit").html(totalElement);
            $(".transmit-box").show();

            var dialog = p4.Dialog.get(1);

            //reset progressbar for iframe uploads
            if( ! $.support.xhrFileUpload && ! $.support.xhrFormDataFileUpload) {
                progressbarAll.width('0%');
            }
            //enabled cancel all button
            $("#cancel-all").attr("disabled", false);

            //prevent dialog box from being closed while files are being downloaded
            dialog.getDomElement().bind("dialogbeforeclose", function(event, ui) {
                if ( ! UploaderManager.Queue.isEmpty()) {
                    p4.Alerts(language.warning, language.fileBeingDownloaded);
                    return false;
                }
            });

            documents.each(function(index, el){
                var index = $(el).find('input[name=uploadIndex]').val();
                UploaderManager.getData(index).submit();
            });
        }
    });

    $('#fileupload', UploaderManager.getContainer()).fileupload({
        namespace: 'phrasea-upload',
        // define our own mediatype to handle and convert the response
        // to prevent errors when Iframe based uploads
        // as they require text/plain or text/html Content-type
        // see http://api.jquery.com/extending-ajax/#Converters
        dataType: 'phrjson',
        converters: {
            'html phrjson': function(htmlEncodedJson) {
                return $.parseJSON(htmlEncodedJson);
            },
            'iframe phrjson': function (iframe) {
                return $.parseJSON(iframe.find('body').text());
            }
        },
        // override "on error" local ajax event to prevent global ajax event from being triggered
        // as all fileupload options are passed as argument to the $.ajax jquery function
        error: function(){return false;},
        // Set singleFileUploads, sequentialUploads to true so the files
        // are upload one by one
        singleFileUploads : true,
        sequentialUploads: true,
        recalculateProgress: true,
        //When a file is added
        add: function (e, data) {
            //Since singleFileUploads &  sequentialUploads are setted to true
            //There is only on file data.files
            $.each(data.files, function (index, file) {
                $('.upload-box').show();

                if (file.error) {
                    var params = $.extend({}, file, {error: language.errorFileApi, language: language});
                    var html = _.template($("#upload_items_error_tpl").html(), params);
                    UploaderManager.getUploadBox().append(html);
                } else if(file.size > maxFileSize){
                    var params = $.extend({}, file, {error: language.errorFileApiTooBig, language: language});
                    var html = _.template($("#upload_items_error_tpl").html(), params);
                    UploaderManager.getUploadBox().append(html);
                } else {
                    // Add data to Queue
                    UploaderManager.addData(data);

                    // Check support of file.size && file.type property
                    var formatedFile = {
                        id: 'file-' + index,
                        size: typeof file.size !== "undefined" ? UploaderManager.Formater.size(file.size) : '',
                        name: file.name,
                        type: typeof file.type !== "undefined" ? file.type : '',
                        uploadIndex: UploaderManager.getUploadIndex(),
                        language: language
                    };

                    //Set context in upload-box
                    var html = _.template($("#upload_items_tpl").html(), formatedFile);
                    UploaderManager.getUploadBox().append(html);

                    var context = $("li", UploaderManager.getUploadBox()).last();

                    var uploadIndex = context.find("input[name=uploadIndex]").val();

                    UploaderManager.addAttributeToData(uploadIndex, 'context', context);

                    UploaderManager.Preview.render(file, function(img){
                        context.find('.thumbnail .canva-wrapper').prepend(img);
                        UploaderManager.addAttributeToData(uploadIndex, 'image', img);
                        UploaderManager.addAttributeToData(uploadIndex, 'b64_image', img.toDataURL("image/png") || '');
                    });
                }
            });

            UploaderManager.getContainer().trigger("file-added");
        },
        //on success upload
        done: function (e, data) {
            // set progress bar to 100% for preventing mozilla bug which never reach 100%
            data.context.find('.progress-bar').width('100%');
            data.context.find('div.progress').removeClass('progress-striped active');
            data.context.find('button.remove-element').removeClass('btn-inverse').addClass('disabled');

            UploaderManager.removeData(data.uploadIndex);
            UploaderManager.getContainer().trigger("file-transmited");

            data.context.find("button.remove-element").remove();

            if( ! $.support.xhrFileUpload && ! $.support.xhrFormDataFileUpload) {
                progressbarAll.width(100 - Math.round((UploaderManager.Queue.getLength() * (100 / totalElement ))) + '%');
            }

            if (UploaderManager.Queue.isEmpty()){
                progressbarAll.width('100%');
                bitrateBox.empty();
                $('#uploadBoxRight .progress').removeClass('progress-striped active');
                var dialog = p4.Dialog.get(1);
                //unbind check before close event & disabled button for cancel all download
                dialog.getDomElement().unbind("dialogbeforeclose");
                //disabled cancel-all button, if queue is empty and last upload success
                $("#cancel-all").attr("disabled", true);
            }

            return false;
        },
        fail: function(){
            //disabled cancel-all button, if queue is empty and last upload fail
            if (UploaderManager.Queue.isEmpty()){
                $("#cancel-all").attr("disabled", true);
            }
        }
    });

    //on submit file
    $('#fileupload', UploaderManager.getContainer()).bind('fileuploadsubmit', function (e, data) {
        var $this = $(this);
        var params = [];
        data.formData = [];

        //get form datas attached to the file
        params.push(data.context.find('input, select').serializeArray());
        params.push($("input", $('.collection-status:visible', UploaderManager.getSettingsBox())).serializeArray());
        params.push($("select", UploaderManager.getSettingsBox()).serializeArray());

        $.each(params, function(i, p) {
            $.each(p, function (i, f){
                data.formData.push(f);
            });
        });

        //remove current context
        data.context.remove();

        //Set new context in download-box
        $.each(data.files, function (index, file) {
            var params = $.extend({}, file, {language: language, id:'file-'+index});
            var html = _.template($("#download_items_tpl").html(), params);

            UploaderManager.getDownloadBox().append(html);

            data.context = $("li", UploaderManager.getDownloadBox()).last();

            //copy image
            data.context.find('.upload-record .canva-wrapper').prepend(data.image);

            //launch ajax request
            var jqXHR = $this.fileupload('send', data)
            .success(function(response){
                if(response.success){
                    //case record
                    if(response.element === 'record'){
                        var html = _.template($("#download_finish_tpl").html(), {heading:response.message, reasons: response.reasons});
                        data.context.find('.upload-record p.success').append(html).show();
                    } else { //case quarantine
                        var html = _.template($("#download_finish_tpl").html(), {heading:response.message, reasons: response.reasons});
                        data.context.find('.upload-record p.error').append(html).show();
                    }
                } else {
                    //fail
                    var html = _.template($("#download_finish_tpl").html(), {heading:response.message, reasons: response.reasons});
                    data.context.find('.upload-record p.error').append(html).show();
                }
            })
            .error(function(jqXHR, textStatus, errorThrown) {
                //Request is aborted
                if (errorThrown === 'abort') {
                    return false;
                } else {
                    data.context.find('.upload-record p.error').append(jqXHR.status + " " + jqXHR.statusText).show();
                }
                //Remove data
                UploaderManager.removeData(data.uploadIndex);
                // Remove cancel button
                $('button.remove-element', data.context).remove();
            });

            //cancel request
            $('button.remove-element', data.context).bind('click', function (e) {
                jqXHR.abort();
                data.context.remove();

                UploaderManager.getContainer().trigger("uploaded-file-removed");
            });
        });

        return false;
    });

    var bitrateBox = $('#uploadBoxRight .bitrate-box');

    // Get one file upload progress & bitrate
    $('#fileupload', UploaderManager.getContainer()).bind('fileuploadprogress', function (e, data) {
        var progressbar = data.context.find('.progress-bar');
        progressbar.width(Math.round(UploaderManager.Formater.pourcent(data.loaded, data.total)) + '%');
        bitrateBox.empty().append(UploaderManager.Formater.bitrate(data.bitrate));
    });

    var progressbarAll = $('#uploadBoxRight .progress-bar-total');

    //Get global upload progress
    $('#fileupload', UploaderManager.getContainer()).bind('fileuploadprogressall', function (e, data) {
        progressbarAll.width(Math.round(UploaderManager.Formater.pourcent(data.loaded, data.total)) + '%');
    });

    $('#fileupload', UploaderManager.getContainer()).bind('fileuploadfail', function (e, data) {
        //Remove from queue
        UploaderManager.removeData(data.uploadIndex);
    });

    $('#fileupload', UploaderManager.getContainer()).bind('fileuploadsend', function (e, data) {

        //IFRAME progress fix
        if( ! $.support.xhrFileUpload && ! $.support.xhrFormDataFileUpload) {
            data.context.find('.progress-bar').width('25%');
        }
    });

    if (filesList !== undefined) {
        $('#fileupload', UploaderManager.getContainer()).fileupload('add', {files: filesList});
    }

});
</script>
<style>
    .btn.page-lazaret a {
        color: black;
    }
</style>
