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