(function ($) {
    $.widget('bs.fileUploader', {
        options: {
            maxFileSize: 20000000, // ~20 mb
            minFileSize: 20, // ~20 kb
            initialResource: null,


            // Selectors
            content: '.content',
            cancelButton: '.cancel',
            progressBar: '.progress',
            uploadingTemplate: '#uploading-template',
            tempFileTemplate: '#temp-file-template',
            errorTemplate: '#error-template'
        },

        _init: function () {
            var that = this,
                $content = this.element.find(this.options.content),
                aborting = false;

            function displayErrorPanel(result) {
                $.tmpl('error', result).appendTo($content.empty());
            }

            function displayCompletePanel(result) {
                $.tmpl('tempFile', result).appendTo($content.empty());
            }

            function displayUploadingPanel(data) {
                $.tmpl('uploading', data).appendTo($content.empty());
                $content.find(that.options.cancelButton).button();
            }

            $(this.options.uploadingTemplate).template('uploading');
            $(this.options.tempFileTemplate).template('tempFile');
            $(this.options.errorTemplate).template('error');

            this.element.fileupload({
                dropZone: null,
                autoUpload: false,
                dataType: 'json',
                maxFileSize: that.options.maxFileSize,
                minFileSize: that.options.minFileSize,

                add: function (event, data) {
                    var xhr;

                    displayUploadingPanel(data);
                    xhr = data.submit()
                        .success(function (result, textStatus, xhr) {
                            if (result.status >= 400) {
                                displayErrorPanel(result);
                                that._trigger('uploadError', result);
                            }
                            else {
                                displayCompletePanel(result);
                                that._trigger('uploadComplete', null, result);
                            }
                        })
                        .error(function (xhr) {
                            var result, eventType;
                            if (aborting) {
                                result = {errors:['Upload canceled.']};
                                eventType = 'uploadCanceled'
                            }
                            else {
                                result = {errors:['Upload failed.']};
                                eventType = 'uploadError'
                            }

                            displayErrorPanel(result);
                            that._trigger(eventType, result);
                        });

                    that.element.delegate(that.options.cancelButton, 'click', function (event) {
                        aborting = true;
                        xhr.abort();
                        aborting = false;
                        return false;
                    });
                }
            });

            if (this.options.initialResource) {
                displayCompletePanel(this.options.initialResource);
            }

        },
        
        destroy: function () {
            this.element.fileupload('destroy');
        },

        openFileSelectDialog: function () {
            this.element.find("input[type='file']").trigger('click');
        }

    });

}(jQuery));

