    <?xml version="1.0" encoding="utf-8"?>
    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="540" height="600" creationComplete="init()" verticalScrollPolicy="off" horizontalScrollPolicy="off" backgroundColor="#ffffff" borderStyle="none" borderColor="#ffffff">
    <mx:Style>
            @font-face {
                fontFamily: "Arial";
                fontWeight: bold;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Arial");
            }
            @font-face {
                fontFamily: "Arial";
                fontWeight: normal;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Arial");
            }
            @font-face {
                fontFamily: "Arial";
                fontWeight: bold;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Arial");
            }
            @font-face {
                fontFamily: "Arial";
                fontWeight: normal;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Arial");
            }
            @font-face {
                fontFamily: "Verdana";
                fontWeight: bold;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Verdana");
            }
            @font-face {
                fontFamily: "Verdana";
                fontWeight: normal;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Verdana");
            }
            @font-face {
                fontFamily: "Verdana";
                fontWeight: bold;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Verdana");
            }
            @font-face {
                fontFamily: "Verdana";
                fontWeight: normal;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Verdana");
            }
            @font-face {
                fontFamily: "Times New Roman";
                fontWeight: bold;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Times New Roman");
            }
            @font-face {
                fontFamily: "Times New Roman";
                fontWeight: normal;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Times New Roman");
            }
            @font-face {
                fontFamily: "Times New Roman";
                fontWeight: bold;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Times New Roman");
            }
            @font-face {
                fontFamily: "Times New Roman";
                fontWeight: normal;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Times New Roman");
            }
             @font-face {
                fontFamily: "Georgia";
                fontWeight: bold;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Georgia");
            }
            @font-face {
                fontFamily: "Georgia";
                fontWeight: normal;
                fontStyle: italic;
                unicode-range: U+0020-U+00F9;
                src: local("Georgia");
            }
            @font-face {
                fontFamily: "Georgia";
                fontWeight: bold;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Georgia");
            }
            @font-face {
                fontFamily: "Georgia";
                fontWeight: normal;
                fontStyle: normal;
                unicode-range: U+0020-U+00F9;
                src: local("Georgia");
            }
    </mx:Style>
        <mx:Script>
            <![CDATA[
            // vou incluir nesse script todas as funcoes do componente original que nao estavam sendo utilizadas
            // que podem ser uteis.
            // mainCanvas administra a area de desenho o resultado esta 10 vezes menor que o tamanho oficial final
            // que é de 31 X 45 cm , os clipArts serao reescalados para 10 vezes menor mas o elemento container inteiro deve ter sua
            // escala multiplicada por 10 para dar a saida final , caso os valores mudem isso tem de ser trocado.
                /////////////
                // Imports //
                /////////////
                import mx.containers.Canvas;
                import mx.controls.TileList;
                import flash.errors.IOError;
                import flash.utils.ByteArray;
                import mx.containers.Panel;
                import mx.events.FlexEvent;
                import mx.containers.Canvas;
                import mx.events.SliderEvent;
                import mx.containers.VBox;
                import mx.containers.TabNavigator;
                import mx.controls.Label;
                import mx.controls.Button;
                import mx.containers.HBox;
                import mx.controls.VRule;
                import mx.core.ScrollPolicy;
                import mx.controls.HSlider;
                import mx.styles.CSSStyleDeclaration;
                import mx.styles.StyleManager;
                import mx.controls.Image;
                import mx.controls.SWFLoader;
                import mx.controls.Alert;
                import mx.events.ResizeEvent;
                import mx.events.IndexChangedEvent;
                import mx.controls.Alert;
                import flash.net.*;
                import flash.events.*;
                import flash.display.Loader;
                import flash.display.Sprite;
                import flash.display.BitmapData;
                import flash.events.TimerEvent;
                import flash.utils.Timer;
                import flash.geom.Matrix;
                import flash.display.Bitmap;
                import flash.geom.Point;
                import flash.geom.Rectangle;
                import flash.filters.ColorMatrixFilter;
                import flash.filters.ConvolutionFilter;
                import components.com.gskinner.geom.ColorMatrix;
                import flash.ui.Mouse;
                import mx.controls.ColorPicker;
                import components.Tools.*;
                import mx.events.ColorPickerEvent;
                import mx.controls.ComboBox;
                import mx.controls.NumericStepper;
                import mx.controls.TextArea;
                import mx.events.NumericStepperEvent;
                import mx.controls.Text;
                import components.Bitmap.Picture;
                import mx.graphics.codec.*;
                import mx.core.ClassFactory;
                import mx.events.ListEvent;

                public const URLREMOTA:String="http://www.4e-commerce.com.br/caliopes/crex_read.php";

                ////////////////
                // Eventos... //
                ////////////////

                // evento que indica quando a imagem que o usuario mandou
                // ja esta pronta para ser editada
                [Event(name="IMAGEREADY", type="flash.events.Event")]

                // evento dispachado quando completou o processamento da imagem
                [Event(name="COMPLETE", type="flash.events.Event")]

                // evento dispachado quando deu um erro no processo de upload da imagem
                [Event(name="ERROR", type="flash.events.Event")]

                [Event(name="SECURITY_ERROR", type="flash.events.Event")]

                ///////////////
                // Embeds... //
                ///////////////

                // animação de quando esta carregando a imagem
                [Embed(source="assets/processing.swf")]
                public var anim:Class;

                public static var panelWidth:int = 480; // tamanho do painel de desenho , esta como estatico pq o tamanho eh identico na frente e fundo das camisas
                public static var panelHeight:int = 440;

                // mensagens que irao aparecer para avisar o usuario do que deve fazer o label cmt eh que recebe essas mensagens
                private var _cmtWelcome:String = "Mande sua imagem ou use as ferramentas de desenho.";

                public var canvasStyle:CSSStyleDeclaration;
                private var _file:FileReference;
                private var fileTypes:FileFilter = new FileFilter("Imagens (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
                private var _maxImageSize:int = 1048600; // Tamanho maximo da imagem que o usuario esta mandando definido aqui com 1 mega
                private var _cmtMaxImageFile:String = "Desculpe, o tamanho m\u00e1ximo da imagem \u00e9: ";
                public var imgLoc:String="";
                private var _rawPixLocation:String = "pix";
                private var _processedPixLocation:String = "processed";
                private var _filePath:String = "http://www.4e-commerce.com.br/caliopes/process.php";
                private var _basePath:String;
                public var mainImage:Loader; // onde carrega as imagens que o usuario manda
                public var resizeBorder:BannerRect; // essa eh a borda que controla o scale dos objetos selecionados
                public var currentTarget:*; // o que esta sendo editado no momento (texto , imagem , desenho..)
                public var currentTool:*; // qual a ferramenta que esta atuando no momento sobre o elemento no canvas
                public var dragging:Boolean = false; // caso esteja ocorrendo um deslocamento de elementos no canvas
                public var cmMatrix:ColorMatrix;
                public var guide:SpriteCanvas; // o guide eh um auxiliar para delinear a area de desenho nao usado por enquanto
                private var _showGuide:Boolean = true; // define se o grid definido acima eh mostrado ou nao
                private var _guideWidth:int = 160;
                private var _guideHeight:int = 120;
                public var finalBMP:BitmapData; // imagem final processada ainda como BitmapData fica aqui

                [Bindable]
                public var anchor:String = ''; // armazena qual ponto de controle do objeto selecionado esta ativado no momento (serve para o resize do elemento selecionado)
                private var boxName:*; // cada um dos pontos de controle eh um box com um nome que define que ponto ele esta no elemento (TL = TopLeft , etc...)
                public var xMouseOffset:Number = 5; // auxiliares para mover os elementos dentro do canvas principal
                public var yMouseOffset:Number = 5;
                public var oldWidth:Number; // auxiliares para resize
                public var oldHeight:Number;
                public var processing:Boolean;
                public var visuals:Canvas;
                public var loader:URLLoader;
                public var fileName:String = '';
                private var _quality:int = 100; // qualidade do jpg
                private var _imageType:String = "jpg";
                private var _clientGetsCopy:Boolean = true; // define se o cliente pega um resultado da imagem modificada ou nao

                public var tool:String; // string definindo qual ferramenta de desenho esta sendo usada
                public var pointer:BannerPointer; // define o pointer do cursor a medida que se trocam as ferramentas
                public var container:SpriteCanvas; // esse eh o srpite principal que contem o que esta sendo editado, tudo eh adicionado a ele

                public var processingAnim:SWFLoader;
                private var _jpegEncoder:JPEGEncoder;
                private var _pngEncoder:PNGEncoder;
                public var request:URLRequest;
                private var _clipArtSource:String = ''; // diretorio onde estao as imagens do clipart
                public var clipArchive:Array;
                public var tile_List:TileList;
                public var finalFile:String = ''; // arquivo final que contem a imagem processada ja no formato de saida
                private var _addFonts:Array; // podemos adicionar fontes lembrando do problema de tamanho pelas fontes embuidas

                ////////////////////////////////////////////
                // getter setters que expoem o componente //
                ////////////////////////////////////////////

                [Inspectable(defaultValue=null)]
                public function set addFonts(value:Array):void {
                    _addFonts = value;
                    for (var f:int=0; f < value.length; f++ ){
                        cmbFont.dataProvider.addItem( {label:value[f]} );
                    }
                }
                public function get addFonts():Array {
                    return _addFonts;
                }
                [Inspectable(defaultValue="")]
                public function set clipArtSource(value:String):void {
                    _clipArtSource = value;
                    loadClipArt(value);
                }
                public function get clipArtSource():String {
                    return _clipArtSource;
                }
                [Inspectable(defaultValue=1048600)]
                public function set maxImageSize(value:int):void {
                    _maxImageSize = value;
                }
                public function get maxImageSize():int {
                    return _maxImageSize;
                }
                [Inspectable(defaultValue="http://www.4e-commerce.com.br/caliopes/process.php")]
                public function set filePath(value:String):void {
                    _filePath = value;
                }
                public function get filePath():String {
                    return _filePath;
                }
                [Inspectable(defaultValue="processed")]
                public function set processedPixLocation(value:String):void {
                    _processedPixLocation = value;
                }
                public function get processedPixLocation():String {
                    return _processedPixLocation;
                }
                [Inspectable(defaultValue="../pix")]
                public function set rawPixLocation(value:String):void {
                    _rawPixLocation = value;
                }
                public function get rawPixLocation():String {
                    return _rawPixLocation;
                }
                [Inspectable(defaultValue=true)]
                public function set clientGetsCopy(value:Boolean):void {
                    _clientGetsCopy = value;
                }
                public function get clientGetsCopy():Boolean {
                    return _clientGetsCopy;
                }
                [Inspectable(defaultValue="jpg")]
                public function set imageType(value:String):void {
                    _imageType = value;
                }
                public function get imageType():String {
                    return _imageType;
                }
                [Inspectable(defaultValue=100)]
                public function set quality(value:int):void {
                    _quality = value;
                }
                public function get quality():int {
                    return _quality;
                }
                [Inspectable(defaultValue=160)]
                public function set guideWidth(value:int):void {
                    _guideWidth = value;
                    try{
                    guide.graphics.clear();
                    drawGuide();
                    guide.x = Math.round((mainCanvas.width - _guideWidth)/2);
                    guide.y = Math.round((mainCanvas.height - _guideHeight)/2);
                    guide.visible = _showGuide;}catch(e:Error){}
                }
                public function get guideWidth():int {
                    return _guideWidth;
                }
                [Inspectable(defaultValue=120)]
                public function set guideHeight(value:int):void {
                    _guideHeight = value;
                    try{
                    guide.graphics.clear();
                    drawGuide();
                    guide.x = Math.round((mainCanvas.width - _guideWidth)/2);
                    guide.y = Math.round((mainCanvas.height - _guideHeight)/2);
                    guide.visible = _showGuide;}catch(e:Error){}
                }
                public function get guideHeight():int {
                    return _guideHeight;
                }
                [Inspectable(defaultValue=true)]
                public function set showGuide(value:Boolean):void {
                    _showGuide = value;
                    if (guide != null)guide.visible = _showGuide;
                }
                public function get showGuide():Boolean {
                    return _showGuide;
                }

                /////////////////////////
                // inicio da aplicacao //
                /////////////////////////

                private function init():void {
                    addEventListener("resize", sizeHandler);
                    initContainer();

                    mainImage = new Loader();

                    initTabControls();

                    cmt.text = _cmtWelcome;

                    mainCanvas.addChild(container);

                    sizeFn();
                    this.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
                }

                // a funcao abaixo inicializa o container que eh o sprite que contem tudo que foi desenhado
                private function initContainer():void{
                    container = new SpriteCanvas();
                    tool = "too";
                    pointer = new BannerPointer();
                    pointer.visible = false;
                    guide = new SpriteCanvas();
                    processing = false;
                    resizeBorder = new BannerRect();
                    currentTarget = null;
                    _basePath = _filePath.substring(0, _filePath.lastIndexOf('/'));
                    _basePath = _basePath.substring(0, _basePath.lastIndexOf('/'));
                    container.addChild(resizeBorder);
                    resizeBorder.visible = false;
                    drawGuide();
                    guide.visible = _showGuide;
                    mainCanvas.addEventListener(MouseEvent.MOUSE_DOWN, mainCanvasDown);
                    mainCanvas.addEventListener(MouseEvent.MOUSE_UP, mainCanvasUp);
                    mainCanvas.addEventListener(ResizeEvent.RESIZE , posGuide);
                    mainCanvas.addEventListener(MouseEvent.MOUSE_OUT, mainCanvasOut);
                    canvasStyle = new CSSStyleDeclaration("canvasStyle");
                    canvasStyle.setStyle("borderStyle", "solid");
                    canvasStyle.setStyle("borderColor", 0xffffff);
                    canvasStyle.setStyle("backgroundAlpha", 1);
                    canvasStyle.setStyle("backgroundColor", 0xffffff);
                    StyleManager.setStyleDeclaration("Canvas",canvasStyle,true);
                    container.addChild(pointer);
                    container.mask = masker;
                }

                // pode ser feito em MXML mas por enquanto esta via AS apenas apaga os icones que indicam que os botoes de
                // focus e sharp estao ativados.
                public function initTabControls():void{
                    focusBlur.visible = focusSharp.visible = false;
                }
                // identico para as ferramentas de desenho
                public function initTabDraw():void{
                    focusRec.visible = focusCir.visible = focusLin.visible = false;    focusToo.visible = true;
                }
                // identico para as de texto
                public function initTabText():void{

                }
                // esse eh o mais chato que inicializa os clips que serao carregados.
                public function initTabClip():void{
                    //if (_showClipTab) { // caso esteja num tabNavigator melhor deixar essa variavel definida
                        tile_List = new TileList();
                        tile_List.itemRenderer = new ClassFactory(components.Tools.visualThumb);
                        tile_List.percentWidth = 100;
                        tile_List.percentHeight = 100;
                        tile_List.height = 104;
                        tile_List.setStyle("left", 10);
                        tile_List.setStyle("right", 4);
                        tile_List.setStyle("top", 0);
                        tile_List.setStyle("bottom", 10);
                        tile_List.setStyle("backgroundColor", 0xFFFFFF);
                        tile_List.setStyle("backgroundAlpha", 0);
                        tile_List.setStyle("borderStyle", "none");
                        tile_List.setStyle("focusAlpha", 0.5);
                        tile_List.direction = "horizontal";
                        tabClip.horizontalScrollPolicy = ScrollPolicy.OFF;
                        tabClip.verticalScrollPolicy = ScrollPolicy.OFF;
                        tile_List.columnWidth = 72;
                        tile_List.addEventListener(ListEvent.ITEM_CLICK, function (event:ListEvent):void {
                            mainImage = new Loader(); // mainImage contem a imagem que selecionada e em imgLoaded deve ocorrer o rescale para 10 X menos
                            mainImage.load(new URLRequest(clipArchive[event.currentTarget.selectedIndex].src));
                            mainImage.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
                            mainImage.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (event:IOErrorEvent):void {
                                dispatchEvent(new Event("ERROR"));
                                Alert.show("Erro carregando imagem", "Clip Art");
                            });
                            mainImage.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (event:SecurityError):void {
                                dispatchEvent(new Event("SECURITY_ERROR"));
                                Alert.show("Erro carregando imagem", "Clip Art");
                            });
                            cmt.text = "Carregando imagem para uso...";
                            dispatchEvent(new Event("IMAGEREADY"));
                        });
                        tile_List.selectable = true;

                        tabClipContainer.addChild(tile_List);
                    //}
                    loadClipArt(_clipArtSource);
                }
                // funcao que sera usada para carregar uma imagem na tela que veio de uma queryString
                public function loadQueryStringImage(img:String):void {
                    mainImage = new Loader();
                    if(img==null){
                        img="";
                    }
                    mainImage.load(new URLRequest('http://www.4e-commerce.com.br/caliopes/processed/'+img));
                    mainImage.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
                    mainImage.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (event:IOErrorEvent):void {
                        dispatchEvent(new Event("ERROR"));
                        //Alert.show("IO Error", "Query String");
                    });
                    mainImage.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (event:SecurityError):void {
                        dispatchEvent(new Event("SECURITY_ERROR"));
                        Alert.show("Security Error", "Query String");
                    });
                    cmt.text = "Carregando imagem para uso...";
                    dispatchEvent(new Event("IMAGEREADY"));
                }

                // isolando os tabs que vao aparecer de acordo com o evento de click dos botoes
                public function showTabDraw(evt:Event):void{
                    tabDraw.visible = true;
                    tabText.visible = false;
                    tabClip.visible = false;
                }
                public function showTabText(evt:Event):void{
                    tabDraw.visible = false;
                    tabText.visible = true;
                    tabClip.visible = false;
                }
                public function showTabClip(evt:Event):void{
                    tabDraw.visible = false;
                    tabText.visible = false;
                    tabClip.visible = true;
                }

                private function sizeHandler(eventObj:Event):void{
                    sizeFn();
                }
                private function sizeFn():void{
                    width = (width < panelWidth) ? panelWidth : width;
                    height = (height < panelHeight) ? panelHeight : height;
                }
                private function posGuide(event:ResizeEvent):void{
                    guide.x = Math.round((mainCanvas.width - _guideWidth)/2);
                    guide.y = Math.round((mainCanvas.height - _guideHeight)/2);
                }
                // desenha o guide vermelho dentro do container
                private function drawGuide():void{
                    var i:Number=0;
                    guide.graphics.moveTo(0,0);
                    do {
                        guide.graphics.lineStyle(1, 0xffffff, 100);
                        guide.graphics.lineTo(i, 0);
                        i += 4;
                        guide.graphics.lineStyle(1, 0xff0000, 100);
                        guide.graphics.lineTo(i, 0);
                        i += 4;
                    } while (i<_guideWidth);
                    guide.graphics.moveTo(_guideWidth, 0);
                    i = 0;
                    do {
                        guide.graphics.lineStyle(1, 0xffffff, 100);
                        guide.graphics.lineTo(_guideWidth, i);
                        i += 4;
                        guide.graphics.lineStyle(1, 0xff0000, 100);
                        guide.graphics.lineTo(_guideWidth, i);
                        i += 4;
                    } while (i<_guideHeight);

                    guide.graphics.moveTo(_guideWidth, _guideHeight);
                    i = _guideWidth;
                    do {
                        guide.graphics.lineStyle(1, 0xffffff, 100);
                        guide.graphics.lineTo(i, _guideHeight);
                        i -= 4;
                        guide.graphics.lineStyle(1, 0xff0000, 100);
                        guide.graphics.lineTo(i, _guideHeight);
                        i -= 4;
                    } while (i>0);
                    guide.graphics.moveTo(0, _guideHeight);
                    i = _guideHeight;
                    do {
                        guide.graphics.lineStyle(1, 0xffffff, 100);
                        guide.graphics.lineTo(0, i);
                        i -= 4;
                        guide.graphics.lineStyle(1, 0xff0000, 100);
                        guide.graphics.lineTo(0, i);
                        i -= 4;
                    } while (i>0);
                    container.addChild(guide);
                }

                private function initReference():void{
                    _file = new FileReference();
                    request = new URLRequest();
                    _file.addEventListener(Event.SELECT, selectHandler);
                    _file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
                    _file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                    _file.addEventListener(Event.COMPLETE, completeHandler);
                }
                // handler de quando o usuario selecionou o arquivo para mandar
                private function selectHandler(event:Event):void{
                    if(_file.size > _maxImageSize){
                        Alert.show(_cmtMaxImageFile+ Math.ceil((_maxImageSize)/1024) + "Kb\nO arquivo que voc\u00ea escolheu tem: " + Math.ceil((_file.size)/1024)) + "Kb";
                        cmt.text = _cmtMaxImageFile + (_maxImageSize) / 1024 + "Kb";
                    }else{
                        var note:String = String(Math.floor(Math.random()*123456));
                        imgLoc = _rawPixLocation+"/"+note+_file.name;
                        request.url = _filePath+"?id="+imgLoc;
                        fileName = _file.name;
                        cmt.text = "Arquivo selecionado. Upload come\u00e7ar\u00e1 em breve..."
                        _file.upload(request);
                    }
                }
                private function ioErrorHandler(event:IOErrorEvent):void{
                    cmt.text = "Desculpe, ocorreu um erro ao mandar o arquivo. Por favor tente novamente!";
                    dispatchEvent(new Event("ERROR"));
                }
                private function progressHandler(event:ProgressEvent):void{
                    cmt.text = "Processando " + Math.floor(event.bytesLoaded/1024) + "Kb de " + Math.floor(event.bytesTotal/1024) + "Kb ...";
                }
                private function completeHandler(event:Event):void{
                    mainImage = new Loader();
                    mainImage.load(new URLRequest(_basePath + '/' + imgLoc));
                    mainImage.addEventListener(IOErrorEvent.IO_ERROR, function (event:IOError):void {
                        dispatchEvent(new Event("ERROR"));
                    });
                    mainImage.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (event:SecurityError):void {
                        dispatchEvent(new Event("SECURITY_ERROR"));
                    });
                    mainImage.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
                    cmt.text = "Carregando imagem para uso...";
                    dispatchEvent(new Event("IMAGEREADY"));
                }
                private function imgLoaded(e:Event):void {
                    var newPix:Picture = new Picture();
                    newPix.drawBitmap(Bitmap(mainImage.content));
                    newPix.addEventListener(MouseEvent.MOUSE_DOWN, mainCanvasDown);
                    newPix.name = "Pix";
                    currentTool = null;
                    newPix.width = mainImage.content.width; // aqui temos de trocar para 10 vezes menos para encaixar na escala correta
                    newPix.height = mainImage.content.height; // idem. Desabilitado enquanto espera aprovacao de tamanho. o final sera: newPix.height = mainImage.content.height / 10 ; por exemplo
                    newPix.x = newPix.y = 0;
                    container.addChild(newPix);
                    container.setChildIndex(guide, container.numChildren-1);
                    mainImage = null;
                    cmt.text = "Imagem pronta para ser editada.";
                }
                private function fnBrowse():void{
                    initReference();
                    _file.browse(new Array(fileTypes));
                }
                // abaixo funcoes de dataTipFormat
                private function fnThick(val:String):String {
                        return "Espessura da Linha: " + String(val.substr(0,2));
                }
                private function fnAlpha(val:String):String {
                        return "Transpar\u00eancia: " + String(val.substr(0,3));
                }
                private function tipsldRotate(val:String):String {
                    return "Rota\u00e7\u00e3o: " + String(val.substr(0,4));
                }
                private function tipFnBright(val:String):String {
                        return "Brilho: " + String(val.substr(0,4));
                }
                private function tipFnSaturation(val:String):String {
                        return "Satura\u00e7\u00e3o: " + String(val.substr(0,4));
                }
                private function tipFnContrast(val:String):String {
                        return "Contraste: " + String(val.substr(0,4));
                }
                private function tipFnHue(val:String):String {
                        return "Hue: " + String(val.substr(0,4));
                }

                // liga e desliga o sharp
                private function fnSharp():void{
                    if(currentTarget != null){
                        if(currentTarget.name == "Pix"){
                            if(!currentTarget.sharpness){
                                adjust_Conv(currentTarget.cnvSharp, [0, -2, 0, -2, 20, -2, 0, -2, 0], 10, -40);
                                cmt.text = "Nitidez Ligada";
                                focusSharp.visible = true;
                            }else{
                                adjust_Conv(currentTarget.cnvSharp, [0, 0, 0, 0, 1, 0, 0, 0, 0], 1, 0);
                                cmt.text = "Nitidez Desligada";
                                focusSharp.visible = false;
                            }
                            currentTarget.sharpness = !currentTarget.sharpness;
                        }else{
                            cmt.text = "Por favor selecione uma imagem primeiro!";
                        }
                    }else{
                        cmt.text = "Por favor selecione uma imagem primeiro!";
                    }
                }
                // liga e desliga o blur de imagem
                private function fnBlur():void{
                    if(currentTarget != null){
                        if(currentTarget.name == "Pix"){
                            if(!currentTarget.blurness){
                                adjust_Conv(currentTarget.cnvBlur, [0, 1, 0, 1, 1, 1, 0, 1, 0], 5, 0);
                                cmt.text = "Borrar Ligado";
                                focusBlur.visible = true;
                            }else{
                                adjust_Conv(currentTarget.cnvBlur, [0, 0, 0, 0, 1, 0, 0, 0, 0], 1, 0);
                                cmt.text = "Borrar Desligado";
                                focusBlur.visible = false;
                            }
                            currentTarget.blurness = !currentTarget.blurness;
                        }else{
                            cmt.text = "Por favor selecione uma imagem primeiro!";
                        }
                    }else{
                        cmt.text = "Por favor selecione uma imagem primeiro!";
                    }
                }
                // administra as teclas DELETE e PAGEUP
                private function keyHandler(event:KeyboardEvent):void {
                    if(currentTarget != null){
                        if (event.charCode == 127){// && currentTarget.name != 'txts') { // BUG: caso tente remover texto com fontes nao embuidas da erro pq nao pertence ao container ?? tem de pesquisar
                            container.removeChild(currentTarget);
                            resizeBorder.visible = false;
                        }else if (event.keyCode == 33) { // pageUp para jogar o elemento pra frente
                            if(currentTarget != null){
                                fnForward();
                            }
                        }else if (event.keyCode == 34){
                            if (currentTarget != null){
                                fnBackward();
                            }
                        }
                    }
                 }

                // dispara o load do clipArt
                private function loadClipArt(val:String):void {
                    if (val) {
                        var ldr:URLLoader = new URLLoader();
                        ldr.load(new URLRequest(_clipArtSource));
                        ldr.addEventListener(Event.COMPLETE, function (event:Event):void {
                            var XMLlib:XML = new XML(ldr.data);
                            clipArchive = new Array();
                            for (var i:uint=0; i<XMLlib.image.length(); i++){
                                clipArchive.push({sn:i+1, src:XMLlib.image[i].src, title:XMLlib.image[i].title});
                            }
                            tile_List.dataProvider = clipArchive;
                        });
                        ldr.addEventListener(IOErrorEvent.IO_ERROR, function (event:IOError):void {
                            dispatchEvent(new Event("ERROR"));
                        });
                        ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (event:SecurityError):void {
                            dispatchEvent(new Event("SECURITY_ERROR"));
                        });
                    }
                }

                // funcoes que controlam a mudança do texto
                 private function fnTextStyle(event:MouseEvent):void{
                    if(currentTarget != null){
                        if(currentTarget.name == 'txts'){
                            currentTarget.changeFont(event.currentTarget.name, '');
                            posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        }
                    }
                }
                private function txtFontChange(event:Event):void{
                    if(currentTarget != null){
                        if(currentTarget.name == 'txts'){
                            currentTarget.changeFont("font", event.target.selectedLabel);
                            posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        }
                    }
                }
                private function fnTextChange(event:Event):void{
                    if(currentTarget != null){
                        if(currentTarget.name == 'txts'){
                            currentTarget.changeFont("text", event.target.text);
                            posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        }
                    }
                }
                // nao usado mais pq o controle de tamanho sera feito pelo reescale de elemento
                /*
                private function changeFontSize(event:NumericStepperEvent):void{
                    if(currentTarget != null){
                        if(currentTarget.name == 'txts'){
                            currentTarget.changeFont("size", event.target.value.toString());
                            posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        }
                    }
                }
                */
                private function changeFontColor(event:ColorPickerEvent):void{
                    if(currentTarget != null){
                        if(currentTarget.name == 'txts'){
                            currentTarget.changeFont("color", event.color.toString());
                            posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        }
                    }
                }
                private function fnText(event:MouseEvent):void{
                    var newText:BannerText = new BannerText(fontColor.selectedColor);
                    newText.x = 100;
                    newText.y = 100;
                    newText.name = 'txts';
                    newText.changeFont("text",txtText.text);
                    container.addChild(newText);
                    newText.addEventListener(MouseEvent.MOUSE_DOWN, mainCanvasDown);
                }
                // funcao principal que administra as ferramentas de desenho
                private function fnDraw(event:MouseEvent):void{
                    focusRec.visible = focusCir.visible = focusToo.visible = focusLin.visible = false;
                    switch(event.target.name){
                        case 'rec':
                            focusRec.visible = true;
                        break;
                        case 'cir':
                            focusCir.visible = true;
                        break;
                        case 'too':
                            focusToo.visible = true;
                        break;
                        case 'lin':
                            focusLin.visible = true;
                            cmt.text = "Segure o CONTROL Key para desenhar uma linha reta..."
                        break;
                    }
                    tool = event.target.name;
                    if(tool != 'too'){
                        mainCanvas.addEventListener(MouseEvent.MOUSE_OVER, mainCanvasOver);
                    }else{
                        mainCanvas.removeEventListener(MouseEvent.MOUSE_MOVE, mainCanvasMove);
                        mainCanvas.removeEventListener(MouseEvent.MOUSE_OVER, mainCanvasOver);
                    }
                }

                // acionada apos a finalizacao do desenho
                public function fnFinalize():void{
                    if(!processing){
                        processing = true;
                        resizeBorder.visible = false;
                        var _mtx:Matrix = new Matrix();
                        _mtx = mainCanvas.transform.matrix;
                        var xn:int = guide.x - mainCanvas.x + 1;
                        var yn:int = guide.y - mainCanvas.y + 1;
                        _mtx.tx = 0;
                        _mtx.ty = 0;
                        visuals = new Canvas();
                        visuals.setStyle("borderStyle", "none");
                        visuals.setStyle("cornerRadius", 0);
                        visuals.setStyle("backgroundAlpha", 0.8);
                        visuals.setStyle("backgroundColor", 0xffffff);
                        visuals.x = 0;
                        visuals.y = 0;
                        processingAnim = new SWFLoader();
                        processingAnim.source = anim;
                        visuals.addChild(processingAnim);
                        if(_showGuide==true){
                            _mtx.tx = -xn;
                            _mtx.ty = -yn;
                            finalBMP = new BitmapData(_guideWidth, _guideHeight); // como guide nao esta sendo usado acaba usando maincanvas
                            // desliga o guide para desenhar
                            guide.visible = false;
                            // antes de mandar dar o draw temos que multiplicar mainCanvas por 10 para encaixar na escala.
                            finalBMP.draw(mainCanvas, _mtx); // finalBMP é o cara que tem a imagem renderizada final ainda como BitmapData
                            // liga de novo
                            guide.visible = true;
                            guide.addChild(visuals);
                            visuals.width = _guideWidth;
                            visuals.height = _guideHeight;
                        }else{
                            finalBMP = new BitmapData(mainCanvas.width, mainCanvas.height);
                            guide.visible = false;
                            finalBMP.draw(mainCanvas, _mtx);
                            container.addChild(visuals);
                            visuals.width = mainCanvas.width;
                            visuals.height = mainCanvas.height;
                        }
                        processingAnim.x = (visuals.width / 2) - 15;
                        processingAnim.y = (visuals.height / 2) - 15;
                        saveImage(encodeImage(_imageType, finalBMP));
                    }
                }
                private function encodeImage(val:String, image:BitmapData):ByteArray {
                    var returnValue:ByteArray;
                    if(val == 'png'){
                        _pngEncoder = new PNGEncoder();
                        returnValue = _pngEncoder.encode(image);
                    }else{
                        _jpegEncoder = new JPEGEncoder(_quality);
                        returnValue = _jpegEncoder.encode(image);
                    }
                    return returnValue;
                }
                private function saveImage(val:ByteArray):void{
                    loader = new URLLoader();
                    request = new URLRequest();
                    loader.addEventListener(IOErrorEvent.IO_ERROR, ProcessIoErrorHandler);
                    loader.addEventListener(Event.COMPLETE, ProcessCompleteHandler);
                    loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
                    request.contentType = "application/octet-stream";
                    var note:String = String(Math.floor(Math.random()*123456));// aqui ele introduz uma variavel randomica para o nome TODO: mexer nisso aqui
                    fileName = (fileName == '') ? 'sampleImage.jpg' : fileName;// caso o sujeito nao coloque nome
                    finalFile =  fileName.substring(0, fileName.lastIndexOf(".")) + '_processed_' + note + '.' + imageType;
                    request.url = "http://www.4e-commerce.com.br/caliopes/process.php?processed=/home/comercio/public_html/caliopes/processed/" + finalFile;
                    request.method = URLRequestMethod.POST;
                    var dataFormat:String = URLLoaderDataFormat.BINARY;
                    loader.dataFormat = dataFormat;
                    request.data = val;
                    finalBMP.dispose();
                    loader.load(request);
                    cmt.text = "Compondo a imagem... Por favor aguarde!";
                }
                private function securityError(event:Event):void{
                    Alert.show("Desculpe, ocorreu uma falha na seguran\u00e7a.", "Picture Format");
                    dispatchEvent(new Event("ERROR"));
                }
                private function ProcessCompleteHandler(event:Event):void{
                    if(_showGuide == true){
                        guide.removeChild(visuals);
                    }else{
                        container.removeChild(visuals);
                    }
                    dispatchEvent(new Event("COMPLETE"));
                    if(_clientGetsCopy){
                        cmt.text = "Imagem processada, selecione onde salvar a nova imagem...";
                        var fr:FileReference = new FileReference();
                        fr.addEventListener(ProgressEvent.PROGRESS, fr_progressHandler);
                        fr.addEventListener(Event.COMPLETE, fr_completeHandler);
                        var request:URLRequest = new URLRequest();
    /*                     request.url = _basePath + '/' + finalFile;
                        fr.download(request); */
                        function fr_progressHandler(event:ProgressEvent):void {
                            cmt.text = "Carregando " + event.bytesLoaded + " bytes de " + event.bytesTotal;
                        }
                        function fr_completeHandler(event:Event):void {
                            cmt.text = "Carregamento completo e imagem salva.";
                        }
                    }else{
                        cmt.text = "Imagem processada!";
                    }
                }
                private function ProcessIoErrorHandler(event:Event):void{
                    Alert.show("Desculpe, ocorreu um erro.", "Picture Format");
                    dispatchEvent(new Event("ERROR"));
                }
                private function mainCanvasOut(event:MouseEvent):void{
                    Mouse.show();
                    pointer.visible = false;
                }

                private function fnForward():void{
                    if(currentTarget != null){
                        container.setChildIndex(currentTarget, container.numChildren-1);
                        container.setChildIndex(guide, container.numChildren-1);
                        container.setChildIndex(resizeBorder, container.numChildren-1);
                    }
                }
                private function fnBackward():void{
                    if(currentTarget != null){
                        container.setChildIndex(currentTarget,0);
                        container.setChildIndex(guide, container.numChildren-1);
                        container.setChildIndex(resizeBorder, container.numChildren-1);
                    }
                }
                private function adjust_Conv(mc:Sprite, mtx:Array, div:Number, bias:Number):void {
                    var convF:ConvolutionFilter = new ConvolutionFilter(3, 3, mtx, div, bias);
                    mc.filters = [convF];
                }
                // retirando os comentarios de dentro da funcao novamente ativa a mensagem de nao deixar rotacionar textos (fonte nao embuida)
                 private function angleChange():void{
                    if(currentTarget != null){
                        //if(currentTarget.name != "txts"){
                            currentTarget.rotation = sldRotate.value;
                            posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        //}else{
                            //cmt.text = "Desculpe, voc\u00ea n\u00e3o pode rotacionar textos.";
                        //}
                    }
                }
                private function colChange():void{
                    if(currentTarget != null){
                        if(currentTarget.name == "Pix"){
                            currentTarget.colors.bright = sldBright.value;
                            currentTarget.colors.contrast = sldContrast.value;
                            currentTarget.colors.saturation = sldSaturation.value;
                            currentTarget.colors.hue = sldHue.value;
                            cmt.text = "Aplicando filtros...";
                            cmMatrix = new ColorMatrix([]);
                            cmMatrix.adjustColor(int(sldBright.value), int(sldContrast.value), int(sldSaturation.value), int(sldHue.value));
                            var newCMF:ColorMatrixFilter = new ColorMatrixFilter(cmMatrix);
                            currentTarget.cnvColor.filters = [newCMF];
                        }else{
                            cmt.text = "Por favor selecione uma imagem primeiro!";
                        }
                    }else{
                        cmt.text = "Por favor selecione uma imagem primeiro!";
                    }
                }

                private function alphaChange():void{
                    if(currentTarget != null){
                        trace (currentTarget.alpha);
                        try{
                            currentTarget.alpha = 1 - (fillAlpha.value/100);
                        }catch(e:Error){}
                    }
                }
                private function thickChange():void{
                    if(currentTarget.name=='rectangle' || currentTarget.name=='circle' || currentTarget.name=='pentool'){
                        currentTarget.changeLine(lineColor.selectedColor, lineThickness.value);
                    }
                }
                private function changeFillColor(event:ColorPickerEvent):void{
                    if(currentTarget.name=='rectangle' || currentTarget.name=='circle' || currentTarget.name=='pentool'){
                        try{
                            currentTarget.changeFill(event.color);
                        }catch(error:Error){}
                    }
                }
                private function changeLineColor(event:ColorPickerEvent):void{
                    if(currentTarget.name=='rectangle' || currentTarget.name=='circle' || currentTarget.name=='pentool'){
                        try{
                            currentTarget.changeLine(event.color, lineThickness.value);
                        }catch(error:Error){}
                    }
                }
                // carrega o texto do target selecionado na Box
                private function syncText():void{
                    if(currentTarget != null){
                        txtText.text = currentTarget.getText();
                    }
                }
                private function mainCanvasDown(event:MouseEvent):void{
                    container.setChildIndex(pointer, container.numChildren-1);
                    cmt.text = event.currentTarget.toString();
                    if(event.target == mainCanvas && tool=="too"){
                        currentTarget = null;
                        resizeBorder.visible = false;
                    }else if((event.currentTarget.name=="Pix" || event.currentTarget.name=="rectangle" || event.currentTarget.name=="circle" || event.currentTarget.name=="pentool") && event.currentTarget != currentTarget){
                        currentTarget = event.currentTarget;
                        if(currentTarget != null){
                            posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        }
                        try{resetSliders();}
                        catch(e:Error){}
                    }else if(event.target == resizeBorder){
                        try{
                            currentTarget.startDrag(false);
                        }catch(error:Error){}
                        resizeBorder.visible = false;
                        dragging = true;
                    }else if(checkArrow(event.target.name)){
                        anchor = event.target.name;
                        boxName = event.target;
                        mainCanvas.addEventListener(MouseEvent.MOUSE_MOVE, mainCanvasMove);
                        xMouseOffset = mainCanvas.mouseX;
                        yMouseOffset = mainCanvas.mouseY;
                        oldWidth = currentTarget.width;
                        oldHeight = currentTarget.height;
                    }else if(event.currentTarget.name=='txts'){
                        currentTarget = event.currentTarget;
                        posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        syncText();
                    }else if(tool != "too"){
                        switch(tool){
                            case 'cir':
                                var newCircle:BannerCircle = new BannerCircle(itemColor.selectedColor,1,1.0,lineColor.selectedColor,lineThickness.value,1.0);
                                newCircle.x = mainCanvas.mouseX;
                                newCircle.y = mainCanvas.mouseY;
                                newCircle.name = 'circle';
                                currentTool = newCircle;
                                currentTarget = newCircle;
                                container.addChild(newCircle);
                                newCircle.addEventListener(MouseEvent.MOUSE_DOWN, mainCanvasDown);
                            break;
                            case 'rec':
                                var newRectangle:BannerRectangle = new BannerRectangle(itemColor.selectedColor,1,1,1.0,lineColor.selectedColor,lineThickness.value,1.0);
                                newRectangle.x = mainCanvas.mouseX;
                                newRectangle.y = mainCanvas.mouseY;
                                newRectangle.name = 'rectangle';
                                currentTool = newRectangle;
                                currentTarget = newRectangle;
                                container.addChild(newRectangle);
                                newRectangle.addEventListener(MouseEvent.MOUSE_DOWN, mainCanvasDown);
                            break;
                            case 'lin':
                                var newPen:BannerPencil = new BannerPencil(lineColor.selectedColor,lineThickness.value,1.0);
                                newPen.x = mainCanvas.mouseX;
                                newPen.y = mainCanvas.mouseY;
                                newPen.name = 'pentool';
                                currentTool = newPen;
                                currentTarget = newPen;
                                container.addChild(newPen);
                                newPen.addEventListener(MouseEvent.MOUSE_DOWN, mainCanvasDown);
                            break;
                        }
                    }
                }
                private function mainCanvasUp(event:MouseEvent):void{
                    currentTool = null;
                    anchor = '';
                    sldRotate.value = 0;
                    if(currentTarget != null){
                        posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                    }else{
                        try{
                            mainCanvas.removeEventListener(MouseEvent.MOUSE_MOVE, mainCanvasMove);
                        }catch(error:Error){}
                    }
                    if(dragging){
                        try{
                            currentTarget.stopDrag();
                        }catch(error:Error){}
                        dragging = false;
                    }
                    //tool = 'too';
                    //focusRec.visible = focusCir.visible = focusLin.visible = false;
                    //focusToo.visible = true;
                    //mainCanvas.addEventListener(MouseEvent.MOUSE_OVER, mainCanvasOver);
                    //pointer.visible = true;
                }
                private function mainCanvasOver(event:MouseEvent):void{
                    if(tool != ''){
                        Mouse.hide();
                        pointer.rotation = 0;
                        pointer.x = mainCanvas.mouseX - 5;
                        pointer.y = mainCanvas.mouseY - 5;
                        pointer.visible = true;
                        event.updateAfterEvent();
                        mainCanvas.addEventListener(MouseEvent.MOUSE_MOVE, mainCanvasMove);
                    }
                }
                private function mainCanvasMove(event:MouseEvent):void{
                    cmt.text = anchor;
                    container.setChildIndex(pointer, container.numChildren-1);
                    if(tool != 'too'){
                        pointer.visible = true;
                        pointer.x = mainCanvas.mouseX - 5;
                        pointer.y = mainCanvas.mouseY - 5;
                        event.updateAfterEvent();
                    }
                    if(anchor != ''){
                        var xval:Number, yval:Number;
                        var xratio:Number, yratio:Number;
                        var old_Height:Number = currentTarget.height;
                        var old_Width:Number = currentTarget.width;
                        var oldX:Number = currentTarget.x;
                        var oldY:Number = currentTarget.y;
                        switch (anchor){
                            case 'br':
                                xval = (mainCanvas.mouseX - xMouseOffset); xratio=xval/oldWidth;
                                yval = (mainCanvas.mouseY - yMouseOffset); yratio=yval/oldHeight;
                                xval = Math.max(xratio,yratio) * oldWidth;
                                yval = Math.max(xratio,yratio) * oldHeight;
                                currentTarget.width = oldWidth + xval;
                                currentTarget.height = oldHeight + yval;
                            break;
                            case 'mr':
                                currentTarget.width = oldWidth + (mainCanvas.mouseX - xMouseOffset);
                            break;
                            case 'mb':
                                currentTarget.height = oldHeight + (mainCanvas.mouseY - yMouseOffset);
                            break;
                            case 'mt':
                                currentTarget.height = oldHeight + (yMouseOffset - mainCanvas.mouseY);
                                currentTarget.y = mainCanvas.mouseY;
                            break;
                            case 'ml':
                                currentTarget.width = oldWidth + (xMouseOffset - mainCanvas.mouseX);
                                currentTarget.x = mainCanvas.mouseX;
                            break;
                            case 'tr':
                                xval = (mainCanvas.mouseX - xMouseOffset); xratio=xval/oldWidth;
                                yval = (yMouseOffset - mainCanvas.mouseY); yratio=yval/oldHeight;
                                xval = Math.max(xratio,yratio) * oldWidth;
                                yval = Math.max(xratio,yratio) * oldHeight;
                                currentTarget.width = oldWidth + xval;
                                currentTarget.height = oldHeight + yval;
                                currentTarget.y += (old_Height - currentTarget.height);
                            break;
                            case 'tl':
                                xval = (xMouseOffset - mainCanvas.mouseX); xratio=xval/oldWidth;
                                yval = (yMouseOffset - mainCanvas.mouseY); yratio=yval/oldHeight;
                                xval = Math.max(xratio,yratio) * oldWidth;
                                yval = Math.max(xratio,yratio) * oldHeight;
                                currentTarget.width = oldWidth + xval;
                                currentTarget.height = oldHeight + yval;
                                currentTarget.y += (old_Height - currentTarget.height);
                                currentTarget.x += (old_Width - currentTarget.width);
                            break;
                            case 'bl':
                                xval = (xMouseOffset - mainCanvas.mouseX); xratio=xval/oldWidth;
                                yval = (mainCanvas.mouseY - yMouseOffset); yratio=yval/oldHeight;
                                xval = Math.max(xratio,yratio) * oldWidth;
                                yval = Math.max(xratio,yratio) * oldHeight;
                                currentTarget.width = oldWidth + xval;
                                currentTarget.height = oldHeight + yval;
                                currentTarget.x += (old_Width - currentTarget.width);
                            break;
                        }
                        posBorder(currentTarget.getBounds(mainCanvas).width, currentTarget.getBounds(mainCanvas).height, currentTarget.getBounds(mainCanvas).x - 1, currentTarget.getBounds(mainCanvas).y - 1);
                        cmt.text = "Dimens\u00e3o: " + Math.round(currentTarget.getBounds(mainCanvas).width).toString() + " x " + Math.round(currentTarget.getBounds(mainCanvas).height).toString();
                    }else if(tool == 'rec' || tool == 'cir'){
                        if(currentTool != null){
                            currentTarget.redraw(itemColor.selectedColor,1.0,lineColor.selectedColor,lineThickness.value,1.0);
                        }
                    }else if(tool == 'lin' && currentTool != null){
                        if(event.ctrlKey){
                            currentTarget.straight(currentTarget.mouseX, currentTarget.mouseY, lineColor.selectedColor, lineThickness.value, 1.0);
                        }else{
                            currentTarget.moveto(currentTarget.mouseX, currentTarget.mouseY);
                        }
                    }
                }
                private function resetSliders():void{
                    sldBright.value = currentTarget.colors.bright;
                    sldContrast.value = currentTarget.colors.contrast;
                    sldSaturation.value = currentTarget.colors.saturation;
                    sldHue.value = currentTarget.colors.hue;
                }
                private function checkArrow(val:String):Boolean{
                    if(val=='tl' || val=='tr' || val=='bl' || val=='br' || val=='ml' || val=='mr' || val=='mt' || val=='mb'){
                        return true;
                    }
                    return false
                }
                private function posBorder(w:Number,h:Number,xPos:Number,yPos:Number):void{
                    resizeBorder.redraw(w,h);
                    resizeBorder.x = xPos;
                    resizeBorder.y = yPos;
                    container.setChildIndex(guide, container.numChildren-1);
                    container.setChildIndex(resizeBorder, container.numChildren-1);
                    resizeBorder.visible = true;
                }
            ]]>
        </mx:Script>
        <!-- toda a aplicacao esta dentro desse canvas -->
        <mx:Canvas id="mainBox" width="100%" height="100%" verticalScrollPolicy="off" horizontalScrollPolicy="off">
            <mx:Label x="10" y="527" text="Label" id="cmt" visible="false"/> <!-- label que avisa ao usuario sobre eventos , etc -->
            <mx:Button x="10" y="50" label="DESENHO" labelPlacement="right" click="showTabDraw(event)"
                     toolTip="Ferramentas de desenho" width="75" height="22" color="#000000" fontSize="8" textAlign="left"/> <!-- esses botoes controlam o que esta sendo usado no momento: ferramentas de texto , desenho , etc) -->
            <mx:Button x="10" y="80" label="TEXTOS" labelPlacement="right" width="75" click="showTabText(event)"
                     toolTip="Ferramentas de texto" color="#000000" fontSize="8" textAlign="left"/>
            <mx:Button x="10" y="110" label="CLIP ARTS" labelPlacement="left" click="showTabClip(event)"
                     toolTip="Imagens" width="75" height="22" color="#000000" fontSize="8" textAlign="left"/>
            <mx:Canvas x="75" y="28" width="167" height="164.65" horizontalScrollPolicy="off" label="Desenho" id="tabDraw" verticalScrollPolicy="off" creationComplete="initTabDraw()" visible="true" borderColor="#579333">
                <mx:Image x="10" y="21" id="focusToo" source="components/assets/focus.png" width="24" height="24"/>
                <mx:Button x="12" y="23" click="fnDraw(event)" id="btnToo" width="20" height="20" icon="@Embed(source='assets/Cursor.png')" paddingLeft="0" paddingRight="6" name="too" toolTip="Clique para selecionar um objeto" paddingTop="0"/>
                <mx:Image x="50" y="21" id="focusRec" source="components/assets/focus.png" width="24" height="24"/>
                <mx:Button x="52" y="23" click="fnDraw(event)" id="btnRec" width="20" height="20" icon="@Embed(source='assets/rectangle.png')" paddingLeft="0" name="rec" toolTip="Clique para desenhar reatngulos" paddingBottom="0" paddingTop="0" paddingRight="2"/>
                <mx:Image x="90" y="21" id="focusCir" source="components/assets/focus.png" width="24" height="24"/>
                <mx:Button x="92" y="23" click="fnDraw(event)" id="btnCir" width="20" height="20" icon="@Embed(source='assets/circle.png')" paddingLeft="0" paddingRight="2" name="cir" toolTip="Clique para desenhar circulos" paddingBottom="0" paddingTop="0"/>
                <mx:Image x="130" y="21" id="focusLin" source="components/assets/focus.png" width="24" height="24"/>
                <mx:Button x="132" y="23" click="fnDraw(event)" id="btnLin" width="20" height="20" icon="@Embed(source='assets/line.png')" paddingLeft="0" paddingRight="2" name="lin" toolTip="Clique para desenhar linhas" paddingBottom="0" paddingTop="0"/>
                <mx:Canvas x="10" y="47" width="60" height="32" id="cnvFilCol">
                    <mx:Image x="4" y="6" id="imgIcnItem" source="components/assets/paintcan.png"/>
                    <mx:ColorPicker x="28" y="3" id="itemColor" selectedColor="#4444CC" itemRollOver="changeFillColor(event)" toolTip="Cor do objeto"/>
                </mx:Canvas>
                <mx:Canvas x="97" y="47" width="60" height="32" id="cnvLinCol">
                    <mx:Image x="4" y="6" id="imgIcnLine" source="components/assets/paintbrush.png"/>
                    <mx:ColorPicker x="28" y="3" id="lineColor" selectedColor="#FF6633" itemRollOver="changeLineColor(event)" toolTip="Cor da linha"/>
                </mx:Canvas>
                <mx:Canvas x="10" y="83" width="147" height="32" id="cnvThick">
                    <mx:Image x="6" y="7" source="components/assets/linethick.gif" id="imgIcnThick"/>
                    <mx:HSlider x="28" y="5" id="lineThickness" value="1" liveDragging="true" maximum="10" tickInterval="1" snapInterval="1" dataTipFormatFunction="fnThick" change="thickChange()" width="109" toolTip="Clique e arraste para mudar o tamanho da borda"/>
                </mx:Canvas>
            </mx:Canvas>
            <mx:Canvas x="75" y="28" width="167" height="164.65" id="tabClip" creationComplete="initTabClip()" borderStyle="solid" backgroundAlpha="1" horizontalScrollPolicy="off" verticalScrollPolicy="auto" visible="false" borderColor="#579333" borderThickness="1" themeColor="#5CBB22">
                <mx:Canvas x="10" y="10" width="147" height="161" id="tabClipContainer">
                </mx:Canvas>
            </mx:Canvas>
            <mx:Panel x="267" y="0" width="265" height="438" borderColor="#579333" borderStyle="solid" color="#000000" backgroundColor="#72C142" backgroundAlpha="1" title="Edite aqui sua estampa" themeColor="#3CFF00">
                <!-- abaixo o canvas principal , a mascara ja esta ai para quando se for usar um contorno de for necessario no futuro -->
                <mx:Canvas id="mainCanvas" width="244" height="355" label="Onde sera realizada a pintura" horizontalScrollPolicy="off" verticalScrollPolicy="off" y="112" x="9" borderStyle="solid" backgroundColor="#FFFFFF" borderColor="#000000" borderThickness="1" cornerRadius="0">
                    <mx:Canvas id="masker" x="0" y="0" width="244" height="355"  label="Mascara da pintura (fica do tamanho do canvas)" horizontalScrollPolicy="off" verticalScrollPolicy="off">
                    </mx:Canvas>
                </mx:Canvas>
                <mx:Button id="btnFinalize" click="fnFinalize()" toolTip="Clique para finalizar e processar a imagem" width="36" height="28" icon="@Embed(source='assets/server_go.png')" paddingLeft="10" paddingRight="10" x="199" y="80" visible="false"/>
            </mx:Panel>
            <mx:Canvas x="75" y="28" width="167" height="164.66669" horizontalScrollPolicy="off" label="Texto" id="tabText" verticalScrollPolicy="off" creationComplete="initTabText()" visible="false" icon="@Embed(source='assets/text_dropcaps.png')" borderColor="#579333">
                <mx:TextArea x="10" y="33" id="txtText" width="147" height="56" change="fnTextChange(event)"/>
                <mx:Button x="10" y="5" click="fnText(event)" id="btnText" labelPlacement="bottom" width="20" height="20" name="txt" toolTip="Novo texto" icon="@Embed(source='assets/text.png')" paddingTop="0" paddingLeft="2"/>
                <mx:Button x="69" y="5" click="fnTextStyle(event)" label="Button" id="btnBold" width="20" height="20" icon="@Embed(source='assets/text_bold.png')" name="bold" toolTip="Bold" paddingLeft="10" paddingTop="0" paddingRight="0"/>
                <mx:Button x="97" y="5" click="fnTextStyle(event)" label="Button" id="btnItalic" width="20" height="20" icon="@Embed(source='assets/text_italic.png')" name="italics" toolTip="Italic" paddingLeft="10" paddingRight="0" paddingTop="0"/>
                <mx:Button x="125" y="5" click="fnTextStyle(event)" label="Button" id="btnUnderline" width="20" height="20" icon="@Embed(source='assets/text_underline.png')" name="underline" toolTip="Underline" paddingLeft="10" paddingRight="0" paddingTop="0"/>
                <mx:ComboBox x="10" y="93" id="cmbFont" width="147" change="txtFontChange(event)" dataProvider="['Arial','Verdana','Times New Roman','Georgia']" toolTip="Clique aqui para trocar a fonte"/>
                <mx:Canvas x="10" y="118" width="63" height="32" id="cnvColor" borderStyle="none" backgroundAlpha="0">
                    <mx:Image id="imgFColor" x="16" y="7" source="components/assets/paintcan.png"/>
                    <mx:ColorPicker x="36" y="3" id="fontColor" selectedColor="#333333" itemRollOver="changeFontColor(event)"/>
                </mx:Canvas>
                <!-- caso queira voltar com o controle de tamanho de fonte eh se descomentar
                <mx:Canvas x="75" y="168" width="80" height="32" id="cnvSize" visible="false">
                  <mx:Image id="imgFSize" x="6" y="7" source="components/assets/text_replace.png"/>
                  <mx:NumericStepper x="32" y="4" id="stpSize" value="12" maximum="100" width="40" change="changeFontSize(event)"/>
                </mx:Canvas>
                -->
            </mx:Canvas>
            <mx:Canvas width="167" height="34" id="cnvBright" horizontalScrollPolicy="off" x="75" y="259">
                <mx:Image x="8" y="8" id="iconBright" source="components/assets/weather_sun.png"/>
                <mx:HSlider x="24" y="4" width="120" id="sldBright" minimum="-100" maximum="100" value="0" snapInterval="5" dataTipFormatFunction="tipFnBright" liveDragging="true"  change="colChange()" toolTip="Clique e arraste para mudar o brilho"/>
            </mx:Canvas>
            <mx:Canvas width="167" height="34" id="cnvContrast" horizontalScrollPolicy="off" x="75" y="301">
                <mx:Image x="8" y="8" id="iconContrast" source="components/assets/contrast.png" />
                <mx:HSlider x="24" y="4" width="120" id="sldContrast" minimum="-100" maximum="100" value="0" snapInterval="5" dataTipFormatFunction="tipFnContrast" liveDragging="true" change="colChange()" toolTip="Clique e arraste para mudar o contraste"/>
            </mx:Canvas>
            <mx:Canvas width="167" height="34" id="cnvSaturation" horizontalScrollPolicy="off" x="75" y="343">
                <mx:Image x="8" y="8" id="iconSaturation" source="components/assets/layers.png"/>
                <mx:HSlider x="24" y="4" width="120" id="sldSaturation" minimum="-100" maximum="100" value="0" snapInterval="5" dataTipFormatFunction="tipFnSaturation" liveDragging="true" change="colChange()" toolTip="Clique e arraste para mudar a saturação"/>
            </mx:Canvas>
            <mx:Canvas width="167" height="34" id="cnvHue" horizontalScrollPolicy="off" x="75" y="385">
                <mx:Image x="8" y="8" id="iconHue" source="components/assets/color_wheel.png"/>
                <mx:HSlider x="24" y="4" width="120" id="sldHue" minimum="-150" maximum="150" value="0" snapInterval="5" dataTipFormatFunction="tipFnHue" liveDragging="true" change="colChange()" toolTip="Clique e arraste para mudar o HUE"/>
            </mx:Canvas>
            <mx:Canvas id="cnvRotate" width="167" height="34" x="75" y="427">
                <mx:Image id="clockwise" source="components/assets/clockwise.png" x="141" y="10"/>
                <mx:HSlider id="sldRotate" minimum="-180" maximum="180" width="120" liveDragging="true" value="0" dataTipFormatFunction="tipsldRotate" change="angleChange()" y="7" x="24" toolTip="Clique e arraste para rotacionar a seleção"/>
                <mx:Image id="anticlockwise"  source="components/assets/anticlockwise.png" x="10" y="10"/>
            </mx:Canvas>
            <mx:Canvas width="201" height="47" id="blurSharpBox" verticalScrollPolicy="off" borderStyle="none" backgroundAlpha="0" horizontalScrollPolicy="off" borderThickness="0" x="58" y="469">
                <mx:Image x="156" y="1" id="focusBlur" source="components/assets/focus.png"/>
                <mx:Image x="0" y="1" source="components/assets/focus.png" id="focusSharp"/>
                <mx:Button x="2" y="4" click="fnSharp()" id="btnSharp" width="40" height="40" icon="@Embed(source='assets/shape_square.png')" paddingLeft="12" paddingRight="12" toolTip="Clique para deixar a imagem mais nítida"/>
                <mx:Button x="158" y="4" click="fnBlur()" id="btnBlur" width="40" height="40" icon="@Embed(source='assets/shading.png')" paddingLeft="12" paddingRight="12" toolTip="Clique para deixar a imagem mais borrada"/>
                <mx:Button id="btnBrowse" click="fnBrowse()" width="36" icon="@Embed(source='assets/folder_new.gif')" height="28" paddingLeft="10" paddingRight="10" x="44.35" y="10" toolTip="Clique para selecionar uma imagem"/>
                <mx:Button id="btnForward" click="fnForward()" toolTip="Clique para colocar o objeto selecionado a frente de todos os outros ou use PAGEUP" width="36" height="28" paddingLeft="10" paddingRight="10" icon="@Embed(source='assets/shape_forward.png')" x="82.35" y="10"/>
                <mx:Button id="btnBackward0" click="fnBackward()" toolTip="Clique para colocar o objeto selecionado abaixo de todos os outros ou use PAGEDOWN" width="36" height="28" paddingLeft="10" paddingRight="10" icon="@Embed(source='assets/shape_forward.png')" x="120.35" y="9.95"/>
            </mx:Canvas>
            <mx:Canvas x="75" y="217" width="167" height="34" id="cnvAlpha" borderStyle="none">
                <mx:Image x="6" y="7" source="components/assets/fillalpha.png" id="imgIcnAlpha"/>
                <mx:HSlider x="24" y="7" id="fillAlpha" value="0" liveDragging="true" maximum="100" tickInterval="1" snapInterval="1" dataTipFormatFunction="fnAlpha" change="alphaChange()" width="120" toolTip="Clique e arraste para mudar a transparência"/>
            </mx:Canvas>
            </mx:Canvas>
    </mx:Canvas>