Roo/dialog/UploadCropbox.js
[roojs1] / Roo / dialog / UploadCropbox.js
1
2 /*
3 * Licence: LGPL
4 */
5
6 /**
7  * @class Roo.dialog.UploadCropbox
8  * @extends Roo.BoxComponent
9  * Dialog UploadCropbox class
10  * @cfg {String} emptyText show when image has been loaded
11  * @cfg {String} rotateNotify show when image too small to rotate
12  * @cfg {Number} errorTimeout default 3000
13  * @cfg {Number} minWidth default 300
14  * @cfg {Number} minHeight default 300
15  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
16  * @cfg {Boolean} isDocument (true|false) default false
17  * @cfg {String} url action url
18  * @cfg {String} paramName default 'imageUpload'
19  * @cfg {String} method default POST
20  * @cfg {Boolean} loadMask (true|false) default true
21  * @cfg {Boolean} loadingText default 'Loading...'
22  * 
23  * @constructor
24  * Create a new UploadCropbox
25  * @param {Object} config The config object
26  */
27
28  Roo.dialog.UploadCropbox = function(config){
29     Roo.dialog.UploadCropbox.superclass.constructor.call(this, config);
30     
31     this.addEvents({
32         /**
33          * @event beforeselectfile
34          * Fire before select file
35          * @param {Roo.dialog.UploadCropbox} this
36          */
37         "beforeselectfile" : true,
38         /**
39          * @event initial
40          * Fire after initEvent
41          * @param {Roo.dialog.UploadCropbox} this
42          */
43         "initial" : true,
44         /**
45          * @event crop
46          * Fire after initEvent
47          * @param {Roo.dialog.UploadCropbox} this
48          * @param {String} data
49          */
50         "crop" : true,
51         /**
52          * @event prepare
53          * Fire when preparing the file data
54          * @param {Roo.dialog.UploadCropbox} this
55          * @param {Object} file
56          */
57         "prepare" : true,
58         /**
59          * @event exception
60          * Fire when get exception
61          * @param {Roo.dialog.UploadCropbox} this
62          * @param {XMLHttpRequest} xhr
63          */
64         "exception" : true,
65         /**
66          * @event beforeloadcanvas
67          * Fire before load the canvas
68          * @param {Roo.dialog.UploadCropbox} this
69          * @param {String} src
70          */
71         "beforeloadcanvas" : true,
72         /**
73          * @event trash
74          * Fire when trash image
75          * @param {Roo.dialog.UploadCropbox} this
76          */
77         "trash" : true,
78         /**
79          * @event download
80          * Fire when download the image
81          * @param {Roo.dialog.UploadCropbox} this
82          */
83         "download" : true,
84         /**
85          * @event footerbuttonclick
86          * Fire when footerbuttonclick
87          * @param {Roo.dialog.UploadCropbox} this
88          * @param {String} type
89          */
90         "footerbuttonclick" : true,
91         /**
92          * @event resize
93          * Fire when resize
94          * @param {Roo.dialog.UploadCropbox} this
95          */
96         "resize" : true,
97         /**
98          * @event rotate
99          * Fire when rotate the image
100          * @param {Roo.dialog.UploadCropbox} this
101          * @param {String} pos
102          */
103         "rotate" : true,
104         /**
105          * @event inspect
106          * Fire when inspect the file
107          * @param {Roo.dialog.UploadCropbox} this
108          * @param {Object} file
109          */
110         "inspect" : true,
111         /**
112          * @event upload
113          * Fire when xhr upload the file
114          * @param {Roo.dialog.UploadCropbox} this
115          * @param {Object} data
116          */
117         "upload" : true,
118         /**
119          * @event arrange
120          * Fire when arrange the file data
121          * @param {Roo.dialog.UploadCropbox} this
122          * @param {Object} formData
123          */
124         "arrange" : true,
125         /**
126          * @event loadcanvas
127          * Fire after load the canvas
128          * @param {Roo.dialog.UploadCropbox}
129          * @param {Object} imgEl
130          */
131         "loadcanvas" : true
132     });
133     
134     this.buttons = this.buttons || Roo.dialog.UploadCropbox.footer.STANDARD;
135 };
136
137 Roo.extend(Roo.dialog.UploadCropbox, Roo.Component,  {
138     
139     emptyText : 'Click to upload image',
140     rotateNotify : 'Image is too small to rotate',
141     errorTimeout : 3000,
142     scale : 0,
143     baseScale : 1,
144     rotate : 0,
145     dragable : false,
146     pinching : false,
147     mouseX : 0,
148     mouseY : 0,
149     cropData : false,
150     minWidth : 300,
151     minHeight : 300,
152     file : false,
153     exif : {},
154     baseRotate : 1,
155     cropType : 'image/jpeg',
156     buttons : false,
157     canvasLoaded : false,
158     isDocument : false,
159     method : 'POST',
160     paramName : 'imageUpload',
161     loadMask : true,
162     loadingText : 'Loading...',
163     maskEl : false,
164     
165     getAutoCreate : function()
166     {
167         var cfg = {
168             tag : 'div',
169             cls : 'roo-upload-cropbox',
170             cn : [
171                 {
172                     tag : 'input',
173                     cls : 'roo-upload-cropbox-selector',
174                     type : 'file'
175                 },
176                 {
177                     tag : 'div',
178                     cls : 'roo-upload-cropbox-body',
179                     style : 'cursor:pointer',
180                     cn : [
181                         {
182                             tag : 'div',
183                             cls : 'roo-upload-cropbox-preview'
184                         },
185                         {
186                             tag : 'div',
187                             cls : 'roo-upload-cropbox-thumb'
188                         },
189                         {
190                             tag : 'div',
191                             cls : 'roo-upload-cropbox-empty-notify',
192                             html : this.emptyText
193                         },
194                         {
195                             tag : 'div',
196                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
197                             html : this.rotateNotify
198                         }
199                     ]
200                 },
201                 {
202                     tag : 'div',
203                     cls : 'roo-upload-cropbox-footer',
204                     cn : {
205                         tag : 'div',
206                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
207                         cn : []
208                     }
209                 }
210             ]
211         };
212         
213         return cfg;
214     },
215     
216     onRender : function(ct, position)
217     {
218         console.log("On Render");
219         console.log(this);
220         Roo.dialog.UploadCropbox.superclass.onRender.call(this, ct, position);
221
222         if(this.el){
223             if (this.el.attr('xtype')) {
224                 this.el.attr('xtypex', this.el.attr('xtype'));
225                 this.el.dom.removeAttribute('xtype');
226                 
227                 this.initEvents();
228             }
229         }
230         else {
231             var cfg = Roo.apply({},  this.getAutoCreate());
232         
233             cfg.id = this.id || Roo.id();
234             
235             if (this.cls) {
236                 cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
237             }
238             
239             if (this.style) { // fixme needs to support more complex style data.
240                 cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
241             }
242             
243             this.el = ct.createChild(cfg, position);
244             
245             this.initEvents();
246         }
247         
248         if (this.buttons.length) {
249             
250             Roo.each(this.buttons, function(bb) {
251                 
252                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
253                 
254                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
255                 
256             }, this);
257         }
258         
259         if(this.loadMask){
260             this.maskEl = this.el;
261         }
262     },
263     
264     initEvents : function()
265     {
266         this.urlAPI = (window.createObjectURL && window) || 
267                                 (window.URL && URL.revokeObjectURL && URL) || 
268                                 (window.webkitURL && webkitURL);
269                         
270         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
271         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
272         
273         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
274         this.selectorEl.hide();
275         
276         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
277         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
278         
279         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
280         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
281         this.thumbEl.hide();
282         
283         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
284         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
285         
286         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
287         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
288         this.errorEl.hide();
289         
290         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
291         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
292         this.footerEl.hide();
293         
294         this.setThumbBoxSize();
295         
296         this.bind();
297         
298         this.resize();
299         
300         this.fireEvent('initial', this);
301     },
302
303     bind : function()
304     {
305         var _this = this;
306         
307         window.addEventListener("resize", function() { _this.resize(); } );
308         
309         this.bodyEl.on('click', this.beforeSelectFile, this);
310         
311         if(Roo.isTouch){
312             this.bodyEl.on('touchstart', this.onTouchStart, this);
313             this.bodyEl.on('touchmove', this.onTouchMove, this);
314             this.bodyEl.on('touchend', this.onTouchEnd, this);
315         }
316         
317         if(!Roo.isTouch){
318             this.bodyEl.on('mousedown', this.onMouseDown, this);
319             this.bodyEl.on('mousemove', this.onMouseMove, this);
320             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
321             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
322             Roo.get(document).on('mouseup', this.onMouseUp, this);
323         }
324         
325         this.selectorEl.on('change', this.onFileSelected, this);
326     },
327     
328     reset : function()
329     {    
330         this.scale = 0;
331         this.baseScale = 1;
332         this.rotate = 0;
333         this.baseRotate = 1;
334         this.dragable = false;
335         this.pinching = false;
336         this.mouseX = 0;
337         this.mouseY = 0;
338         this.cropData = false;
339         this.notifyEl.dom.innerHTML = this.emptyText;
340         
341         // this.selectorEl.dom.value = '';
342         
343     },
344     
345     resize : function()
346     {
347         if(this.fireEvent('resize', this) != false){
348             this.setThumbBoxPosition();
349             this.setCanvasPosition();
350         }
351     },
352     
353     onFooterButtonClick : function(e, el, o, type)
354     {
355         switch (type) {
356             case 'rotate-left' :
357                 this.onRotateLeft(e);
358                 break;
359             case 'rotate-right' :
360                 this.onRotateRight(e);
361                 break;
362             case 'picture' :
363                 this.beforeSelectFile(e);
364                 break;
365             case 'trash' :
366                 this.trash(e);
367                 break;
368             case 'crop' :
369                 this.crop(e);
370                 break;
371             case 'download' :
372                 this.download(e);
373                 break;
374             default :
375                 break;
376         }
377         
378         this.fireEvent('footerbuttonclick', this, type);
379     },
380     
381     beforeSelectFile : function(e)
382     {
383         e.preventDefault();
384         
385         if(this.fireEvent('beforeselectfile', this) != false){
386             this.selectorEl.dom.click();
387         }
388     },
389     
390     onFileSelected : function(e)
391     {
392         e.preventDefault();
393         
394         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
395             return;
396         }
397         
398         var file = this.selectorEl.dom.files[0];
399         
400         if(this.fireEvent('inspect', this, file) != false){
401             this.prepare(file);
402         }
403         
404     },
405     
406     trash : function(e)
407     {
408         this.fireEvent('trash', this);
409     },
410     
411     download : function(e)
412     {
413         this.fireEvent('download', this);
414     },
415     
416     loadCanvas : function(src)
417     {   
418         if(this.fireEvent('beforeloadcanvas', this, src) != false){
419             
420             this.reset();
421             
422             this.imageEl = document.createElement('img');
423             
424             var _this = this;
425             
426             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
427             
428             this.imageEl.src = src;
429         }
430     },
431     
432     onLoadCanvas : function()
433     {   
434         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
435         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
436
437         var _this = this;
438
439         if(this.imageEl.OriginWidth < this.minWidth) {
440             
441             Roo.Msg.show({
442                 title: 'Error',
443                 msg: "Image width should be at least 720",
444                 buttons: {ok : true},
445                 fn: function(res) {
446                     _this.selectorEl.dom.click();
447                 }
448             });
449         }
450
451         if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
452         
453             this.bodyEl.un('click', this.beforeSelectFile, this);
454             
455             this.notifyEl.hide();
456             this.thumbEl.show();
457             this.footerEl.show();
458             
459             this.baseRotateLevel();
460             
461             if(this.isDocument){
462                 this.setThumbBoxSize();
463             }
464             
465             this.setThumbBoxPosition();
466             
467             this.baseScaleLevel();
468             
469             this.draw();
470             
471             this.resize();
472             
473             this.canvasLoaded = true;
474         
475         }
476         
477         if(this.loadMask){
478             this.maskEl.unmask();
479         }
480         
481     },
482     
483     setCanvasPosition : function()
484     {   
485         if(!this.canvasEl){
486             return;
487         }
488         
489         var pw = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
490         var ph = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
491         
492         this.previewEl.setLeft(pw);
493         this.previewEl.setTop(ph);
494         
495     },
496     
497     onMouseDown : function(e)
498     {   
499         e.stopEvent();
500         
501         this.dragable = true;
502         this.pinching = false;
503         
504         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
505             this.dragable = false;
506             return;
507         }
508         
509         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
510         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
511         
512     },
513     
514     onMouseMove : function(e)
515     {   
516         e.stopEvent();
517         
518         if(!this.canvasLoaded){
519             return;
520         }
521         
522         if (!this.dragable){
523             return;
524         }
525         
526         var minX = Math.ceil(this.thumbEl.getLeft(true));
527         var minY = Math.ceil(this.thumbEl.getTop(true));
528         
529         var maxX = Math.ceil(minX + this.thumbEl.getWidth() - this.canvasEl.width);
530         var maxY = Math.ceil(minY + this.thumbEl.getHeight() - this.canvasEl.height);
531         
532         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
533         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
534         
535         x = x - this.mouseX;
536         y = y - this.mouseY;
537         
538         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
539         var bgY = Math.ceil(y + this.previewEl.getTop(true));
540         
541         bgX = (minX < bgX) ? minX : ((maxX > bgX) ? maxX : bgX);
542         bgY = (minY < bgY) ? minY : ((maxY > bgY) ? maxY : bgY);
543         
544         this.previewEl.setLeft(bgX);
545         this.previewEl.setTop(bgY);
546         
547         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
548         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
549     },
550     
551     onMouseUp : function(e)
552     {   
553         e.stopEvent();
554         
555         this.dragable = false;
556     },
557     
558     onMouseWheel : function(e)
559     {   
560         e.stopEvent();
561         
562         this.startScale = this.scale;
563         console.log("START SCALE: " + this.scale);
564         this.scale = (e.getWheelDelta() == 1) ? (this.scale + 1) : (this.scale - 1);
565         console.log("END SCALE: " + this.scale);
566         if(!this.zoomable()){
567             this.scale = this.startScale;
568             return;
569         }
570         
571         this.draw();
572         
573         return;
574     },
575     
576     zoomable : function()
577     {
578         console.log("THUMBEL");
579         console.log(this.thumbEl);
580         var minScale = this.thumbEl.getWidth() / this.minWidth;
581         
582         if(this.minWidth < this.minHeight){
583             minScale = this.thumbEl.getHeight() / this.minHeight;
584         }
585
586         console.log("MINSCALE: " + minScale);
587         
588         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
589         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
590
591         var maxWidth = this.imageEl.OriginWidth;
592         var maxHeight = this.imageEl.OriginHeight;
593
594         if(this.imageEl.OriginWidth / this.imageEl.OriginHeight  > this.minWidth / this.minHeight && this.imageEl.OriginHeight < this.minHeight) {
595             maxHeight = this.minHeight;
596             maxWidth = this.imageEl.OriginWidth / this.imageEl.OriginHeight * this.minHeight;
597         }
598         if(this.imageEl.OriginWidth / this.imageEl.OriginHeight  < this.minWidth / this.minHeight && this.imageEl.OriginWidth < this.minWidth) {
599             maxWidth = this.minWidth;
600             maxHeight = this.imageEl.OriginHeight /this.imageEl.OriginWidth * this.minWidth;
601         }
602
603         console.log("GETSCALELEVEL: " + this.getScaleLevel());
604         console.log("width: " + width);
605         console.log("height: " + height);
606         console.log("maxWidth: " + maxWidth);
607         console.log("maxHeight: " + maxHeight);
608         
609         if(
610                 this.isDocument &&
611                 (this.rotate == 0 || this.rotate == 180) && 
612                 (
613                     width > this.imageEl.OriginWidth || 
614                     height > this.imageEl.OriginHeight ||
615                     (width < this.minWidth && height < this.minHeight)
616                 )
617         ){
618             return false;
619         }
620         
621         if(
622                 this.isDocument &&
623                 (this.rotate == 90 || this.rotate == 270) && 
624                 (
625                     width > this.imageEl.OriginWidth || 
626                     height > this.imageEl.OriginHeight ||
627                     (width < this.minHeight && height < this.minWidth)
628                 )
629         ){
630             return false;
631         }
632         
633         if(
634                 !this.isDocument &&
635                 (this.rotate == 0 || this.rotate == 180) && 
636                 (
637                     width < this.minWidth ||
638                     height < this.minHeight ||
639                     width > maxWidth ||
640                     height > maxHeight
641                 )
642         ){
643             return false;
644         }
645         
646         if(
647                 !this.isDocument &&
648                 (this.rotate == 90 || this.rotate == 270) && 
649                 (
650                     width < this.minHeight || 
651                     width > this.imageEl.OriginWidth || 
652                     height < this.minWidth || 
653                     height > this.imageEl.OriginHeight
654                 )
655         ){
656             return false;
657         }
658         
659         return true;
660         
661     },
662     
663     onRotateLeft : function(e)
664     {   
665         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
666             
667             var minScale = this.thumbEl.getWidth() / this.minWidth;
668             
669             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
670             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
671             
672             this.startScale = this.scale;
673             
674             while (this.getScaleLevel() < minScale){
675             
676                 this.scale = this.scale + 1;
677                 
678                 if(!this.zoomable()){
679                     break;
680                 }
681                 
682                 if(
683                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
684                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
685                 ){
686                     continue;
687                 }
688                 
689                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
690
691                 this.draw();
692                 
693                 return;
694             }
695             
696             this.scale = this.startScale;
697             
698             this.onRotateFail();
699             
700             return false;
701         }
702         
703         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
704
705         if(this.isDocument){
706             this.setThumbBoxSize();
707             this.setThumbBoxPosition();
708             this.setCanvasPosition();
709         }
710         
711         this.draw();
712         
713         this.fireEvent('rotate', this, 'left');
714         
715     },
716     
717     onRotateRight : function(e)
718     {
719         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
720             
721             var minScale = this.thumbEl.getWidth() / this.minWidth;
722         
723             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
724             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
725             
726             this.startScale = this.scale;
727             
728             while (this.getScaleLevel() < minScale){
729             
730                 this.scale = this.scale + 1;
731                 
732                 if(!this.zoomable()){
733                     break;
734                 }
735                 
736                 if(
737                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
738                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
739                 ){
740                     continue;
741                 }
742                 
743                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
744
745                 this.draw();
746                 
747                 return;
748             }
749             
750             this.scale = this.startScale;
751             
752             this.onRotateFail();
753             
754             return false;
755         }
756         
757         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
758
759         if(this.isDocument){
760             this.setThumbBoxSize();
761             this.setThumbBoxPosition();
762             this.setCanvasPosition();
763         }
764         
765         this.draw();
766         
767         this.fireEvent('rotate', this, 'right');
768     },
769     
770     onRotateFail : function()
771     {
772         this.errorEl.show(true);
773         
774         var _this = this;
775         
776         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
777     },
778     
779     draw : function()
780     {
781         this.previewEl.dom.innerHTML = '';
782         
783         var canvasEl = document.createElement("canvas");
784         
785         var contextEl = canvasEl.getContext("2d");
786         
787         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
788         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
789         var center = this.imageEl.OriginWidth / 2;
790         
791         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
792             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
793             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
794             center = this.imageEl.OriginHeight / 2;
795         }
796         
797         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
798         
799         contextEl.translate(center, center);
800         contextEl.rotate(this.rotate * Math.PI / 180);
801
802         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
803         
804         this.canvasEl = document.createElement("canvas");
805         
806         this.contextEl = this.canvasEl.getContext("2d");
807         
808         switch (this.rotate) {
809             case 0 :
810                 
811                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
812                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
813                 
814                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
815                 
816                 break;
817             case 90 : 
818                 
819                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
820                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
821                 
822                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
823                     this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
824                     break;
825                 }
826                 
827                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
828                 
829                 break;
830             case 180 :
831                 
832                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
833                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
834                 
835                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
836                     this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
837                     break;
838                 }
839                 
840                 this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
841                 
842                 break;
843             case 270 :
844                 
845                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
846                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
847         
848                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
849                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
850                     break;
851                 }
852                 
853                 this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
854                 
855                 break;
856             default : 
857                 break;
858         }
859         
860         this.previewEl.appendChild(this.canvasEl);
861         
862         this.setCanvasPosition();
863     },
864     
865     crop : function()
866     {
867         if(!this.canvasLoaded){
868             return;
869         }
870         
871         var imageCanvas = document.createElement("canvas");
872         
873         var imageContext = imageCanvas.getContext("2d");
874         
875         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
876         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
877         
878         var center = imageCanvas.width / 2;
879         
880         imageContext.translate(center, center);
881         
882         imageContext.rotate(this.rotate * Math.PI / 180);
883         
884         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
885         
886         var canvas = document.createElement("canvas");
887         
888         var context = canvas.getContext("2d");
889                 
890         canvas.width = this.minWidth;
891         canvas.height = this.minHeight;
892
893         switch (this.rotate) {
894             case 0 :
895                 
896                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
897                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
898                 
899                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
900                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
901                 
902                 var targetWidth = this.minWidth - 2 * x;
903                 var targetHeight = this.minHeight - 2 * y;
904                 
905                 var scale = 1;
906                 
907                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
908                     scale = targetWidth / width;
909                 }
910                 
911                 if(x > 0 && y == 0){
912                     scale = targetHeight / height;
913                 }
914                 
915                 if(x > 0 && y > 0){
916                     scale = targetWidth / width;
917                     
918                     if(width < height){
919                         scale = targetHeight / height;
920                     }
921                 }
922                 
923                 context.scale(scale, scale);
924                 
925                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
926                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
927
928                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
929                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
930
931                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
932                 
933                 break;
934             case 90 : 
935                 
936                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
937                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
938                 
939                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
940                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
941                 
942                 var targetWidth = this.minWidth - 2 * x;
943                 var targetHeight = this.minHeight - 2 * y;
944                 
945                 var scale = 1;
946                 
947                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
948                     scale = targetWidth / width;
949                 }
950                 
951                 if(x > 0 && y == 0){
952                     scale = targetHeight / height;
953                 }
954                 
955                 if(x > 0 && y > 0){
956                     scale = targetWidth / width;
957                     
958                     if(width < height){
959                         scale = targetHeight / height;
960                     }
961                 }
962                 
963                 context.scale(scale, scale);
964                 
965                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
966                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
967
968                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
969                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
970                 
971                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
972                 
973                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
974                 
975                 break;
976             case 180 :
977                 
978                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
979                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
980                 
981                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
982                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
983                 
984                 var targetWidth = this.minWidth - 2 * x;
985                 var targetHeight = this.minHeight - 2 * y;
986                 
987                 var scale = 1;
988                 
989                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
990                     scale = targetWidth / width;
991                 }
992                 
993                 if(x > 0 && y == 0){
994                     scale = targetHeight / height;
995                 }
996                 
997                 if(x > 0 && y > 0){
998                     scale = targetWidth / width;
999                     
1000                     if(width < height){
1001                         scale = targetHeight / height;
1002                     }
1003                 }
1004                 
1005                 context.scale(scale, scale);
1006                 
1007                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1008                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1009
1010                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1011                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1012
1013                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1014                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
1015                 
1016                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1017                 
1018                 break;
1019             case 270 :
1020                 
1021                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
1022                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
1023                 
1024                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
1025                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
1026                 
1027                 var targetWidth = this.minWidth - 2 * x;
1028                 var targetHeight = this.minHeight - 2 * y;
1029                 
1030                 var scale = 1;
1031                 
1032                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1033                     scale = targetWidth / width;
1034                 }
1035                 
1036                 if(x > 0 && y == 0){
1037                     scale = targetHeight / height;
1038                 }
1039                 
1040                 if(x > 0 && y > 0){
1041                     scale = targetWidth / width;
1042                     
1043                     if(width < height){
1044                         scale = targetHeight / height;
1045                     }
1046                 }
1047                 
1048                 context.scale(scale, scale);
1049                 
1050                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1051                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1052
1053                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1054                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1055                 
1056                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1057                 
1058                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1059                 
1060                 break;
1061             default : 
1062                 break;
1063         }
1064         
1065         this.cropData = canvas.toDataURL(this.cropType);
1066         
1067         if(this.fireEvent('crop', this, this.cropData) !== false){
1068             this.process(this.file, this.cropData);
1069         }
1070         
1071         return;
1072         
1073     },
1074     
1075     setThumbBoxSize : function()
1076     {
1077         var width, height;
1078         
1079         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
1080             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
1081             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
1082             
1083             this.minWidth = width;
1084             this.minHeight = height;
1085             
1086             if(this.rotate == 90 || this.rotate == 270){
1087                 this.minWidth = height;
1088                 this.minHeight = width;
1089             }
1090         }
1091         
1092         height = 300;
1093         width = Math.ceil(this.minWidth * height / this.minHeight);
1094         
1095         if(this.minWidth > this.minHeight){
1096             width = 300;
1097             height = Math.ceil(this.minHeight * width / this.minWidth);
1098         }
1099         
1100         this.thumbEl.setStyle({
1101             width : width + 'px',
1102             height : height + 'px'
1103         });
1104
1105         return;
1106             
1107     },
1108     
1109     setThumbBoxPosition : function()
1110     {
1111         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
1112         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
1113         
1114         this.thumbEl.setLeft(x);
1115         this.thumbEl.setTop(y);
1116         
1117     },
1118     
1119     baseRotateLevel : function()
1120     {
1121         this.baseRotate = 1;
1122         
1123         if(
1124                 typeof(this.exif) != 'undefined' &&
1125                 typeof(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
1126                 [1, 3, 6, 8].indexOf(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != -1
1127         ){
1128             this.baseRotate = this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']];
1129         }
1130         
1131         this.rotate = Roo.dialog.UploadCropbox['Orientation'][this.baseRotate];
1132         
1133     },
1134     
1135     baseScaleLevel : function()
1136     {
1137         var width, height;
1138         
1139         if(this.isDocument){
1140             
1141             if(this.baseRotate == 6 || this.baseRotate == 8){
1142             
1143                 height = this.thumbEl.getHeight();
1144                 this.baseScale = height / this.imageEl.OriginWidth;
1145
1146                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
1147                     width = this.thumbEl.getWidth();
1148                     this.baseScale = width / this.imageEl.OriginHeight;
1149                 }
1150
1151                 return;
1152             }
1153
1154             height = this.thumbEl.getHeight();
1155             this.baseScale = height / this.imageEl.OriginHeight;
1156
1157             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
1158                 width = this.thumbEl.getWidth();
1159                 this.baseScale = width / this.imageEl.OriginWidth;
1160             }
1161
1162             return;
1163         }
1164         
1165         if(this.baseRotate == 6 || this.baseRotate == 8){
1166             
1167             width = this.thumbEl.getHeight();
1168             this.baseScale = width / this.imageEl.OriginHeight;
1169             
1170             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
1171                 height = this.thumbEl.getWidth();
1172                 this.baseScale = height / this.imageEl.OriginHeight;
1173             }
1174             
1175             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1176                 height = this.thumbEl.getWidth();
1177                 this.baseScale = height / this.imageEl.OriginHeight;
1178                 
1179                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
1180                     width = this.thumbEl.getHeight();
1181                     this.baseScale = width / this.imageEl.OriginWidth;
1182                 }
1183             }
1184             
1185             return;
1186         }
1187         
1188         width = this.thumbEl.getWidth();
1189         this.baseScale = width / this.imageEl.OriginWidth;
1190         
1191         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
1192             height = this.thumbEl.getHeight();
1193             this.baseScale = height / this.imageEl.OriginHeight;
1194         }
1195         
1196         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1197             
1198             height = this.thumbEl.getHeight();
1199             this.baseScale = height / this.imageEl.OriginHeight;
1200             
1201             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
1202                 width = this.thumbEl.getWidth();
1203                 this.baseScale = width / this.imageEl.OriginWidth;
1204             }
1205             
1206         }
1207         
1208         return;
1209     },
1210     
1211     getScaleLevel : function()
1212     {
1213         console.log("BASESCALE: " + this.baseScale);
1214         return this.baseScale * Math.pow(1.02, this.scale);
1215     },
1216     
1217     onTouchStart : function(e)
1218     {
1219         if(!this.canvasLoaded){
1220             this.beforeSelectFile(e);
1221             return;
1222         }
1223         
1224         var touches = e.browserEvent.touches;
1225         
1226         if(!touches){
1227             return;
1228         }
1229         
1230         if(touches.length == 1){
1231             this.onMouseDown(e);
1232             return;
1233         }
1234         
1235         if(touches.length != 2){
1236             return;
1237         }
1238         
1239         var coords = [];
1240         
1241         for(var i = 0, finger; finger = touches[i]; i++){
1242             coords.push(finger.pageX, finger.pageY);
1243         }
1244         
1245         var x = Math.pow(coords[0] - coords[2], 2);
1246         var y = Math.pow(coords[1] - coords[3], 2);
1247         
1248         this.startDistance = Math.sqrt(x + y);
1249         
1250         this.startScale = this.scale;
1251         
1252         this.pinching = true;
1253         this.dragable = false;
1254         
1255     },
1256     
1257     onTouchMove : function(e)
1258     {
1259         if(!this.pinching && !this.dragable){
1260             return;
1261         }
1262         
1263         var touches = e.browserEvent.touches;
1264         
1265         if(!touches){
1266             return;
1267         }
1268         
1269         if(this.dragable){
1270             this.onMouseMove(e);
1271             return;
1272         }
1273         
1274         var coords = [];
1275         
1276         for(var i = 0, finger; finger = touches[i]; i++){
1277             coords.push(finger.pageX, finger.pageY);
1278         }
1279         
1280         var x = Math.pow(coords[0] - coords[2], 2);
1281         var y = Math.pow(coords[1] - coords[3], 2);
1282         
1283         this.endDistance = Math.sqrt(x + y);
1284         
1285         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
1286         
1287         if(!this.zoomable()){
1288             this.scale = this.startScale;
1289             return;
1290         }
1291         
1292         this.draw();
1293         
1294     },
1295     
1296     onTouchEnd : function(e)
1297     {
1298         this.pinching = false;
1299         this.dragable = false;
1300         
1301     },
1302     
1303     process : function(file, crop)
1304     {
1305         if(this.loadMask){
1306             this.maskEl.mask(this.loadingText);
1307         }
1308         
1309         this.xhr = new XMLHttpRequest();
1310         
1311         file.xhr = this.xhr;
1312
1313         this.xhr.open(this.method, this.url, true);
1314         
1315         var headers = {
1316             "Accept": "application/json",
1317             "Cache-Control": "no-cache",
1318             "X-Requested-With": "XMLHttpRequest"
1319         };
1320         
1321         for (var headerName in headers) {
1322             var headerValue = headers[headerName];
1323             if (headerValue) {
1324                 this.xhr.setRequestHeader(headerName, headerValue);
1325             }
1326         }
1327         
1328         var _this = this;
1329         
1330         this.xhr.onload = function()
1331         {
1332             _this.xhrOnLoad(_this.xhr);
1333         }
1334         
1335         this.xhr.onerror = function()
1336         {
1337             _this.xhrOnError(_this.xhr);
1338         }
1339         
1340         var formData = new FormData();
1341
1342         formData.append('returnHTML', 'NO');
1343         
1344         if(crop){
1345             formData.append('crop', crop);
1346         }
1347         
1348         if(typeof(file) != 'undefined' && (typeof(file.id) == 'undefined' || file.id * 1 < 1)){
1349             formData.append(this.paramName, file, file.name);
1350         }
1351         
1352         if(typeof(file.filename) != 'undefined'){
1353             formData.append('filename', file.filename);
1354         }
1355         
1356         if(typeof(file.mimetype) != 'undefined'){
1357             formData.append('mimetype', file.mimetype);
1358         }
1359         
1360         if(this.fireEvent('arrange', this, formData) != false){
1361             this.xhr.send(formData);
1362         };
1363     },
1364     
1365     xhrOnLoad : function(xhr)
1366     {
1367         if(this.loadMask){
1368             this.maskEl.unmask();
1369         }
1370         
1371         if (xhr.readyState !== 4) {
1372             this.fireEvent('exception', this, xhr);
1373             return;
1374         }
1375
1376         var response = Roo.decode(xhr.responseText);
1377         
1378         if(!response.success){
1379             this.fireEvent('exception', this, xhr);
1380             return;
1381         }
1382         
1383         var response = Roo.decode(xhr.responseText);
1384         
1385         this.fireEvent('upload', this, response);
1386         
1387     },
1388     
1389     xhrOnError : function()
1390     {
1391         if(this.loadMask){
1392             this.maskEl.unmask();
1393         }
1394         
1395         Roo.log('xhr on error');
1396         
1397         var response = Roo.decode(xhr.responseText);
1398           
1399         Roo.log(response);
1400         
1401     },
1402     
1403     prepare : function(file)
1404     {   
1405         if(this.loadMask){
1406             this.maskEl.mask(this.loadingText);
1407         }
1408         
1409         this.file = false;
1410         this.exif = {};
1411         
1412         if(typeof(file) === 'string'){
1413             this.loadCanvas(file);
1414             return;
1415         }
1416         
1417         if(!file || !this.urlAPI){
1418             return;
1419         }
1420         
1421         this.file = file;
1422         this.cropType = file.type;
1423         
1424         var _this = this;
1425         
1426         if(this.fireEvent('prepare', this, this.file) != false){
1427             
1428             var reader = new FileReader();
1429             
1430             reader.onload = function (e) {
1431                 if (e.target.error) {
1432                     Roo.log(e.target.error);
1433                     return;
1434                 }
1435                 
1436                 var buffer = e.target.result,
1437                     dataView = new DataView(buffer),
1438                     offset = 2,
1439                     maxOffset = dataView.byteLength - 4,
1440                     markerBytes,
1441                     markerLength;
1442                 
1443                 if (dataView.getUint16(0) === 0xffd8) {
1444                     while (offset < maxOffset) {
1445                         markerBytes = dataView.getUint16(offset);
1446                         
1447                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
1448                             markerLength = dataView.getUint16(offset + 2) + 2;
1449                             if (offset + markerLength > dataView.byteLength) {
1450                                 Roo.log('Invalid meta data: Invalid segment size.');
1451                                 break;
1452                             }
1453                             
1454                             if(markerBytes == 0xffe1){
1455                                 _this.parseExifData(
1456                                     dataView,
1457                                     offset,
1458                                     markerLength
1459                                 );
1460                             }
1461                             
1462                             offset += markerLength;
1463                             
1464                             continue;
1465                         }
1466                         
1467                         break;
1468                     }
1469                     
1470                 }
1471                 
1472                 var url = _this.urlAPI.createObjectURL(_this.file);
1473                 
1474                 _this.loadCanvas(url);
1475                 
1476                 return;
1477             }
1478             
1479             reader.readAsArrayBuffer(this.file);
1480             
1481         }
1482         
1483     },
1484     
1485     parseExifData : function(dataView, offset, length)
1486     {
1487         var tiffOffset = offset + 10,
1488             littleEndian,
1489             dirOffset;
1490     
1491         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1492             // No Exif data, might be XMP data instead
1493             return;
1494         }
1495         
1496         // Check for the ASCII code for "Exif" (0x45786966):
1497         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1498             // No Exif data, might be XMP data instead
1499             return;
1500         }
1501         if (tiffOffset + 8 > dataView.byteLength) {
1502             Roo.log('Invalid Exif data: Invalid segment size.');
1503             return;
1504         }
1505         // Check for the two null bytes:
1506         if (dataView.getUint16(offset + 8) !== 0x0000) {
1507             Roo.log('Invalid Exif data: Missing byte alignment offset.');
1508             return;
1509         }
1510         // Check the byte alignment:
1511         switch (dataView.getUint16(tiffOffset)) {
1512         case 0x4949:
1513             littleEndian = true;
1514             break;
1515         case 0x4D4D:
1516             littleEndian = false;
1517             break;
1518         default:
1519             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
1520             return;
1521         }
1522         // Check for the TIFF tag marker (0x002A):
1523         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
1524             Roo.log('Invalid Exif data: Missing TIFF marker.');
1525             return;
1526         }
1527         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
1528         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
1529         
1530         this.parseExifTags(
1531             dataView,
1532             tiffOffset,
1533             tiffOffset + dirOffset,
1534             littleEndian
1535         );
1536     },
1537     
1538     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
1539     {
1540         var tagsNumber,
1541             dirEndOffset,
1542             i;
1543         if (dirOffset + 6 > dataView.byteLength) {
1544             Roo.log('Invalid Exif data: Invalid directory offset.');
1545             return;
1546         }
1547         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
1548         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
1549         if (dirEndOffset + 4 > dataView.byteLength) {
1550             Roo.log('Invalid Exif data: Invalid directory size.');
1551             return;
1552         }
1553         for (i = 0; i < tagsNumber; i += 1) {
1554             this.parseExifTag(
1555                 dataView,
1556                 tiffOffset,
1557                 dirOffset + 2 + 12 * i, // tag offset
1558                 littleEndian
1559             );
1560         }
1561         // Return the offset to the next directory:
1562         return dataView.getUint32(dirEndOffset, littleEndian);
1563     },
1564     
1565     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
1566     {
1567         var tag = dataView.getUint16(offset, littleEndian);
1568         
1569         this.exif[tag] = this.getExifValue(
1570             dataView,
1571             tiffOffset,
1572             offset,
1573             dataView.getUint16(offset + 2, littleEndian), // tag type
1574             dataView.getUint32(offset + 4, littleEndian), // tag length
1575             littleEndian
1576         );
1577     },
1578     
1579     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
1580     {
1581         var tagType = Roo.dialog.UploadCropbox.exifTagTypes[type],
1582             tagSize,
1583             dataOffset,
1584             values,
1585             i,
1586             str,
1587             c;
1588     
1589         if (!tagType) {
1590             Roo.log('Invalid Exif data: Invalid tag type.');
1591             return;
1592         }
1593         
1594         tagSize = tagType.size * length;
1595         // Determine if the value is contained in the dataOffset bytes,
1596         // or if the value at the dataOffset is a pointer to the actual data:
1597         dataOffset = tagSize > 4 ?
1598                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
1599         if (dataOffset + tagSize > dataView.byteLength) {
1600             Roo.log('Invalid Exif data: Invalid data offset.');
1601             return;
1602         }
1603         if (length === 1) {
1604             return tagType.getValue(dataView, dataOffset, littleEndian);
1605         }
1606         values = [];
1607         for (i = 0; i < length; i += 1) {
1608             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
1609         }
1610         
1611         if (tagType.ascii) {
1612             str = '';
1613             // Concatenate the chars:
1614             for (i = 0; i < values.length; i += 1) {
1615                 c = values[i];
1616                 // Ignore the terminating NULL byte(s):
1617                 if (c === '\u0000') {
1618                     break;
1619                 }
1620                 str += c;
1621             }
1622             return str;
1623         }
1624         return values;
1625     }
1626     
1627 });
1628
1629 Roo.apply(Roo.dialog.UploadCropbox, {
1630     tags : {
1631         'Orientation': 0x0112
1632     },
1633     
1634     Orientation: {
1635             1: 0, //'top-left',
1636 //            2: 'top-right',
1637             3: 180, //'bottom-right',
1638 //            4: 'bottom-left',
1639 //            5: 'left-top',
1640             6: 90, //'right-top',
1641 //            7: 'right-bottom',
1642             8: 270 //'left-bottom'
1643     },
1644     
1645     exifTagTypes : {
1646         // byte, 8-bit unsigned int:
1647         1: {
1648             getValue: function (dataView, dataOffset) {
1649                 return dataView.getUint8(dataOffset);
1650             },
1651             size: 1
1652         },
1653         // ascii, 8-bit byte:
1654         2: {
1655             getValue: function (dataView, dataOffset) {
1656                 return String.fromCharCode(dataView.getUint8(dataOffset));
1657             },
1658             size: 1,
1659             ascii: true
1660         },
1661         // short, 16 bit int:
1662         3: {
1663             getValue: function (dataView, dataOffset, littleEndian) {
1664                 return dataView.getUint16(dataOffset, littleEndian);
1665             },
1666             size: 2
1667         },
1668         // long, 32 bit int:
1669         4: {
1670             getValue: function (dataView, dataOffset, littleEndian) {
1671                 return dataView.getUint32(dataOffset, littleEndian);
1672             },
1673             size: 4
1674         },
1675         // rational = two long values, first is numerator, second is denominator:
1676         5: {
1677             getValue: function (dataView, dataOffset, littleEndian) {
1678                 return dataView.getUint32(dataOffset, littleEndian) /
1679                     dataView.getUint32(dataOffset + 4, littleEndian);
1680             },
1681             size: 8
1682         },
1683         // slong, 32 bit signed int:
1684         9: {
1685             getValue: function (dataView, dataOffset, littleEndian) {
1686                 return dataView.getInt32(dataOffset, littleEndian);
1687             },
1688             size: 4
1689         },
1690         // srational, two slongs, first is numerator, second is denominator:
1691         10: {
1692             getValue: function (dataView, dataOffset, littleEndian) {
1693                 return dataView.getInt32(dataOffset, littleEndian) /
1694                     dataView.getInt32(dataOffset + 4, littleEndian);
1695             },
1696             size: 8
1697         }
1698     },
1699     
1700     footer : {
1701         STANDARD : [
1702             {
1703                 tag : 'div',
1704                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1705                 action : 'rotate-left',
1706                 cn : [
1707                     {
1708                         tag : 'button',
1709                         cls : 'btn btn-default',
1710                         html : '<i class="fa fa-undo"></i>'
1711                     }
1712                 ]
1713             },
1714             {
1715                 tag : 'div',
1716                 cls : 'btn-group roo-upload-cropbox-picture',
1717                 action : 'picture',
1718                 cn : [
1719                     {
1720                         tag : 'button',
1721                         cls : 'btn btn-default',
1722                         html : '<i class="fa fa-picture-o"></i>'
1723                     }
1724                 ]
1725             },
1726             {
1727                 tag : 'div',
1728                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1729                 action : 'rotate-right',
1730                 cn : [
1731                     {
1732                         tag : 'button',
1733                         cls : 'btn btn-default',
1734                         html : '<i class="fa fa-repeat"></i>'
1735                     }
1736                 ]
1737             }
1738         ],
1739         DOCUMENT : [
1740             {
1741                 tag : 'div',
1742                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1743                 action : 'rotate-left',
1744                 cn : [
1745                     {
1746                         tag : 'button',
1747                         cls : 'btn btn-default',
1748                         html : '<i class="fa fa-undo"></i>'
1749                     }
1750                 ]
1751             },
1752             {
1753                 tag : 'div',
1754                 cls : 'btn-group roo-upload-cropbox-download',
1755                 action : 'download',
1756                 cn : [
1757                     {
1758                         tag : 'button',
1759                         cls : 'btn btn-default',
1760                         html : '<i class="fa fa-download"></i>'
1761                     }
1762                 ]
1763             },
1764             {
1765                 tag : 'div',
1766                 cls : 'btn-group roo-upload-cropbox-crop',
1767                 action : 'crop',
1768                 cn : [
1769                     {
1770                         tag : 'button',
1771                         cls : 'btn btn-default',
1772                         html : '<i class="fa fa-crop"></i>'
1773                     }
1774                 ]
1775             },
1776             {
1777                 tag : 'div',
1778                 cls : 'btn-group roo-upload-cropbox-trash',
1779                 action : 'trash',
1780                 cn : [
1781                     {
1782                         tag : 'button',
1783                         cls : 'btn btn-default',
1784                         html : '<i class="fa fa-trash"></i>'
1785                     }
1786                 ]
1787             },
1788             {
1789                 tag : 'div',
1790                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1791                 action : 'rotate-right',
1792                 cn : [
1793                     {
1794                         tag : 'button',
1795                         cls : 'btn btn-default',
1796                         html : '<i class="fa fa-repeat"></i>'
1797                     }
1798                 ]
1799             }
1800         ],
1801         ROTATOR : [
1802             {
1803                 tag : 'div',
1804                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1805                 action : 'rotate-left',
1806                 cn : [
1807                     {
1808                         tag : 'button',
1809                         cls : 'btn btn-default',
1810                         html : '<i class="fa fa-undo"></i>'
1811                     }
1812                 ]
1813             },
1814             {
1815                 tag : 'div',
1816                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1817                 action : 'rotate-right',
1818                 cn : [
1819                     {
1820                         tag : 'button',
1821                         cls : 'btn btn-default',
1822                         html : '<i class="fa fa-repeat"></i>'
1823                     }
1824                 ]
1825             }
1826         ]
1827     }
1828 });