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