$( function() {
    {# Add event when user click on "Go" button #}
    $("#buttonGo").bind("click", function() {
        {# Hide form #}
        $("#upload_form_form").css("display", "none");

        {% if handler != 'PhpMyAdmin\\Plugins\\Import\\Upload\\UploadNoplugin' %}
            {# Some variable for javascript #}
            {% set ajax_url = 'import_status.php?id=' ~ upload_id ~ '&' ~ Url_getCommonRaw({
                'import_status': 1
            }) %}
            {% set promot_str = Sanitize_jsFormat(
                'The file being uploaded is probably larger than the maximum allowed size or this is a known bug in webkit based (Safari, Google Chrome, Arora etc.) browsers.'|trans,
                false
            ) %}
            {% set statustext_str = Sanitize_escapeJsString('%s of %s'|trans) %}
            {% set second_str = Sanitize_jsFormat('%s/sec.'|trans, false) %}
            {% set remaining_min = Sanitize_jsFormat('About %MIN min. %SEC sec. remaining.'|trans, false) %}
            {% set remaining_second = Sanitize_jsFormat('About %SEC sec. remaining.'|trans, false) %}
            {% set processed_str = Sanitize_jsFormat(
                'The file is being processed, please be patient.'|trans,
                false
            ) %}
            {% set import_url = Url_getCommonRaw({'import_status': 1}) %}

            {% set upload_html %}
                {% spaceless %}
                    <div class="upload_progress">
                        <div class="upload_progress_bar_outer">
                            <div class="percentage"></div>
                            <div id="status" class="upload_progress_bar_inner">
                                <div class="percentage"></div>
                            </div>
                        </div>
                        <div>
                            <img src="{{ pma_theme_image }}ajax_clock_small.gif" width="16" height="16" alt="ajax clock" /> {{ Sanitize_jsFormat('Uploading your import file…'|trans, false) -}}
                        </div>
                        <div id="statustext"></div>
                    </div>
                {% endspaceless %}
            {% endset %}

            {# Start output #}
            var finished = false;
            var percent  = 0.0;
            var total    = 0;
            var complete = 0;
            var original_title = parent && parent.document ? parent.document.title : false;
            var import_start;

            var perform_upload = function () {
            new $.getJSON(
                "{{ ajax_url|raw }}",
                {},
                function(response) {
                    finished = response.finished;
                    percent = response.percent;
                    total = response.total;
                    complete = response.complete;

                    if (total==0 && complete==0 && percent==0) {
                        $("#upload_form_status_info").html('<img src="{{ pma_theme_image }}ajax_clock_small.gif" width="16" height="16" alt="ajax clock" /> {{ promot_str|raw }}');
                        $("#upload_form_status").css("display", "none");
                    } else {
                        var now = new Date();
                        now = Date.UTC(
                            now.getFullYear(),
                            now.getMonth(),
                            now.getDate(),
                            now.getHours(),
                            now.getMinutes(),
                            now.getSeconds())
                            + now.getMilliseconds() - 1000;
                        var statustext = PMA_sprintf(
                            "{{ statustext_str|raw }}",
                            formatBytes(
                                complete, 1, PMA_messages.strDecimalSeparator
                            ),
                            formatBytes(
                                total, 1, PMA_messages.strDecimalSeparator
                            )
                        );

                        if ($("#importmain").is(":visible")) {
                            {# Show progress UI #}
                            $("#importmain").hide();
                            $("#import_form_status")
                            .html('{{ upload_html|raw }}')
                            .show();
                            import_start = now;
                        }
                        else if (percent > 9 || complete > 2000000) {
                            {# Calculate estimated time #}
                            var used_time = now - import_start;
                            var seconds = parseInt(((total - complete) / complete) * used_time / 1000);
                            var speed = PMA_sprintf(
                                "{{ second_str|raw }}",
                                formatBytes(complete / used_time * 1000, 1, PMA_messages.strDecimalSeparator)
                            );

                            var minutes = parseInt(seconds / 60);
                            seconds %= 60;
                            var estimated_time;
                            if (minutes > 0) {
                                estimated_time = "{{ remaining_min|raw }}"
                                    .replace("%MIN", minutes)
                                    .replace("%SEC", seconds);
                            }
                            else {
                                estimated_time = "{{ remaining_second|raw }}"
                                .replace("%SEC", seconds);
                            }

                            statustext += "<br />" + speed + "<br /><br />" + estimated_time;
                        }

                        var percent_str = Math.round(percent) + "%";
                        $("#status").animate({width: percent_str}, 150);
                        $(".percentage").text(percent_str);

                        {# Show percent in window title #}
                        if (original_title !== false) {
                            parent.document.title
                                = percent_str + " - " + original_title;
                        }
                        else {
                            document.title
                                = percent_str + " - " + original_title;
                        }
                        $("#statustext").html(statustext);
                    }

                    if (finished == true) {
                        if (original_title !== false) {
                            parent.document.title = original_title;
                        }
                        else {
                            document.title = original_title;
                        }
                        $("#importmain").hide();
                        {# Loads the message, either success or mysql error #}
                        $("#import_form_status")
                        .html('<img src="{{ pma_theme_image }}ajax_clock_small.gif" width="16" height="16" alt="ajax clock" /> {{ processed_str|raw }}')
                        .show();
                        $("#import_form_status").load("import_status.php?message=true&{{ import_url|raw }}");
                        PMA_reloadNavigation();

                        {# If finished #}
                    }
                    else {
                        setTimeout(perform_upload, 1000);
                    }
                });
            };
            setTimeout(perform_upload, 1000);
        {% else %}
            {# No plugin available #}
            {% set image_tag -%}
                <img src="{{ pma_theme_image -}}
                    ajax_clock_small.gif" width="16" height="16" alt="ajax clock" />
                {{- Sanitize_jsFormat(
                    'Please be patient, the file is being uploaded. Details about the upload are not available.'|trans,
                    false
                ) -}}
                {{- Util_showDocu('faq', 'faq2-9') -}}
            {%- endset %}
            $('#upload_form_status_info').html('{{ image_tag|raw }}');
            $("#upload_form_status").css("display", "none");
        {% endif %}
    });
});
