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