corn_js 0.0.1 → 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1307 @@
1
+ /**
2
+ * http://github.com/valums/file-uploader
3
+ *
4
+ * Multiple file upload component with progress-bar, drag-and-drop.
5
+ * © 2010 Andrew Valums ( andrew(at)valums.com )
6
+ *
7
+ * Licensed under GNU GPL 2 or later, see license.txt.
8
+ */
9
+ /**
10
+ * http://github.com/jgoguen/file-uploader
11
+ * Forked from http://github.com/valums/file-uploader
12
+ * © 2010 Andrew Valums ( andrew(at)valums.com )
13
+ * © 2011 Joel Goguen ( jgoguen(at)jgoguen.ca )
14
+ *
15
+ * Script now depends on jQuery for functioning.
16
+ *
17
+ * Licensed under GNU GPL 2 or later and GNU LGPL 2 or later, see license.txt.
18
+ */
19
+
20
+ //
21
+ // Helper functions
22
+ //
23
+
24
+ var qq = qq || {};
25
+
26
+ /**
27
+ * Adds all missing properties from second obj to first obj
28
+ */
29
+ qq.extend = function(first, second){
30
+ for (var prop in second){
31
+ first[prop] = second[prop];
32
+ }
33
+ };
34
+
35
+ /**
36
+ * Searches for a given element in the array, returns -1 if it is not present.
37
+ * @param {Number} [from] The index at which to begin the search
38
+ */
39
+ qq.indexOf = function(arr, elt, from){
40
+ if (arr.indexOf) return arr.indexOf(elt, from);
41
+
42
+ from = from || 0;
43
+ var len = arr.length;
44
+
45
+ if (from < 0) from += len;
46
+
47
+ for (; from < len; from++){
48
+ if (from in arr && arr[from] === elt){
49
+ return from;
50
+ }
51
+ }
52
+ return -1;
53
+ };
54
+
55
+ qq.getUniqueId = (function(){
56
+ var id = 0;
57
+ return function(){ return id++; };
58
+ })();
59
+
60
+ //
61
+ // Events
62
+
63
+ qq.attach = function(element, type, fn){
64
+ if (element.addEventListener){
65
+ element.addEventListener(type, fn, false);
66
+ } else if (element.attachEvent){
67
+ element.attachEvent('on' + type, fn);
68
+ }
69
+ };
70
+ qq.detach = function(element, type, fn){
71
+ if (element.removeEventListener){
72
+ element.removeEventListener(type, fn, false);
73
+ } else if (element.attachEvent){
74
+ element.detachEvent('on' + type, fn);
75
+ }
76
+ };
77
+
78
+ qq.preventDefault = function(e){
79
+ if (e.preventDefault){
80
+ e.preventDefault();
81
+ } else{
82
+ e.returnValue = false;
83
+ }
84
+ };
85
+
86
+ //
87
+ // Node manipulations
88
+
89
+ /**
90
+ * Insert node a before node b.
91
+ */
92
+ qq.insertBefore = function(a, b){
93
+ b.parentNode.insertBefore(a, b);
94
+ };
95
+ qq.remove = function(element){
96
+ element.parentNode.removeChild(element);
97
+ };
98
+
99
+ qq.contains = function(parent, descendant){
100
+ // compareposition returns false in this case
101
+ if (parent == descendant) return true;
102
+
103
+ if (parent.contains){
104
+ return parent.contains(descendant);
105
+ } else {
106
+ return !!(descendant.compareDocumentPosition(parent) & 8);
107
+ }
108
+ };
109
+
110
+ /**
111
+ * Creates and returns element from html string
112
+ * Uses innerHTML to create an element
113
+ */
114
+ qq.toElement = (function(){
115
+ var div = document.createElement('div');
116
+ return function(html){
117
+ div.innerHTML = html;
118
+ var element = div.firstChild;
119
+ div.removeChild(element);
120
+ return element;
121
+ };
122
+ })();
123
+
124
+ //
125
+ // Node properties and attributes
126
+
127
+ /**
128
+ * Sets styles for an element.
129
+ * Fixes opacity in IE6-8.
130
+ */
131
+ qq.css = function(element, styles){
132
+ if (styles.opacity != null){
133
+ if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
134
+ styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
135
+ }
136
+ }
137
+ qq.extend(element.style, styles);
138
+ };
139
+ qq.hasClass = function(element, name){
140
+ var re = new RegExp('(^| )' + name + '( |$)');
141
+ return re.test(element.className);
142
+ };
143
+ qq.addClass = function(element, name){
144
+ if (!qq.hasClass(element, name)){
145
+ element.className += ' ' + name;
146
+ }
147
+ };
148
+ qq.removeClass = function(element, name){
149
+ var re = new RegExp('(^| )' + name + '( |$)');
150
+ element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
151
+ };
152
+ qq.setText = function(element, text){
153
+ element.innerText = text;
154
+ element.textContent = text;
155
+ };
156
+
157
+ //
158
+ // Selecting elements
159
+
160
+ qq.children = function(element){
161
+ var children = [],
162
+ child = element.firstChild;
163
+
164
+ while (child){
165
+ if (child.nodeType == 1){
166
+ children.push(child);
167
+ }
168
+ child = child.nextSibling;
169
+ }
170
+
171
+ return children;
172
+ };
173
+
174
+ qq.getByClass = function(element, className){
175
+ if (element.querySelectorAll){
176
+ return element.querySelectorAll('.' + className);
177
+ }
178
+
179
+ var result = [];
180
+ var candidates = element.getElementsByTagName("*");
181
+ var len = candidates.length;
182
+
183
+ for (var i = 0; i < len; i++){
184
+ if (qq.hasClass(candidates[i], className)){
185
+ result.push(candidates[i]);
186
+ }
187
+ }
188
+ return result;
189
+ };
190
+
191
+ /**
192
+ * obj2url() takes a json-object as argument and generates
193
+ * a querystring. pretty much like jQuery.param()
194
+ *
195
+ * how to use:
196
+ *
197
+ * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
198
+ *
199
+ * will result in:
200
+ *
201
+ * `http://any.url/upload?otherParam=value&a=b&c=d`
202
+ *
203
+ * @param Object JSON-Object
204
+ * @param String current querystring-part
205
+ * @return String encoded querystring
206
+ */
207
+ qq.obj2url = function(obj, temp, prefixDone){
208
+ var uristrings = [],
209
+ prefix = '&',
210
+ add = function(nextObj, i){
211
+ var nextTemp = temp
212
+ ? (/\[\]$/.test(temp)) // prevent double-encoding
213
+ ? temp
214
+ : temp+'['+i+']'
215
+ : i;
216
+ if ((nextTemp != 'undefined') && (i != 'undefined')) {
217
+ uristrings.push(
218
+ (typeof nextObj === 'object')
219
+ ? qq.obj2url(nextObj, nextTemp, true)
220
+ : (Object.prototype.toString.call(nextObj) === '[object Function]')
221
+ ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
222
+ : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
223
+ );
224
+ }
225
+ };
226
+
227
+ if (!prefixDone && temp) {
228
+ prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
229
+ uristrings.push(temp);
230
+ uristrings.push(qq.obj2url(obj));
231
+ } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
232
+ // we wont use a for-in-loop on an array (performance)
233
+ for (var i = 0, len = obj.length; i < len; ++i){
234
+ add(obj[i], i);
235
+ }
236
+ } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
237
+ // for anything else but a scalar, we will use for-in-loop
238
+ for (var i in obj){
239
+ add(obj[i], i);
240
+ }
241
+ } else {
242
+ uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
243
+ }
244
+
245
+ return uristrings.join(prefix)
246
+ .replace(/^&/, '')
247
+ .replace(/%20/g, '+');
248
+ };
249
+
250
+ //
251
+ //
252
+ // Uploader Classes
253
+ //
254
+ //
255
+
256
+ var qq = qq || {};
257
+
258
+ /**
259
+ * Creates upload button, validates upload, but doesn't create file list or dd.
260
+ */
261
+ qq.FileUploaderBasic = function(o){
262
+ this._options = {
263
+ // set to true to see the server response
264
+ debug: false,
265
+ action: '/server/upload',
266
+ params: {},
267
+ button: null,
268
+ uploadButtonText: 'Upload a file',
269
+ multiple: true,
270
+ maxConnections: 3,
271
+ useBase2Prefixes: false,
272
+ // validation
273
+ allowedExtensions: [],
274
+ sizeLimit: 0,
275
+ minSizeLimit: 0,
276
+ evalResponse : false, // used in rails UJS perform the direct callback evaluation
277
+ // events
278
+ // return false to cancel submit
279
+ onSubmit: function(id, fileName){},
280
+ onProgress: function(id, fileName, loaded, total){},
281
+ onComplete: function(id, fileName, responseJSON,qq){},
282
+ onCancel: function(id, fileName){},
283
+ // messages
284
+ messages: {
285
+ typeError: "{file} has invalid extension. Only {extensions} are allowed.",
286
+ sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
287
+ minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
288
+ emptyError: "{file} is empty, please select files again without it.",
289
+ onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
290
+ },
291
+ showMessage: function(message){
292
+ alert(message);
293
+ }
294
+ };
295
+ qq.extend(this._options, o);
296
+
297
+ // number of files being uploaded
298
+ this._filesInProgress = 0;
299
+ this._handler = this._createUploadHandler();
300
+
301
+ if (this._options.button){
302
+ this._button = this._createUploadButton(this._options.button);
303
+ }
304
+
305
+ this._preventLeaveInProgress();
306
+ };
307
+
308
+ qq.FileUploaderBasic.prototype = {
309
+ setParams: function(params){
310
+ this._options.params = params;
311
+ },
312
+ getInProgress: function(){
313
+ return this._filesInProgress;
314
+ },
315
+ _createUploadButton: function(element){
316
+ var self = this;
317
+
318
+ var btn = new qq.UploadButton({
319
+ element: element,
320
+ multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
321
+ onChange: function(input){
322
+ self._onInputChange(input);
323
+ }
324
+ });
325
+ $(btn._element).contents().first().replaceWith(this._options.uploadButtonText);
326
+ return btn;
327
+ },
328
+ _createUploadHandler: function(){
329
+ var self = this,
330
+ handlerClass;
331
+
332
+ if(qq.UploadHandlerXhr.isSupported()){
333
+ handlerClass = 'UploadHandlerXhr';
334
+ } else {
335
+ handlerClass = 'UploadHandlerForm';
336
+ }
337
+
338
+ var handler = new qq[handlerClass]({
339
+ debug: this._options.debug,
340
+ action: this._options.action,
341
+ maxConnections: this._options.maxConnections,
342
+ evalResponse : this._options.evalResponse,
343
+ onProgress: function(id, fileName, loaded, total){
344
+ self._onProgress(id, fileName, loaded, total);
345
+ self._options.onProgress.call(self, id, fileName, loaded, total);
346
+ },
347
+ onComplete: function(id, fileName, result,qq){
348
+ self._onComplete(id, fileName, result,qq);
349
+ self._options.onComplete.call(self, id, fileName, result,qq);
350
+ },
351
+ onCancel: function(id, fileName){
352
+ self._onCancel(id, fileName);
353
+ self._options.onCancel.call(self, id, fileName);
354
+ }
355
+ });
356
+
357
+ return handler;
358
+ },
359
+ _preventLeaveInProgress: function(){
360
+ var self = this;
361
+
362
+ qq.attach(window, 'beforeunload', function(e){
363
+ if (!self._filesInProgress){return;}
364
+
365
+ var e = e || window.event;
366
+ // for ie, ff
367
+ e.returnValue = self._options.messages.onLeave;
368
+ // for webkit
369
+ return self._options.messages.onLeave;
370
+ });
371
+ },
372
+ _onSubmit: function(id, fileName){
373
+ this._filesInProgress++;
374
+ },
375
+ _onProgress: function(id, fileName, loaded, total){
376
+ },
377
+ _onComplete: function(id, fileName, result,qq){
378
+ this._filesInProgress--;
379
+ if (result.error){
380
+ this._options.showMessage(result.error);
381
+ }
382
+ },
383
+ _onCancel: function(id, fileName){
384
+ this._filesInProgress--;
385
+ },
386
+ _onInputChange: function(input){
387
+ if (this._handler instanceof qq.UploadHandlerXhr){
388
+ this._uploadFileList(input.files);
389
+ } else {
390
+ if (this._validateFile(input)){
391
+ this._uploadFile(input);
392
+ }
393
+ }
394
+ this._button.reset();
395
+ },
396
+ _uploadFileList: function(files){
397
+ for (var i=0; i<files.length; i++){
398
+ if ( !this._validateFile(files[i])){
399
+ return;
400
+ }
401
+ }
402
+
403
+ for (var i=0; i<files.length; i++){
404
+ this._uploadFile(files[i]);
405
+ }
406
+ },
407
+ _uploadFile: function(fileContainer){
408
+ var id = this._handler.add(fileContainer);
409
+ var fileName = this._handler.getName(id);
410
+
411
+ if (this._options.onSubmit(id, fileName) !== false){
412
+ this._onSubmit(id, fileName);
413
+ this._handler.upload(id, this._options.params);
414
+ }
415
+ },
416
+ _validateFile: function(file){
417
+ var name, size;
418
+
419
+ if (file.value){
420
+ // it is a file input
421
+ // get input value and remove path to normalize
422
+ name = file.value.replace(/.*(\/|\\)/, "");
423
+ if(file.files)
424
+ {
425
+ size = file.files[0].fileSize;
426
+ }
427
+ } else {
428
+ // fix missing properties in Safari
429
+ name = file.fileName != null ? file.fileName : file.name;
430
+ size = file.fileSize != null ? file.fileSize : file.size;
431
+ }
432
+
433
+ if (! this._isAllowedExtension(name)){
434
+ this._error('typeError', name);
435
+ return false;
436
+
437
+ } else if (size === 0){
438
+ this._error('emptyError', name);
439
+ return false;
440
+
441
+ } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
442
+ this._error('sizeError', name);
443
+ return false;
444
+
445
+ } else if (size && size < this._options.minSizeLimit){
446
+ this._error('minSizeError', name);
447
+ return false;
448
+ }
449
+
450
+ return true;
451
+ },
452
+ _error: function(code, fileName){
453
+ var message = this._options.messages[code];
454
+ function r(name, replacement){ message = message.replace(name, replacement); }
455
+
456
+ r('{file}', this._formatFileName(fileName));
457
+ r('{extensions}', this._options.allowedExtensions.join(', '));
458
+ r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
459
+ r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
460
+
461
+ this._options.showMessage(message);
462
+ },
463
+ _formatFileName: function(name){
464
+ if (name.length > 33){
465
+ name = name.slice(0, 19) + '...' + name.slice(-13);
466
+ }
467
+ return name;
468
+ },
469
+ _isAllowedExtension: function(fileName){
470
+ var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
471
+ var allowed = this._options.allowedExtensions;
472
+
473
+ if (!allowed.length){return true;}
474
+
475
+ for (var i=0; i<allowed.length; i++){
476
+ if (allowed[i].toLowerCase() == ext){ return true;}
477
+ }
478
+
479
+ return false;
480
+ },
481
+ _formatSize: function(bytes){
482
+ var i = 0;
483
+ var suffixes;
484
+
485
+ if(this._options.useBase2Prefixes)
486
+ {
487
+ while (bytes > 1024) {
488
+ bytes = bytes / 1024;
489
+ i++;
490
+ }
491
+ suffixes = ['B', 'kiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'YiB'];
492
+ }
493
+ else
494
+ {
495
+ while (bytes > 1000) {
496
+ bytes = bytes / 1000;
497
+ i++;
498
+ }
499
+ suffixes = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'YB'];
500
+ }
501
+
502
+ return Math.max(bytes, 0.1).toFixed(1) + suffixes[i];
503
+ }
504
+ };
505
+
506
+
507
+ /**
508
+ * Class that creates upload widget with drag-and-drop and file list
509
+ * @inherits qq.FileUploaderBasic
510
+ */
511
+ qq.FileUploader = function(o){
512
+ // call parent constructor
513
+ qq.FileUploaderBasic.apply(this, arguments);
514
+
515
+ // additional options
516
+ qq.extend(this._options, {
517
+ element: null,
518
+ // if set, will be used instead of qq-upload-list in template
519
+ listElement: null,
520
+
521
+ template: '<div class="qq-uploader">' +
522
+ '<div class="qq-upload-drop-area"><span>Trascina qui per upload</span></div>' +
523
+ '<div class="qq-upload-button">Upload di un file</div>' +
524
+ '<ul class="qq-upload-list"></ul>' +
525
+ '</div>',
526
+
527
+ // template for one item in file list
528
+ fileTemplate: '<li>' +
529
+ '<span class="qq-upload-file"></span>' +
530
+ '<span class="qq-upload-spinner"></span>' +
531
+ '<span class="qq-upload-size"></span>' +
532
+ '<a class="qq-upload-cancel" href="#">Interrompi</a>' +
533
+ '<span class="qq-upload-failed-text">Upload fallito</span>' +
534
+ '</li>',
535
+
536
+ classes: {
537
+ // used to get elements from templates
538
+ button: 'qq-upload-button',
539
+ drop: 'qq-upload-drop-area',
540
+ dropActive: 'qq-upload-drop-area-active',
541
+ list: 'qq-upload-list',
542
+
543
+ file: 'qq-upload-file',
544
+ spinner: 'qq-upload-spinner',
545
+ size: 'qq-upload-size',
546
+ cancel: 'qq-upload-cancel',
547
+
548
+ // added to list item when upload completes
549
+ // used in css to hide progress spinner
550
+ success: 'qq-upload-success',
551
+ fail: 'qq-upload-fail'
552
+ }
553
+ });
554
+ // overwrite options with user supplied
555
+ qq.extend(this._options, o);
556
+
557
+ this._element = this._options.element;
558
+ this._element.innerHTML = this._options.template;
559
+ this._listElement = this._options.listElement || this._find(this._element, 'list');
560
+
561
+ this._classes = this._options.classes;
562
+
563
+ this._button = this._createUploadButton(this._find(this._element, 'button'));
564
+
565
+ this._bindCancelEvent();
566
+ this._setupDragDrop();
567
+ };
568
+
569
+ // inherit from Basic Uploader
570
+ qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);
571
+
572
+ qq.extend(qq.FileUploader.prototype, {
573
+ /**
574
+ * Gets one of the elements listed in this._options.classes
575
+ **/
576
+ _find: function(parent, type){
577
+ var element = qq.getByClass(parent, this._options.classes[type])[0];
578
+ if (!element){
579
+ throw new Error('element not found ' + type);
580
+ }
581
+
582
+ return element;
583
+ },
584
+ _setupDragDrop: function(){
585
+ var self = this,
586
+ dropArea = this._find(this._element, 'drop');
587
+
588
+ var dz = new qq.UploadDropZone({
589
+ element: dropArea,
590
+ onEnter: function(e){
591
+ qq.addClass(dropArea, self._classes.dropActive);
592
+ e.stopPropagation();
593
+ },
594
+ onLeave: function(e){
595
+ e.stopPropagation();
596
+ },
597
+ onLeaveNotDescendants: function(e){
598
+ qq.removeClass(dropArea, self._classes.dropActive);
599
+ },
600
+ onDrop: function(e){
601
+ dropArea.style.display = 'none';
602
+ qq.removeClass(dropArea, self._classes.dropActive);
603
+ self._uploadFileList(e.dataTransfer.files);
604
+ }
605
+ });
606
+
607
+ dropArea.style.display = 'none';
608
+
609
+ qq.attach(document, 'dragenter', function(e){
610
+ if (!dz._isValidFileDrag(e)) return;
611
+
612
+ dropArea.style.display = 'block';
613
+ });
614
+ qq.attach(document, 'dragleave', function(e){
615
+ if (!dz._isValidFileDrag(e)) return;
616
+
617
+ var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
618
+ // only fire when leaving document out
619
+ if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){
620
+ dropArea.style.display = 'none';
621
+ }
622
+ });
623
+ },
624
+ _onSubmit: function(id, fileName){
625
+ qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
626
+ this._addToList(id, fileName);
627
+ },
628
+ _onProgress: function(id, fileName, loaded, total){
629
+ qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);
630
+
631
+ var item = this._getItemByFileId(id);
632
+ var size = this._find(item, 'size');
633
+ size.style.display = 'inline';
634
+
635
+ var text;
636
+ if (loaded != total){
637
+ text = Math.round(loaded / total * 100) + '% of ' + this._formatSize(total);
638
+ } else {
639
+ text = this._formatSize(total);
640
+ this._totalSizeText = text;
641
+ }
642
+
643
+ if(this._totalSizeText)
644
+ {
645
+ qq.setText(size, this._totalSizeText);
646
+ }
647
+ else if(text)
648
+ {
649
+ qq.setText(size, text);
650
+ }
651
+ else
652
+ {
653
+ qq.setText(size, "calculating...");
654
+ }
655
+ },
656
+ _onComplete: function(id, fileName, result){
657
+ qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
658
+
659
+ // mark completed
660
+ var item = this._getItemByFileId(id);
661
+ qq.remove(this._find(item, 'cancel'));
662
+ qq.remove(this._find(item, 'spinner'));
663
+
664
+ if (result.success){
665
+ qq.addClass(item, this._classes.success);
666
+ if(this._totalSizeText)
667
+ {
668
+ var item = this._getItemByFileId(id);
669
+ var size = this._find(item, 'size');
670
+ qq.setText(size, this._totalSizeText);
671
+ this._totalSizeText = '';
672
+ }
673
+ } else {
674
+ qq.addClass(item, this._classes.fail);
675
+ }
676
+ },
677
+ _addToList: function(id, fileName){
678
+ var item = qq.toElement(this._options.fileTemplate);
679
+ item.qqFileId = id;
680
+
681
+ var fileElement = this._find(item, 'file');
682
+ qq.setText(fileElement, this._formatFileName(fileName));
683
+ this._find(item, 'size').style.display = 'none';
684
+
685
+ this._listElement.appendChild(item);
686
+ },
687
+ _getItemByFileId: function(id){
688
+ var item = this._listElement.firstChild;
689
+
690
+ // there can't be txt nodes in dynamically created list
691
+ // and we can use nextSibling
692
+ while (item){
693
+ if (item.qqFileId == id) return item;
694
+ item = item.nextSibling;
695
+ }
696
+ },
697
+ /**
698
+ * delegate click event for cancel link
699
+ **/
700
+ _bindCancelEvent: function(){
701
+ var self = this,
702
+ list = this._listElement;
703
+
704
+ qq.attach(list, 'click', function(e){
705
+ e = e || window.event;
706
+ var target = e.target || e.srcElement;
707
+
708
+ if (qq.hasClass(target, self._classes.cancel)){
709
+ qq.preventDefault(e);
710
+
711
+ var item = target.parentNode;
712
+ self._handler.cancel(item.qqFileId);
713
+ qq.remove(item);
714
+ }
715
+ });
716
+ }
717
+ });
718
+
719
+ qq.UploadDropZone = function(o){
720
+ this._options = {
721
+ element: null,
722
+ onEnter: function(e){},
723
+ onLeave: function(e){},
724
+ // is not fired when leaving element by hovering descendants
725
+ onLeaveNotDescendants: function(e){},
726
+ onDrop: function(e){}
727
+ };
728
+ qq.extend(this._options, o);
729
+
730
+ this._element = this._options.element;
731
+
732
+ this._disableDropOutside();
733
+ this._attachEvents();
734
+ };
735
+
736
+ qq.UploadDropZone.prototype = {
737
+ _disableDropOutside: function(e){
738
+ // run only once for all instances
739
+ if (!qq.UploadDropZone.dropOutsideDisabled ){
740
+
741
+ qq.attach(document, 'dragover', function(e){
742
+ if (e.dataTransfer){
743
+ e.dataTransfer.dropEffect = 'none';
744
+ e.preventDefault();
745
+ }
746
+ });
747
+
748
+ qq.UploadDropZone.dropOutsideDisabled = true;
749
+ }
750
+ },
751
+ _attachEvents: function(){
752
+ var self = this;
753
+
754
+ qq.attach(self._element, 'dragover', function(e){
755
+ if (!self._isValidFileDrag(e)) return;
756
+
757
+ var effect = e.dataTransfer.effectAllowed;
758
+ if (effect == 'move' || effect == 'linkMove'){
759
+ e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
760
+ } else {
761
+ e.dataTransfer.dropEffect = 'copy'; // for Chrome
762
+ }
763
+
764
+ e.stopPropagation();
765
+ e.preventDefault();
766
+ });
767
+
768
+ qq.attach(self._element, 'dragenter', function(e){
769
+ if (!self._isValidFileDrag(e)) return;
770
+
771
+ self._options.onEnter(e);
772
+ });
773
+
774
+ qq.attach(self._element, 'dragleave', function(e){
775
+ if (!self._isValidFileDrag(e)) return;
776
+
777
+ self._options.onLeave(e);
778
+
779
+ var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
780
+ // do not fire when moving a mouse over a descendant
781
+ if (qq.contains(this, relatedTarget)) return;
782
+
783
+ self._options.onLeaveNotDescendants(e);
784
+ });
785
+
786
+ qq.attach(self._element, 'drop', function(e){
787
+ if (!self._isValidFileDrag(e)) return;
788
+
789
+ e.preventDefault();
790
+ self._options.onDrop(e);
791
+ });
792
+ },
793
+ _isValidFileDrag: function(e){
794
+ var dt = e.dataTransfer,
795
+ // do not check dt.types.contains in webkit, because it crashes safari 4
796
+ isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;
797
+
798
+ // dt.effectAllowed is none in Safari 5
799
+ // dt.types.contains check is for firefox
800
+ return dt && dt.effectAllowed != 'none' &&
801
+ (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));
802
+
803
+ }
804
+ };
805
+
806
+ qq.UploadButton = function(o){
807
+ this._options = {
808
+ element: null,
809
+ // if set to true adds multiple attribute to file input
810
+ multiple: false,
811
+ // name attribute of file input
812
+ name: 'file',
813
+ onChange: function(input){},
814
+ hoverClass: 'qq-upload-button-hover',
815
+ focusClass: 'qq-upload-button-focus'
816
+ };
817
+
818
+ qq.extend(this._options, o);
819
+
820
+ this._element = this._options.element;
821
+
822
+ // make button suitable container for input
823
+ qq.css(this._element, {
824
+ position: 'relative',
825
+ overflow: 'hidden',
826
+ // Make sure browse button is in the right side
827
+ // in Internet Explorer
828
+ direction: 'ltr'
829
+ });
830
+
831
+ this._input = this._createInput();
832
+ };
833
+
834
+ qq.UploadButton.prototype = {
835
+ /* returns file input element */
836
+ getInput: function(){
837
+ return this._input;
838
+ },
839
+ /* cleans/recreates the file input */
840
+ reset: function(){
841
+ if (this._input.parentNode){
842
+ qq.remove(this._input);
843
+ }
844
+
845
+ qq.removeClass(this._element, this._options.focusClass);
846
+ this._input = this._createInput();
847
+ },
848
+ _createInput: function(){
849
+ var input = document.createElement("input");
850
+
851
+ if (this._options.multiple){
852
+ input.setAttribute("multiple", "multiple");
853
+ }
854
+
855
+ input.setAttribute("type", "file");
856
+ input.setAttribute("name", this._options.name);
857
+
858
+ qq.css(input, {
859
+ position: 'absolute',
860
+ // in Opera only 'browse' button
861
+ // is clickable and it is located at
862
+ // the right side of the input
863
+ right: 0,
864
+ top: 0,
865
+ fontFamily: 'Arial',
866
+ // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
867
+ fontSize: '12px', //changed from 118
868
+ margin: 0,
869
+ padding: 0,
870
+ cursor: 'pointer',
871
+ opacity: 0
872
+ });
873
+
874
+ this._element.appendChild(input);
875
+
876
+ var self = this;
877
+ qq.attach(input, 'change', function(){
878
+ self._options.onChange(input);
879
+ });
880
+
881
+ qq.attach(input, 'mouseover', function(){
882
+ qq.addClass(self._element, self._options.hoverClass);
883
+ });
884
+ qq.attach(input, 'mouseout', function(){
885
+ qq.removeClass(self._element, self._options.hoverClass);
886
+ });
887
+ qq.attach(input, 'focus', function(){
888
+ qq.addClass(self._element, self._options.focusClass);
889
+ });
890
+ qq.attach(input, 'blur', function(){
891
+ qq.removeClass(self._element, self._options.focusClass);
892
+ });
893
+
894
+ // IE and Opera, unfortunately have 2 tab stops on file input
895
+ // which is unacceptable in our case, disable keyboard access
896
+ if (window.attachEvent){
897
+ // it is IE or Opera
898
+ input.setAttribute('tabIndex', "-1");
899
+ }
900
+
901
+ return input;
902
+ }
903
+ };
904
+
905
+ /**
906
+ * Class for uploading files, uploading itself is handled by child classes
907
+ */
908
+ qq.UploadHandlerAbstract = function(o){
909
+ this._options = {
910
+ debug: false,
911
+ action: '/upload.php',
912
+ // maximum number of concurrent uploads
913
+ maxConnections: 999,
914
+ onProgress: function(id, fileName, loaded, total){},
915
+ onComplete: function(id, fileName, response,qq){},
916
+ onCancel: function(id, fileName){}
917
+ };
918
+ qq.extend(this._options, o);
919
+
920
+ this._queue = [];
921
+ // params for files in queue
922
+ this._params = [];
923
+ };
924
+ qq.UploadHandlerAbstract.prototype = {
925
+ log: function(str){
926
+ if (this._options.debug && window.console) console.log('[uploader] ' + str);
927
+ },
928
+ /**
929
+ * Adds file or file input to the queue
930
+ * @returns id
931
+ **/
932
+ add: function(file){},
933
+ /**
934
+ * Sends the file identified by id and additional query params to the server
935
+ */
936
+ upload: function(id, params){
937
+ var len = this._queue.push(id);
938
+
939
+ var copy = {};
940
+ qq.extend(copy, params);
941
+ this._params[id] = copy;
942
+
943
+ // if too many active uploads, wait...
944
+ if (len <= this._options.maxConnections){
945
+ this._upload(id, this._params[id]);
946
+ }
947
+ },
948
+ /**
949
+ * Cancels file upload by id
950
+ */
951
+ cancel: function(id){
952
+ this._cancel(id);
953
+ this._dequeue(id);
954
+ },
955
+ /**
956
+ * Cancells all uploads
957
+ */
958
+ cancelAll: function(){
959
+ for (var i=0; i<this._queue.length; i++){
960
+ this._cancel(this._queue[i]);
961
+ }
962
+ this._queue = [];
963
+ },
964
+ /**
965
+ * Returns name of the file identified by id
966
+ */
967
+ getName: function(id){},
968
+ /**
969
+ * Returns size of the file identified by id
970
+ */
971
+ getSize: function(id){},
972
+ /**
973
+ * Returns id of files being uploaded or
974
+ * waiting for their turn
975
+ */
976
+ getQueue: function(){
977
+ return this._queue;
978
+ },
979
+ /**
980
+ * Actual upload method
981
+ */
982
+ _upload: function(id){},
983
+ /**
984
+ * Actual cancel method
985
+ */
986
+ _cancel: function(id){},
987
+ /**
988
+ * Removes element from queue, starts upload of next
989
+ */
990
+ _dequeue: function(id){
991
+ var i = qq.indexOf(this._queue, id);
992
+ this._queue.splice(i, 1);
993
+
994
+ var max = this._options.maxConnections;
995
+
996
+ if (this._queue.length >= max && i < max){
997
+ var nextId = this._queue[max-1];
998
+ this._upload(nextId, this._params[nextId]);
999
+ }
1000
+ }
1001
+ };
1002
+
1003
+ /**
1004
+ * Class for uploading files using form and iframe
1005
+ * @inherits qq.UploadHandlerAbstract
1006
+ */
1007
+ qq.UploadHandlerForm = function(o){
1008
+ qq.UploadHandlerAbstract.apply(this, arguments);
1009
+
1010
+ this._inputs = {};
1011
+ };
1012
+ // @inherits qq.UploadHandlerAbstract
1013
+ qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);
1014
+
1015
+ qq.extend(qq.UploadHandlerForm.prototype, {
1016
+ add: function(fileInput){
1017
+ fileInput.setAttribute('name', 'qqfile');
1018
+ var id = 'qq-upload-handler-iframe' + qq.getUniqueId();
1019
+
1020
+ this._inputs[id] = fileInput;
1021
+
1022
+ // remove file input from DOM
1023
+ if (fileInput.parentNode){
1024
+ qq.remove(fileInput);
1025
+ }
1026
+
1027
+ return id;
1028
+ },
1029
+ getName: function(id){
1030
+ // get input value and remove path to normalize
1031
+ return this._inputs[id].value.replace(/.*(\/|\\)/, "");
1032
+ },
1033
+ _cancel: function(id){
1034
+ this._options.onCancel(id, this.getName(id));
1035
+
1036
+ delete this._inputs[id];
1037
+
1038
+ var iframe = document.getElementById(id);
1039
+ if (iframe){
1040
+ // to cancel request set src to something else
1041
+ // we use src="javascript:false;" because it doesn't
1042
+ // trigger ie6 prompt on https
1043
+ iframe.setAttribute('src', 'javascript:false;');
1044
+
1045
+ qq.remove(iframe);
1046
+ }
1047
+ },
1048
+ _upload: function(id, params){
1049
+ var input = this._inputs[id];
1050
+
1051
+ if (!input){
1052
+ throw new Error('file with passed id was not added, or already uploaded or cancelled');
1053
+ }
1054
+
1055
+ var fileName = this.getName(id);
1056
+
1057
+ var iframe = this._createIframe(id);
1058
+ var form = this._createForm(iframe, params);
1059
+ form.appendChild(input);
1060
+
1061
+ var self = this;
1062
+ this._attachLoadEvent(iframe, function(){
1063
+ self.log('iframe loaded');
1064
+
1065
+ var response = self._getIframeContentJSON(iframe);
1066
+
1067
+ self._options.onComplete(id, fileName, response,qq);
1068
+ self._dequeue(id);
1069
+
1070
+ delete self._inputs[id];
1071
+ // timeout added to fix busy state in FF3.6
1072
+ setTimeout(function(){
1073
+ qq.remove(iframe);
1074
+ }, 1);
1075
+ });
1076
+
1077
+ form.submit();
1078
+ qq.remove(form);
1079
+
1080
+ return id;
1081
+ },
1082
+ _attachLoadEvent: function(iframe, callback){
1083
+ qq.attach(iframe, 'load', function(){
1084
+ // when we remove iframe from dom
1085
+ // the request stops, but in IE load
1086
+ // event fires
1087
+ if (!iframe.parentNode){
1088
+ return;
1089
+ }
1090
+
1091
+ // fixing Opera 10.53
1092
+ if (iframe.contentDocument &&
1093
+ iframe.contentDocument.body &&
1094
+ iframe.contentDocument.body.innerHTML == "false"){
1095
+ // In Opera event is fired second time
1096
+ // when body.innerHTML changed from false
1097
+ // to server response approx. after 1 sec
1098
+ // when we upload file with iframe
1099
+ return;
1100
+ }
1101
+
1102
+ callback();
1103
+ });
1104
+ },
1105
+ /**
1106
+ * Returns json object received by iframe from server.
1107
+ */
1108
+ _getIframeContentJSON: function(iframe){
1109
+ // iframe.contentWindow.document - for IE<7
1110
+ var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
1111
+ response;
1112
+
1113
+ this.log("converting iframe's innerHTML to JSON");
1114
+ this.log("innerHTML = " + doc.body.firstChild.innerHTML);
1115
+
1116
+ try {
1117
+ response = eval("(" + doc.body.firstChild.innerHTML + ")");
1118
+ } catch(err){
1119
+ response = {};
1120
+ }
1121
+
1122
+ return response;
1123
+ },
1124
+ /**
1125
+ * Creates iframe with unique name
1126
+ */
1127
+ _createIframe: function(id){
1128
+ // We can't use following code as the name attribute
1129
+ // won't be properly registered in IE6, and new window
1130
+ // on form submit will open
1131
+ // var iframe = document.createElement('iframe');
1132
+ // iframe.setAttribute('name', id);
1133
+
1134
+ var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
1135
+ // src="javascript:false;" removes ie6 prompt on https
1136
+
1137
+ iframe.setAttribute('id', id);
1138
+
1139
+ iframe.style.display = 'none';
1140
+ document.body.appendChild(iframe);
1141
+
1142
+ return iframe;
1143
+ },
1144
+ /**
1145
+ * Creates form, that will be submitted to iframe
1146
+ */
1147
+ _createForm: function(iframe, params){
1148
+ // We can't use the following code in IE6
1149
+ // var form = document.createElement('form');
1150
+ // form.setAttribute('method', 'post');
1151
+ // form.setAttribute('enctype', 'multipart/form-data');
1152
+ // Because in this case file won't be attached to request
1153
+ var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');
1154
+
1155
+ var queryString = qq.obj2url(params, this._options.action);
1156
+
1157
+ form.setAttribute('action', queryString);
1158
+ form.setAttribute('target', iframe.name);
1159
+ form.style.display = 'none';
1160
+ document.body.appendChild(form);
1161
+
1162
+ return form;
1163
+ }
1164
+ });
1165
+
1166
+ /**
1167
+ * Class for uploading files using xhr
1168
+ * @inherits qq.UploadHandlerAbstract
1169
+ */
1170
+ qq.UploadHandlerXhr = function(o){
1171
+ qq.UploadHandlerAbstract.apply(this, arguments);
1172
+
1173
+ this._files = [];
1174
+ this._xhrs = [];
1175
+
1176
+ // current loaded size in bytes for each file
1177
+ this._loaded = [];
1178
+ };
1179
+
1180
+ // static method
1181
+ qq.UploadHandlerXhr.isSupported = function(){
1182
+ var input = document.createElement('input');
1183
+ input.type = 'file';
1184
+
1185
+ return (
1186
+ 'multiple' in input &&
1187
+ typeof File != "undefined" &&
1188
+ typeof (new XMLHttpRequest()).upload != "undefined" );
1189
+ };
1190
+
1191
+ // @inherits qq.UploadHandlerAbstract
1192
+ qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype);
1193
+
1194
+ qq.extend(qq.UploadHandlerXhr.prototype, {
1195
+ /**
1196
+ * Adds file to the queue
1197
+ * Returns id to use with upload, cancel
1198
+ **/
1199
+ add: function(file){
1200
+ if (!(file instanceof File)){
1201
+ throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
1202
+ }
1203
+
1204
+ return this._files.push(file) - 1;
1205
+ },
1206
+ getName: function(id){
1207
+ var file = this._files[id];
1208
+ // fix missing name in Safari 4
1209
+ return file.fileName != null ? file.fileName : file.name;
1210
+ },
1211
+ getSize: function(id){
1212
+ var file = this._files[id];
1213
+ return file.fileSize != null ? file.fileSize : file.size;
1214
+ },
1215
+ /**
1216
+ * Returns uploaded bytes for file identified by id
1217
+ */
1218
+ getLoaded: function(id){
1219
+ return this._loaded[id] || 0;
1220
+ },
1221
+ /**
1222
+ * Sends the file identified by id and additional query params to the server
1223
+ * @param {Object} params name-value string pairs
1224
+ */
1225
+ _upload: function(id, params){
1226
+ var file = this._files[id],
1227
+ name = this.getName(id),
1228
+ size = this.getSize(id);
1229
+
1230
+ this._loaded[id] = 0;
1231
+
1232
+ var xhr = this._xhrs[id] = new XMLHttpRequest();
1233
+ var self = this;
1234
+
1235
+ xhr.upload.onprogress = function(e){
1236
+ if (e.lengthComputable){
1237
+ self._loaded[id] = e.loaded;
1238
+ self._options.onProgress(id, name, e.loaded, e.total);
1239
+ }
1240
+ };
1241
+
1242
+ xhr.onreadystatechange = function(){
1243
+ if (xhr.readyState == 4){
1244
+ self._onComplete(id, xhr);
1245
+ }
1246
+ };
1247
+
1248
+ // build query string
1249
+ params = params || {};
1250
+ params['qqfile'] = name;
1251
+ var queryString = qq.obj2url(params, this._options.action);
1252
+
1253
+ xhr.open("POST", queryString, true);
1254
+ xhr.setRequestHeader("Accept", "text/javascript");
1255
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
1256
+ xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
1257
+ xhr.setRequestHeader("Content-Type", "application/octet-stream");
1258
+ xhr.send(file);
1259
+ },
1260
+ _onComplete: function(id, xhr){
1261
+ // the request was aborted/cancelled
1262
+ if (!this._files[id]) return;
1263
+
1264
+ var name = this.getName(id);
1265
+ var size = this.getSize(id);
1266
+
1267
+ this._options.onProgress(id, name, size, size);
1268
+
1269
+ if (xhr.status == 200){
1270
+ this.log("xhr - server response received");
1271
+ this.log("responseText = " + xhr.responseText);
1272
+
1273
+ var response;
1274
+
1275
+ try {
1276
+
1277
+ if(this._options.evalResponse){
1278
+ response = eval(xhr.responseText);
1279
+ }else{
1280
+ response = eval("(" + xhr.responseText + ")");
1281
+ }
1282
+
1283
+ } catch(err){
1284
+ response = {};
1285
+ }
1286
+
1287
+ this._options.onComplete(id, name, response,this);
1288
+
1289
+ } else {
1290
+ this._options.onComplete(id, name, {},this);
1291
+ }
1292
+
1293
+ this._files[id] = null;
1294
+ this._xhrs[id] = null;
1295
+ this._dequeue(id);
1296
+ },
1297
+ _cancel: function(id){
1298
+ this._options.onCancel(id, this.getName(id));
1299
+
1300
+ this._files[id] = null;
1301
+
1302
+ if (this._xhrs[id]){
1303
+ this._xhrs[id].abort();
1304
+ this._xhrs[id] = null;
1305
+ }
1306
+ }
1307
+ });