<style>
    #progress {
        width: 250px;
        display: none;
    }
    .progress {
        margin-bottom: 5px;
    }
    #file-errors,
    #text-errors,
    #uploaded-file {
        display: none;
    }
</style>

<div>
    <a href="<?php echo $this->url('fileupload')?>">&laquo; Back to Examples Listing</a>
</div>

<h2><?php echo ($this->title) ?: 'File Upload Examples' ?></h2>

<?php
// Configure Errors Helper
$errorsHelper  = $this->plugin('formelementerrors');
$errorsHelper
    ->setMessageOpenFormat('<div class="help-block">')
    ->setMessageSeparatorString('</div><div class="help-block">')
    ->setMessageCloseString('</div>');

// Init Form
$form = $this->form;
$form->setAttribute('class', 'form-horizontal');
$form->setAttribute('action', $this->url('fileupload/progress/session_partial'));
$form->prepare();
?>
<?php echo $this->form()->openTag($form); ?>
<fieldset>
    <legend><?php echo ($this->legend) ?: 'Progress Upload' ?></legend>

    <?php
    //
    // Progress id hidden field.
    // *NOTE* The hidden element MUST be before the file elements.
    //
    echo $this->formFileSessionProgress();
    ?>

    <?php
    //
    // Text Input
    //
    $elem = $form->get('text');
    $elem->setLabelAttributes(array('class' => 'control-label'));
    $errors = $elem->getMessages();
    $errorClass = (!empty($errors)) ? ' error' : '';
    ?>
    <div id="text-controls" class="control-group<?php echo $errorClass ?>">
        <?php echo $this->formLabel($elem); ?>
        <div class="controls">
            <?php echo $this->formText($elem); ?>
            <?php echo $errorsHelper($elem); ?>
            <div id="text-errors" class="help-block"></div>
        </div>
    </div>

    <?php
    //
    // File Input
    //
    $elem = $form->get('file');
    $elem->setLabelAttributes(array('class' => 'control-label'));
    $errors = $elem->getMessages();
    $errorClass = (!empty($errors)) ? ' error' : '';
    ?>
    <div id="file-controls" class="control-group<?php echo $errorClass ?>">
        <?php echo $this->formLabel($elem); ?>
        <div class="controls">
            <?php echo $this->formFile($elem); ?>
            <?php echo $errorsHelper($elem); ?>
            <div id="file-errors" class="help-block"></div>

            <div id="progress" class="help-block">
                <div class="progress progress-info progress-striped active">
                    <div class="bar"></div>
                </div>
                <p></p>
            </div>
            <?php if (!empty($this->tempFiles)) { ?>
                <!--
                Note: You might not want to render the file input in this
                case either, depending on your use-case.
                -->
                <div class="help-block">
                    Uploaded: <ul>
                        <?php foreach ($this->tempFiles as $tempFile) { ?>
                            <li><?php echo $this->escapeHtml($tempFile['name']) ?></li>
                        <?php } ?>
                    </ul>
                </div>
            <?php } ?>
            <div id="uploaded-file" class="help-block"></div>
        </div>
    </div>

    <div id="action-buttons" class="control-group">
        <div class="controls">
            <button class="btn btn-primary">Submit</button>
        </div>
    </div>

    <div id="output"></div>

