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