Source: widgets/SpwDraw.js

Retour à la documentation
/**
 * @class spw.widgets.SpwDraw
 */
define([
        "dojo/_base/declare","spw/api/SpwBaseTemplatedWidget",
        "dojo/text!./templates/SpwDraw.html","dojo/i18n!./nls/SpwDraw",
        "dojo/query", "dojo/dom-construct", "dojo/dom-class",
        "dojo/_base/array", "dojo/_base/lang", "dojo/on",
        "spw/api/MapServiceFactory",
        "esri/layers/GraphicsLayer",
        "esri/toolbars/edit", "spw/api/SpwDrawToolbar", "esri/graphic",
        "esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol",
        "dojo/_base/Color", "esri/symbols/SimpleMarkerSymbol", "esri/tasks/LengthsParameters",
        "esri/tasks/GeometryService", "esri/symbols/TextSymbol", "esri/geometry/Point",
        "esri/symbols/Font", "esri/tasks/AreasAndLengthsParameters", "spw/api/MessageManager",
        "esri/geometry/Polygon", "dijit/form/ToggleButton", "esri/symbols/PictureMarkerSymbol",
        "dijit/Dialog", "dijit/form/Button", "dojo/json","dojo/request", "esri/geometry/screenUtils",
        "spw/api/Utils", "dojo/dom-style", "dijit/form/ValidationTextBox", "dojo/touch", "spw/api/GeometryUtils",
        "esri/geometry/Polyline", "spw/api/ProjectionManager", "esri/symbols/jsonUtils", "dojo/dom-form", "spw/api/ViewUtils",

        "dijit/DropDownMenu", "dijit/form/DropDownButton", "dijit/CheckedMenuItem",
        "dijit/TitlePane", "dojox/widget/ColorPicker", "dijit/form/HorizontalSlider",
        "dijit/form/NumberSpinner", "dijit/form/Select", "dijit/form/Textarea", "dijit/MenuItem"
    ],
    function(declare, SpwBaseTemplatedWidget, template, labels,
             query, domConstruct, domClass, array, lang, on,
             MapServiceFactory,
             GraphicsLayer,
             Edit, Draw, Graphic, SimpleFillSymbol, SimpleLineSymbol, Color,
             SimpleMarkerSymbol, LengthsParameters, GeometryService,
             TextSymbol, Point, Font, AreasAndLengthsParameters, MessageManager,
             Polygon, ToggleButton, PictureMarkerSymbol, Dialog, Button, JSON, request, screenUtils,
             Utils, domStyle, ValidationTextBox, touch, GeometryUtils, Polyline, ProjectionManager, symbolsJsonUtils,
             domForm, ViewUtils) {

        return declare("spw.widgets.SpwDraw", [SpwBaseTemplatedWidget], {

            templateString: template,
            labels: labels,

            /*START config*/
            toolList: null,
            pictogrammes: null,
            restfulUrl: null,
            layerName: 'SpwDrawPersonnalData',
            helpText: '',
            "widgetTitle": "Dessiner",
            "position": "panel-light",
            "iconClass": "drawIcon",
            "enableMyDrawings": false,
            "height": "auto",
            "right": "15px",
            "top": "85px",
            "width": "320px",
            /*END config*/

            _graphicLayer: null,
            _graphicLayerClickHandler: null,
            _drawToolbar: null,
            _editToolbar: null,
            _spwMap: null,
            _mapService: null,

            _mapServices: null,

            dropDownMenu: null,
            apercuPane: null,

            pictoChooseZone: null,
            pictoButtons: null,

            colorPickerLineButton: null,
            colorPickerLine: null,
            colorPickerFillButton: null,
            colorPickerFill: null,
            fillOpacitySlider: null,
            weightLineSpinner: null,
            styleLineSelect: null,
            typePointSelect: null,
            sizPointSpinner: null,
            displayLengthSelect: null,
            displaySuperfSelect: null,
            colorPickerTextButton: null,
            colorPickerText: null,
            textareaText: null,
            textFontSelect: null,
            textSizeSpinner: null,
            textWeightSelect: null,
            textStyleSelect: null,
            textRadiusSpinner: null,
            widthPictoSpinner: null,
            heightPictoSpinner: null,

            textRadiusRow: null,
            textWeightRow: null,
            textStyleRow: null,
            textSizeRow: null,
            textValueRow: null,
            textColorRow: null,
            textFontRow: null,
            displaySuperfRow: null,
            separatorLineRow: null,
            lineStyleRow: null,
            lineWeightRow: null,
            lineColorRow: null,
            separatorFondRow: null,
            fondOpacityRow: null,
            fondColorRow: null,
            separatorPointRow: null,
            taillePointRow: null,
            typePointRow: null,
            displayLengthRow: null,
            pictoRow: null,
            heightPictoRow: null,
            widthPictoRow: null,

            serviceNameSuffix: '<span style="color: #f00; padding-left: 5px;"><br>(Édition en cours)</span>',

            constructor: function (config) {
            },

            postMixInProperties: function (config) {
                this.inherited(arguments);

                this._spwMap = this.spwViewer.get('spwMap');

                this.own(
                    on(this._spwMap, this._spwMap.events.MapServiceRemoved, lang.hitch(this, this.onMapServiceRemoved)),
                    on(this._spwMap, this._spwMap.events.MapServiceAdded, lang.hitch(this, this.onMapServiceAdded)),
                    on(this._spwMap, this._spwMap.events.EditMapService, lang.hitch(this, this.onEditMapService))
                );

                if(this.restfulUrl){
                    request(this.restfulUrl, {method:'GET', handleAs:'json'}).then(lang.hitch(this, function(data){
                        if(data.code == 0 && data.obj){
                            localStorage.setItem(this.layerName, data.obj);
                        }
                    }));
                }
            },

            onMapServiceAdded: function(service) {
                if (service.get('globalType') === 'DATA_MAP_SERVICE') {
                    if (!this.activated) {
                        return;
                    }

                    if (this._mapService && service.serviceId === this._mapService.serviceId) {
                        this.buildTOC();
                        return;
                    }

                    if (!this._fromThis && (this._mapService == null || service.get('currentDrawing'))) {
                        this.addMapService(service.serviceId);
                    }

                    if (!this._fromThis) {
                        this.buildTOC();
                    }

                    this._fromThis = false;
                }
            },

            onEditMapService: function(service) {
                if (!this.activated) {
                    this.onActivate();
                }

                if (this._mapService && service.serviceId === this._mapService.serviceId) {
                    return;
                }

                this.deactivateAll();
                this.addMapService(service.serviceId);
            },

            onMapServiceRemoved: function(service) {
                if (!this._disableRemovedHandler && this._mapService && this._mapService.serviceId === service.serviceId) {
                    this.selectLabel(true);

                    if (this._mapService) {
                        this._mapService.set('currentDrawing', false);
                    }

                    this._mapService = null;

                    if (this.activated) {
                        this.onNewLayerClick();
                    }
                }

                array.some(this._mapServices, lang.hitch(this, function(ms, idx) {
                    if (ms.serviceId === service.serviceId) {
                        this._mapServices.splice(idx, 1);
                        return true;
                    }

                    return false;
                }));

                this.buildTOC();
                this._disableRemovedHandler = false;
            },

            buildRendering: function (config) {
                this.inherited(arguments);

                array.forEach(this.dropDownMenu.getChildren(), lang.hitch(this, function(menuItem){
                    menuItem.on('click', lang.hitch(this, function(e){this.onMenuItemClick(e, menuItem);}));
                }));

                this.own(
                    on(this.DropDownButton, touch.press, lang.hitch(this, this.onDrawToolsButtonClick)),
                    on(this.EditButton, touch.press, lang.hitch(this, this.onEditButtonClick)),
                    on(this.EraseButton, touch.press, lang.hitch(this, this.onEraseButtonClick)),
                    on(this.SaveButton, touch.press, lang.hitch(this, this.onSaveButtonClick)),
                    on(this.NewLayerButton, touch.press, lang.hitch(this, this.onNewLayerClick))
                );

                if(this.pictogrammes && this.pictogrammes.length > 0){
                    this.pictoButtons = [];
                    array.forEach(this.pictogrammes, lang.hitch(this, function(picto){
                        var btn = new ToggleButton({
                            showLabel: true,
                            checked: false,
                            onChange: lang.hitch(this, function(){ this.onPictoChanged(btn); }),
                            label: '<img src="'+picto+'" style="width:32px;height:32px;"/>',
                            pictoSrc: picto
                        }, domConstruct.create("div", {style:"display:inline-block;"}, this.pictoChooseZone));
                        this.pictoButtons.push(btn);
                    }));
                }

                this.hideProperties();

                if(this.toolList){
                    this.restrictTools();
                }
                array.forEach(this.dropDownMenu.getChildren(), lang.hitch(this, function(item){
                    if(item.drawData == 'PICTO' && !this.pictogrammes) item.domNode.style.display = 'none';
                }));

                this.DropDownButton.on('click', function(){
                    setTimeout(lang.hitch(this, function() {
                        this.closeDropDown();
                        this.openDropDown();
                    }), 100);
                });

                this.dropDownMenu.onOpen = function(){
                    domClass.add(this._popupWrapper, "drawMenuPopup");
                    domClass.remove(this._popupWrapper, "dijitMenuPopup");

                    domStyle.set(this._popupWrapper, 'z-index', '2001');
                };
            },


            onPictoChanged: function(currentBtn){
                if(currentBtn.get('checked')){
                    this.set('_currPicto', currentBtn.pictoSrc);
                    array.forEach(this.pictoButtons, lang.hitch(this, function(btn){
                        if(currentBtn != btn){
                            btn.set('checked', false);
                        }
                    }));
                } else {
                    this.set('_currPicto', null);
                }
            },

            currentPicto: function(){
                var ret = null;
                array.some(this.pictoButtons, lang.hitch(this, function(btn){
                    if(btn.get('checked')){
                        ret = btn.pictoSrc;
                        return true;
                    }
                    return false;
                }));
                return ret;
            },

            restrictTools: function(){
                array.forEach(this.dropDownMenu.getChildren(), lang.hitch(this, function(item){
                    if(this.toolList.indexOf(item.drawData) == -1){
                        item.domNode.style.display = 'none';
                    }
                }));
            },

            postCreate: function() {
                this.inherited(arguments);

                if (!this.enableMyDrawings) {
                    domStyle.set(this.SaveButton, 'display', 'none');
                }

                this._curDrawingNode.on('keyup', lang.hitch(this, function() {
                    if (!this._curDrawingNode.isValid()) {
                        this._curDrawingNode.displayMessage();
                        return;
                    }

                    if (this._mapService == null) {
                        return;
                    }

                    this._mapService.set('label', this._curDrawingNode.get('value'));
                }));

                this._validateButton.on(touch.press, lang.hitch(this, function() {
                    if (this._mapService == null) {
                        MessageManager.getInstance().notifyError('Aucun dessin en cours');
                        return;
                    }

                    this.saveData(this._mapService.get('label'));
                    this.drawingSavedMessage.style.opacity = 100;
                    setTimeout(lang.hitch(this, function(){ this.drawingSavedMessage.style.opacity = 0; }), 5000);
                }));

                if (this.enableMyDrawings === false) {
                    domStyle.set(this._validateButtonContainer, 'display', 'none');
                }

                this._drawToolbar = new Draw(this._spwMap.get('esriMap'));
                this._editToolbar = new Edit(this._spwMap.get('esriMap'), { textSymbolEditorHolder: this.txtSymbolEditorHolder });

                this._spwMap.on(this._spwMap.events.MapCreated, lang.hitch(this, function(map) {
                    if (this.spwViewer.get('spwMap').loaded) {
                        this._drawToolbar = null;
                        this._editToolbar = null;

                        this.domNode && this.deactivateAll();

                        this._drawToolbar = new Draw(map);
                        this._editToolbar = new Edit(map, {
                            textSymbolEditorHolder: this.txtSymbolEditorHolder
                        });

                        this._mapService = null;

                        /*if (this.activated) {
                         this.onActivate();
                         }*/
                    }
                    else {
                        on.once(this.spwViewer.get('spwMap'), this.spwViewer.get('spwMap').events.MapLoaded, lang.hitch(this, function() {
                            this._drawToolbar = null;
                            this._editToolbar = null;

                            this.domNode && this.deactivateAll();

                            this._drawToolbar = new Draw(map);
                            this._editToolbar = new Edit(map, {
                                textSymbolEditorHolder: this.txtSymbolEditorHolder
                            });

                            this._mapService = null;

                            /*if (this.activated) {
                             this.onActivate();
                             }*/
                        }));
                    }
                }));
            },

            watchHandlers: null,

            buildTOC: function() {
                domConstruct.empty(this.drawListNode);

                this.watchHandlers = this.watchHandlers || [];

                array.forEach(this.watchHandlers, function(w) {
                    w.unwatch();
                });

                this.watchHandlers = [];

                var mss = this.spwViewer.get('spwMap').getMapServices({
                    globalType: 'DATA_MAP_SERVICE'
                });

                var ids = [];

                array.forEach(mss, lang.hitch(this, function(ms, idx) {
                    ids.push(ms.serviceId);
                    this.buildTOCItemFromService(ms, idx === 0);
                }));

                var json = localStorage.getItem(this.layerName);
                var data = JSON.parse(json);

                array.forEach(data, lang.hitch(this, function(d, idx) {
                    if (ids.indexOf(d.id) > -1) {
                        return;
                    }

                    this.buildTOCItemFromStorage(d, ids.length === 0 && idx === 0);
                }));
            },

            buildTOCItemFromService: function(service, first) {
                var li = domConstruct.create('li', null, this.drawListNode);

                if (first) {
                    domStyle.set(li, 'border', 'none');
                }

                var txtBox = null;

                if (this._mapService && service.serviceId === this._mapService.serviceId) {
                    txtBox = new ValidationTextBox({
                        required: true,
                        value: service.label,
                        style: 'width: 100px;',
                        onKeyUp: lang.hitch(this, function() {
                            if (!txtBox.isValid()) {
                                txtBox.displayMessage();
                                return;
                            }

                            service.set('label', txtBox.get('value'));
                        })
                    }, domConstruct.create('input', null, li));

                    this.watchHandlers.push(service.watch('label', lang.hitch(this, function(name, old, val) {
                        txtBox.set('value', val);
                        this._curDrawingNode.set('value', val);
                        query(this.domNode).query('.layerName').forEach(lang.hitch(this, function(n) { n.innerHTML = val; }));
                    })));

                    domConstruct.create('span', {
                        innerHTML: this.serviceNameSuffix
                    }, li);

                    txtBox.startup();
                }
                else {
                    var span = domConstruct.create('span', {
                        innerHTML: service.label
                    }, li, 'first');

                    this.watchHandlers.push(service.watch('label', function(name, old, val) {
                        span.innerHTML = val;
                    }));
                }

                domConstruct.create('span', {
                    "class": "trashIcon",
                    onclick: lang.hitch(this, function(){
                        this.deleteDrawLayerById(service.serviceId);
                    })
                }, li);

                if (this._mapService && service.serviceId === this._mapService.serviceId && txtBox) {
                    domConstruct.create('span', {
                        "class": "saveIcon",
                        onclick: lang.hitch(this, function(){
                            this.saveData(this._mapService.get('label'));
                        })
                    }, li);
                }
                else {
                    domConstruct.create('span', {
                        "class": "saveIcon",
                        style: 'opacity: 0; cursor: default;'
                    }, li);
                }

                domConstruct.create('span', {
                    "class": "unloadIcon",
                    onclick: lang.hitch(this, function(){
                        var id = service.serviceId;

                        if (service.newLayer && txtBox) {
                            id = this.saveData(service.get('label'));
                        }

                        this.spwViewer.get('spwMap').removeMapService(id);
                    })
                }, li);
            },

            buildTOCItemFromStorage: function(item, first) {
                var li = domConstruct.create('li', null, this.drawListNode);

                if (first) {
                    domStyle.set(li, 'border', 'none');
                }

                var span = domConstruct.create('span', {
                    innerHTML: item.name
                }, li, 'first');

                domConstruct.create('span', {
                    "class": "trashIcon",
                    onclick: lang.hitch(this, function(){
                        this.deleteDrawLayerById(item.id);
                    })
                }, li);

                domConstruct.create('span', {
                    "class": "loadIcon",
                    onclick: lang.hitch(this, function(){
                        this.addMapService(item.id, item.name, item.data);
                        this.drawLayerId = item.id;
                    })
                }, li);
            },

            startup: function() {
                this.inherited(arguments);
            },

            onActivate: function(){
                this.inherited(arguments);

                this.selectLabel(true);
                this._mapService = null;

                this.onNewLayerClick();

                this.selectLabel();
                this._mapService.show();
                this.buildTOC();
            },

            onDeactivate: function() {
                var wasActivated = this.activated;

                this.inherited(arguments);

                this.DropDownButton.closeDropDown();

                if (wasActivated) {
                    this.deactivateAll();

                    if (this._mapService && this._mapService.get('newLayer')) {
                        this._mapService.set('inTOC', false);
                        this._mapService.hide();
                    }
                    this.selectLabel(true);
                }
            },

            onMenuItemClick: function(e, menuItem) {
                this.deselectDrawMenuItems();
                menuItem.set('checked', true);

                this.activateDrawTool(menuItem.drawData);
            },

            deselectDrawMenuItems: function(){
                array.forEach(this.dropDownMenu.getChildren(), lang.hitch(this, function(menuItem, idx){
                    menuItem.set('checked', false);
                }));
            },

            activateTool: function(tool){
                domClass.add(this[tool + 'Button'], "activated");
                domClass.add(this['draw' + tool + 'Content'], "activated");
            },

            deactivateTool: function(tool){
                domClass.remove(this[tool + 'Button'], "activated");
                domClass.remove(this['draw' + tool + 'Content'], "activated");
            },

            deactivateRefresh: function() {
                this.deactivateTool('DrawTools');
                this.deactivateTool('Edit');
                this.deactivateTool('Erase');
                this.deactivateEraseTool();
                this.deactivateDrawTool();
                this.deactivateEditTool();

                array.forEach(this.dropDownMenu.getChildren(), lang.hitch(this, function(menuItem, idx){
                    if (idx < 3) {
                        menuItem.set('checked', false);
                    }
                }));
            },

            deactivateAll: function(){
                this.deactivateTool('DrawTools');
                this.deactivateTool('Edit');
                this.deactivateTool('Erase');
                this.deactivateTool('Save');
                if(this.spwViewer && this.spwViewer.spwMap && this.spwViewer.spwMap.esriMap) {
                    this.deactivateEraseTool();
                    this.deactivateDrawTool();
                    this.deactivateEditTool();
                    this.deselectDrawMenuItems();
                }
            },

            onDrawToolsButtonClick : function(e){
                this.deactivateAll();
                domClass.add(this.DrawToolsButton, "activated");
            },

            onEditButtonClick: function(e) {
                this.deactivateAll();
                this.activateTool('Edit');
                this.activateEditTool();
            },

            onEraseButtonClick: function(e) {
                this.deactivateAll();
                this.activateTool('Erase');
                this.activateEraseTool();
            },

            onSaveButtonClick: function(e){
                this.deactivateAll();
                this.activateTool('Save');
            },

            _mouseOutHandler: null,
            _mouseOverHandler: null,
            activateEraseTool: function() {
                this.deactivateEditTool();
                this.deactivateDrawTool();

                this._graphicLayerClickHandler = this._graphicLayer.on("click", lang.hitch(this, function(evt){
                    if(!evt.graphic.associatedGraphic){
                        if (evt.graphic._buffer) {
                            evt.graphic = evt.graphic._buffer;
                        }

                        if (evt.graphic._coordinates) {
                            this._graphicLayer.remove(evt.graphic._coordinates);
                        }

                        if(evt.graphic.hasOwnProperty("associatedMesure")){
                            this._graphicLayer.remove(evt.graphic.associatedMesure);
                        }
                        if(evt.graphic.hasOwnProperty("associatedArea")){
                            this._graphicLayer.remove(evt.graphic.associatedArea);
                        }
                        if (evt.graphic._buffers) {
                            array.forEach(evt.graphic._buffers, lang.hitch(this, function(buf) {
                                buf.associatedMesure && this._graphicLayer.remove(buf.associatedMesure);
                                this._graphicLayer.remove(buf);
                            }));
                        }
                        this._graphicLayer.remove(evt.graphic);
                        if (this._graphicLayer.graphics.length == 0) {
                            this._mapService.defaultProperties = [];
                            this.savePropertiesForLayerCheckbox.set('checked', false);
                        }
                    }
                }));

                this._mouseOverHandler =  this._graphicLayer.on("mouse-over", lang.hitch(this, function(evt){
                    if(!evt.graphic.associatedGraphic && !evt.graphic._originalSymbol){
                        if (evt.graphic._buffer) {
                            evt.graphic = evt.graphic._buffer;
                        }

                        if (evt.graphic._buffers) {
                            array.forEach(evt.graphic._buffers, lang.hitch(this, function(buf) {
                                lang.mixin(buf, {_originalSymbol: buf.symbol});
                                this.createHighlightSymbol(buf);
                                buf.setSymbol(buf.symbol);
                            }));
                        }

                        lang.mixin(evt.graphic, {_originalSymbol: evt.graphic.symbol});
                        this.createHighlightSymbol(evt.graphic);
                        evt.graphic.setSymbol(evt.graphic.symbol);
                    }
                }));
                this._mouseOutHandler = this._graphicLayer.on("mouse-out", lang.hitch(this, function(evt){
                    if(!evt.graphic.associatedGraphic){
                        if (evt.graphic._buffer) {
                            evt.graphic = evt.graphic._buffer;
                        }

                        if (evt.graphic._buffers) {
                            array.forEach(evt.graphic._buffers, lang.hitch(this, function(buf) {
                                buf.setSymbol(buf._originalSymbol);
                                delete buf._originalSymbol;
                            }));
                        }
                        evt.graphic.setSymbol(evt.graphic._originalSymbol);
                        delete evt.graphic._originalSymbol;
                    }
                }));
            },

            createHighlightSymbol: function(graphic) {
                switch (graphic.geometry.type) {
                    case 'point':
                    case 'multipoint':
                        if(graphic.symbol.type == 'textsymbol'){
                            this._createTextHighlightSymbol(graphic);
                        }
                        else if(graphic.symbol.type == 'picturemarkersymbol'){
                            graphic.symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, graphic.symbol.width + 5, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0, 255, 255]), 3), new Color([0, 255, 255, 0.5]));
                        }
                        else {
                            graphic.symbol = new SimpleMarkerSymbol(graphic.symbol.style, graphic.symbol.size + 10, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0, 255, 255]), graphic.symbol.outline.width + 4), new Color([0, 255, 255, 0.5]));
                        }
                        break;
                    case 'polyline':
                    case 'extent':
                        graphic.symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0, 255, 255]), graphic.symbol.width + 4);
                        break;
                    case 'polygon':
                        graphic.symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0, 255, 255]), 4), new Color([0, 255, 255, 0.5]));
                        break;
                }
            },

            _createTextHighlightSymbol: function(graphic){
                var font  = new Font();
                font.setSize(graphic.symbol.font.size + 8);
                font.setWeight(Font.WEIGHT_BOLDER);

                var textSymbol = new TextSymbol();
                textSymbol.setText(graphic.symbol.text);
                textSymbol.setColor(new Color([0, 255, 255, 0.5]));
                textSymbol.setFont(font);
                textSymbol.setAlign(Font.ALIGN_START);
                textSymbol.setAngle(graphic.symbol.angle);

                graphic.symbol = textSymbol;
            },

            _editEndHandler: [],
            activateEditTool: function() {
                this.deactivateEraseTool();
                this.deactivateDrawTool();

                this._graphicLayerClickHandler = this._graphicLayer.on("click", lang.hitch(this, function(evt){
                    var defaultProperties = this._mapService.defaultProperties;
                    var graphic = evt.graphic;
                    if (defaultProperties && defaultProperties.length > 0) {
                        if (!graphic.attributes) {
                            graphic.attributes = {};
                            array.forEach(defaultProperties, lang.hitch(this, function(p) {
                                graphic.attributes[p] = '';
                            }))
                        }
                    }
                    domClass.add(this['draw' + 'DrawTools' + 'Content'], "activated");
                    this.initEditCurrentType(evt.graphic);

                    if (evt.graphic._buffer) {
                        // c'est un buffer, ne rien faire
                    }
                    else if(evt.graphic.symbol && evt.graphic.symbol.type == "textsymbol"){
                        this._editToolbar.activate(Edit.EDIT_TEXT|Edit.MOVE, evt.graphic);
                    } else if(evt.graphic.symbol && evt.graphic.symbol.type == "picturemarkersymbol"){
                        this._editToolbar.activate(Edit.MOVE, evt.graphic);
                    } else {
                        this._editToolbar.activate(Edit.EDIT_VERTICES|Edit.EDIT_TEXT|Edit.MOVE|Edit.ROTATE|Edit.SCALE, evt.graphic);

                        if(this._editEndHandler){
                            array.forEach(this._editEndHandler, function(handler){handler.remove()});
                            this._editEndHandler = [];
                        }

                        if (evt.graphic._bufferValue) {
                            this.bufferSpinner.set('value', evt.graphic._bufferValue);
                        }
                        else {
                            this.bufferSpinner.reset();
                        }

                        if (evt.graphic._coordinates) {
                            this.coordsCheckBox.set('checked', true);
                        }
                        else {
                            this.coordsCheckBox.set('checked', false);
                        }

                        if (evt.graphic._repetitionValue) {
                            this.repetitionSpinner.set('value', evt.graphic._repetitionValue);
                        }
                        else {
                            this.repetitionSpinner.reset();
                        }

                        this.bufferLabelsCheckBox.set('checked', evt.graphic._bufferLabels == null ? true : evt.graphic._bufferLabels);

                        this._editEndHandler.push(this._editToolbar.on("scale-stop", lang.hitch(this, this.onGraphicEditEnd)));
                        this._editEndHandler.push(this._editToolbar.on("vertex-move-stop", lang.hitch(this, this.onGraphicEditEnd)));
                        this._editEndHandler.push(this._editToolbar.on("graphic-move-stop", lang.hitch(this, this.onGraphicEditEnd)));
                    }

                    this.hideProperties();

                    if(evt.graphic && evt.graphic.symbol){
                        this.showEditToolProperties(evt.graphic);
                        this.listenPropertiesChange();
                    }

                    this.showApercu();
                }));
            },

            onGraphicEditEnd: function(editEvent){
                var g = editEvent.graphic;

                if (g._buffers) {
                    this.createBuffers(g, this.bufferSpinner.get('value'), this.repetitionSpinner.get('value'));
                }

                if (g._coordinates) {
                    this.displayCoords(g);
                }

                if(g.associatedMesure){
                    this._graphicLayer.remove(g.associatedMesure);
                    delete g.associatedMesure;
                }
                if(g.associatedArea){
                    this._graphicLayer.remove(g.associatedArea);
                    delete g.associatedArea;
                }

                if(this.displayLengthSelect.get('value') != "NULL" && g.geometry.type == "polyline"){
                    this.displayLength(g);
                }
                if((this.displayLengthSelect.get('value') != "NULL" || this.displaySuperfSelect.get('value') != "NULL") && g.geometry.type == "polygon"){
                    this.displayAreasAndLength(g);
                }

                console.log("End Edit OK");
            },

            _editListener: null,
            listenPropertiesChange: function(){
                this.removePropertiesChange();
                this._editListener = [];

                this._editListener.push(this.colorPickerFill.on('change', lang.hitch(this, function(newColor){
                    var graphic = this._editToolbar.getCurrentState().graphic;
                    var a = graphic.symbol.color.a;
                    graphic.symbol.color = new Color(newColor);
                    if(typeof a != 'undefined'){
                        graphic.symbol.color.a = a;
                    }
                    graphic.setSymbol(graphic.symbol);
                })));

                this._editListener.push(this.fillOpacitySlider.on('change', lang.hitch(this, function(newValue){
                    var graphic = this._editToolbar.getCurrentState().graphic;
                    graphic.symbol.color.a = newValue / 100;
                    graphic.setSymbol(graphic.symbol);
                })));

                this._editListener.push(this.colorPickerLine.on('change', lang.hitch(this, function(newColor){
                    var graphic = this._editToolbar.getCurrentState().graphic;
                    if(graphic.symbol.outline)
                        graphic.symbol.outline.color = new Color(newColor);
                    else
                        graphic.symbol.color = new Color(newColor);
                    graphic.setSymbol(graphic.symbol);
                })));

                this._editListener.push(this.weightLineSpinner.on('change', lang.hitch(this, function(newValue){
                    var graphic = this._editToolbar.getCurrentState().graphic;
                    if(graphic.symbol.outline)
                        graphic.symbol.outline.width = newValue;
                    else
                        graphic.symbol.width = newValue;
                    graphic.setSymbol(graphic.symbol);
                })));

                this._editListener.push(this.styleLineSelect.on('change', lang.hitch(this, function(newValue){
                    var graphic = this._editToolbar.getCurrentState().graphic;
                    if(graphic.symbol.outline)
                        graphic.symbol.outline.style = SimpleLineSymbol[this.styleLineSelect.get('value')];
                    else
                        graphic.symbol.style = SimpleLineSymbol[this.styleLineSelect.get('value')];
                    graphic.setSymbol(graphic.symbol);
                })));

                this._editListener.push(this.displayLengthSelect.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;

                    if(g.associatedMesure){
                        this._graphicLayer.remove(g.associatedMesure);
                        delete g.associatedMesure;
                    }
                    if(g.associatedArea){
                        this._graphicLayer.remove(g.associatedArea);
                        delete g.associatedArea;
                    }

                    if(this.displayLengthSelect.get('value') != "NULL" && g.geometry.type == "polyline"){
                        this.displayLength(g);
                    }
                    if((this.displayLengthSelect.get('value') != "NULL" || this.displaySuperfSelect.get('value') != "NULL") && g.geometry.type == "polygon"){
                        this.displayAreasAndLength(g);
                    }
                })));
                this._editListener.push(this.displaySuperfSelect.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;

                    if(g.associatedMesure){
                        this._graphicLayer.remove(g.associatedMesure);
                        delete g.associatedMesure;
                    }
                    if(g.associatedArea){
                        this._graphicLayer.remove(g.associatedArea);
                        delete g.associatedArea;
                    }

                    if((this.displayLengthSelect.get('value') != "NULL" || this.displaySuperfSelect.get('value') != "NULL") && g.geometry.type == "polygon"){
                        this.displayAreasAndLength(g);
                    }
                })));

                this._editListener.push(this.colorPickerText.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.setColor(new Color(newValue));
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.textareaText.on('keyup', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.setText(this.textareaText.get('value'));
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.textFontSelect.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.font.setFamily(newValue);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.bufferSpinner.on('change', lang.hitch(this, function(newValue){
                    this.createBuffers(this._editToolbar.getCurrentState().graphic, newValue,
                        this.repetitionSpinner.get('value'));
                })));
                this._editListener.push(this.bufferLabelsCheckBox.on('change', lang.hitch(this, function(){
                    this.createBuffers(this._editToolbar.getCurrentState().graphic, this.bufferSpinner.get('value'),
                        this.repetitionSpinner.get('value'));
                })));
                this._editListener.push(this.repetitionSpinner.on('change', lang.hitch(this, function(newValue){
                    this.createBuffers(this._editToolbar.getCurrentState().graphic, this.bufferSpinner.get('value'),
                        newValue);
                })));
                this._editListener.push(this.textSizeSpinner.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.font.setSize(newValue);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.textWeightSelect.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.font.setWeight(Font[newValue]);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.textStyleSelect.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.font.setStyle(Font[newValue]);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.textRadiusSpinner.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.setAngle(newValue);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.typePointSelect.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.setStyle(SimpleMarkerSymbol[newValue]);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.sizePointSpinner.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.setSize(newValue);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.heightPictoSpinner.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.setHeight(newValue);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.widthPictoSpinner.on('change', lang.hitch(this, function(newValue){
                    var g = this._editToolbar.getCurrentState().graphic;
                    g.symbol.setWidth(newValue);
                    g.setSymbol(g.symbol);
                })));
                this._editListener.push(this.watch('_currPicto', lang.hitch(this, function(prop, oldValue, newValue){
                    if(newValue){
                        var g = this._editToolbar.getCurrentState().graphic;
                        g.symbol.setUrl(newValue);
                        g.setSymbol(g.symbol);
                    }
                })));
            },

            removePropertiesChange: function() {
                array.forEach(this._editListener, lang.hitch(this, function(handler){
                    handler.remove();
                }));
                this._editListener = null;
            },

            _drawHandler: null,
            _currentType: null,
            activateDrawTool: function(drawData) {
                this.deactivateDrawTool();
                this.deactivateEditTool();
                this.deactivateEraseTool();

                this.activateTool('DrawTools');

                this.initCurrentType(drawData);

                if(Draw[drawData]){
                    this._drawHandler = this._drawToolbar.on('draw-end', lang.hitch(this, this.onDrawEnd));
                    this._drawToolbar.activate(Draw[drawData]);
                    this.showDrawToolProperties(drawData);
                } else if (drawData == 'TEXT'){
                    this._drawHandler = this._drawToolbar.on('draw-end', lang.hitch(this, this.onAddText));
                    this._drawToolbar.activate(Draw.POINT);
                    this.showDrawToolProperties(drawData);
                } else if (drawData == 'PICTO'){
                    this._drawHandler = this._drawToolbar.on('draw-end', lang.hitch(this, this.onAddPicto));
                    this._drawToolbar.activate(Draw.POINT);
                    this.showDrawToolProperties(drawData);
                } else if (drawData == 'DB_ARROW'){
                    this._drawHandler = this._drawToolbar.on('draw-end', lang.hitch(this, this.onAddDbArrow));
                    this._drawToolbar.activate(Draw.POINT);
                    this.showDrawToolProperties(drawData);
                } else if (typeof(this[drawData+'Activated']) == 'function'){
                    this[drawData+'Activated'].apply(this, []);
                }
                else {
                    console.log("Invalid draw data. Tool not defined : " + drawData);
                }

                this.showApercu();
            },

            onAddDbArrow: function(evt) {
                var m = this.spwViewer.get('spwMap').esriMap, g = screenUtils.toScreenGeometry(m.extent, m.width, m.height, evt.geometry);

                var geometry = new Polygon([[g.x, g.y+50],[g.x+200, g.y+50], [g.x+200, g.y+100], [g.x+250, g.y], [g.x+200, g.y-100], [g.x+200, g.y-50], [g.x, g.y-50], [g.x, g.y-100], [g.x-50, g.y], [g.x, g.y+100], [g.x, g.y+50]]);
                geometry = screenUtils.toMapGeometry(m.extent, m.width, m.height, geometry);
                var graphic = new Graphic(geometry, this.getSymbolParameter());

                if((this.displayLengthSelect.get('value') != "NULL" || this.displaySuperfSelect.get('value') != "NULL") && geometry.type == "polygon"){
                    this.displayAreasAndLength(graphic);
                }
                this.addGraphic(graphic);
            },

            _toPolygon: function(c, a, b) {
                var d = this.spwViewer.get('spwMap').esriMap, g = new Polygon(d.spatialReference);
                g.addRing(array.map(c, function(c) {
                    return d.toMap({
                        x: c[0] + a,
                        y: c[1] + b
                    });
                }));
                return g;
            },

            showApercu: function(){
                var c = domConstruct.create('canvas', {width:"230", height:'200', style:"border: 1px solid gray;"});
                this.apercuPane.set('content', c);
                var ctx = c.getContext("2d");

                switch(this._currentType)
                {
                    case 'point':
                        this.drawPoint(ctx);
                        break;
                    case 'line':
                        this.drawLine(ctx, 10, 100, 220, 100);
                        break;

                    case 'shape':
                        this.drawShape(ctx);
                        break;
                    case 'text':
                        this.drawText(ctx);
                        break;
                    case 'picto':
                        this.drawImage(ctx);
                        break;
                }
                this.listenApercuPropertiesChange();
            },

            hideApercu: function(){
                this.removeApercuPropertiesChange();
                this.apercuPane.set('content', '<div></div>');
            },

            _apercuListener: null,
            listenApercuPropertiesChange: function(){
                this.removeApercuPropertiesChange();
                this._apercuListener = [];

                this._apercuListener.push(this.colorPickerFill.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.fillOpacitySlider.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.colorPickerLine.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.weightLineSpinner.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.styleLineSelect.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.displayLengthSelect.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.displaySuperfSelect.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.colorPickerText.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.textareaText.on('keyup', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.textFontSelect.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.textSizeSpinner.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.textWeightSelect.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.textStyleSelect.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.textRadiusSpinner.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.typePointSelect.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.sizePointSpinner.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.heightPictoSpinner.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.widthPictoSpinner.on('change', lang.hitch(this, this.showApercu)));
                this._apercuListener.push(this.watch('_currPicto', lang.hitch(this, this.showApercu)));
            },

            removeApercuPropertiesChange: function() {
                array.forEach(this._apercuListener, lang.hitch(this, function(handler){
                    handler.remove();
                }));
                this._apercuListener = null;
            },

            drawShape: function(ctx) {
                ctx.beginPath();
                ctx.rect(20, 25, 190, 150);
                ctx.fillStyle = this.colorPickerFill.get('value');
                ctx.globalAlpha=this.fillOpacitySlider.get('value')/100;
                ctx.fill();

                ctx.globalAlpha = 1;
                this.drawLine(ctx, 20, 25, 210, 25);
                this.drawLine(ctx, 20, 25, 20, 175);
                this.drawLine(ctx, 20, 175, 210, 175);
                this.drawLine(ctx, 210, 25, 210, 175);
            },

            drawLine: function(ctx, xmin, ymin, xmax, ymax){
                ctx.beginPath();
                ctx.strokeStyle = this.colorPickerLine.get('value');
                ctx.lineWidth = this.weightLineSpinner.get('value');
                ctx.moveTo(xmin,ymin);

                var invert = !(xmin < xmax), min = xmin < xmax ? xmin : ymin, max = xmin < xmax ? xmax : ymax;
                switch(this.styleLineSelect.get('value')){
                    case 'STYLE_DASH':
                        for(var i = min; i < max; i = this._lineAndMove(ctx, 4, 3, xmax, ymax, i, invert)); break;
                    case 'STYLE_DASHDOT':
                        for(var i = min, dash = 1; i < max; i = (dash++%2) ? this._lineAndMove(ctx, 4, 3, xmax, ymax, i, invert) : this._lineAndMove(ctx, 1, 3, xmax, ymax, i, invert)); break;
                    case 'STYLE_DASHDOTDOT':
                        for(var i = min, point = 3; i < max; i = (!(point++%3)) ? this._lineAndMove(ctx, 8, 3, xmax, ymax, i, invert) : this._lineAndMove(ctx, 1, 3, xmax, ymax, i, invert)); break;
                    case 'STYLE_DOT':
                        for(var i = min; i < max; i = this._lineAndMove(ctx, 1, 3, xmax, ymax, i, invert)); break;
                    case 'STYLE_LONGDASH':
                        for(var i = min; i < max; i = this._lineAndMove(ctx, 8, 3, xmax, ymax, i, invert)); break;
                    case 'STYLE_LONGDASHDOT':
                        for(var i = min, dash = 1; i < max; i = (dash++%2) ? this._lineAndMove(ctx, 8, 3, xmax, ymax, i, invert) : this._lineAndMove(ctx, 1, 3, xmax, ymax, i, invert)); break;
                    case 'STYLE_SHORTDASH':
                        for(var i = min; i < max; i = this._lineAndMove(ctx, 4, 1, xmax, ymax, i, invert)); break;
                    case 'STYLE_SHORTDASHDOT':
                        for(var i = min, dash = 1; i < max; i = (dash++%2) ? this._lineAndMove(ctx, 4, 1, xmax, ymax, i, invert) : this._lineAndMove(ctx, 1, 1, xmax, ymax, i, invert)); break;
                    case 'STYLE_SHORTDASHDOTDOT':
                        for(var i = xmin, point = 3; i < max; i = (!(point++%3)) ? this._lineAndMove(ctx, 4, 1, xmax, ymax, i, invert) : this._lineAndMove(ctx, 1, 1, xmax, ymax, i, invert)); break;
                    case 'STYLE_SHORTDOT':
                        for(var i = min; i < max; i = this._lineAndMove(ctx, 1, 1, xmax, ymax, i, invert)); break;
                    case 'STYLE_SOLID': ctx.lineTo(xmax, ymax); break;
                }
                ctx.stroke();
            },

            drawPoint: function(ctx) {
                switch(this.typePointSelect.get('value'))
                {
                    case 'STYLE_CIRCLE':
                        ctx.beginPath();
                        ctx.arc(ctx.canvas.width / 2, ctx.canvas.height / 2, this.sizePointSpinner.get('value')/2, 0, 2 * Math.PI, false);
                        ctx.fillStyle = this.colorPickerFill.get('value');
                        ctx.globalAlpha=this.fillOpacitySlider.get('value')/100;
                        ctx.fill();

                        ctx.globalAlpha=1;
                        this.drawCircleLine(ctx);

                        break;
                    case 'STYLE_CROSS':
                        var size = this.sizePointSpinner.get('value');
                        ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
                        this.drawLine(ctx, -size/2, 0, size/2, 0);
                        this.drawLine(ctx, 0, -size/2, 0, size/2);
                        break;
                    case 'STYLE_DIAMOND':
                        ctx.beginPath();
                        ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
                        ctx.rotate((Math.PI*2/360)*45);

                        var size = this.sizePointSpinner.get('value');
                        var antehypo = Math.sqrt(Math.pow(size, 2)/2);

                        ctx.rect(-antehypo/2, -antehypo/2, antehypo, antehypo);
                        ctx.fillStyle = this.colorPickerFill.get('value');
                        ctx.globalAlpha=this.fillOpacitySlider.get('value')/100;
                        ctx.fill();

                        ctx.globalAlpha = 1;
                        this.drawLine(ctx, -antehypo/2, -antehypo/2, antehypo/2, -antehypo/2);
                        this.drawLine(ctx, -antehypo/2, -antehypo/2, -antehypo/2, antehypo/2);
                        this.drawLine(ctx, antehypo/2, -antehypo/2, antehypo/2, antehypo/2);
                        this.drawLine(ctx, -antehypo/2, antehypo/2, antehypo/2, antehypo/2);

                        break;
                    case 'STYLE_SQUARE':
                        ctx.beginPath();
                        ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
                        var size = this.sizePointSpinner.get('value');
                        ctx.rect(-size/2, -size/2, size, size);
                        ctx.fillStyle = this.colorPickerFill.get('value');
                        ctx.globalAlpha=this.fillOpacitySlider.get('value')/100;
                        ctx.fill();

                        ctx.globalAlpha = 1;
                        this.drawLine(ctx, -size/2, -size/2, size/2, -size/2);
                        this.drawLine(ctx, -size/2, -size/2, -size/2, size/2);
                        this.drawLine(ctx, -size/2, size/2, size/2, size/2);
                        this.drawLine(ctx, size/2, -size/2, size/2, size/2);

                        break;
                    case 'STYLE_X':
                        ctx.beginPath();
                        var size = this.sizePointSpinner.get('value');
                        var hypo = Math.sqrt(2*Math.pow(size, 2));
                        ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
                        ctx.rotate((Math.PI*2/360)*45);
                        this.drawLine(ctx, -hypo/2, 0, hypo/2, 0);
                        this.drawLine(ctx, 0, -hypo/2, 0, hypo/2);
                        break;
                }
            },

            drawCircleLine: function(ctx){
                switch(this.styleLineSelect.get('value')){
                    case 'STYLE_DASH': this._circleLineAndMove(ctx, 4,3); break;
                    case 'STYLE_DASHDOT': this._circleLineAndMove(ctx, 4, 3, 1, 3);break;
                    case 'STYLE_DASHDOTDOT': this._circleLineAndMove(ctx, 8, 3, 1, 3, 1, 3); break;
                    case 'STYLE_DOT': this._circleLineAndMove(ctx, 1,3); break;
                    case 'STYLE_LONGDASH': this._circleLineAndMove(ctx, 8, 3); break;break;
                    case 'STYLE_LONGDASHDOT': this._circleLineAndMove(ctx, 8, 3, 1, 3); break;break;
                    case 'STYLE_SHORTDASH': this._circleLineAndMove(ctx, 4, 1); break;break;
                    case 'STYLE_SHORTDASHDOT': this._circleLineAndMove(ctx, 4, 1, 1, 1); break;
                    case 'STYLE_SHORTDASHDOTDOT': this._circleLineAndMove(ctx, 4, 1, 1, 1, 1, 1); break;
                    case 'STYLE_SHORTDOT':this._circleLineAndMove(ctx, 1,1);  break;
                    case 'STYLE_SOLID': this._circleLineAndMove(ctx, (Math.PI*2*(this.sizePointSpinner.get('value')/2))/this.weightLineSpinner.get('value'),0); break;
                }
            },

            _circleLineAndMove: function(ctx, ratioLine, ratioSpace, ratioLine2, ratioSpace2, ratioLine3, ratioSpace3) {
                var cpt=0, alternate = ratioLine3 ? 3 : (ratioLine2 ? 2 : 1);
                var angle = this.weightLineSpinner.get('value')/(this.sizePointSpinner.get('value')/2);
                for(var i = 0 ; i < 2 * Math.PI; ){
                    ctx.beginPath();
                    ctx.lineWidth = this.weightLineSpinner.get('value');
                    var val = cpt++%alternate, ratioL, ratioS;
                    if(val === 0){ ratioL = ratioLine; ratioS = ratioSpace; }
                    else if(val === 1){ ratioL = ratioLine2; ratioS = ratioSpace2; }
                    else { ratioL = ratioLine3; ratioS = ratioSpace3; }

                    ctx.strokeStyle = this.colorPickerLine.get('value');
                    ctx.arc(ctx.canvas.width / 2, ctx.canvas.height / 2, this.sizePointSpinner.get('value')/2, i, i+=(angle*ratioL), false);
                    ctx.stroke();

                    ctx.strokeStyle = 'transparent';
                    ctx.arc(ctx.canvas.width / 2, ctx.canvas.height / 2, this.sizePointSpinner.get('value')/2, i, i+=(angle*ratioS), false);
                    ctx.stroke();
                }
            },

            drawImage: function(ctx) {
                var p = this.currentPicto();
                if(p){
                    var img = domConstruct.create("img", {onload: lang.hitch(this, function(){
                        ctx.drawImage(img,10,10,this.widthPictoSpinner.get('value'),this.heightPictoSpinner.get('value'));
                    }), src: p});
                }
            },

            drawText: function(ctx) {
                ctx.font = (this.textStyleSelect.get('value') != 'STYLE_NORMAL' ? 'italic' : '') + ' ' + ((this.textWeightSelect.get('value').indexOf('BOLD') > -1) ? 'bold' : '') + ' ' + this.textSizeSpinner.get('value') + 'px "'+this.textFontSelect.get('value')+'"';
                ctx.fillStyle = this.colorPickerText.get('value');
                ctx.translate(90, 100);
                ctx.rotate((Math.PI*2/360)*this.textRadiusSpinner.get('value'));
                ctx.fillText('Aperçu', -40, 0);
            },

            _lineAndMove: function(ctx, lineRatio, moveRatio, xmax, ymax, i, invert){
                var lx = (ctx.lineWidth)*lineRatio;
                var mx = (ctx.lineWidth)*moveRatio;
                if(invert){
                    ctx.lineTo(xmax, i+=((i+lx) < ymax ? lx : ymax-i));
                    ctx.moveTo(xmax, i+=((i+mx) < ymax ? mx : ymax-i));
                } else {
                    ctx.lineTo(i+=((i+lx) < xmax ? lx : xmax-i),ymax);
                    ctx.moveTo(i+=((i+mx) < xmax ? mx : xmax-i),ymax);
                }
                return i;
            },

            onAddText: function(evt){
                var pt = evt.geometry;
                var font  = new Font();
                font.setFamily(this.textFontSelect.get('value'));
                font.setSize(this.textSizeSpinner.get('value'));
                font.setWeight(Font[this.textWeightSelect.get('value')]);
                font.setStyle(Font[this.textStyleSelect.get('value')]);

                var textSymbol = new TextSymbol();
                textSymbol.setText(this.textareaText.get('value'));
                textSymbol.setColor(new Color(this.colorPickerText.get('value')));
                textSymbol.setFont(font);
                textSymbol.setAlign(Font.ALIGN_START);
                textSymbol.setAngle(this.textRadiusSpinner.get('value'));

                var gra = new Graphic(pt, textSymbol);
                this.addGraphic(gra);
            },

            onAddPicto: function(evt){
                var pt = evt.geometry;
                var p = new PictureMarkerSymbol(this.currentPicto(), this.widthPictoSpinner.get('value'), this.heightPictoSpinner.get('value'));
                var gra = new Graphic(pt, p);
                this.addGraphic(gra);
            },

            showDrawToolProperties: function(drawData) {
                this.hideProperties();
                switch(this._currentType)
                {
                    case 'point': this.showPointProperties(); break;
                    case 'line': this.showLineProperties(); break;
                    case 'shape': this.showPolygonProperties(); break;
                    case 'text': this.showTextProperties(); break;
                    case 'picto': this.showPictoProperties(); break;
                    default:
                        if(typeof(this['show'+drawData+'Properties']) == 'function') {
                            this['show'+drawData+'Properties'].apply(this, []);
                        } break;
                }

                switch(drawData) {
                    case 'ELLIPSE':
                    case 'CIRCLE':
                    case 'TRIANGLE':
                    case 'EXTENT':
                    case 'FREEHAND_POLYGON':
                    case 'POLYGON':
                    case 'UP_ARROW':
                    case 'DOWN_ARROW':
                    case 'LEFT_ARROW':
                    case 'RIGHT_ARROW':
                        this.measureLabel.innerHTML = 'Périmètre';
                        break;
                    default:
                        this.measureLabel.innerHTML = 'Longueur';
                }
            },

            showTextProperties: function(){
                this.textWeightRow.style.display = '';
                this.textStyleRow.style.display = '';
                this.textSizeRow.style.display = '';
                this.textValueRow.style.display = '';
                this.textColorRow.style.display = '';
                this.textFontRow.style.display = '';
                this.textRadiusRow.style.display = '';
            },

            showPictoProperties: function(){
                this.pictoRow.style.display = '';
                this.heightPictoRow.style.display = '';
                this.widthPictoRow.style.display = '';
            },

            showLineProperties: function(){
                this.displayLengthRow.style.display = '';
                this.separatorLineRow.style.display = '';
                this.lineStyleRow.style.display = '';
                this.lineWeightRow.style.display = '';
                this.lineColorRow.style.display = '';
                this.separatorBufferRow.style.display = '';
                this.displayBufferRow.style.display = '';
                this.displayRepetitionRow.style.display = '';
                this.displayBufferLabelsRow.style.display = '';
            },

            showPolygonProperties: function() {
                this.displaySuperfRow.style.display = '';
                this.displayLengthRow.style.display = '';
                this.separatorLineRow.style.display = '';
                this.lineStyleRow.style.display = '';
                this.lineWeightRow.style.display = '';
                this.lineColorRow.style.display = '';
                this.separatorFondRow.style.display = '';
                this.fondOpacityRow.style.display = '';
                this.fondColorRow.style.display = '';
                this.separatorBufferRow.style.display = '';
                this.displayBufferRow.style.display = '';
                this.displayRepetitionRow.style.display = '';
                this.displayBufferLabelsRow.style.display = '';
            },

            showPointProperties: function(visible){
                this.lineStyleRow.style.display = '';
                this.lineWeightRow.style.display = '';
                this.lineColorRow.style.display = '';
                this.separatorFondRow.style.display = '';
                this.fondOpacityRow.style.display = '';
                this.fondColorRow.style.display = '';
                this.separatorPointRow.style.display = '';
                this.taillePointRow.style.display = '';
                this.typePointRow.style.display = '';
                this.separatorBufferRow.style.display = '';
                this.displayBufferRow.style.display = '';
                this.displayRepetitionRow.style.display = '';
                this.displayBufferLabelsRow.style.display = '';
                this.separatorCoordsRow.style.display = '';
                this.displayCoordsRow.style.display = '';
            },

            hideProperties: function(){
                this.displaySuperfRow.style.display = 'none';
                this.displayLengthRow.style.display = 'none';
                this.separatorLineRow.style.display = 'none';
                this.lineStyleRow.style.display = 'none';
                this.lineWeightRow.style.display = 'none';
                this.lineColorRow.style.display = 'none';
                this.separatorFondRow.style.display = 'none';
                this.fondOpacityRow.style.display = 'none';
                this.fondColorRow.style.display = 'none';
                this.separatorPointRow.style.display = 'none';
                this.taillePointRow.style.display = 'none';
                this.typePointRow.style.display = 'none';
                this.textWeightRow.style.display = 'none';
                this.textStyleRow.style.display = 'none';
                this.textSizeRow.style.display = 'none';
                this.textValueRow.style.display = 'none';
                this.textColorRow.style.display = 'none';
                this.textFontRow.style.display = 'none';
                this.textRadiusRow.style.display = 'none';
                this.pictoRow.style.display = 'none';
                this.heightPictoRow.style.display = 'none';
                this.widthPictoRow.style.display = 'none';
                this.separatorBufferRow.style.display= 'none';
                this.displayBufferRow.style.display = 'none';
                this.displayRepetitionRow.style.display = 'none';
                this.displayBufferLabelsRow.style.display = 'none';
                this.separatorCoordsRow.style.display = 'none';
                this.displayCoordsRow.style.display = 'none';
            },

            showEditToolProperties: function(graphic) {
                this.hideProperties();
                switch(this._currentType)
                {
                    case 'point': this.initializePointControls(graphic); this.showPointProperties(); break;
                    case 'text': this.initializeTextControls(graphic); this.showTextProperties(); break;
                    case 'line': this.initializeLineControls(graphic); this.showLineProperties(); break;
                    case 'shape': this.initializePolygonControls(graphic); this.showPolygonProperties(); break;
                    case 'picto': this.initializePictoControls(graphic); this.showPictoProperties(); break;
                }
            },

            initEditCurrentType: function(graphic){
                if (!graphic.symbol) {
                    graphic.symbol =  symbolsJsonUtils.fromJson(this._mapService.layer.renderer.getSymbol().toJson());
                }
                switch(graphic.geometry.type)
                {
                    case 'point': this._currentType = (graphic.symbol.type != "textsymbol" ? (!graphic.symbol || graphic.symbol.type != "picturemarkersymbol" ? 'point' : 'picto') : 'text'); break;
                    case 'polyline': this._currentType = 'line'; break;
                    case 'polygon': this._currentType = 'shape'; break;
                }
                this.configurePropertiesForm(graphic);
            },

            _currentEditingGraphic: null,
            _formTab: null,
            configurePropertiesForm: function(graphic) {
                domConstruct.empty(this.propertiesForm);
                this._currentEditingGraphic = graphic;
                ViewUtils.showElement(this.propertiesContainer);
                ViewUtils.hideElement(this._savePropertiesButton);
                ViewUtils.hideElement(this._savePropertiesForLayerCheckboxContainer);
                if (graphic.attributes) {
                    var attributes = graphic.attributes;
                    var attr = Object.keys(graphic.attributes);
                    if (attr && attr.length > 0) {
                        ViewUtils.showElement(this._savePropertiesButton);
                        ViewUtils.showElement(this._savePropertiesForLayerCheckboxContainer);
                        this._formTab = domConstruct.create('table', {style: {'width': '100%'}}, this.propertiesForm);
                        array.forEach(attr, lang.hitch(this, function(a) {
                            this.buildRow(attributes, a);
                        }))
                    }
                } else {
                    this._formTab = domConstruct.create('table', {style: {'width': '100%'}}, this.propertiesForm);
                }
                if (this._graphicLayer.graphics.length > 1) {
                    ViewUtils.hideElement(this._savePropertiesForLayerCheckboxContainer);
                }
            },

            buildRow: function(attributes, a) {
                ViewUtils.showElement(this._savePropertiesButton);
                ViewUtils.showElement(this._savePropertiesForLayerCheckboxContainer);
                if (this._graphicLayer.graphics.length > 1) {
                    ViewUtils.hideElement(this._savePropertiesForLayerCheckboxContainer);
                }
                var tr = domConstruct.create('tr', null, this._formTab);

                var tdLabel = domConstruct.create('td', {style: {'width': '100px'}}, tr);
                var label = domConstruct.create('label', {for: ''+a, innerHTML: ''+a +': ', style:{'font-size': '12px', 'width': '100px'}}, tdLabel);

                var tdInput = domConstruct.create('td', {style: {'width': '150px'}}, tr);
                var txtBox = new ValidationTextBox({
                    value: attributes && attributes[a] ? attributes[a] : '',
                    name: a,
                    style: 'width: 150px;'
                }, domConstruct.create('input', null));
                tdInput.appendChild(txtBox.domNode);

                var tdDelete = domConstruct.create('td', {style: {'width': '50px'}}, tr);
                var deleteIcon = domConstruct.create('div', {class: 'deleteIcon'}, tdDelete);
                deleteIcon.onclick=lang.hitch(this, function() {
                    domConstruct.empty(tr);
                    this.setGraphicProperties(false);
                });
            },

            saveProperties: function(reload) {
                if (this._currentEditingGraphic) {
                    this.setGraphicProperties(true);
                    this.configurePropertiesForm(this._currentEditingGraphic);
                }
            },

            setGraphicProperties: function(showMessage) {
                var formObj = domForm.toObject(this.propertiesForm);
                this._currentEditingGraphic.attributes = formObj;
                if (showMessage) {
                    MessageManager.getInstance().notifyInfo('Propriétés sauvegardées', 'Infos', 3000);
                }
            },

            addProperty: function() {
                this.buildRow(this._currentEditingGraphic.attributes, this._newAttrName.value);
                this._newAttrName.set('value', '');
                this.setGraphicProperties(false);
            },

            savePropertiesForLayerCheckboxClicked: function() {
                if (this.savePropertiesForLayerCheckbox.checked) {
                    if (this._currentEditingGraphic) {
                        var formObj = domForm.toObject(this.propertiesForm);
                        var keys = Object.keys(formObj);
                        this._mapService.defaultProperties = keys;
                        MessageManager.getInstance().notifyInfo('Propriétés définies pour la couche', 'Infos', 3000);
                    }
                } else {
                    this._mapService.defaultProperties = [];
                    MessageManager.getInstance().notifyInfo('Propriétés de la couche supprimées', 'Infos', 3000);
                }

            },

            initializePolygonControls: function(graphic) {
                this.displaySuperfSelect.set('value', (graphic.geometry && graphic.associatedArea) ? graphic.associatedArea.selectedValue : 'NULL');
                this.displayLengthSelect.set('value', (graphic.geometry && graphic.associatedMesure) ? graphic.associatedMesure.selectedValue : 'NULL');

                if (graphic.symbol.outline) {
                    this.styleLineSelect.set('value', this.getLineStyleFromValue(graphic.symbol.outline.style));
                    this.weightLineSpinner.set('value', graphic.symbol.outline.width);
                    this.colorPickerLine.setColor(graphic.symbol.outline.color.toString());this.onLineColorChange(graphic.symbol.outline.color.toString());
                }

                this.fillOpacitySlider.set('value', graphic.symbol.color.a * 100);
                this.colorPickerFill.setColor(graphic.symbol.color.toString());this.onFillColorChange(graphic.symbol.color.toString());
            },

            initializeLineControls: function(graphic) {
                this.displayLengthSelect.set('value', (graphic.geometry && graphic.associatedMesure) ? graphic.associatedMesure.selectedValue : 'NULL');
                this.styleLineSelect.set('value', this.getLineStyleFromValue(graphic.symbol.style));
                this.weightLineSpinner.set('value', graphic.symbol.width);
                this.colorPickerLine.setColor(graphic.symbol.color.toString());this.onLineColorChange(graphic.symbol.color.toString());
            },

            initializePointControls: function(graphic){
                if(graphic.symbol.outline){
                    this.styleLineSelect.set('value', this.getLineStyleFromValue(graphic.symbol.outline.style));
                    this.weightLineSpinner.set('value', graphic.symbol.outline.width);
                    this.colorPickerLine.setColor(graphic.symbol.outline.color.toString());this.onLineColorChange(graphic.symbol.outline.color.toString());
                }
                this.fillOpacitySlider.set('value', graphic.symbol.color.a * 100);
                this.colorPickerFill.setColor(graphic.symbol.color.toString());this.onFillColorChange(graphic.symbol.color.toString());
                this.sizePointSpinner.set('value', graphic.symbol.size);
                this.typePointSelect.set('value', this.getMarkerStyleFromValue(graphic.symbol.style));
            },

            initializeTextControls: function(graphic){
                this.colorPickerText.setColor(graphic.symbol.color.toString());this.onTextColorChange(graphic.symbol.color.toString());
                this.textareaText.set('value', graphic.symbol.text);
                this.textFontSelect.set('value', graphic.symbol.font.family);
                this.textSizeSpinner.set('value', graphic.symbol.font.size);
                this.textWeightSelect.set('value', this.getTextWeightFromValue(graphic.symbol.font.weight));
                this.textStyleSelect.set('value', this.getTextStyleFromValue(graphic.symbol.font.style));
                this.textRadiusSpinner.set('value', graphic.symbol.angle);
            },

            initializePictoControls: function(graphic){
                var val = graphic.symbol.url;

                array.some(this.pictoButtons, lang.hitch(this, function(btn){
                    if(btn.pictoSrc == val){
                        btn.set('checked', true);
                        return true;
                    }
                    return false;
                }));

                this.widthPictoSpinner.set('value', graphic.symbol.width);
                this.heightPictoSpinner.set('value', graphic.symbol.height);
            },

            getLineStyleFromValue: function(style){
                for(var k in SimpleLineSymbol){
                    if(typeof SimpleLineSymbol[k] == 'string' && style == SimpleLineSymbol[k]){
                        return k;
                    }
                }
                return style;
            },

            getTextStyleFromValue: function(style){
                for(var k in Font){
                    if(typeof Font[k] == 'string' && style == Font[k]){
                        return k;
                    }
                }
                return style;
            },

            getTextWeightFromValue: function(weight){
                for(var k in Font){
                    if(typeof Font[k] == 'string' && weight == Font[k]){
                        return k;
                    }
                }
                return weight;
            },

            getMarkerStyleFromValue: function(style){
                for(var k in SimpleMarkerSymbol){
                    if(typeof SimpleMarkerSymbol[k] == 'string' && style == SimpleMarkerSymbol[k]){
                        return k;
                    }
                }
                return style;
            },

            addGraphic: function(g) {
                this._graphicLayer.add(g);

                // var length = this._graphicLayer.graphics.length;

                if (this._mapService.get('newLayer')) {
                    // sauver la couche !
                    this.saveData(this._mapService.get('label'));
                }
            },

            onDrawEnd: function(evt) {
                var geometry = evt.geometry;

                if(geometry.type == "extent"){
                    geometry = new Polygon([[geometry.xmax, geometry.ymax], [geometry.xmax, geometry.ymin], [geometry.xmin, geometry.ymin], [geometry.xmin, geometry.ymax], [geometry.xmax, geometry.ymax]]);
                    geometry.spatialReference = this.spwViewer.get('spatialReference');
                }

                var graphic = new Graphic(geometry, this.getSymbolParameter());

                if (/shape|point|line/.test(this._currentType)) {
                    this.createBuffers(graphic, this.bufferSpinner.get('value'), this.repetitionSpinner.get('value'));
                }

                if(this.displayLengthSelect.get('value') != "NULL" && geometry.type == "polyline"){
                    this.displayLength(graphic);
                }

                if((this.displayLengthSelect.get('value') != "NULL" || this.displaySuperfSelect.get('value') != "NULL") && geometry.type == "polygon"){
                    this.displayAreasAndLength(graphic);
                }

                this.displayCoords(graphic);

                this.addGraphic(graphic);
            },

            createBuffers: function(g, buf, repetition) {
                array.forEach(g._buffers, lang.hitch(this, function(buf) {
                    buf.associatedMesure && this._graphicLayer.remove(buf.associatedMesure);
                    this._graphicLayer.remove(buf);
                }));

                g._bufferValue = buf;
                g._repetitionValue = repetition;
                g._bufferLabels = this.bufferLabelsCheckBox.get('checked');

                g._buffers = null;

                if (buf <= 0 || repetition <= 0) {
                    return;
                }

                var symbol = this.getBufferSymbol();

                var graphs = [];
                var tmpGraph = null;

                var center = null;

                if (this._currentType === 'shape') {
                    center = g.geometry.getCentroid();
                }
                else if (this._currentType === 'point') {
                    center = g.geometry;
                }
                else {
                    center = g.geometry.getExtent().getCenter();
                }

                for (var i = 1; i <= repetition; ++i) {
                    tmpGraph = new Graphic(GeometryUtils.buffer(g.geometry, buf * i, 'meters'), symbol);
                    tmpGraph._buffer = g;

                    graphs.push(tmpGraph);
                    this._graphicLayer.add(tmpGraph);

                    if (this.bufferLabelsCheckBox.get('checked')) {
                        var width = tmpGraph.geometry.getExtent().getWidth();
                        var height = tmpGraph.geometry.getExtent().getHeight();

                        var lineAt45 = new Polyline([
                            [center.x, center.y],
                            [center.x + (Math.cos(-45) * width), center.y + (Math.sin(-45) * height)]
                        ]);
                        lineAt45.setSpatialReference(center.spatialReference);

                        var pt = GeometryUtils.intersection(tmpGraph.geometry, lineAt45);

                        var txt = new Graphic(
                            pt,
                            new TextSymbol(
                                "" + (Math.round(buf * i * 1000) / 1000) + " m",
                                new Font("16pt", Font.STYLE_NORMAL, Font.VARIANT_NORMAL, Font.WEIGHT_BOLD, "Courier"),
                                symbol.color
                            ).setOffset(40,0)
                        );

                        lang.mixin(tmpGraph, {associatedMesure: txt});
                        lang.mixin(txt, {associatedGraphic: tmpGraph, selectedValue: (buf * i)});

                        this._graphicLayer.add(txt);
                    }
                }

                g._buffers = graphs;
            },

            displayCoords: function(g) {
                if (g._coordinates) {
                    this._graphicLayer.remove(g._coordinates);
                    g._coordinates = null;
                }

                if (this._currentType === 'point' && this.coordsCheckBox.get('checked')) {
                    var mapSrid = this.spwViewer.get('spwMap').getSpatialReferenceSRID();
                    var geom = g.geometry;

                    if (mapSrid != 31370) {
                        geom = ProjectionManager.getInstance().transform(mapSrid, 4326, geom);
                    }

                    var txt = new Graphic(
                        g.geometry,
                        new TextSymbol(
                            '(' + (Math.round(geom.x*100)/100) + ', ' + (Math.round(geom.y*100)/100) + ')',
                            new Font("12pt", Font.STYLE_NORMAL, Font.VARIANT_NORMAL, Font.WEIGHT_BOLD, "Courier"),
                            g.symbol.outline ? g.symbol.outline.color ? g.symbol.outline.color : g.symbol.color : g.symbol.color
                        ).setOffset(0, -20)
                    );

                    lang.mixin(g, {_coordinates: txt});
                    lang.mixin(txt, {associatedGraphic: g});
                    this._graphicLayer.add(txt);
                }
            },

            displayLength: function(g){
                var mesure = GeometryUtils.geometryLength(g.geometry, 'meters');
                if(this.displayLengthSelect.get('value') == "KM"){
                    mesure /= 1000;
                }
                var graphic = new Graphic(new Point(g.geometry.paths[0][0], this.spwViewer.get('spatialReference')), new TextSymbol(mesure + (this.displayLengthSelect.get('value') == "KM" ? "Km" : "m"), new Font("14pt").setWeight(Font.WEIGHT_BOLD)));
                lang.mixin(g, {associatedMesure: graphic});
                lang.mixin(graphic, {associatedGraphic: g, selectedValue: this.displayLengthSelect.get('value')});
                this._graphicLayer.add(graphic);
            },

            displayAreasAndLength: function(g) {
                //AREA
                if(this.displaySuperfSelect.get('value') != "NULL"){
                    var area = GeometryUtils.area(g.geometry, 'square-meters');
                    if(this.displaySuperfSelect.get('value') == "KM2"){
                        area /= 1000000;
                    }
                    area = Math.round(area * 100) / 100;
                    var graphic = new Graphic(new Point(g.geometry.rings[0][Math.round(g.geometry.rings[0].length/2)], this.spwViewer.get('spatialReference')), new TextSymbol(area + (this.displaySuperfSelect.get('value') == "KM2" ? "Km2" : "m2"), new Font("14pt").setWeight(Font.WEIGHT_BOLD)));
                    lang.mixin(g, {associatedArea: graphic});
                    lang.mixin(graphic, {associatedGraphic: g, selectedValue: this.displaySuperfSelect.get('value')});
                    this._graphicLayer.add(graphic);
                }
                // PERIMETER
                if(this.displayLengthSelect.get('value') != "NULL"){
                    var mesure = GeometryUtils.geometryLength(g.geometry, 'meters');
                    if(this.displayLengthSelect.get('value') == "KM"){
                        mesure /= 1000;
                    }
                    mesure = Math.round(mesure * 100, 2) / 100;
                    var graphic = new Graphic(new Point(g.geometry.rings[0][0], this.spwViewer.get('spatialReference')), new TextSymbol(mesure + (this.displayLengthSelect.get('value') == "KM" ? "Km" : "m"), new Font("14pt").setWeight(Font.WEIGHT_BOLD)));
                    lang.mixin(g, {associatedMesure: graphic});
                    lang.mixin(graphic, {associatedGraphic: g, selectedValue: this.displayLengthSelect.get('value')});
                    this._graphicLayer.add(graphic);
                }
            },

            initCurrentType: function(dataType){
                switch(dataType){
                    case 'POINT':
                        this._currentType = 'point';
                        break;
                    case 'LINE':
                    case 'POLYLINE':
                    case 'FREEHAND_POLYLINE':
                        this._currentType = 'line';
                        break;
                    case 'CIRCLE':
                    case 'POLYGON':
                    case 'ELLIPSE':
                    case 'FREEHAND_POLYGON':
                    case 'RIGHT_ARROW':
                    case 'LEFT_ARROW':
                    case 'DOWN_ARROW':
                    case 'UP_ARROW':
                    case 'DB_ARROW':
                    case 'EXTENT':
                    case 'TRIANGLE':
                        this._currentType = 'shape';
                        break;
                    case 'TEXT':
                        this._currentType = 'text';
                        break;
                    case 'PICTO':
                        this._currentType = 'picto';
                        break;
                    default: break;
                }
            },

            getBufferSymbol: function() {
                var colorLine = new Color(this.colorPickerLine.get('value'));
                var weightLine = this.weightLineSpinner.get('value');
                var colorFill = new Color(this.colorPickerFill.get('value')); colorFill.a = this.fillOpacitySlider.get('value') / 100;

                return new SimpleFillSymbol().setColor(null).outline.setColor(colorLine).setWidth(weightLine);
            },

            getSymbolParameter: function() {
                var colorLine = new Color(this.colorPickerLine.get('value'));
                var weightLine = this.weightLineSpinner.get('value');
                var sizePoint = this.sizePointSpinner.get('value');
                var colorFill = new Color(this.colorPickerFill.get('value')); colorFill.a = this.fillOpacitySlider.get('value') / 100;
                var styleLine = SimpleLineSymbol[this.styleLineSelect.get('value')];
                var typePoint = SimpleMarkerSymbol[this.typePointSelect.get('value')];

                var s;
                switch(this._currentType)
                {
                    case 'point':
                        s = new SimpleMarkerSymbol(typePoint, sizePoint, new SimpleLineSymbol(styleLine, colorLine, weightLine), colorFill);
                        break;
                    case 'line':
                        s = new SimpleLineSymbol(styleLine, colorLine, weightLine);
                        break;
                    case 'shape':
                        s = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(styleLine, colorLine, weightLine), colorFill);
                        break;
                    case 'text':
                        break;
                    default: break;
                }
                return s;
            },

            deactivateEraseTool: function() {
                if(this._graphicLayerClickHandler && this._graphicLayerClickHandler.advice){
                    this._graphicLayerClickHandler.remove();
                }
                if(this._mouseOutHandler)
                    this._mouseOutHandler.remove();
                if(this._mouseOverHandler)
                    this._mouseOverHandler.remove();
            },

            deactivateEditTool: function() {
                this.hideProperties();
                this.hideApercu();
                ViewUtils.hideElement(this.propertiesContainer);

                this.removePropertiesChange();

                if(this._graphicLayerClickHandler && this._graphicLayerClickHandler.advice){
                    this._graphicLayerClickHandler.remove();
                }
                if(this._editEndHandler){
                    array.forEach(this._editEndHandler, function(handler){handler.remove()});
                    this._editEndHandler = [];
                }
                if(this._editToolbar && this._editToolbar.getCurrentState().tool){
                    this._editToolbar.deactivate();
                }
            },

            deactivateDrawTool: function() {
                this.hideProperties();
                this.hideApercu();

                this._currentType = null;
                if(this._drawHandler && this._drawHandler.advice){
                    this._drawHandler.remove();
                }

                if (this._drawToolbar) {
                    this._drawToolbar.deactivate();
                }
            },

            onLineColorChange: function(newColor){
                query(".colorPreviewIcon", this.colorPickerLineButton.domNode).forEach(function(node){
                    node.style.backgroundColor = newColor;
                });
            },

            onFillColorChange: function(newColor){
                query(".colorPreviewIcon", this.colorPickerFillButton.domNode).forEach(function(node){
                    node.style.backgroundColor = newColor;
                });
            },

            onTextColorChange: function(newColor){
                query(".colorPreviewIcon", this.colorPickerTextButton.domNode).forEach(function(node){
                    node.style.backgroundColor = newColor;
                });
            },

            onNewLayerClick: function(){

                this.deactivateRefresh();

                this.selectLabel(true);

                if (this._mapService && this._mapService.get('newLayer')) {
                    this._graphicLayer.clear();
                }
                else {
                    this._mapService = this.spwViewer.get('spwMap').getMapServiceById(this.layerName);

                    if (this._mapService == null) {
                        this._fromThis = true;

                        this._mapService = this.spwViewer.get('spwMap').addMapService({
                            type: MapServiceFactory.types.DRAW_LAYER,
                            serviceId: this.layerName
                        });
                    }
                    else {
                        this._mapService.set('inTOC', true);
                    }

                    this._graphicLayer = this._mapService.get('layer');
                }
                console.log('default properties:', this._mapService.defaultProperties);
                this.selectLabel();
                this.buildTOC();
                this.drawLayerName = null;
                this.drawLayerId = null;
            },

            selectLabel: function(remove) {
                if (!this._mapService) {
                    return;
                }

                if (!remove && !this._mapService.get('currentDrawing')) {
                    this._mapService.set('currentDrawing', true);

                    this._curDrawingNode.set('value', this._mapService.get('label'));
                    query(this.domNode).query('.layerName').forEach(lang.hitch(this, function(n) { n.innerHTML = this._mapService.get('label'); }));

                    this.drawLayerId = this._mapService.serviceId;
                }
                else if (remove) {
                    this._mapService.set('currentDrawing', false);
                    this.drawLayerId = null;
                }
            },

            onLoadLayerClick: function(){
                var content = domConstruct.create("div", {innerHTML:'<p>Veuillez choisir la couche à ouvrir :</p>'});
                var delDialog = new Dialog({
                    title: "Enregistrer la couche de dessins courante",
                    content: content,
                    style: "width: 300px"
                });

                var input = domConstruct.create('select', {size:5, style:'width: 100%; margin: 0 0 5px 0;'}, content);
                var data = localStorage.getItem(this.layerName);
                var jsonData = JSON.parse(data);

                array.forEach(jsonData, function(j, idx){domConstruct.create('option', {innerHTML:j.name, value:idx}, input);});

                var div = domConstruct.create('div', {style:'text-align:right;'}, content);
                new Button({label:'Ouvrir'}, domConstruct.create('div', {}, div)).on('click', lang.hitch(this, function(){
                    var idx = input.options[input.selectedIndex].value;
                    this.drawLayerId = jsonData[idx].id;

                    this.addMapService(jsonData[idx].id, jsonData[idx].name, jsonData[idx].data);

                    delDialog.hide();
                }));
                new Button({label:'Annuler'}, domConstruct.create('div', {}, div)).on('click', lang.hitch(this, function(){
                    delDialog.hide();
                }));
                delDialog.show();
            },

            onSaveLayerClick: function(){

                if(this._graphicLayer.graphics.length < 1){
                    var content = domConstruct.create("div", {innerHTML:"<p>Impossible d'enregistrer la couche courante car aucun dessin n'est présent.</p>"});
                    var div = domConstruct.create('div', {style:'text-align:right;'}, content);
                    var d = new Dialog({
                        title: "Impossible d'enregistrer",
                        content: content,
                        style: "width: 300px"
                    });
                    new Button({label:'Fermer'}, domConstruct.create('div', {}, div)).on('click', lang.hitch(this, function(){
                        d.hide();
                    }));
                    d.show();
                } else {
                    var content = domConstruct.create("div", {innerHTML:'<p>Veuillez nommer cette nouvelle couche.</p>'});
                    var input = domConstruct.create('input', {value:this.drawLayerName ? this.drawLayerName : ''}, domConstruct.create('p', {innerHTML:'Nom : '}, content));
                    var div = domConstruct.create('div', {style:'text-align:right;'}, content);
                    var delDialog = new Dialog({
                        title: "Enregistrer la couche de dessins courante",
                        content: content,
                        style: "width: 300px"
                    });
                    new Button({label:'Enregistrer'}, domConstruct.create('div', {}, div)).on('click', lang.hitch(this, function() {
                        this.saveData(input.value);

                        delDialog.hide();
                    }));
                    new Button({label:'Annuler'}, domConstruct.create('div', {}, div)).on('click', lang.hitch(this, function(){
                        delDialog.hide();
                    }));
                    delDialog.show();
                }
            },

            saveData: function(name) {
                var data = localStorage.getItem(this.layerName);
                var dataJson = data ? JSON.parse(data) : [];
                var graphicsToSave = this.graphicsToJson();
                var found = false;
                var newId = null;

                if (this.drawLayerId) {
                    found = array.some(dataJson, lang.hitch(this, function(d) {
                        if (d.id === this.drawLayerId) {
                            newId = d.id;
                            d.name = name;
                            d.data = graphicsToSave;

                            return true;
                        }

                        return false;
                    }));
                }

                if (!found) {
                    newId = Utils.guid();

                    dataJson.push({
                        id: newId,
                        name: name,
                        data: graphicsToSave
                    });
                }

                var drawings = JSON.stringify(dataJson);

                localStorage.setItem(this.layerName, drawings);
                this.addMapService(newId, name, graphicsToSave);

                this.drawLayerId = newId;

                if(this.restfulUrl){
                    request(this.restfulUrl, {method:'POST', data:{drawings:drawings}}).then(lang.hitch(this, function(data){
                        console.log("POST drawings DONE.", data);
                    }));
                }

                return newId;
            },

            addMapService: function(id, name, jsonGraphics) {
                this.selectLabel(true);

                if (this._mapService && this._mapService.get('newLayer')) {
                    this._disableRemovedHandler = true;
                    this._spwMap.removeMapService(this._mapService.serviceId);
                }

                this._mapService = this._spwMap.getMapServiceById(id);

                if (this._mapService == null) {
                    if (name == null) {
                        return;
                    }

                    this._fromThis = true;
                    this._mapService = this._spwMap.addMapService({
                        type: MapServiceFactory.types.DRAW_LAYER,
                        serviceId: id,
                        label: name,
                        newLayer: false,
                        graphicsJSON: jsonGraphics,
                        canDefineDefaultProperties: true,
                        editable: true
                    });
                }
                else {
                    this._mapService.set('inTOC', true);
                    this._mapService.set('newLayer', false);
                    this._mapService.setGraphics(jsonGraphics);
                }

                this.selectLabel();
                this._graphicLayer = this._mapService.get('layer');
                this._mapService.show();
                this.buildTOC();
            },

            graphicsToJson: function() {
                var data = [];
                array.forEach(this._graphicLayer.graphics, lang.hitch(this, function(g) {
                    if (g._buffer) {
                        return;
                    }

                    if (g.associatedGraphic) {
                        return;
                    }

                    var json = g.toJson();

                    if (g._buffers) {
                        lang.mixin(json, {
                            _buffers: array.map(g._buffers, function(buf) {
                                var tmp = buf.toJson();

                                if (buf.associatedMesure) {
                                    tmp.associatedMesure = buf.associatedMesure.toJson();
                                }

                                return tmp;
                            }),
                            _bufferValue: g._bufferValue,
                            _repetitionValue: g._repetitionValue,
                            _bufferLabels: g._bufferLabels
                        });
                    }

                    if (g.associatedMesure) {
                        lang.mixin(json, {
                            associatedMesure: g.associatedMesure.toJson(),
                            selectedMesureValue: g.associatedMesure.selectedValue
                        });
                    }

                    if (g.associatedArea) {
                        lang.mixin(json, {
                            associatedArea: g.associatedArea.toJson(),
                            selectedAreaValue: g.associatedArea.selectedValue
                        });
                    }

                    if (g._coordinates) {
                        lang.mixin(json, {
                            _coordinates: g._coordinates.toJson()
                        })
                    }

                    data.push(json);
                }));
                return JSON.stringify(data);
            },

            onDeleteLayerClick: function(){
                var content = domConstruct.create("div", {innerHTML:'<p>Les dessins courants seront perdus. Voulez-vous supprimer cette couche ?</p>'});
                var div = domConstruct.create('div', {style:'text-align:right;'}, content);
                var delDialog = new Dialog({
                    title: "Suppression de la couche courante",
                    content: content,
                    style: "width: 300px"
                });
                new Button({label:'Supprimer'}, domConstruct.create('div', {}, div)).on('click', lang.hitch(this, function(){
                    if(this.drawLayerId){
                        this.deleteDrawLayerById(this.drawLayerId);
                    }
                    //this.onNewLayerClick();
                    delDialog.hide();
                }));
                new Button({label:'Annuler'}, domConstruct.create('div', {}, div)).on('click', lang.hitch(this, function(){
                    delDialog.hide();
                }));
                delDialog.show();
            },

            deleteDrawLayerById: function(id){
                var data = localStorage.getItem(this.layerName);
                var dataJson = data ? JSON.parse(data):[];

                array.some(dataJson, function(j, idx){
                    if(j.id == id){
                        dataJson.splice(idx, 1);
                        return true;
                    }
                    return false;
                });

                if (this._mapService && this._mapService.serviceId === id) {
                    this.selectLabel(true);
                }

                var drawings = JSON.stringify(dataJson);
                localStorage.setItem(this.layerName, drawings);

                if (!this._spwMap.removeMapService(id, true)) {
                    this.buildTOC();
                }

                if(this.restfulUrl){
                    request(this.restfulUrl, {method:'POST', data:{drawings:drawings}}).then(lang.hitch(this, function(data){
                        console.log("POST drawings DONE.", data);
                    }));
                }
            },

            deleteDrawLayerByName: function(name){
                var data = localStorage.getItem(this.layerName);
                var dataJson = data ? JSON.parse(data):[];
                array.some(dataJson, function(j, idx){
                    if(j.name == name){
                        dataJson.splice(idx, 1);
                        return true;
                    }
                    return false;
                });
                var drawings = JSON.stringify(dataJson);
                localStorage.setItem(this.layerName, drawings);
                if(this.restfulUrl){
                    request(this.restfulUrl, {method:'POST', data:{drawings:drawings}}).then(lang.hitch(this, function(data){
                        console.log("POST drawings DONE.", data);
                    }));
                }
            },

            getDrawLayerByName: function(name){
                var data = localStorage.getItem(this.layerName), dataJson = data ? JSON.parse(data):[], layer = null;
                array.some(dataJson, function(j, idx){
                    if(j.name == name){
                        layer = JSON.parse(j.data);
                        return true;
                    }
                    return false;
                });
                return layer;
            },

            destroy: function() {
                // if(this.spwViewer.spwMap.esriMap) {
                //     this.deactivateDrawTool();
                //     this.deactivateEditTool();
                //     this.deactivateEraseTool();
                // }
                this.inherited(arguments);
            }

        });
    });