</fieldset>
<?php echo $this->form()->closeTag($form); ?>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="/js/jquery.form.js"></script>
<script>
    var userInputs = ['text', 'file'];

    /**
     * Error Message functions
     */
    function hideErrors() {
        $(userInputs).each(function(i, name) {
            $('#' + name + '-controls').removeClass('error');
            $('#' + name + '-errors').hide().html('');
        });
    }

    function showErrors(errors) {
        $(userInputs).each(function(i, name) {
            if (errors[name]) {
                $('#' + name + '-controls').addClass('error');
                var errDiv = $('#' + name + '-errors').show().html('');
                for (key in errors[name]) {
                    if (errors[name].hasOwnProperty(key)) {
                        errDiv.append('<div>' + errors[name][key] + '</div>');
                    }
                }
            }
        });
    }

    function hideUploadedFile() {
        $('#uploaded-file').hide().text('');
    }

    function showUploadedFile(name) {
        $('#uploaded-file').show().text('Uploaded: ' + name);
    }

    function hideFormElements() {
        $('#file').hide();
        $('#action-buttons').hide();
    }

    function showFormElements() {
        $('#file').show();
        $('#action-buttons').show();
    }

    /**
     * Progress Bar functions
     */
    var progressInterval;

    function hideProgress() {
        clearInterval(progressInterval);
        $('#progress').hide();
    }

    function showProgress(amount, message) {
        $('#progress').show();
        $('#progress .bar').width(amount + '%');
        $('#progress > p').html(message);
        if (amount < 100) {
            $('#progress .progress')
                .addClass('active')
                .addClass('progress-info')
                .removeClass('progress-success');
        } else {
            $('#progress .progress')
                .removeClass('active')
                .removeClass('progress-info')
                .addClass('progress-success');
        }
    }

    function getProgress() {
        var url = '/file-upload-examples/progress/session-progress?id=' + $('#progress_key').val();
        $.getJSON(url, function(data) {
            //console.log(data);
            if (data.status && !data.status.done) {
                var value = Math.floor((data.status.current / data.status.total) * 100);
                showProgress(value, 'Uploading...');
            } else {
                showProgress(100, 'Complete!');
                clearInterval(progressInterval);
            }
        });
    }

    function startProgress() {
        showProgress(0, 'Starting upload...');
        progressInterval = setInterval(getProgress, 900);
    }

    function removeProgressKeyFromPostArray(arr) {
        var progressKeyName = $('#progress_key').attr('name');
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].name == progressKeyName) {
                arr.splice(i, 1);
                break;
            }
        }
    }

    /**
     * On Ready...
     */
    $(function() {
        $('#file-form').on('submit', function(e) {
            e.preventDefault();

            hideFormElements();
            hideErrors();

            //$.fn.ajaxSubmit.debug = true;
            $(this).ajaxSubmit({
                beforeSubmit: function(arr, $form, options) {
                    // form data array is an array of objects with name and value properties
                    // [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

                    // Remove the file progress id if no file being uploaded,
                    // otherwise you will see backend errors:
                    //   "PHP Warning:  Unknown: The session id is too long or contains illegal characters,
                    //    valid characters are a-z, A-Z, 0-9 and '-,' in Unknown on line 0"
                    // http://php.net/manual/en/session.upload-progress.php
                    if ($('#file').val() == '') {
                        removeProgressKeyFromPostArray(arr);
                    }

                    // Notify backend that submit is via ajax
                    arr.push({ name: "isAjax", value: "1" });

                    // You can also return false to cancel submit
                },
                success: function (response, statusText, xhr, $form) {
                    if (response.status) {
                        // Redirect to success page
                        window.location.replace(response.redirect);
                        // It is better than using window.location.href =,
                        // because replace() does not put the originating page
                        // in the session history, meaning the user won't get
                        // stuck in a never-ending back-button fiasco.
                        // http://stackoverflow.com/a/506004

                        // You don't necessarily have to redirect here...
                        // You could remain on the page and display new form data.
                    } else {
                        // Clear the file input, otherwise the same file gets re-uploaded
                        // http://stackoverflow.com/a/1043969
                        var fileInput = $('#file');
                        fileInput.replaceWith( fileInput.val('').clone( true ) );

                        // Fill in errors
                        showErrors(response.formErrors);

                        // Show the current uploaded file
                        if (response.tempFile) {
                            showUploadedFile(response.tempFile.name);
                        } else {
                            hideUploadedFile();
                        }
                    }

                    showFormElements();
                    setTimeout(hideProgress, 1000);
                },
                error: function(a, b, c) {
                    console.log(a, b, c);
                    hideProgress();
                    alert('Problem when submitting form! Please try again.');
                }
            });
            if ($('#file').val() != '') {
                // Only start the progress if the file input is filled in
                startProgress();
                hideUploadedFile();
            }
        });

    });
</script>
