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         if(this.imageEl.OriginWidth < this.minWidth) {
438             Roo.Msg.show({
439                 title: 'Error',
440                 msg: "Image width should be at least 720",
441                 buttons: {ok : true},
442                 fn: function(res) {
443                     console.log(this);
444                 }
445             });
446         }
447
448         if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
449         
450             this.bodyEl.un('click', this.beforeSelectFile, this);
451             
452             this.notifyEl.hide();
453             this.thumbEl.show();
454             this.footerEl.show();
455             
456             this.baseRotateLevel();
457             
458             if(this.isDocument){
459                 this.setThumbBoxSize();
460             }
461             
462             this.setThumbBoxPosition();
463             
464             this.baseScaleLevel();
465             
466             this.draw();
467             
468             this.resize();
469             
470             this.canvasLoaded = true;
471         
472         }
473         
474         if(this.loadMask){
475             this.maskEl.unmask();
476         }
477         
478     },
479     
480     setCanvasPosition : function()
481     {   
482         if(!this.canvasEl){
483             return;
484         }
485         
486         var pw = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
487         var ph = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
488         
489         this.previewEl.setLeft(pw);
490         this.previewEl.setTop(ph);
491         
492     },
493     
494     onMouseDown : function(e)
495     {   
496         e.stopEvent();
497         
498         this.dragable = true;
499         this.pinching = false;
500         
501         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
502             this.dragable = false;
503             return;
504         }
505         
506         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
507         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
508         
509     },
510     
511     onMouseMove : function(e)
512     {   
513         e.stopEvent();
514         
515         if(!this.canvasLoaded){
516             return;
517         }
518         
519         if (!this.dragable){
520             return;
521         }
522         
523         var minX = Math.ceil(this.thumbEl.getLeft(true));
524         var minY = Math.ceil(this.thumbEl.getTop(true));
525         
526         var maxX = Math.ceil(minX + this.thumbEl.getWidth() - this.canvasEl.width);
527         var maxY = Math.ceil(minY + this.thumbEl.getHeight() - this.canvasEl.height);
528         
529         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
530         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
531         
532         x = x - this.mouseX;
533         y = y - this.mouseY;
534         
535         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
536         var bgY = Math.ceil(y + this.previewEl.getTop(true));
537         
538         bgX = (minX < bgX) ? minX : ((maxX > bgX) ? maxX : bgX);
539         bgY = (minY < bgY) ? minY : ((maxY > bgY) ? maxY : bgY);
540         
541         this.previewEl.setLeft(bgX);
542         this.previewEl.setTop(bgY);
543         
544         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
545         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
546     },
547     
548     onMouseUp : function(e)
549     {   
550         e.stopEvent();
551         
552         this.dragable = false;
553     },
554     
555     onMouseWheel : function(e)
556     {   
557         e.stopEvent();
558         
559         this.startScale = this.scale;
560         console.log("START SCALE: " + this.scale);
561         this.scale = (e.getWheelDelta() == 1) ? (this.scale + 1) : (this.scale - 1);
562         console.log("END SCALE: " + this.scale);
563         if(!this.zoomable()){
564             this.scale = this.startScale;
565             return;
566         }
567         
568         this.draw();
569         
570         return;
571     },
572     
573     zoomable : function()
574     {
575         console.log("THUMBEL");
576         console.log(this.thumbEl);
577         var minScale = this.thumbEl.getWidth() / this.minWidth;
578         
579         if(this.minWidth < this.minHeight){
580             minScale = this.thumbEl.getHeight() / this.minHeight;
581         }
582
583         console.log("MINSCALE: " + minScale);
584         
585         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
586         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
587
588         var maxWidth = this.imageEl.OriginWidth;
589         var maxHeight = this.imageEl.OriginHeight;
590
591         if(this.imageEl.OriginWidth / this.imageEl.OriginHeight  > this.minWidth / this.minHeight && this.imageEl.OriginHeight < this.minHeight) {
592             maxHeight = this.minHeight;
593             maxWidth = this.imageEl.OriginWidth / this.imageEl.OriginHeight * this.minHeight;
594         }
595         if(this.imageEl.OriginWidth / this.imageEl.OriginHeight  < this.minWidth / this.minHeight && this.imageEl.OriginWidth < this.minWidth) {
596             maxWidth = this.minWidth;
597             maxHeight = this.imageEl.OriginHeight /this.imageEl.OriginWidth * this.minWidth;
598         }
599
600         console.log("GETSCALELEVEL: " + this.getScaleLevel());
601         console.log("width: " + width);
602         console.log("height: " + height);
603         console.log("maxWidth: " + maxWidth);
604         console.log("maxHeight: " + maxHeight);
605         
606         if(
607                 this.isDocument &&
608                 (this.rotate == 0 || this.rotate == 180) && 
609                 (
610                     width > this.imageEl.OriginWidth || 
611                     height > this.imageEl.OriginHeight ||
612                     (width < this.minWidth && height < this.minHeight)
613                 )
614         ){
615             return false;
616         }
617         
618         if(
619                 this.isDocument &&
620                 (this.rotate == 90 || this.rotate == 270) && 
621                 (
622                     width > this.imageEl.OriginWidth || 
623                     height > this.imageEl.OriginHeight ||
624                     (width < this.minHeight && height < this.minWidth)
625                 )
626         ){
627             return false;
628         }
629         
630         if(
631                 !this.isDocument &&
632                 (this.rotate == 0 || this.rotate == 180) && 
633                 (
634                     width < this.minWidth ||
635                     height < this.minHeight ||
636                     width > maxWidth ||
637                     height > maxHeight
638                 )
639         ){
640             return false;
641         }
642         
643         if(
644                 !this.isDocument &&
645                 (this.rotate == 90 || this.rotate == 270) && 
646                 (
647                     width < this.minHeight || 
648                     width > this.imageEl.OriginWidth || 
649                     height < this.minWidth || 
650                     height > this.imageEl.OriginHeight
651                 )
652         ){
653             return false;
654         }
655         
656         return true;
657         
658     },
659     
660     onRotateLeft : function(e)
661     {   
662         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
663             
664             var minScale = this.thumbEl.getWidth() / this.minWidth;
665             
666             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
667             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
668             
669             this.startScale = this.scale;
670             
671             while (this.getScaleLevel() < minScale){
672             
673                 this.scale = this.scale + 1;
674                 
675                 if(!this.zoomable()){
676                     break;
677                 }
678                 
679                 if(
680                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
681                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
682                 ){
683                     continue;
684                 }
685                 
686                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
687
688                 this.draw();
689                 
690                 return;
691             }
692             
693             this.scale = this.startScale;
694             
695             this.onRotateFail();
696             
697             return false;
698         }
699         
700         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
701
702         if(this.isDocument){
703             this.setThumbBoxSize();
704             this.setThumbBoxPosition();
705             this.setCanvasPosition();
706         }
707         
708         this.draw();
709         
710         this.fireEvent('rotate', this, 'left');
711         
712     },
713     
714     onRotateRight : function(e)
715     {
716         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
717             
718             var minScale = this.thumbEl.getWidth() / this.minWidth;
719         
720             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
721             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
722             
723             this.startScale = this.scale;
724             
725             while (this.getScaleLevel() < minScale){
726             
727                 this.scale = this.scale + 1;
728                 
729                 if(!this.zoomable()){
730                     break;
731                 }
732                 
733                 if(
734                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
735                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
736                 ){
737                     continue;
738                 }
739                 
740                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
741
742                 this.draw();
743                 
744                 return;
745             }
746             
747             this.scale = this.startScale;
748             
749             this.onRotateFail();
750             
751             return false;
752         }
753         
754         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
755
756         if(this.isDocument){
757             this.setThumbBoxSize();
758             this.setThumbBoxPosition();
759             this.setCanvasPosition();
760         }
761         
762         this.draw();
763         
764         this.fireEvent('rotate', this, 'right');
765     },
766     
767     onRotateFail : function()
768     {
769         this.errorEl.show(true);
770         
771         var _this = this;
772         
773         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
774     },
775     
776     draw : function()
777     {
778         this.previewEl.dom.innerHTML = '';
779         
780         var canvasEl = document.createElement("canvas");
781         
782         var contextEl = canvasEl.getContext("2d");
783         
784         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
785         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
786         var center = this.imageEl.OriginWidth / 2;
787         
788         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
789             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
790             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
791             center = this.imageEl.OriginHeight / 2;
792         }
793         
794         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
795         
796         contextEl.translate(center, center);
797         contextEl.rotate(this.rotate * Math.PI / 180);
798
799         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
800         
801         this.canvasEl = document.createElement("canvas");
802         
803         this.contextEl = this.canvasEl.getContext("2d");
804         
805         switch (this.rotate) {
806             case 0 :
807                 
808                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
809                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
810                 
811                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
812                 
813                 break;
814             case 90 : 
815                 
816                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
817                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
818                 
819                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
820                     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);
821                     break;
822                 }
823                 
824                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
825                 
826                 break;
827             case 180 :
828                 
829                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
830                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
831                 
832                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
833                     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);
834                     break;
835                 }
836                 
837                 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);
838                 
839                 break;
840             case 270 :
841                 
842                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
843                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
844         
845                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
846                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
847                     break;
848                 }
849                 
850                 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);
851                 
852                 break;
853             default : 
854                 break;
855         }
856         
857         this.previewEl.appendChild(this.canvasEl);
858         
859         this.setCanvasPosition();
860     },
861     
862     crop : function()
863     {
864         if(!this.canvasLoaded){
865             return;
866         }
867         
868         var imageCanvas = document.createElement("canvas");
869         
870         var imageContext = imageCanvas.getContext("2d");
871         
872         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
873         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
874         
875         var center = imageCanvas.width / 2;
876         
877         imageContext.translate(center, center);
878         
879         imageContext.rotate(this.rotate * Math.PI / 180);
880         
881         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
882         
883         var canvas = document.createElement("canvas");
884         
885         var context = canvas.getContext("2d");
886                 
887         canvas.width = this.minWidth;
888         canvas.height = this.minHeight;
889
890         switch (this.rotate) {
891             case 0 :
892                 
893                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
894                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
895                 
896                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
897                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
898                 
899                 var targetWidth = this.minWidth - 2 * x;
900                 var targetHeight = this.minHeight - 2 * y;
901                 
902                 var scale = 1;
903                 
904                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
905                     scale = targetWidth / width;
906                 }
907                 
908                 if(x > 0 && y == 0){
909                     scale = targetHeight / height;
910                 }
911                 
912                 if(x > 0 && y > 0){
913                     scale = targetWidth / width;
914                     
915                     if(width < height){
916                         scale = targetHeight / height;
917                     }
918                 }
919                 
920                 context.scale(scale, scale);
921                 
922                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
923                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
924
925                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
926                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
927
928                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
929                 
930                 break;
931             case 90 : 
932                 
933                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
934                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
935                 
936                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
937                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
938                 
939                 var targetWidth = this.minWidth - 2 * x;
940                 var targetHeight = this.minHeight - 2 * y;
941                 
942                 var scale = 1;
943                 
944                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
945                     scale = targetWidth / width;
946                 }
947                 
948                 if(x > 0 && y == 0){
949                     scale = targetHeight / height;
950                 }
951                 
952                 if(x > 0 && y > 0){
953                     scale = targetWidth / width;
954                     
955                     if(width < height){
956                         scale = targetHeight / height;
957                     }
958                 }
959                 
960                 context.scale(scale, scale);
961                 
962                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
963                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
964
965                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
966                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
967                 
968                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
969                 
970                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
971                 
972                 break;
973             case 180 :
974                 
975                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
976                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
977                 
978                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
979                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
980                 
981                 var targetWidth = this.minWidth - 2 * x;
982                 var targetHeight = this.minHeight - 2 * y;
983                 
984                 var scale = 1;
985                 
986                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
987                     scale = targetWidth / width;
988                 }
989                 
990                 if(x > 0 && y == 0){
991                     scale = targetHeight / height;
992                 }
993                 
994                 if(x > 0 && y > 0){
995                     scale = targetWidth / width;
996                     
997                     if(width < height){
998                         scale = targetHeight / height;
999                     }
1000                 }
1001                 
1002                 context.scale(scale, scale);
1003                 
1004                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1005                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1006
1007                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1008                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1009
1010                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1011                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
1012                 
1013                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1014                 
1015                 break;
1016             case 270 :
1017                 
1018                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
1019                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
1020                 
1021                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
1022                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
1023                 
1024                 var targetWidth = this.minWidth - 2 * x;
1025                 var targetHeight = this.minHeight - 2 * y;
1026                 
1027                 var scale = 1;
1028                 
1029                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1030                     scale = targetWidth / width;
1031                 }
1032                 
1033                 if(x > 0 && y == 0){
1034                     scale = targetHeight / height;
1035                 }
1036                 
1037                 if(x > 0 && y > 0){
1038                     scale = targetWidth / width;
1039                     
1040                     if(width < height){
1041                         scale = targetHeight / height;
1042                     }
1043                 }
1044                 
1045                 context.scale(scale, scale);
1046                 
1047                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1048                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1049
1050                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1051                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1052                 
1053                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1054                 
1055                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1056                 
1057                 break;
1058             default : 
1059                 break;
1060         }
1061         
1062         this.cropData = canvas.toDataURL(this.cropType);
1063         
1064         if(this.fireEvent('crop', this, this.cropData) !== false){
1065             this.process(this.file, this.cropData);
1066         }
1067         
1068         return;
1069         
1070     },
1071     
1072     setThumbBoxSize : function()
1073     {
1074         var width, height;
1075         
1076         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
1077             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
1078             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
1079             
1080             this.minWidth = width;
1081             this.minHeight = height;
1082             
1083             if(this.rotate == 90 || this.rotate == 270){
1084                 this.minWidth = height;
1085                 this.minHeight = width;
1086             }
1087         }
1088         
1089         height = 300;
1090         width = Math.ceil(this.minWidth * height / this.minHeight);
1091         
1092         if(this.minWidth > this.minHeight){
1093             width = 300;
1094             height = Math.ceil(this.minHeight * width / this.minWidth);
1095         }
1096         
1097         this.thumbEl.setStyle({
1098             width : width + 'px',
1099             height : height + 'px'
1100         });
1101
1102         return;
1103             
1104     },
1105     
1106     setThumbBoxPosition : function()
1107     {
1108         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
1109         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
1110         
1111         this.thumbEl.setLeft(x);
1112         this.thumbEl.setTop(y);
1113         
1114     },
1115     
1116     baseRotateLevel : function()
1117     {
1118         this.baseRotate = 1;
1119         
1120         if(
1121                 typeof(this.exif) != 'undefined' &&
1122                 typeof(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
1123                 [1, 3, 6, 8].indexOf(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != -1
1124         ){
1125             this.baseRotate = this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']];
1126         }
1127         
1128         this.rotate = Roo.dialog.UploadCropbox['Orientation'][this.baseRotate];
1129         
1130     },
1131     
1132     baseScaleLevel : function()
1133     {
1134         var width, height;
1135         
1136         if(this.isDocument){
1137             
1138             if(this.baseRotate == 6 || this.baseRotate == 8){
1139             
1140                 height = this.thumbEl.getHeight();
1141                 this.baseScale = height / this.imageEl.OriginWidth;
1142
1143                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
1144                     width = this.thumbEl.getWidth();
1145                     this.baseScale = width / this.imageEl.OriginHeight;
1146                 }
1147
1148                 return;
1149             }
1150
1151             height = this.thumbEl.getHeight();
1152             this.baseScale = height / this.imageEl.OriginHeight;
1153
1154             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
1155                 width = this.thumbEl.getWidth();
1156                 this.baseScale = width / this.imageEl.OriginWidth;
1157             }
1158
1159             return;
1160         }
1161         
1162         if(this.baseRotate == 6 || this.baseRotate == 8){
1163             
1164             width = this.thumbEl.getHeight();
1165             this.baseScale = width / this.imageEl.OriginHeight;
1166             
1167             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
1168                 height = this.thumbEl.getWidth();
1169                 this.baseScale = height / this.imageEl.OriginHeight;
1170             }
1171             
1172             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1173                 height = this.thumbEl.getWidth();
1174                 this.baseScale = height / this.imageEl.OriginHeight;
1175                 
1176                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
1177                     width = this.thumbEl.getHeight();
1178                     this.baseScale = width / this.imageEl.OriginWidth;
1179                 }
1180             }
1181             
1182             return;
1183         }
1184         
1185         width = this.thumbEl.getWidth();
1186         this.baseScale = width / this.imageEl.OriginWidth;
1187         
1188         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
1189             height = this.thumbEl.getHeight();
1190             this.baseScale = height / this.imageEl.OriginHeight;
1191         }
1192         
1193         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1194             
1195             height = this.thumbEl.getHeight();
1196             this.baseScale = height / this.imageEl.OriginHeight;
1197             
1198             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
1199                 width = this.thumbEl.getWidth();
1200                 this.baseScale = width / this.imageEl.OriginWidth;
1201             }
1202             
1203         }
1204         
1205         return;
1206     },
1207     
1208     getScaleLevel : function()
1209     {
1210         console.log("BASESCALE: " + this.baseScale);
1211         return this.baseScale * Math.pow(1.02, this.scale);
1212     },
1213     
1214     onTouchStart : function(e)
1215     {
1216         if(!this.canvasLoaded){
1217             this.beforeSelectFile(e);
1218             return;
1219         }
1220         
1221         var touches = e.browserEvent.touches;
1222         
1223         if(!touches){
1224             return;
1225         }
1226         
1227         if(touches.length == 1){
1228             this.onMouseDown(e);
1229             return;
1230         }
1231         
1232         if(touches.length != 2){
1233             return;
1234         }
1235         
1236         var coords = [];
1237         
1238         for(var i = 0, finger; finger = touches[i]; i++){
1239             coords.push(finger.pageX, finger.pageY);
1240         }
1241         
1242         var x = Math.pow(coords[0] - coords[2], 2);
1243         var y = Math.pow(coords[1] - coords[3], 2);
1244         
1245         this.startDistance = Math.sqrt(x + y);
1246         
1247         this.startScale = this.scale;
1248         
1249         this.pinching = true;
1250         this.dragable = false;
1251         
1252     },
1253     
1254     onTouchMove : function(e)
1255     {
1256         if(!this.pinching && !this.dragable){
1257             return;
1258         }
1259         
1260         var touches = e.browserEvent.touches;
1261         
1262         if(!touches){
1263             return;
1264         }
1265         
1266         if(this.dragable){
1267             this.onMouseMove(e);
1268             return;
1269         }
1270         
1271         var coords = [];
1272         
1273         for(var i = 0, finger; finger = touches[i]; i++){
1274             coords.push(finger.pageX, finger.pageY);
1275         }
1276         
1277         var x = Math.pow(coords[0] - coords[2], 2);
1278         var y = Math.pow(coords[1] - coords[3], 2);
1279         
1280         this.endDistance = Math.sqrt(x + y);
1281         
1282         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
1283         
1284         if(!this.zoomable()){
1285             this.scale = this.startScale;
1286             return;
1287         }
1288         
1289         this.draw();
1290         
1291     },
1292     
1293     onTouchEnd : function(e)
1294     {
1295         this.pinching = false;
1296         this.dragable = false;
1297         
1298     },
1299     
1300     process : function(file, crop)
1301     {
1302         if(this.loadMask){
1303             this.maskEl.mask(this.loadingText);
1304         }
1305         
1306         this.xhr = new XMLHttpRequest();
1307         
1308         file.xhr = this.xhr;
1309
1310         this.xhr.open(this.method, this.url, true);
1311         
1312         var headers = {
1313             "Accept": "application/json",
1314             "Cache-Control": "no-cache",
1315             "X-Requested-With": "XMLHttpRequest"
1316         };
1317         
1318         for (var headerName in headers) {
1319             var headerValue = headers[headerName];
1320             if (headerValue) {
1321                 this.xhr.setRequestHeader(headerName, headerValue);
1322             }
1323         }
1324         
1325         var _this = this;
1326         
1327         this.xhr.onload = function()
1328         {
1329             _this.xhrOnLoad(_this.xhr);
1330         }
1331         
1332         this.xhr.onerror = function()
1333         {
1334             _this.xhrOnError(_this.xhr);
1335         }
1336         
1337         var formData = new FormData();
1338
1339         formData.append('returnHTML', 'NO');
1340         
1341         if(crop){
1342             formData.append('crop', crop);
1343         }
1344         
1345         if(typeof(file) != 'undefined' && (typeof(file.id) == 'undefined' || file.id * 1 < 1)){
1346             formData.append(this.paramName, file, file.name);
1347         }
1348         
1349         if(typeof(file.filename) != 'undefined'){
1350             formData.append('filename', file.filename);
1351         }
1352         
1353         if(typeof(file.mimetype) != 'undefined'){
1354             formData.append('mimetype', file.mimetype);
1355         }
1356         
1357         if(this.fireEvent('arrange', this, formData) != false){
1358             this.xhr.send(formData);
1359         };
1360     },
1361     
1362     xhrOnLoad : function(xhr)
1363     {
1364         if(this.loadMask){
1365             this.maskEl.unmask();
1366         }
1367         
1368         if (xhr.readyState !== 4) {
1369             this.fireEvent('exception', this, xhr);
1370             return;
1371         }
1372
1373         var response = Roo.decode(xhr.responseText);
1374         
1375         if(!response.success){
1376             this.fireEvent('exception', this, xhr);
1377             return;
1378         }
1379         
1380         var response = Roo.decode(xhr.responseText);
1381         
1382         this.fireEvent('upload', this, response);
1383         
1384     },
1385     
1386     xhrOnError : function()
1387     {
1388         if(this.loadMask){
1389             this.maskEl.unmask();
1390         }
1391         
1392         Roo.log('xhr on error');
1393         
1394         var response = Roo.decode(xhr.responseText);
1395           
1396         Roo.log(response);
1397         
1398     },
1399     
1400     prepare : function(file)
1401     {   
1402         if(this.loadMask){
1403             this.maskEl.mask(this.loadingText);
1404         }
1405         
1406         this.file = false;
1407         this.exif = {};
1408         
1409         if(typeof(file) === 'string'){
1410             this.loadCanvas(file);
1411             return;
1412         }
1413         
1414         if(!file || !this.urlAPI){
1415             return;
1416         }
1417         
1418         this.file = file;
1419         this.cropType = file.type;
1420         
1421         var _this = this;
1422         
1423         if(this.fireEvent('prepare', this, this.file) != false){
1424             
1425             var reader = new FileReader();
1426             
1427             reader.onload = function (e) {
1428                 if (e.target.error) {
1429                     Roo.log(e.target.error);
1430                     return;
1431                 }
1432                 
1433                 var buffer = e.target.result,
1434                     dataView = new DataView(buffer),
1435                     offset = 2,
1436                     maxOffset = dataView.byteLength - 4,
1437                     markerBytes,
1438                     markerLength;
1439                 
1440                 if (dataView.getUint16(0) === 0xffd8) {
1441                     while (offset < maxOffset) {
1442                         markerBytes = dataView.getUint16(offset);
1443                         
1444                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
1445                             markerLength = dataView.getUint16(offset + 2) + 2;
1446                             if (offset + markerLength > dataView.byteLength) {
1447                                 Roo.log('Invalid meta data: Invalid segment size.');
1448                                 break;
1449                             }
1450                             
1451                             if(markerBytes == 0xffe1){
1452                                 _this.parseExifData(
1453                                     dataView,
1454                                     offset,
1455                                     markerLength
1456                                 );
1457                             }
1458                             
1459                             offset += markerLength;
1460                             
1461                             continue;
1462                         }
1463                         
1464                         break;
1465                     }
1466                     
1467                 }
1468                 
1469                 var url = _this.urlAPI.createObjectURL(_this.file);
1470                 
1471                 _this.loadCanvas(url);
1472                 
1473                 return;
1474             }
1475             
1476             reader.readAsArrayBuffer(this.file);
1477             
1478         }
1479         
1480     },
1481     
1482     parseExifData : function(dataView, offset, length)
1483     {
1484         var tiffOffset = offset + 10,
1485             littleEndian,
1486             dirOffset;
1487     
1488         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1489             // No Exif data, might be XMP data instead
1490             return;
1491         }
1492         
1493         // Check for the ASCII code for "Exif" (0x45786966):
1494         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1495             // No Exif data, might be XMP data instead
1496             return;
1497         }
1498         if (tiffOffset + 8 > dataView.byteLength) {
1499             Roo.log('Invalid Exif data: Invalid segment size.');
1500             return;
1501         }
1502         // Check for the two null bytes:
1503         if (dataView.getUint16(offset + 8) !== 0x0000) {
1504             Roo.log('Invalid Exif data: Missing byte alignment offset.');
1505             return;
1506         }
1507         // Check the byte alignment:
1508         switch (dataView.getUint16(tiffOffset)) {
1509         case 0x4949:
1510             littleEndian = true;
1511             break;
1512         case 0x4D4D:
1513             littleEndian = false;
1514             break;
1515         default:
1516             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
1517             return;
1518         }
1519         // Check for the TIFF tag marker (0x002A):
1520         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
1521             Roo.log('Invalid Exif data: Missing TIFF marker.');
1522             return;
1523         }
1524         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
1525         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
1526         
1527         this.parseExifTags(
1528             dataView,
1529             tiffOffset,
1530             tiffOffset + dirOffset,
1531             littleEndian
1532         );
1533     },
1534     
1535     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
1536     {
1537         var tagsNumber,
1538             dirEndOffset,
1539             i;
1540         if (dirOffset + 6 > dataView.byteLength) {
1541             Roo.log('Invalid Exif data: Invalid directory offset.');
1542             return;
1543         }
1544         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
1545         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
1546         if (dirEndOffset + 4 > dataView.byteLength) {
1547             Roo.log('Invalid Exif data: Invalid directory size.');
1548             return;
1549         }
1550         for (i = 0; i < tagsNumber; i += 1) {
1551             this.parseExifTag(
1552                 dataView,
1553                 tiffOffset,
1554                 dirOffset + 2 + 12 * i, // tag offset
1555                 littleEndian
1556             );
1557         }
1558         // Return the offset to the next directory:
1559         return dataView.getUint32(dirEndOffset, littleEndian);
1560     },
1561     
1562     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
1563     {
1564         var tag = dataView.getUint16(offset, littleEndian);
1565         
1566         this.exif[tag] = this.getExifValue(
1567             dataView,
1568             tiffOffset,
1569             offset,
1570             dataView.getUint16(offset + 2, littleEndian), // tag type
1571             dataView.getUint32(offset + 4, littleEndian), // tag length
1572             littleEndian
1573         );
1574     },
1575     
1576     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
1577     {
1578         var tagType = Roo.dialog.UploadCropbox.exifTagTypes[type],
1579             tagSize,
1580             dataOffset,
1581             values,
1582             i,
1583             str,
1584             c;
1585     
1586         if (!tagType) {
1587             Roo.log('Invalid Exif data: Invalid tag type.');
1588             return;
1589         }
1590         
1591         tagSize = tagType.size * length;
1592         // Determine if the value is contained in the dataOffset bytes,
1593         // or if the value at the dataOffset is a pointer to the actual data:
1594         dataOffset = tagSize > 4 ?
1595                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
1596         if (dataOffset + tagSize > dataView.byteLength) {
1597             Roo.log('Invalid Exif data: Invalid data offset.');
1598             return;
1599         }
1600         if (length === 1) {
1601             return tagType.getValue(dataView, dataOffset, littleEndian);
1602         }
1603         values = [];
1604         for (i = 0; i < length; i += 1) {
1605             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
1606         }
1607         
1608         if (tagType.ascii) {
1609             str = '';
1610             // Concatenate the chars:
1611             for (i = 0; i < values.length; i += 1) {
1612                 c = values[i];
1613                 // Ignore the terminating NULL byte(s):
1614                 if (c === '\u0000') {
1615                     break;
1616                 }
1617                 str += c;
1618             }
1619             return str;
1620         }
1621         return values;
1622     }
1623     
1624 });
1625
1626 Roo.apply(Roo.dialog.UploadCropbox, {
1627     tags : {
1628         'Orientation': 0x0112
1629     },
1630     
1631     Orientation: {
1632             1: 0, //'top-left',
1633 //            2: 'top-right',
1634             3: 180, //'bottom-right',
1635 //            4: 'bottom-left',
1636 //            5: 'left-top',
1637             6: 90, //'right-top',
1638 //            7: 'right-bottom',
1639             8: 270 //'left-bottom'
1640     },
1641     
1642     exifTagTypes : {
1643         // byte, 8-bit unsigned int:
1644         1: {
1645             getValue: function (dataView, dataOffset) {
1646                 return dataView.getUint8(dataOffset);
1647             },
1648             size: 1
1649         },
1650         // ascii, 8-bit byte:
1651         2: {
1652             getValue: function (dataView, dataOffset) {
1653                 return String.fromCharCode(dataView.getUint8(dataOffset));
1654             },
1655             size: 1,
1656             ascii: true
1657         },
1658         // short, 16 bit int:
1659         3: {
1660             getValue: function (dataView, dataOffset, littleEndian) {
1661                 return dataView.getUint16(dataOffset, littleEndian);
1662             },
1663             size: 2
1664         },
1665         // long, 32 bit int:
1666         4: {
1667             getValue: function (dataView, dataOffset, littleEndian) {
1668                 return dataView.getUint32(dataOffset, littleEndian);
1669             },
1670             size: 4
1671         },
1672         // rational = two long values, first is numerator, second is denominator:
1673         5: {
1674             getValue: function (dataView, dataOffset, littleEndian) {
1675                 return dataView.getUint32(dataOffset, littleEndian) /
1676                     dataView.getUint32(dataOffset + 4, littleEndian);
1677             },
1678             size: 8
1679         },
1680         // slong, 32 bit signed int:
1681         9: {
1682             getValue: function (dataView, dataOffset, littleEndian) {
1683                 return dataView.getInt32(dataOffset, littleEndian);
1684             },
1685             size: 4
1686         },
1687         // srational, two slongs, first is numerator, second is denominator:
1688         10: {
1689             getValue: function (dataView, dataOffset, littleEndian) {
1690                 return dataView.getInt32(dataOffset, littleEndian) /
1691                     dataView.getInt32(dataOffset + 4, littleEndian);
1692             },
1693             size: 8
1694         }
1695     },
1696     
1697     footer : {
1698         STANDARD : [
1699             {
1700                 tag : 'div',
1701                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1702                 action : 'rotate-left',
1703                 cn : [
1704                     {
1705                         tag : 'button',
1706                         cls : 'btn btn-default',
1707                         html : '<i class="fa fa-undo"></i>'
1708                     }
1709                 ]
1710             },
1711             {
1712                 tag : 'div',
1713                 cls : 'btn-group roo-upload-cropbox-picture',
1714                 action : 'picture',
1715                 cn : [
1716                     {
1717                         tag : 'button',
1718                         cls : 'btn btn-default',
1719                         html : '<i class="fa fa-picture-o"></i>'
1720                     }
1721                 ]
1722             },
1723             {
1724                 tag : 'div',
1725                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1726                 action : 'rotate-right',
1727                 cn : [
1728                     {
1729                         tag : 'button',
1730                         cls : 'btn btn-default',
1731                         html : '<i class="fa fa-repeat"></i>'
1732                     }
1733                 ]
1734             }
1735         ],
1736         DOCUMENT : [
1737             {
1738                 tag : 'div',
1739                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1740                 action : 'rotate-left',
1741                 cn : [
1742                     {
1743                         tag : 'button',
1744                         cls : 'btn btn-default',
1745                         html : '<i class="fa fa-undo"></i>'
1746                     }
1747                 ]
1748             },
1749             {
1750                 tag : 'div',
1751                 cls : 'btn-group roo-upload-cropbox-download',
1752                 action : 'download',
1753                 cn : [
1754                     {
1755                         tag : 'button',
1756                         cls : 'btn btn-default',
1757                         html : '<i class="fa fa-download"></i>'
1758                     }
1759                 ]
1760             },
1761             {
1762                 tag : 'div',
1763                 cls : 'btn-group roo-upload-cropbox-crop',
1764                 action : 'crop',
1765                 cn : [
1766                     {
1767                         tag : 'button',
1768                         cls : 'btn btn-default',
1769                         html : '<i class="fa fa-crop"></i>'
1770                     }
1771                 ]
1772             },
1773             {
1774                 tag : 'div',
1775                 cls : 'btn-group roo-upload-cropbox-trash',
1776                 action : 'trash',
1777                 cn : [
1778                     {
1779                         tag : 'button',
1780                         cls : 'btn btn-default',
1781                         html : '<i class="fa fa-trash"></i>'
1782                     }
1783                 ]
1784             },
1785             {
1786                 tag : 'div',
1787                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1788                 action : 'rotate-right',
1789                 cn : [
1790                     {
1791                         tag : 'button',
1792                         cls : 'btn btn-default',
1793                         html : '<i class="fa fa-repeat"></i>'
1794                     }
1795                 ]
1796             }
1797         ],
1798         ROTATOR : [
1799             {
1800                 tag : 'div',
1801                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1802                 action : 'rotate-left',
1803                 cn : [
1804                     {
1805                         tag : 'button',
1806                         cls : 'btn btn-default',
1807                         html : '<i class="fa fa-undo"></i>'
1808                     }
1809                 ]
1810             },
1811             {
1812                 tag : 'div',
1813                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1814                 action : 'rotate-right',
1815                 cn : [
1816                     {
1817                         tag : 'button',
1818                         cls : 'btn btn-default',
1819                         html : '<i class="fa fa-repeat"></i>'
1820                     }
1821                 ]
1822             }
1823         ]
1824     }
1825 });