;( function($, window, document, undefined) {
    'use strict';

    function hash(s) {
        return s.split('').reduce(function(a,b) {
            a = ((a<<5)-a)+b.charCodeAt(0);
            return a&a;
        }, 0);
    }

    function isImage (file) {
        var extension = file.name.substr(file.name.lastIndexOf('.') + 1);
        return [
            'png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg'
        ].indexOf(extension) !== -1;
    }

    function fileSize(size) {
        var i = Math.floor( Math.log(size) / Math.log(1024) );
        return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
    }

    window.MediaUpload = function (files, successCallback) {
        $('#uploads-list').empty();
        $.each(files, function(idx, file) {
            var formData = new FormData();
            formData.append('image', file);

            var image = isImage(file) ? URL.createObjectURL(file) : '/vendor/ignite/images/placeholder.png';
            var identifier = hash(file.name);
            var $template = $($('#upload-template').html());

            $template.attr('id', 'file-' + identifier);
            $template.find('.upload-template-image').attr('src', image);

            $.ajax({
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function(evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = ((evt.loaded / evt.total) * 100);
                            var $item = $('#file-' + identifier);

                            $item.find('.upload-template-progress-bar')
                                .css('width', percentComplete + '%')
                                .attr('value-now', percentComplete);
                            if (percentComplete < 100) {
                                $item.find('.upload-template-percent').html(
                                    percentComplete + '%'
                                );
                            } else {
                                $item.find('.upload-template-progress-bar')
                                    .removeClass('progress-bar-striped active');
                                $item.find('.upload-template-percent').html(
                                    'Upload complete. Processing...'
                                );
                            }
                        }
                    }, false);
                    return xhr;
                },
                beforeSend: function() {
                    $template.find('.upload-template-name').text(file.name);
                    $template.find('.upload-template-size').text(fileSize(file.size));
                    $template.find('.upload-template-progress-bar').attr('value-now', 0);
                    $('#uploads-list').append($template);
                    $('#upload-modal').modal('show');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('#upload-modal').modal('show');

                    var $item = $('#file-' + identifier);

                    $item
                        .find('.upload-template-progress-bar')
                        .css('width', '100%')
                        .attr('value-now', '100');

                    $item
                        .find('.upload-template-progress-bar')
                        .removeClass('progress-bar-warning progress-bar-striped active')
                        .addClass('progress-bar-danger');

                    $item
                        .find('.upload-template-percent')
                        .html('Error: ' + errorThrown);
                },
                success: function (url) {
                    $('#file-' + identifier)
                        .find('.upload-template-progress-bar')
                        .removeClass('progress-bar-warning progress-bar-striped active')
                        .addClass('progress-bar-success');
                    $template.find('.upload-template-percent').html('Done');

                    successCallback(url, (idx + 1) === files.length);
                },
                method: 'POST',
                data: formData,
                url: '/admin/cms/media/api/upload',
                contentType: false,
                processData: false,
                headers: {
                    'X-CSRF-TOKEN': window.Laravel.csrfToken
                }
            });
        });
    };

} )(jQuery, window, document);