update domain in click to refresh message
[namibia] / public / js / vendor / jquery.fileupload.js
1 /*
2  * jQuery File Upload Plugin 5.19.3
3  * https://github.com/blueimp/jQuery-File-Upload
4  *
5  * Copyright 2010, Sebastian Tschan
6  * https://blueimp.net
7  *
8  * Licensed under the MIT license:
9  * http://www.opensource.org/licenses/MIT
10  */
11
12 /*jslint nomen: true, unparam: true, regexp: true */
13 /*global define, window, document, Blob, FormData, location */
14
15 (function (factory) {
16     'use strict';
17     if (typeof define === 'function' && define.amd) {
18         // Register as an anonymous AMD module:
19         define([
20             'jquery',
21             'jquery.ui.widget'
22         ], factory);
23     } else {
24         // Browser globals:
25         factory(window.jQuery);
26     }
27 }(function ($) {
28     'use strict';
29
30     // The FileReader API is not actually used, but works as feature detection,
31     // as e.g. Safari supports XHR file uploads via the FormData API,
32     // but not non-multipart XHR file uploads:
33     $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
34     $.support.xhrFormDataFileUpload = !!window.FormData;
35
36     // The fileupload widget listens for change events on file input fields defined
37     // via fileInput setting and paste or drop events of the given dropZone.
38     // In addition to the default jQuery Widget methods, the fileupload widget
39     // exposes the "add" and "send" methods, to add or directly send files using
40     // the fileupload API.
41     // By default, files added via file input selection, paste, drag & drop or
42     // "add" method are uploaded immediately, but it is possible to override
43     // the "add" callback option to queue file uploads.
44     $.widget('blueimp.fileupload', {
45
46         options: {
47             // The drop target element(s), by the default the complete document.
48             // Set to null to disable drag & drop support:
49             dropZone: $(document),
50             // The paste target element(s), by the default the complete document.
51             // Set to null to disable paste support:
52             pasteZone: $(document),
53             // The file input field(s), that are listened to for change events.
54             // If undefined, it is set to the file input fields inside
55             // of the widget element on plugin initialization.
56             // Set to null to disable the change listener.
57             fileInput: undefined,
58             // By default, the file input field is replaced with a clone after
59             // each input field change event. This is required for iframe transport
60             // queues and allows change events to be fired for the same file
61             // selection, but can be disabled by setting the following option to false:
62             replaceFileInput: true,
63             // The parameter name for the file form data (the request argument name).
64             // If undefined or empty, the name property of the file input field is
65             // used, or "files[]" if the file input name property is also empty,
66             // can be a string or an array of strings:
67             paramName: undefined,
68             // By default, each file of a selection is uploaded using an individual
69             // request for XHR type uploads. Set to false to upload file
70             // selections in one request each:
71             singleFileUploads: true,
72             // To limit the number of files uploaded with one XHR request,
73             // set the following option to an integer greater than 0:
74             limitMultiFileUploads: undefined,
75             // Set the following option to true to issue all file upload requests
76             // in a sequential order:
77             sequentialUploads: false,
78             // To limit the number of concurrent uploads,
79             // set the following option to an integer greater than 0:
80             limitConcurrentUploads: undefined,
81             // Set the following option to true to force iframe transport uploads:
82             forceIframeTransport: false,
83             // Set the following option to the location of a redirect url on the
84             // origin server, for cross-domain iframe transport uploads:
85             redirect: undefined,
86             // The parameter name for the redirect url, sent as part of the form
87             // data and set to 'redirect' if this option is empty:
88             redirectParamName: undefined,
89             // Set the following option to the location of a postMessage window,
90             // to enable postMessage transport uploads:
91             postMessage: undefined,
92             // By default, XHR file uploads are sent as multipart/form-data.
93             // The iframe transport is always using multipart/form-data.
94             // Set to false to enable non-multipart XHR uploads:
95             multipart: true,
96             // To upload large files in smaller chunks, set the following option
97             // to a preferred maximum chunk size. If set to 0, null or undefined,
98             // or the browser does not support the required Blob API, files will
99             // be uploaded as a whole.
100             maxChunkSize: undefined,
101             // When a non-multipart upload or a chunked multipart upload has been
102             // aborted, this option can be used to resume the upload by setting
103             // it to the size of the already uploaded bytes. This option is most
104             // useful when modifying the options object inside of the "add" or
105             // "send" callbacks, as the options are cloned for each file upload.
106             uploadedBytes: undefined,
107             // By default, failed (abort or error) file uploads are removed from the
108             // global progress calculation. Set the following option to false to
109             // prevent recalculating the global progress data:
110             recalculateProgress: true,
111             // Interval in milliseconds to calculate and trigger progress events:
112             progressInterval: 100,
113             // Interval in milliseconds to calculate progress bitrate:
114             bitrateInterval: 500,
115
116             // Additional form data to be sent along with the file uploads can be set
117             // using this option, which accepts an array of objects with name and
118             // value properties, a function returning such an array, a FormData
119             // object (for XHR file uploads), or a simple object.
120             // The form of the first fileInput is given as parameter to the function:
121             formData: function (form) {
122                 return form.serializeArray();
123             },
124
125             // The add callback is invoked as soon as files are added to the fileupload
126             // widget (via file input selection, drag & drop, paste or add API call).
127             // If the singleFileUploads option is enabled, this callback will be
128             // called once for each file in the selection for XHR file uplaods, else
129             // once for each file selection.
130             // The upload starts when the submit method is invoked on the data parameter.
131             // The data object contains a files property holding the added files
132             // and allows to override plugin options as well as define ajax settings.
133             // Listeners for this callback can also be bound the following way:
134             // .bind('fileuploadadd', func);
135             // data.submit() returns a Promise object and allows to attach additional
136             // handlers using jQuery's Deferred callbacks:
137             // data.submit().done(func).fail(func).always(func);
138             add: function (e, data) {
139                 data.submit();
140             },
141
142             // Other callbacks:
143             // Callback for the submit event of each file upload:
144             // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
145             // Callback for the start of each file upload request:
146             // send: function (e, data) {}, // .bind('fileuploadsend', func);
147             // Callback for successful uploads:
148             // done: function (e, data) {}, // .bind('fileuploaddone', func);
149             // Callback for failed (abort or error) uploads:
150             // fail: function (e, data) {}, // .bind('fileuploadfail', func);
151             // Callback for completed (success, abort or error) requests:
152             // always: function (e, data) {}, // .bind('fileuploadalways', func);
153             // Callback for upload progress events:
154             // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
155             // Callback for global upload progress events:
156             // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
157             // Callback for uploads start, equivalent to the global ajaxStart event:
158             // start: function (e) {}, // .bind('fileuploadstart', func);
159             // Callback for uploads stop, equivalent to the global ajaxStop event:
160             // stop: function (e) {}, // .bind('fileuploadstop', func);
161             // Callback for change events of the fileInput(s):
162             // change: function (e, data) {}, // .bind('fileuploadchange', func);
163             // Callback for paste events to the pasteZone(s):
164             // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
165             // Callback for drop events of the dropZone(s):
166             // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
167             // Callback for dragover events of the dropZone(s):
168             // dragover: function (e) {}, // .bind('fileuploaddragover', func);
169
170             // The plugin options are used as settings object for the ajax calls.
171             // The following are jQuery ajax settings required for the file uploads:
172             processData: false,
173             contentType: false,
174             cache: false
175         },
176
177         // A list of options that require a refresh after assigning a new value:
178         _refreshOptionsList: [
179             'fileInput',
180             'dropZone',
181             'pasteZone',
182             'multipart',
183             'forceIframeTransport'
184         ],
185
186         _BitrateTimer: function () {
187             this.timestamp = +(new Date());
188             this.loaded = 0;
189             this.bitrate = 0;
190             this.getBitrate = function (now, loaded, interval) {
191                 var timeDiff = now - this.timestamp;
192                 if (!this.bitrate || !interval || timeDiff > interval) {
193                     this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
194                     this.loaded = loaded;
195                     this.timestamp = now;
196                 }
197                 return this.bitrate;
198             };
199         },
200
201         _isXHRUpload: function (options) {
202             return !options.forceIframeTransport &&
203                 ((!options.multipart && $.support.xhrFileUpload) ||
204                 $.support.xhrFormDataFileUpload);
205         },
206
207         _getFormData: function (options) {
208             var formData;
209             if (typeof options.formData === 'function') {
210                 return options.formData(options.form);
211             }
212                         if ($.isArray(options.formData)) {
213                 return options.formData;
214             }
215                         if (options.formData) {
216                 formData = [];
217                 $.each(options.formData, function (name, value) {
218                     formData.push({name: name, value: value});
219                 });
220                 return formData;
221             }
222             return [];
223         },
224
225         _getTotal: function (files) {
226             var total = 0;
227             $.each(files, function (index, file) {
228                 total += file.size || 1;
229             });
230             return total;
231         },
232
233         _onProgress: function (e, data) {
234             if (e.lengthComputable) {
235                 var now = +(new Date()),
236                     total,
237                     loaded;
238                 if (data._time && data.progressInterval &&
239                         (now - data._time < data.progressInterval) &&
240                         e.loaded !== e.total) {
241                     return;
242                 }
243                 data._time = now;
244                 total = data.total || this._getTotal(data.files);
245                 loaded = parseInt(
246                     e.loaded / e.total * (data.chunkSize || total),
247                     10
248                 ) + (data.uploadedBytes || 0);
249                 this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
250                 data.lengthComputable = true;
251                 data.loaded = loaded;
252                 data.total = total;
253                 data.bitrate = data._bitrateTimer.getBitrate(
254                     now,
255                     loaded,
256                     data.bitrateInterval
257                 );
258                 // Trigger a custom progress event with a total data property set
259                 // to the file size(s) of the current upload and a loaded data
260                 // property calculated accordingly:
261                 this._trigger('progress', e, data);
262                 // Trigger a global progress event for all current file uploads,
263                 // including ajax calls queued for sequential file uploads:
264                 this._trigger('progressall', e, {
265                     lengthComputable: true,
266                     loaded: this._loaded,
267                     total: this._total,
268                     bitrate: this._bitrateTimer.getBitrate(
269                         now,
270                         this._loaded,
271                         data.bitrateInterval
272                     )
273                 });
274             }
275         },
276
277         _initProgressListener: function (options) {
278             var that = this,
279                 xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
280             // Accesss to the native XHR object is required to add event listeners
281             // for the upload progress event:
282             if (xhr.upload) {
283                 $(xhr.upload).bind('progress', function (e) {
284                     var oe = e.originalEvent;
285                     // Make sure the progress event properties get copied over:
286                     e.lengthComputable = oe.lengthComputable;
287                     e.loaded = oe.loaded;
288                     e.total = oe.total;
289                     that._onProgress(e, options);
290                 });
291                 options.xhr = function () {
292                     return xhr;
293                 };
294             }
295         },
296
297         _initXHRData: function (options) {
298             var formData,
299                 file = options.files[0],
300                 // Ignore non-multipart setting if not supported:
301                 multipart = options.multipart || !$.support.xhrFileUpload,
302                 paramName = options.paramName[0];
303             options.headers = options.headers || {};
304             if (options.contentRange) {
305                 options.headers['Content-Range'] = options.contentRange;
306             }
307             if (!multipart) {
308                 options.headers['Content-Disposition'] = 'attachment; filename="' +
309                     encodeURI(file.name) + '"';
310                 options.contentType = file.type;
311                 options.data = options.blob || file;
312             } else if ($.support.xhrFormDataFileUpload) {
313                 if (options.postMessage) {
314                     // window.postMessage does not allow sending FormData
315                     // objects, so we just add the File/Blob objects to
316                     // the formData array and let the postMessage window
317                     // create the FormData object out of this array:
318                     formData = this._getFormData(options);
319                     if (options.blob) {
320                         formData.push({
321                             name: paramName,
322                             value: options.blob
323                         });
324                     } else {
325                         $.each(options.files, function (index, file) {
326                             formData.push({
327                                 name: options.paramName[index] || paramName,
328                                 value: file
329                             });
330                         });
331                     }
332                 } else {
333                     if (options.formData instanceof FormData) {
334                         formData = options.formData;
335                     } else {
336                         formData = new FormData();
337                         $.each(this._getFormData(options), function (index, field) {
338                             formData.append(field.name, field.value);
339                         });
340                     }
341                     if (options.blob) {
342                         options.headers['Content-Disposition'] = 'attachment; filename="' +
343                             encodeURI(file.name) + '"';
344                         options.headers['Content-Description'] = encodeURI(file.type);
345                         formData.append(paramName, options.blob, file.name);
346                     } else {
347                         $.each(options.files, function (index, file) {
348                             // File objects are also Blob instances.
349                             // This check allows the tests to run with
350                             // dummy objects:
351                             if (file instanceof Blob) {
352                                 formData.append(
353                                     options.paramName[index] || paramName,
354                                     file,
355                                     file.name
356                                 );
357                             }
358                         });
359                     }
360                 }
361                 options.data = formData;
362             }
363             // Blob reference is not needed anymore, free memory:
364             options.blob = null;
365         },
366
367         _initIframeSettings: function (options) {
368             // Setting the dataType to iframe enables the iframe transport:
369             options.dataType = 'iframe ' + (options.dataType || '');
370             // The iframe transport accepts a serialized array as form data:
371             options.formData = this._getFormData(options);
372             // Add redirect url to form data on cross-domain uploads:
373             if (options.redirect && $('<a></a>').prop('href', options.url)
374                     .prop('host') !== location.host) {
375                 options.formData.push({
376                     name: options.redirectParamName || 'redirect',
377                     value: options.redirect
378                 });
379             }
380         },
381
382         _initDataSettings: function (options) {
383             if (this._isXHRUpload(options)) {
384                 if (!this._chunkedUpload(options, true)) {
385                     if (!options.data) {
386                         this._initXHRData(options);
387                     }
388                     this._initProgressListener(options);
389                 }
390                 if (options.postMessage) {
391                     // Setting the dataType to postmessage enables the
392                     // postMessage transport:
393                     options.dataType = 'postmessage ' + (options.dataType || '');
394                 }
395             } else {
396                 this._initIframeSettings(options, 'iframe');
397             }
398         },
399
400         _getParamName: function (options) {
401             var fileInput = $(options.fileInput),
402                 paramName = options.paramName;
403             if (!paramName) {
404                 paramName = [];
405                 fileInput.each(function () {
406                     var input = $(this),
407                         name = input.prop('name') || 'files[]',
408                         i = (input.prop('files') || [1]).length;
409                     while (i) {
410                         paramName.push(name);
411                         i -= 1;
412                     }
413                 });
414                 if (!paramName.length) {
415                     paramName = [fileInput.prop('name') || 'files[]'];
416                 }
417             } else if (!$.isArray(paramName)) {
418                 paramName = [paramName];
419             }
420             return paramName;
421         },
422
423         _initFormSettings: function (options) {
424             // Retrieve missing options from the input field and the
425             // associated form, if available:
426             if (!options.form || !options.form.length) {
427                 options.form = $(options.fileInput.prop('form'));
428                 // If the given file input doesn't have an associated form,
429                 // use the default widget file input's form:
430                 if (!options.form.length) {
431                     options.form = $(this.options.fileInput.prop('form'));
432                 }
433             }
434             options.paramName = this._getParamName(options);
435             if (!options.url) {
436                 options.url = options.form.prop('action') || location.href;
437             }
438             // The HTTP request method must be "POST" or "PUT":
439             options.type = (options.type || options.form.prop('method') || '')
440                 .toUpperCase();
441             if (options.type !== 'POST' && options.type !== 'PUT') {
442                 options.type = 'POST';
443             }
444             if (!options.formAcceptCharset) {
445                 options.formAcceptCharset = options.form.attr('accept-charset');
446             }
447         },
448
449         _getAJAXSettings: function (data) {
450             var options = $.extend({}, this.options, data);
451             this._initFormSettings(options);
452             this._initDataSettings(options);
453             return options;
454         },
455
456         // Maps jqXHR callbacks to the equivalent
457         // methods of the given Promise object:
458         _enhancePromise: function (promise) {
459             promise.success = promise.done;
460             promise.error = promise.fail;
461             promise.complete = promise.always;
462             return promise;
463         },
464
465         // Creates and returns a Promise object enhanced with
466         // the jqXHR methods abort, success, error and complete:
467         _getXHRPromise: function (resolveOrReject, context, args) {
468             var dfd = $.Deferred(),
469                 promise = dfd.promise();
470             context = context || this.options.context || promise;
471             if (resolveOrReject === true) {
472                 dfd.resolveWith(context, args);
473             } else if (resolveOrReject === false) {
474                 dfd.rejectWith(context, args);
475             }
476             promise.abort = dfd.promise;
477             return this._enhancePromise(promise);
478         },
479
480         // Parses the Range header from the server response
481         // and returns the uploaded bytes:
482         _getUploadedBytes: function (jqXHR) {
483             var range = jqXHR.getResponseHeader('Range'),
484                 parts = range && range.split('-'),
485                 upperBytesPos = parts && parts.length > 1 &&
486                     parseInt(parts[1], 10);
487             return upperBytesPos && upperBytesPos + 1;
488         },
489
490         // Uploads a file in multiple, sequential requests
491         // by splitting the file up in multiple blob chunks.
492         // If the second parameter is true, only tests if the file
493         // should be uploaded in chunks, but does not invoke any
494         // upload requests:
495         _chunkedUpload: function (options, testOnly) {
496             var that = this,
497                 file = options.files[0],
498                 fs = file.size,
499                 ub = options.uploadedBytes = options.uploadedBytes || 0,
500                 mcs = options.maxChunkSize || fs,
501                 slice = file.slice || file.webkitSlice || file.mozSlice,
502                 dfd = $.Deferred(),
503                 promise = dfd.promise(),
504                 jqXHR,
505                 upload;
506             if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
507                     options.data) {
508                 return false;
509             }
510             if (testOnly) {
511                 return true;
512             }
513             if (ub >= fs) {
514                 file.error = 'Uploaded bytes exceed file size';
515                 return this._getXHRPromise(
516                     false,
517                     options.context,
518                     [null, 'error', file.error]
519                 );
520             }
521             // The chunk upload method:
522             upload = function (i) {
523                 // Clone the options object for each chunk upload:
524                 var o = $.extend({}, options);
525                 o.blob = slice.call(
526                     file,
527                     ub,
528                     ub + mcs
529                 );
530                 // Store the current chunk size, as the blob itself
531                 // will be dereferenced after data processing:
532                 o.chunkSize = o.blob.size;
533                 // Expose the chunk bytes position range:
534                 o.contentRange = 'bytes ' + ub + '-' +
535                     (ub + o.chunkSize - 1) + '/' + fs;
536                 // Process the upload data (the blob and potential form data):
537                 that._initXHRData(o);
538                 // Add progress listeners for this chunk upload:
539                 that._initProgressListener(o);
540                 jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
541                     .done(function (result, textStatus, jqXHR) {
542                         ub = that._getUploadedBytes(jqXHR) ||
543                             (ub + o.chunkSize);
544                         // Create a progress event if upload is done and
545                         // no progress event has been invoked for this chunk:
546                         if (!o.loaded) {
547                             that._onProgress($.Event('progress', {
548                                 lengthComputable: true,
549                                 loaded: ub - o.uploadedBytes,
550                                 total: ub - o.uploadedBytes
551                             }), o);
552                         }
553                         options.uploadedBytes = o.uploadedBytes = ub;
554                         if (ub < fs) {
555                             // File upload not yet complete,
556                             // continue with the next chunk:
557                             upload();
558                         } else {
559                             dfd.resolveWith(
560                                 o.context,
561                                 [result, textStatus, jqXHR]
562                             );
563                         }
564                     })
565                     .fail(function (jqXHR, textStatus, errorThrown) {
566                         dfd.rejectWith(
567                             o.context,
568                             [jqXHR, textStatus, errorThrown]
569                         );
570                     });
571             };
572             this._enhancePromise(promise);
573             promise.abort = function () {
574                 return jqXHR.abort();
575             };
576             upload();
577             return promise;
578         },
579
580         _beforeSend: function (e, data) {
581             if (this._active === 0) {
582                 // the start callback is triggered when an upload starts
583                 // and no other uploads are currently running,
584                 // equivalent to the global ajaxStart event:
585                 this._trigger('start');
586                 // Set timer for global bitrate progress calculation:
587                 this._bitrateTimer = new this._BitrateTimer();
588             }
589             this._active += 1;
590             // Initialize the global progress values:
591             this._loaded += data.uploadedBytes || 0;
592             this._total += this._getTotal(data.files);
593         },
594
595         _onDone: function (result, textStatus, jqXHR, options) {
596             if (!this._isXHRUpload(options)) {
597                 // Create a progress event for each iframe load:
598                 this._onProgress($.Event('progress', {
599                     lengthComputable: true,
600                     loaded: 1,
601                     total: 1
602                 }), options);
603             }
604             options.result = result;
605             options.textStatus = textStatus;
606             options.jqXHR = jqXHR;
607             this._trigger('done', null, options);
608         },
609
610         _onFail: function (jqXHR, textStatus, errorThrown, options) {
611             options.jqXHR = jqXHR;
612             options.textStatus = textStatus;
613             options.errorThrown = errorThrown;
614             this._trigger('fail', null, options);
615             if (options.recalculateProgress) {
616                 // Remove the failed (error or abort) file upload from
617                 // the global progress calculation:
618                 this._loaded -= options.loaded || options.uploadedBytes || 0;
619                 this._total -= options.total || this._getTotal(options.files);
620             }
621         },
622
623         _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
624             this._active -= 1;
625             options.textStatus = textStatus;
626             if (jqXHRorError && jqXHRorError.always) {
627                 options.jqXHR = jqXHRorError;
628                 options.result = jqXHRorResult;
629             } else {
630                 options.jqXHR = jqXHRorResult;
631                 options.errorThrown = jqXHRorError;
632             }
633             this._trigger('always', null, options);
634             if (this._active === 0) {
635                 // The stop callback is triggered when all uploads have
636                 // been completed, equivalent to the global ajaxStop event:
637                 this._trigger('stop');
638                 // Reset the global progress values:
639                 this._loaded = this._total = 0;
640                 this._bitrateTimer = null;
641             }
642         },
643
644         _onSend: function (e, data) {
645             var that = this,
646                 jqXHR,
647                 aborted,
648                 slot,
649                 pipe,
650                 options = that._getAJAXSettings(data),
651                 send = function () {
652                     that._sending += 1;
653                     // Set timer for bitrate progress calculation:
654                     options._bitrateTimer = new that._BitrateTimer();
655                     jqXHR = jqXHR || (
656                         ((aborted || that._trigger('send', e, options) === false) &&
657                         that._getXHRPromise(false, options.context, aborted)) ||
658                         that._chunkedUpload(options) || $.ajax(options)
659                     ).done(function (result, textStatus, jqXHR) {
660                         that._onDone(result, textStatus, jqXHR, options);
661                     }).fail(function (jqXHR, textStatus, errorThrown) {
662                         that._onFail(jqXHR, textStatus, errorThrown, options);
663                     }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
664                         that._sending -= 1;
665                         that._onAlways(
666                             jqXHRorResult,
667                             textStatus,
668                             jqXHRorError,
669                             options
670                         );
671                         if (options.limitConcurrentUploads &&
672                                 options.limitConcurrentUploads > that._sending) {
673                             // Start the next queued upload,
674                             // that has not been aborted:
675                             var nextSlot = that._slots.shift(),
676                                 isPending;
677                             while (nextSlot) {
678                                 // jQuery 1.6 doesn't provide .state(),
679                                 // while jQuery 1.8+ removed .isRejected():
680                                 isPending = nextSlot.state ?
681                                         nextSlot.state() === 'pending' :
682                                         !nextSlot.isRejected();
683                                 if (isPending) {
684                                     nextSlot.resolve();
685                                     break;
686                                 }
687                                 nextSlot = that._slots.shift();
688                             }
689                         }
690                     });
691                     return jqXHR;
692                 };
693             this._beforeSend(e, options);
694             if (this.options.sequentialUploads ||
695                     (this.options.limitConcurrentUploads &&
696                     this.options.limitConcurrentUploads <= this._sending)) {
697                 if (this.options.limitConcurrentUploads > 1) {
698                     slot = $.Deferred();
699                     this._slots.push(slot);
700                     pipe = slot.pipe(send);
701                 } else {
702                     pipe = (this._sequence = this._sequence.pipe(send, send));
703                 }
704                 // Return the piped Promise object, enhanced with an abort method,
705                 // which is delegated to the jqXHR object of the current upload,
706                 // and jqXHR callbacks mapped to the equivalent Promise methods:
707                 pipe.abort = function () {
708                     aborted = [undefined, 'abort', 'abort'];
709                     if (!jqXHR) {
710                         if (slot) {
711                             slot.rejectWith(options.context, aborted);
712                         }
713                         return send();
714                     }
715                     return jqXHR.abort();
716                 };
717                 return this._enhancePromise(pipe);
718             }
719             return send();
720         },
721
722         _onAdd: function (e, data) {
723             var that = this,
724                 result = true,
725                 options = $.extend({}, this.options, data),
726                 limit = options.limitMultiFileUploads,
727                 paramName = this._getParamName(options),
728                 paramNameSet,
729                 paramNameSlice,
730                 fileSet,
731                 i;
732             if (!(options.singleFileUploads || limit) ||
733                     !this._isXHRUpload(options)) {
734                 fileSet = [data.files];
735                 paramNameSet = [paramName];
736             } else if (!options.singleFileUploads && limit) {
737                 fileSet = [];
738                 paramNameSet = [];
739                 for (i = 0; i < data.files.length; i += limit) {
740                     fileSet.push(data.files.slice(i, i + limit));
741                     paramNameSlice = paramName.slice(i, i + limit);
742                     if (!paramNameSlice.length) {
743                         paramNameSlice = paramName;
744                     }
745                     paramNameSet.push(paramNameSlice);
746                 }
747             } else {
748                 paramNameSet = paramName;
749             }
750             data.originalFiles = data.files;
751             $.each(fileSet || data.files, function (index, element) {
752                 var newData = $.extend({}, data);
753                 newData.files = fileSet ? element : [element];
754                 newData.paramName = paramNameSet[index];
755                 newData.submit = function () {
756                     newData.jqXHR = this.jqXHR =
757                         (that._trigger('submit', e, this) !== false) &&
758                         that._onSend(e, this);
759                     return this.jqXHR;
760                 };
761                 return (result = that._trigger('add', e, newData));
762             });
763             return result;
764         },
765
766         _replaceFileInput: function (input) {
767             var inputClone = input.clone(true);
768             $('<form></form>').append(inputClone)[0].reset();
769             // Detaching allows to insert the fileInput on another form
770             // without loosing the file input value:
771             input.after(inputClone).detach();
772             // Avoid memory leaks with the detached file input:
773             $.cleanData(input.unbind('remove'));
774             // Replace the original file input element in the fileInput
775             // elements set with the clone, which has been copied including
776             // event handlers:
777             this.options.fileInput = this.options.fileInput.map(function (i, el) {
778                 if (el === input[0]) {
779                     return inputClone[0];
780                 }
781                 return el;
782             });
783             // If the widget has been initialized on the file input itself,
784             // override this.element with the file input clone:
785             if (input[0] === this.element[0]) {
786                 this.element = inputClone;
787             }
788         },
789
790         _handleFileTreeEntry: function (entry, path) {
791             var that = this,
792                 dfd = $.Deferred(),
793                 errorHandler = function (e) {
794                     if (e && !e.entry) {
795                         e.entry = entry;
796                     }
797                     // Since $.when returns immediately if one
798                     // Deferred is rejected, we use resolve instead.
799                     // This allows valid files and invalid items
800                     // to be returned together in one set:
801                     dfd.resolve([e]);
802                 },
803                 dirReader;
804             path = path || '';
805             if (entry.isFile) {
806                 if (entry._file) {
807                     // Workaround for Chrome bug #149735
808                     entry._file.relativePath = path;
809                     dfd.resolve(entry._file);
810                 } else {
811                     entry.file(function (file) {
812                         file.relativePath = path;
813                         dfd.resolve(file);
814                     }, errorHandler);
815                 }
816             } else if (entry.isDirectory) {
817                 dirReader = entry.createReader();
818                 dirReader.readEntries(function (entries) {
819                     that._handleFileTreeEntries(
820                         entries,
821                         path + entry.name + '/'
822                     ).done(function (files) {
823                         dfd.resolve(files);
824                     }).fail(errorHandler);
825                 }, errorHandler);
826             } else {
827                 // Return an empy list for file system items
828                 // other than files or directories:
829                 dfd.resolve([]);
830             }
831             return dfd.promise();
832         },
833
834         _handleFileTreeEntries: function (entries, path) {
835             var that = this;
836             return $.when.apply(
837                 $,
838                 $.map(entries, function (entry) {
839                     return that._handleFileTreeEntry(entry, path);
840                 })
841             ).pipe(function () {
842                 return Array.prototype.concat.apply(
843                     [],
844                     arguments
845                 );
846             });
847         },
848
849         _getDroppedFiles: function (dataTransfer) {
850             dataTransfer = dataTransfer || {};
851             var items = dataTransfer.items;
852             if (items && items.length && (items[0].webkitGetAsEntry ||
853                     items[0].getAsEntry)) {
854                 return this._handleFileTreeEntries(
855                     $.map(items, function (item) {
856                         var entry;
857                         if (item.webkitGetAsEntry) {
858                             entry = item.webkitGetAsEntry();
859                             if (entry) {
860                                 // Workaround for Chrome bug #149735:
861                                 entry._file = item.getAsFile();
862                             }
863                             return entry;
864                         }
865                         return item.getAsEntry();
866                     })
867                 );
868             }
869             return $.Deferred().resolve(
870                 $.makeArray(dataTransfer.files)
871             ).promise();
872         },
873
874         _getSingleFileInputFiles: function (fileInput) {
875             fileInput = $(fileInput);
876             var entries = fileInput.prop('webkitEntries') ||
877                     fileInput.prop('entries'),
878                 files,
879                 value;
880             if (entries && entries.length) {
881                 return this._handleFileTreeEntries(entries);
882             }
883             files = $.makeArray(fileInput.prop('files'));
884             if (!files.length) {
885                 value = fileInput.prop('value');
886                 if (!value) {
887                     return $.Deferred().resolve([]).promise();
888                 }
889                 // If the files property is not available, the browser does not
890                 // support the File API and we add a pseudo File object with
891                 // the input value as name with path information removed:
892                 files = [{name: value.replace(/^.*\\/, '')}];
893             } else if (files[0].name === undefined && files[0].fileName) {
894                 // File normalization for Safari 4 and Firefox 3:
895                 $.each(files, function (index, file) {
896                     file.name = file.fileName;
897                     file.size = file.fileSize;
898                 });
899             }
900             return $.Deferred().resolve(files).promise();
901         },
902
903         _getFileInputFiles: function (fileInput) {
904             if (!(fileInput instanceof $) || fileInput.length === 1) {
905                 return this._getSingleFileInputFiles(fileInput);
906             }
907             return $.when.apply(
908                 $,
909                 $.map(fileInput, this._getSingleFileInputFiles)
910             ).pipe(function () {
911                 return Array.prototype.concat.apply(
912                     [],
913                     arguments
914                 );
915             });
916         },
917
918         _onChange: function (e) {
919             var that = this,
920                 data = {
921                     fileInput: $(e.target),
922                     form: $(e.target.form)
923                 };
924             this._getFileInputFiles(data.fileInput).always(function (files) {
925                 data.files = files;
926                 if (that.options.replaceFileInput) {
927                     that._replaceFileInput(data.fileInput);
928                 }
929                 if (that._trigger('change', e, data) !== false) {
930                     that._onAdd(e, data);
931                 }
932             });
933         },
934
935         _onPaste: function (e) {
936             var cbd = e.originalEvent.clipboardData,
937                 items = (cbd && cbd.items) || [],
938                 data = {files: []};
939             $.each(items, function (index, item) {
940                 var file = item.getAsFile && item.getAsFile();
941                 if (file) {
942                     data.files.push(file);
943                 }
944             });
945             if (this._trigger('paste', e, data) === false ||
946                     this._onAdd(e, data) === false) {
947                 return false;
948             }
949         },
950
951         _onDrop: function (e) {
952             e.preventDefault();
953             var that = this,
954                 dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
955                 data = {};
956             this._getDroppedFiles(dataTransfer).always(function (files) {
957                 data.files = files;
958                 if (that._trigger('drop', e, data) !== false) {
959                     that._onAdd(e, data);
960                 }
961             });
962         },
963
964         _onDragOver: function (e) {
965             var dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
966             if (this._trigger('dragover', e) === false) {
967                 return false;
968             }
969             if (dataTransfer) {
970                 dataTransfer.dropEffect = 'copy';
971             }
972             e.preventDefault();
973         },
974
975         _initEventHandlers: function () {
976             if (this._isXHRUpload(this.options)) {
977                 this._on(this.options.dropZone, {
978                     dragover: this._onDragOver,
979                     drop: this._onDrop
980                 });
981                 this._on(this.options.pasteZone, {
982                     paste: this._onPaste
983                 });
984             }
985             this._on(this.options.fileInput, {
986                 change: this._onChange
987             });
988         },
989
990         _destroyEventHandlers: function () {
991             this._off(this.options.dropZone, 'dragover drop');
992             this._off(this.options.pasteZone, 'paste');
993             this._off(this.options.fileInput, 'change');
994         },
995
996         _setOption: function (key, value) {
997             var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
998             if (refresh) {
999                 this._destroyEventHandlers();
1000             }
1001             this._super(key, value);
1002             if (refresh) {
1003                 this._initSpecialOptions();
1004                 this._initEventHandlers();
1005             }
1006         },
1007
1008         _initSpecialOptions: function () {
1009             var options = this.options;
1010             if (options.fileInput === undefined) {
1011                 options.fileInput = this.element.is('input[type="file"]') ?
1012                         this.element : this.element.find('input[type="file"]');
1013             } else if (!(options.fileInput instanceof $)) {
1014                 options.fileInput = $(options.fileInput);
1015             }
1016             if (!(options.dropZone instanceof $)) {
1017                 options.dropZone = $(options.dropZone);
1018             }
1019             if (!(options.pasteZone instanceof $)) {
1020                 options.pasteZone = $(options.pasteZone);
1021             }
1022         },
1023
1024         _create: function () {
1025             var options = this.options;
1026             // Initialize options set via HTML5 data-attributes:
1027             $.extend(options, $(this.element[0].cloneNode(false)).data());
1028             this._initSpecialOptions();
1029             this._slots = [];
1030             this._sequence = this._getXHRPromise(true);
1031             this._sending = this._active = this._loaded = this._total = 0;
1032             this._initEventHandlers();
1033         },
1034
1035         _destroy: function () {
1036             this._destroyEventHandlers();
1037         },
1038
1039         // This method is exposed to the widget API and allows adding files
1040         // using the fileupload API. The data parameter accepts an object which
1041         // must have a files property and can contain additional options:
1042         // .fileupload('add', {files: filesList});
1043         add: function (data) {
1044             var that = this;
1045             if (!data || this.options.disabled) {
1046                 return;
1047             }
1048             if (data.fileInput && !data.files) {
1049                 this._getFileInputFiles(data.fileInput).always(function (files) {
1050                     data.files = files;
1051                     that._onAdd(null, data);
1052                 });
1053             } else {
1054                 data.files = $.makeArray(data.files);
1055                 this._onAdd(null, data);
1056             }
1057         },
1058
1059         // This method is exposed to the widget API and allows sending files
1060         // using the fileupload API. The data parameter accepts an object which
1061         // must have a files or fileInput property and can contain additional options:
1062         // .fileupload('send', {files: filesList});
1063         // The method returns a Promise object for the file upload call.
1064         send: function (data) {
1065             if (data && !this.options.disabled) {
1066                 if (data.fileInput && !data.files) {
1067                     var that = this,
1068                         dfd = $.Deferred(),
1069                         promise = dfd.promise(),
1070                         jqXHR,
1071                         aborted;
1072                     promise.abort = function () {
1073                         aborted = true;
1074                         if (jqXHR) {
1075                             return jqXHR.abort();
1076                         }
1077                         dfd.reject(null, 'abort', 'abort');
1078                         return promise;
1079                     };
1080                     this._getFileInputFiles(data.fileInput).always(
1081                         function (files) {
1082                             if (aborted) {
1083                                 return;
1084                             }
1085                             data.files = files;
1086                             jqXHR = that._onSend(null, data).then(
1087                                 function (result, textStatus, jqXHR) {
1088                                     dfd.resolve(result, textStatus, jqXHR);
1089                                 },
1090                                 function (jqXHR, textStatus, errorThrown) {
1091                                     dfd.reject(jqXHR, textStatus, errorThrown);
1092                                 }
1093                             );
1094                         }
1095                     );
1096                     return this._enhancePromise(promise);
1097                 }
1098                 data.files = $.makeArray(data.files);
1099                 if (data.files.length) {
1100                     return this._onSend(null, data);
1101                 }
1102             }
1103             return this._getXHRPromise(false, data && data.context);
1104         }
1105
1106     });
1107
1108 }));