]> git.mxchange.org Git - friendica.git/blob - include/ajaxupload.js
you and me babe
[friendica.git] / include / ajaxupload.js
1 /**
2  * AJAX Upload ( http://valums.com/ajax-upload/ ) 
3  * Copyright (c) Andris Valums
4  * Licensed under the MIT license ( http://valums.com/mit-license/ )
5  * Thanks to Gary Haran, David Mark, Corey Burns and others for contributions. 
6  */
7
8 (function () {
9     /* global window */
10     /* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true */
11     
12     /**
13      * Wrapper for FireBug's console.log
14      */
15     function log(){
16         if (typeof(console) != 'undefined' && typeof(console.log) == 'function'){            
17             Array.prototype.unshift.call(arguments, '[Ajax Upload]');
18             console.log( Array.prototype.join.call(arguments, ' '));
19         }
20     } 
21
22     /**
23      * Attaches event to a dom element.
24      * @param {Element} el
25      * @param type event name
26      * @param fn callback This refers to the passed element
27      */
28     function addEvent(el, type, fn){
29         if (el.addEventListener) {
30             el.addEventListener(type, fn, false);
31         } else if (el.attachEvent) {
32             el.attachEvent('on' + type, function(){
33                 fn.call(el);
34                 });
35             } else {
36             throw new Error('not supported or DOM not loaded');
37         }
38     }   
39     
40     /**
41      * Attaches resize event to a window, limiting
42      * number of event fired. Fires only when encounteres
43      * delay of 100 after series of events.
44      * 
45      * Some browsers fire event multiple times when resizing
46      * http://www.quirksmode.org/dom/events/resize.html
47      * 
48      * @param fn callback This refers to the passed element
49      */
50     function addResizeEvent(fn){
51         var timeout;
52                
53             addEvent(window, 'resize', function(){
54             if (timeout){
55                 clearTimeout(timeout);
56             }
57             timeout = setTimeout(fn, 100);                        
58         });
59     }    
60     
61     // Needs more testing, will be rewriten for next version        
62     // getOffset function copied from jQuery lib (http://jquery.com/)
63     if (document.documentElement.getBoundingClientRect){
64         // Get Offset using getBoundingClientRect
65         // http://ejohn.org/blog/getboundingclientrect-is-awesome/
66         var getOffset = function(el){
67             var box = el.getBoundingClientRect();
68             var doc = el.ownerDocument;
69             var body = doc.body;
70             var docElem = doc.documentElement; // for ie 
71             var clientTop = docElem.clientTop || body.clientTop || 0;
72             var clientLeft = docElem.clientLeft || body.clientLeft || 0;
73              
74             // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
75             // while others are logical. Make all logical, like in IE8. 
76             var zoom = 1;            
77             if (body.getBoundingClientRect) {
78                 var bound = body.getBoundingClientRect();
79                 zoom = (bound.right - bound.left) / body.clientWidth;
80             }
81             
82             if (zoom > 1) {
83                 clientTop = 0;
84                 clientLeft = 0;
85             }
86             
87             var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;
88             
89             return {
90                 top: top,
91                 left: left
92             };
93         };        
94     } else {
95         // Get offset adding all offsets 
96         var getOffset = function(el){
97             var top = 0, left = 0;
98             do {
99                 top += el.offsetTop || 0;
100                 left += el.offsetLeft || 0;
101                 el = el.offsetParent;
102             } while (el);
103             
104             return {
105                 left: left,
106                 top: top
107             };
108         };
109     }
110     
111     /**
112      * Returns left, top, right and bottom properties describing the border-box,
113      * in pixels, with the top-left relative to the body
114      * @param {Element} el
115      * @return {Object} Contains left, top, right,bottom
116      */
117     function getBox(el){
118         var left, right, top, bottom;
119         var offset = getOffset(el);
120         left = offset.left;
121         top = offset.top;
122         
123         right = left + el.offsetWidth;
124         bottom = top + el.offsetHeight;
125         
126         return {
127             left: left,
128             right: right,
129             top: top,
130             bottom: bottom
131         };
132     }
133     
134     /**
135      * Helper that takes object literal
136      * and add all properties to element.style
137      * @param {Element} el
138      * @param {Object} styles
139      */
140     function addStyles(el, styles){
141         for (var name in styles) {
142             if (styles.hasOwnProperty(name)) {
143                 el.style[name] = styles[name];
144             }
145         }
146     }
147         
148     /**
149      * Function places an absolutely positioned
150      * element on top of the specified element
151      * copying position and dimentions.
152      * @param {Element} from
153      * @param {Element} to
154      */    
155     function copyLayout(from, to){
156             var box = getBox(from);
157         
158         addStyles(to, {
159                 position: 'absolute',                    
160                 left : box.left + 'px',
161                 top : box.top + 'px',
162                 width : from.offsetWidth + 'px',
163                 height : from.offsetHeight + 'px'
164             });        
165         to.title = from.title;
166     }
167
168     /**
169     * Creates and returns element from html chunk
170     * Uses innerHTML to create an element
171     */
172     var toElement = (function(){
173         var div = document.createElement('div');
174         return function(html){
175             div.innerHTML = html;
176             var el = div.firstChild;
177             return div.removeChild(el);
178         };
179     })();
180             
181     /**
182      * Function generates unique id
183      * @return unique id 
184      */
185     var getUID = (function(){
186         var id = 0;
187         return function(){
188             return 'ValumsAjaxUpload' + id++;
189         };
190     })();        
191  
192     /**
193      * Get file name from path
194      * @param {String} file path to file
195      * @return filename
196      */  
197     function fileFromPath(file){
198         return file.replace(/.*(\/|\\)/, "");
199     }
200     
201     /**
202      * Get file extension lowercase
203      * @param {String} file name
204      * @return file extenstion
205      */    
206     function getExt(file){
207         return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
208     }
209
210     function hasClass(el, name){        
211         var re = new RegExp('\\b' + name + '\\b');        
212         return re.test(el.className);
213     }    
214     function addClass(el, name){
215         if ( ! hasClass(el, name)){   
216             el.className += ' ' + name;
217         }
218     }    
219     function removeClass(el, name){
220         var re = new RegExp('\\b' + name + '\\b');                
221         el.className = el.className.replace(re, '');        
222     }
223     
224     function removeNode(el){
225         el.parentNode.removeChild(el);
226     }
227
228     /**
229      * Easy styling and uploading
230      * @constructor
231      * @param button An element you want convert to 
232      * upload button. Tested dimentions up to 500x500px
233      * @param {Object} options See defaults below.
234      */
235     window.AjaxUpload = function(button, options){
236         this._settings = {
237             // Location of the server-side upload script
238             action: 'upload.php',
239             // File upload name
240             name: 'userfile',
241             // Additional data to send
242             data: {},
243             // Submit file as soon as it's selected
244             autoSubmit: true,
245             // The type of data that you're expecting back from the server.
246             // html and xml are detected automatically.
247             // Only useful when you are using json data as a response.
248             // Set to "json" in that case. 
249             responseType: false,
250             // Class applied to button when mouse is hovered
251             hoverClass: 'hover',
252             // Class applied to button when button is focused
253             focusClass: 'focus',
254             // Class applied to button when AU is disabled
255             disabledClass: 'disabled',            
256             // When user selects a file, useful with autoSubmit disabled
257             // You can return false to cancel upload                    
258             onChange: function(file, extension){
259             },
260             // Callback to fire before file is uploaded
261             // You can return false to cancel upload
262             onSubmit: function(file, extension){
263             },
264             // Fired when file upload is completed
265             // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
266             onComplete: function(file, response){
267             }
268         };
269                         
270         // Merge the users options with our defaults
271         for (var i in options) {
272             if (options.hasOwnProperty(i)){
273                 this._settings[i] = options[i];
274             }
275         }
276                 
277         // button isn't necessary a dom element
278         if (button.jquery){
279             // jQuery object was passed
280             button = button[0];
281         } else if (typeof button == "string") {
282             if (/^#.*/.test(button)){
283                 // If jQuery user passes #elementId don't break it                                      
284                 button = button.slice(1);                
285             }
286             
287             button = document.getElementById(button);
288         }
289         
290         if ( ! button || button.nodeType !== 1){
291             throw new Error("Please make sure that you're passing a valid element"); 
292         }
293                 
294         if ( button.nodeName.toUpperCase() == 'A'){
295             // disable link                       
296             addEvent(button, 'click', function(e){
297                 if (e && e.preventDefault){
298                     e.preventDefault();
299                 } else if (window.event){
300                     window.event.returnValue = false;
301                 }
302             });
303         }
304                     
305         // DOM element
306         this._button = button;        
307         // DOM element                 
308         this._input = null;
309         // If disabled clicking on button won't do anything
310         this._disabled = false;
311         
312         // if the button was disabled before refresh if will remain
313         // disabled in FireFox, let's fix it
314         this.enable();        
315         
316         this._rerouteClicks();
317     };
318     
319     // assigning methods to our class
320     AjaxUpload.prototype = {
321         setData: function(data){
322             this._settings.data = data;
323         },
324         disable: function(){            
325             addClass(this._button, this._settings.disabledClass);
326             this._disabled = true;
327             
328             var nodeName = this._button.nodeName.toUpperCase();            
329             if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
330                 this._button.setAttribute('disabled', 'disabled');
331             }            
332             
333             // hide input
334             if (this._input){
335                 // We use visibility instead of display to fix problem with Safari 4
336                 // The problem is that the value of input doesn't change if it 
337                 // has display none when user selects a file           
338                 this._input.parentNode.style.visibility = 'hidden';
339             }
340         },
341         enable: function(){
342             removeClass(this._button, this._settings.disabledClass);
343             this._button.removeAttribute('disabled');
344             this._disabled = false;
345             
346         },
347         /**
348          * Creates invisible file input 
349          * that will hover above the button
350          * <div><input type='file' /></div>
351          */
352         _createInput: function(){ 
353             var self = this;
354                         
355             var input = document.createElement("input");
356             input.setAttribute('type', 'file');
357             input.setAttribute('name', this._settings.name);
358
359             addStyles(input, {
360                 'position' : 'absolute',
361                 // in Opera only 'browse' button
362                 // is clickable and it is located at
363                 // the right side of the input
364                 'right' : 0,
365                 'margin' : 0,
366                 'padding' : 0,
367                 'fontSize' : '480px',
368                 // in Firefox if font-family is set to
369                 // 'inherit' the input doesn't work
370                 'fontFamily' : 'sans-serif',
371                 'cursor' : 'pointer'
372             });            
373
374             var div = document.createElement("div");                        
375             addStyles(div, {
376                 'display' : 'block',
377                 'position' : 'absolute',
378                 'overflow' : 'hidden',
379                 'margin' : 0,
380                 'padding' : 0,                
381                 'opacity' : 0,
382                 // Make sure browse button is in the right side
383                 // in Internet Explorer
384                 'direction' : 'ltr',
385                 //Max zIndex supported by Opera 9.0-9.2
386                 'zIndex': 2147483583
387             });
388             
389             // Make sure that element opacity exists.
390             // Otherwise use IE filter            
391             if ( div.style.opacity !== "0") {
392                 if (typeof(div.filters) == 'undefined'){
393                     throw new Error('Opacity not supported by the browser');
394                 }
395                 div.style.filter = "alpha(opacity=0)";
396             }            
397             
398             addEvent(input, 'change', function(){
399                  
400                 if ( ! input || input.value === ''){                
401                     return;                
402                 }
403                             
404                 // Get filename from input, required                
405                 // as some browsers have path instead of it          
406                 var file = fileFromPath(input.value);
407                                 
408                 if (false === self._settings.onChange.call(self, file, getExt(file))){
409                     self._clearInput();                
410                     return;
411                 }
412                 
413                 // Submit form when value is changed
414                 if (self._settings.autoSubmit) {
415                     self.submit();
416                 }
417             });            
418
419             addEvent(input, 'mouseover', function(){
420                 addClass(self._button, self._settings.hoverClass);
421             });
422             
423             addEvent(input, 'mouseout', function(){
424                 removeClass(self._button, self._settings.hoverClass);
425                 removeClass(self._button, self._settings.focusClass);
426                 
427                 // We use visibility instead of display to fix problem with Safari 4
428                 // The problem is that the value of input doesn't change if it 
429                 // has display none when user selects a file           
430                 input.parentNode.style.visibility = 'hidden';
431
432             });   
433                         
434             addEvent(input, 'focus', function(){
435                 addClass(self._button, self._settings.focusClass);
436             });
437             
438             addEvent(input, 'blur', function(){
439                 removeClass(self._button, self._settings.focusClass);
440             });
441             
442                 div.appendChild(input);
443             document.body.appendChild(div);
444               
445             this._input = input;
446         },
447         _clearInput : function(){
448             if (!this._input){
449                 return;
450             }            
451                              
452             // this._input.value = ''; Doesn't work in IE6                               
453             removeNode(this._input.parentNode);
454             this._input = null;                                                                   
455             this._createInput();
456             
457             removeClass(this._button, this._settings.hoverClass);
458             removeClass(this._button, this._settings.focusClass);
459         },
460         /**
461          * Function makes sure that when user clicks upload button,
462          * the this._input is clicked instead
463          */
464         _rerouteClicks: function(){
465             var self = this;
466             
467             // IE will later display 'access denied' error
468             // if you use using self._input.click()
469             // other browsers just ignore click()
470
471             addEvent(self._button, 'mouseover', function(){
472                 if (self._disabled){
473                     return;
474                 }
475                                 
476                 if ( ! self._input){
477                         self._createInput();
478                 }
479                 
480                 var div = self._input.parentNode;                            
481                 copyLayout(self._button, div);
482                 div.style.visibility = 'visible';
483                                 
484             });
485             
486             
487             // commented because we now hide input on mouseleave
488             /**
489              * When the window is resized the elements 
490              * can be misaligned if button position depends
491              * on window size
492              */
493             //addResizeEvent(function(){
494             //    if (self._input){
495             //        copyLayout(self._button, self._input.parentNode);
496             //    }
497             //});            
498                                          
499         },
500         /**
501          * Creates iframe with unique name
502          * @return {Element} iframe
503          */
504         _createIframe: function(){
505             // We can't use getTime, because it sometimes return
506             // same value in safari :(
507             var id = getUID();            
508              
509             // We can't use following code as the name attribute
510             // won't be properly registered in IE6, and new window
511             // on form submit will open
512             // var iframe = document.createElement('iframe');
513             // iframe.setAttribute('name', id);                        
514  
515             var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
516             // src="javascript:false; was added
517             // because it possibly removes ie6 prompt 
518             // "This page contains both secure and nonsecure items"
519             // Anyway, it doesn't do any harm.            
520             iframe.setAttribute('id', id);
521             
522             iframe.style.display = 'none';
523             document.body.appendChild(iframe);
524             
525             return iframe;
526         },
527         /**
528          * Creates form, that will be submitted to iframe
529          * @param {Element} iframe Where to submit
530          * @return {Element} form
531          */
532         _createForm: function(iframe){
533             var settings = this._settings;
534                         
535             // We can't use the following code in IE6
536             // var form = document.createElement('form');
537             // form.setAttribute('method', 'post');
538             // form.setAttribute('enctype', 'multipart/form-data');
539             // Because in this case file won't be attached to request                    
540             var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
541                         
542             form.setAttribute('action', settings.action);
543             form.setAttribute('target', iframe.name);                                   
544             form.style.display = 'none';
545             document.body.appendChild(form);
546             
547             // Create hidden input element for each data key
548             for (var prop in settings.data) {
549                 if (settings.data.hasOwnProperty(prop)){
550                     var el = document.createElement("input");
551                     el.setAttribute('type', 'hidden');
552                     el.setAttribute('name', prop);
553                     el.setAttribute('value', settings.data[prop]);
554                     form.appendChild(el);
555                 }
556             }
557             return form;
558         },
559         /**
560          * Gets response from iframe and fires onComplete event when ready
561          * @param iframe
562          * @param file Filename to use in onComplete callback 
563          */
564         _getResponse : function(iframe, file){            
565             // getting response
566             var toDeleteFlag = false, self = this, settings = this._settings;   
567                
568             addEvent(iframe, 'load', function(){                
569                 
570                 if (// For Safari 
571                     iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
572                     // For FF, IE
573                     iframe.src == "javascript:'<html></html>';"){                                                                        
574                         // First time around, do not delete.
575                         // We reload to blank page, so that reloading main page
576                         // does not re-submit the post.
577                         
578                         if (toDeleteFlag) {
579                             // Fix busy state in FF3
580                             setTimeout(function(){
581                                 removeNode(iframe);
582                             }, 0);
583                         }
584                                                 
585                         return;
586                 }
587                 
588                 var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
589                 
590                 // fixing Opera 9.26,10.00
591                 if (doc.readyState && doc.readyState != 'complete') {
592                    // Opera fires load event multiple times
593                    // Even when the DOM is not ready yet
594                    // this fix should not affect other browsers
595                    return;
596                 }
597                 
598                 // fixing Opera 9.64
599                 if (doc.body && doc.body.innerHTML == "false") {
600                     // In Opera 9.64 event was fired second time
601                     // when body.innerHTML changed from false 
602                     // to server response approx. after 1 sec
603                     return;
604                 }
605                 
606                 var response;
607                 
608                 if (doc.XMLDocument) {
609                     // response is a xml document Internet Explorer property
610                     response = doc.XMLDocument;
611                 } else if (doc.body){
612                     // response is html document or plain text
613                     response = doc.body.innerHTML;
614                     
615                     if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
616                         // If the document was sent as 'application/javascript' or
617                         // 'text/javascript', then the browser wraps the text in a <pre>
618                         // tag and performs html encoding on the contents.  In this case,
619                         // we need to pull the original text content from the text node's
620                         // nodeValue property to retrieve the unmangled content.
621                         // Note that IE6 only understands text/html
622                         if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
623                             doc.normalize();
624                             response = doc.body.firstChild.firstChild.nodeValue;
625                         }
626                         
627                         if (response) {
628                             response = eval("(" + response + ")");
629                         } else {
630                             response = {};
631                         }
632                     }
633                 } else {
634                     // response is a xml document
635                     response = doc;
636                 }
637                 
638                 settings.onComplete.call(self, file, response);
639                 
640                 // Reload blank page, so that reloading main page
641                 // does not re-submit the post. Also, remember to
642                 // delete the frame
643                 toDeleteFlag = true;
644                 
645                 // Fix IE mixed content issue
646                 iframe.src = "javascript:'<html></html>';";
647             });            
648         },        
649         /**
650          * Upload file contained in this._input
651          */
652         submit: function(){                        
653             var self = this, settings = this._settings;
654             
655             if ( ! this._input || this._input.value === ''){                
656                 return;                
657             }
658                                     
659             var file = fileFromPath(this._input.value);
660             
661             // user returned false to cancel upload
662             if (false === settings.onSubmit.call(this, file, getExt(file))){
663                 this._clearInput();                
664                 return;
665             }
666             
667             // sending request    
668             var iframe = this._createIframe();
669             var form = this._createForm(iframe);
670             
671             // assuming following structure
672             // div -> input type='file'
673             removeNode(this._input.parentNode);            
674             removeClass(self._button, self._settings.hoverClass);
675             removeClass(self._button, self._settings.focusClass);
676                         
677             form.appendChild(this._input);
678                         
679             form.submit();
680
681             // request set, clean up                
682             removeNode(form); form = null;                          
683             removeNode(this._input); this._input = null;            
684             
685             // Get response from iframe and fire onComplete event when ready
686             this._getResponse(iframe, file);            
687
688             // get ready for next request            
689             this._createInput();
690         }
691     };
692 })();