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