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