// inicializar o mapa			
function initApp(toolbar){
    
    // INIT TOOLBAR CONTENT
    initToolbarContent(toolbar);
    
    // iniciar a Tab de Print
    //app.printTab.map = app.map;
    //addItemsTabPrint(app.printTab);

    // desabilitar o click direito do mouse    
    //disableRightClickMouse(OpenLayers.i18n('Text right click'));  
    
    maximizeWindow();
    
    /*
    var model = [{"text":"Lugares","expanded":true,"expandable":true,"checked":false,"checkable":false,"href":"","hrefTarget":"_blank","layerName":"","layerNames":null,"children":[{"text":"Toponímia dos Lugares","expanded":false,"expandable":false,"checked":true,"checkable":true,"href":"","hrefTarget":"_blank","layerName":"Toponímia dos Lugares","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1025","tipoid":"1","grupoid":"11","leaf":true,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null}],"icon":"images/mapa/temas/16x16/layer-group.gif","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1024","tipoid":"","grupoid":"10","leaf":false,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null},{"text":"PDM","expanded":true,"expandable":true,"checked":false,"checkable":false,"href":"","hrefTarget":"_blank","layerName":"","layerNames":null,"children":[{"text":"Vectorial","expanded":true,"expandable":true,"checked":false,"checkable":false,"href":"","hrefTarget":"_blank","layerName":"","layerNames":null,"children":[{"text":"Ordenamento","expanded":false,"expandable":false,"checked":false,"checkable":true,"href":"legenda_ord_figeiro_vinhos.pdf","hrefTarget":"_blank","layerName":"Ordenamento","layerNames":null,"children":[{"text":"","expanded":false,"expandable":false,"checked":false,"checkable":false,"href":null,"hrefTarget":"_blank","layerName":null,"layerNames":null,"children":null,"icon":null,"iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":null,"tipoid":null,"grupoid":null,"leaf":true,"zoomtoextent":false,"tablezoomtoextent":null,"legendurl":"pdm/pdm_2_rossio_vcambra.png"}],"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1019","tipoid":"","grupoid":"5","leaf":false,"zoomtoextent":true,"tablezoomtoextent":"pdm_centro_histor","legendurl":null}],"icon":"images/mapa/temas/16x16/layer-group.gif","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1055","tipoid":"","grupoid":"16","leaf":false,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null},{"text":"Raster","expanded":true,"expandable":true,"checked":false,"checkable":false,"href":"","hrefTarget":"_blank","layerName":"","layerNames":null,"children":[{"text":"Reserva Ecológica Nacional","expanded":false,"expandable":false,"checked":false,"checkable":true,"href":"legenda_ren_raster_figueiro.pdf","hrefTarget":"_blank","layerName":"Reserva Ecológica Nacional","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1051","tipoid":"","grupoid":"14","leaf":true,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null},{"text":"Condicionantes","expanded":false,"expandable":false,"checked":false,"checkable":true,"href":"legenda_cond_raster_figueiro.pdf","hrefTarget":"_blank","layerName":"Condicionantes","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1050","tipoid":"","grupoid":"13","leaf":true,"zoomtoextent":true,"tablezoomtoextent":"","legendurl":null},{"text":"Ordenamento","expanded":false,"expandable":false,"checked":false,"checkable":true,"href":"legenda_ord_raster_figueiro.pdf","hrefTarget":"_blank","layerName":"Ordenamento","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1049","tipoid":"","grupoid":"12","leaf":true,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null}],"icon":"images/mapa/temas/16x16/layer-group.gif","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1054","tipoid":"","grupoid":"15","leaf":false,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null}],"icon":"images/mapa/temas/16x16/layer-group.gif","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1018","tipoid":"","grupoid":"4","leaf":false,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null},{"text":"Cartografia","expanded":true,"expandable":true,"checked":false,"checkable":false,"href":"","hrefTarget":"_blank","layerName":"","layerNames":null,"children":[{"text":"Planimetria","expanded":false,"expandable":false,"checked":false,"checkable":true,"href":"","hrefTarget":"_blank","layerName":"Planimetria","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1023","tipoid":"","grupoid":"9","leaf":true,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null}],"icon":"images/mapa/temas/16x16/layer-group.gif","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1022","tipoid":"","grupoid":"8","leaf":false,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null},{"text":"Ortofotomapas","expanded":true,"expandable":true,"checked":false,"checkable":false,"href":"","hrefTarget":"_blank","layerName":"","layerNames":null,"children":[{"text":"Ortofotomapa","expanded":false,"expandable":false,"checked":false,"checkable":true,"href":"","hrefTarget":"_blank","layerName":"Ortofotomapa","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1021","tipoid":"","grupoid":"7","leaf":true,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null}],"icon":"images/mapa/temas/16x16/layer-group.gif","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1020","tipoid":"","grupoid":"6","leaf":false,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null},{"text":"Limites Administrativos","expanded":true,"expandable":true,"checked":false,"checkable":false,"href":"","hrefTarget":"_blank","layerName":"","layerNames":null,"children":[{"text":"Freguesias","expanded":false,"expandable":false,"checked":true,"checkable":true,"href":"","hrefTarget":"_blank","layerName":"Freguesias","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1017","tipoid":"2","grupoid":"3","leaf":true,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null},{"text":"Concelhos","expanded":false,"expandable":false,"checked":true,"checkable":true,"href":"","hrefTarget":"_blank","layerName":"Concelhos","layerNames":null,"children":null,"icon":"images/mapa/temas/16x16/maplayer.png","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1016","tipoid":"","grupoid":"2","leaf":true,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null}],"icon":"images/mapa/temas/16x16/layer-group.gif","iconCls":null,"disabled":false,"draggable":false,"editable":false,"qtip":null,"qtipCfg":null,"id_layer":"1015","tipoid":"","grupoid":"1","leaf":false,"zoomtoextent":false,"tablezoomtoextent":"","legendurl":null}];
        
    var tree = new Municipia.controls.LayerTree({map: app.map,
                                                  el: 'treeView',
                                                  model: model,
                                                  useArrows: true
                                                  });
    tree.render();                                                  
      */                                            
    // funcão para permitir efecuar algo no fim de estar carregada
    endApp();      
}

function initMap(){
    
    // avoid pink tiles
    OpenLayers.DOTS_PER_INCH = 72;
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
    OpenLayers.Util.onImageLoadErrorColor = 'transparent';
    OpenLayers.ImgPath = app.baseUrl+'images/mapa/';
    //OpenLayers.ProxyHost = app.proxyWFS; //app.appPath;
    OpenLayers.Lang.setCode("pt-PT");
    
    app.controls = getControls();
    app.layersSelectable = [];
    app.layersHighlight = [];        
   /*
    var options = {
	    controls: [], 
	    Projection: new OpenLayers.Projection(app.srsGlobal),
        displayProjection: new OpenLayers.Projection(app.srsGlobal),
	    numZoomLevels: 10,
        maxResolution: 0.001373291015625,
        //resolutions: [0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.00002145767211914062,0.00001072883605957031,0.00000536441802978515,0.00000268220901489257],
        //resolutions: [0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.000021457672119140625,0.000010728836059570312,0.000005364418029785156,0.000002682209014892578,0.000001341104507446289,6.705522537231445e-7,3.3527612686157226e-7,1.6763806343078613e-7],
        //resolutions: [1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.00002145767211914062,0.00001072883605957031,0.00000536441802978515,0.00000268220901489257],
        maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90),
        restrictedExtent: new OpenLayers.Bounds(app.llExtent, app.lbExtent, app.urExtent, app.utExtent)
    };
    */
    
    var options = {};
    options.controls = [];
    
    if(app.srsGlobal !== ''){
        options.projection = new OpenLayers.Projection(app.srsGlobal); 
    }
    if(app.displayProjection !== ''){
        options.displayProjection = new OpenLayers.Projection(app.srsDisplay);
    }
    if(app.srsGlobalUnits !== ''){
        options.units = app.srsGlobalUnits; 
    }
    if(app.llMaxExtent !== '' && app.lbMaxExtent !== '' && app.urMaxExtent !== '' && app.utMaxExtent !== ''){
        options.maxExtent = new OpenLayers.Bounds(app.llMaxExtent, app.lbMaxExtent, app.urMaxExtent, app.utMaxExtent);
    }
    if(app.llRestrictedExtent !== '' && app.lbRestrictedExtent !== '' && app.urRestrictedExtent !== '' && app.utRestrictedExtent !== ''){
        options.restrictedExtent = new OpenLayers.Bounds(app.llRestrictedExtent, app.lbRestrictedExtent, app.urRestrictedExtent, app.utRestrictedExtent);        
    }
    
    /*
    if(app.numZoomLevels!='')
        options.numZoomLevels = 10;   
        
    if(app.maxZoomLevel!='')
        //options.maxZoomLevel = 8;    
    */
    app.optionsLayer = {};

    //if(app.srsGlobal!='')
    //    app.optionsLayer.projection = new OpenLayers.Projection(app.srsGlobal); 
    //if(app.displayProjection!='')
    //    app.optionsLayer.displayProjection = new OpenLayers.Projection(app.srsDisplay);
    //if(app.srsGlobalUnits!='')
    //    app.optionsLayer.units = app.srsGlobalUnits;    
    //if(app.numZoomLevels!='')
    //    app.optionsLayer.numZoomLevels = app.numZoomLevels;   
    //if(app.maxZoomLevel!='')
    //    app.optionsLayer.maxZoomLevel = app.maxZoomLevel;   
    
    if(app.maxResolution !== ''){
        app.optionsLayer.maxResolution = app.maxResolution;
    }else{
        app.optionsLayer.maxResolution = null;
    }
    
    app.minResolution = 3.17478168804209E-6;
    if(app.minResolution !== ''){
        app.optionsLayer.minResolution = app.minResolution;
    }else{
        app.optionsLayer.maxResolution = null;
    }
                
    if(app.resolutions !== ''){
      app.optionsLayer.resolutions = app.resolutions;
    }  
      
    //options.resolutions = [26458.319045841046,13229.159522920523,6614.579761460262,3662.3592200799267,2645.831904584105,1831.1796100399633,1322.9159522920525,915.5898050199817,661.4579761460262,457.79490250999083,264.5831904584105,228.89745125499542,132.29159522920526,114.44872562749771,66.14579761460263,57.224362813748854,28.612181406874427,26.458319045841044,14.306090703437214,13.229159522920522,7.153045351718607,6.614579761460261,3.5765226758593034,2.6458319045841043,1.7882613379296504,1.3229159522920522,0.8941306689648258,0.6614579761460261,0.529166380916821,0.4470653344824126,0.2645831904584105,0.22353266724120585,0.19843739284380787,0.13229159522920525,0.06614579761460262];
    if(app.scales !== ''){
      app.optionsLayer.scales = app.scales;    
    }
      
      
    //if(app.llMaxExtent!='' && app.lbMaxExtent!='' && app.urMaxExtent!='' && app.utMaxExtent!='')
    //    app.optionsLayer.maxExtent = new OpenLayers.Bounds(app.llMaxExtent, app.lbMaxExtent, app.urMaxExtent, app.utMaxExtent);
    //if(app.llRestrictedExtent!='' && app.lbRestrictedExtent!='' && app.urRestrictedExtent!='' && app.utRestrictedExtent!='')
    //    app.optionsLayer.restrictedExtent = new OpenLayers.Bounds(app.llRestrictedExtent, app.lbRestrictedExtent, app.urRestrictedExtent, app.utRestrictedExtent);        
  
  
    //options.resolutions = [305.748113086,152.874056543,76.437028271,38.218514136,19.109257068,9.554628534,4.777314267,2.388657133,1.194328567,0.59716428337097171575,0.298582142];
    
    app.map = new OpenLayers.Map($('olmap'), options);
    //app.map = new OpenLayers.Map(app.mapPanel.body.id, options);
    app.options = options;
    // eventos para a TreeView    
    app.map.events.register("addlayer", app.map, window.onChangeLayer);
    //app.map.events.register("changelayer", app.map, window.onChangeLayer);
    //app.map.events.register("changebaselayer", app.map, window.onChangeLayer);
    app.map.events.register("zoomend", app.map, window.onChangeLayer);
    app.map.events.register("mousemove", app.map, function(e) {
        app.currentPixelPos = new OpenLayers.Pixel(e.xy.x, e.xy.y);
    });

    // INIT MAP CONTENT
    initMapContent();        
}

// Adicionar Layers ao mapa
function initMapContent(){    
    
    // BASELAYERS  
    var baseLayers = getBaseLayers();
    if(baseLayers !== null && baseLayers.length === 0){
        return;
    }
            
    app.map.addLayers(baseLayers);
    
    // A Layer de Highlight tem de ficar a seguir às baselayers...
    //app.map.addLayers(getLayerHighlight());
    
    //if (!app.map.getCenter()) {app.map.zoomToMaxExtent()}
	app.bounds = null;
	var closest = false;
    if(app.llExtent !== null && app.lbExtent !== null && app.urExtent !== null && app.utExtent !== null && app.datumExtent !== null){
        //app.map.zoomToExtent(new OpenLayers.Bounds(app.llExtent, app.lbExtent, app.urExtent, app.utExtent));         
        if(Proj4js.defs[app.datumExtent]){
            var bounds = new OpenLayers.Bounds(app.llExtent, app.lbExtent, app.urExtent, app.utExtent);
            var proj = new OpenLayers.Projection(app.datumExtent);
            app.bounds = bounds.transform(proj, new OpenLayers.Projection(app.srsGlobal));
            closest = true;
        }
		//app.bounds = new OpenLayers.Bounds(app.llExtent, app.lbExtent, app.urExtent, app.utExtent);         
    }else{        
        app.bounds = new OpenLayers.Bounds(app.llRestrictedExtent, app.lbRestrictedExtent, app.urRestrictedExtent, app.utRestrictedExtent); 
    }
    
	if(app.bounds !== null){
	    //app.map.zoomToExtent(app.bounds, closest); 
	    var zoom = 0;
	    if (app.map.baseLayer != null) {
            zoom = app.map.baseLayer.getZoomForExtent(app.bounds, false);
        }else{
            zoom = app.map.getZoomForExtent(app.bounds, false);
        }
        if(zoom<app.minZoomLevel){
            zoom=app.minZoomLevel;
        }
	    app.map.setCenter(app.bounds.getCenterLonLat(),zoom);
	    
	    //app.map.setCenter(app.bounds.getCenterLonLat(), app.map.getZoomForExtent(app.bounds,false), null, true);
		//app.map.setCenter(app.bounds.getCenterLonLat(),2);
	}
    //app.map.zoomToExtent(new OpenLayers.Bounds(-20037508.34, -20037508.34,20037508.34, 20037508.34));                       			   
     
	// OVERLAYERS
    app.map.addLayers(getOverLayers());
    
    // CONTROLS
    addControls2Mapa();   
    
    /* popups */    
    if(getURLParam("servicename").toLowerCase() === 'roteiro')
    {
        addGetFeatureInfoWFS();
    }
    else if(getURLParam("servicename").toLowerCase().indexOf('plantas')>-1)
    {
        //Carregar Planos
        //renderLimites('MunWebGis.asmx/getLimitesPlanos', 'planos', 'consultas/vcambra/loteamentos/loteamento_','(Ver Loteamento)', 'Não foi possivel carregar os limites dos planos.');
    }
    else if(getURLParam("servicename").toLowerCase().indexOf('geobras')>-1)
    {
        //Carregar Obras
        //renderLimites('MunWebGis.asmx/getLimitesObras', 'geobras', 'consultas/soure/obras/','(Ver Processo)', 'Não foi possivel carregar os limites dos processos.');
    }
    
    // ADICIONAR UMA LAYER ADICIONAL PARA O CASO DE SER NECESSÁRIO DESENHAR ALGO SOB O MAPA 
    // VERIFICAR SE É NECESSÁRIO ALTERAR A POSIÇÃO DESTA LAYER
    app.vectorsLayer = new OpenLayers.Layer.Vector("edition",{styleMap:getStyleMeasure()});
    app.map.addLayer(app.vectorsLayer);   
    
    if(app.layersHighlight.length>0){
        var highlightStyle = getStyleSelected();
        highlightStyle.fillOpacity = 0;
        var highlightOptions = 
        {
            hover: true,
            highlightOnly: true,
            selectStyle: highlightStyle,
            eventListeners: {
                    beforefeaturehighlighted: onPopupClose,
                    featureunhighlighted: onPopupClose
                }
        };

        app.highlightFeatureControl = new OpenLayers.Control.SelectFeature(app.layersHighlight, highlightOptions);
        app.map.addControl(app.highlightFeatureControl);
        app.highlightFeatureControl.activate();    
    }
    
    if(app.layersSelectable.length>0){
        var selectOptions = 
        {
            multiple: false,
            clickout: true,
            toggle: true,
            hover: false,
            onSelect: onFeatureSelect,
            onUnselect: onFeatureUnselect
        };

        app.selectFeatureControl = new OpenLayers.Control.SelectFeature(app.layersSelectable, selectOptions);
        app.map.addControl(app.selectFeatureControl);
        app.selectFeatureControl.activate();
    }
    
    
}

function renderLimites(url, layername, pathlink, namelink, msgError){
    var layer_style_planos = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style_planos.strokeWidth = 5;
    layer_style_planos.fillOpacity = 0;
    layer_style_planos.strokeOpacity = 0;   
    
    var planos = new OpenLayers.Layer.Vector(layername, { style: layer_style_planos });
    app.map.addLayers([planos]);
    app.layersSelectable.push(planos);
    app.layersHighlight.push(planos);
    
    try {
        var charset = "UTF-8";
        var params = OpenLayers.Util.applyDefaults({
        }, this.params);
        
        //alert(((app.urlApp.lastIndexOf('/')==app.urlApp.length-1)? app.urlApp : (app.urlApp+"/")) + 'MunWebGis.asmx/getMapasPlantasLocalizacao');
        OpenLayers.Request.POST({
            url: url,
            data: "{\"appID\":\""+app.appID+"\"}",
            params: params,
            headers: {
                'Content-type': "application/json",
                'Content-length': 1,
                'Connection': "close"
            },
            callback: function(request) {
                if (request.status >= 200 && request.status < 300) {
                    loadLimites_CallBack(request.responseText, layername, pathlink, namelink);
                }else{
                    Ext.MessageBox.alert('Erro', msgError);
                }
            },
            scope: this
        });
        
    } catch (err) {
        Ext.MessageBox.alert('Erro', msgError);
    }
}

function loadLimites_CallBack(data, layername, pathlink, namelink){
    var limites = data;
    if (limites != null) {
        var layer = app.map.getLayersByName(layername)[0];
        if(layer){
            var json_format = new OpenLayers.Format.JSON();
            var result = json_format.read(eval(limites));
            if(result!=null && result.listaLimites){
                var lista = result.listaLimites;
                for(var i = 0;i<lista.length;i++){
                    var limite = lista[i];
                    var in_options = {
                        'internalProjection': app.map.baseLayer.projection,
                        'externalProjection': new OpenLayers.Projection('EPSG:'+limite.srs)
                    }; 
                    var wkt_format = new OpenLayers.Format.WKT(in_options);
                    var feature = wkt_format.read(limite.geomwkt);
                    if (feature != null && feature != undefined) {
                        var popupHTML = "<div>";
                        popupHTML += "<div class='getfeatureinfosubtitle'>"+limite.titulo+"</div><p><span class='getfeatureinfofooterTxt'>"+limite.nome+"</span>";
                        if(limite.auxiliar!=''){
                            popupHTML += "   <a id='linkPlanos' onclick='javascript:window.open(\"" + pathlink + limite.auxiliar + ".pdf\");return false;'>"+namelink+"</a>";
                        }
                        popupHTML += "</br></div>";
                        feature.data = { tipo: layername,
                            html: popupHTML,
                            codigo: limite.id_cruzamento
                        };
                        layer.addFeatures(feature);
                    }
                }
                if(lista.length>0){
                    //layer.setVisibility(true);
                    for(var l = 0;l<app.map.layers.length;l++){
                        if(app.map.layers[l].name.search(/limites planos/i)>-1){
                            var visibility = app.map.layers[l].visibility;
                            if(!app.map.layers[l].inRange && visibility)
                                visibility = false;
                            layer.setVisibility(visibility);
                            break;
                        }
                    }
                }
            }
        }
    }
}

/*
function DoZoomPlano(planoCod, layerId) {
    var layer = getLayerByProperty(layerId,'id_layer');
    if (layer != null) {
        var layerPlanos = app.map.getLayersByName("planos")[0];
        if(layerPlanos){
            var features = layerPlanos.features;
            for (var i = 0; i < features.length; i++) {
                var feature = features[i];
                if(feture.codigo == planoCod){
                    layer.setVisibility(true);
                    var bnd = feature.geometry.getBounds().clone();
                    bnd.left = bnd.left - 50;
                    bnd.right = bnd.right + 50;
                    bnd.top = bnd.top + 50;
                    bnd.bottom = bnd.bottom - 50;
                    app.map.zoomToExtent(bnd);
                }                
            }
        }
    }
    Geo.Plugins.Ajax.panelPlanos.GetPlanoGeometry(planoCod, adminUnit, DoZoomPlano_CallBack);    
}
*/

function onFeatureSelect(feature) {
    onPopupClose();
    app.selectedFeature = feature;
    if (feature.data && (feature.data["tipo"] == "planos" || feature.data["tipo"] == "geobras")){
        var layerLimites = feature.layer;
        var style = app.highlightFeatureControl?app.highlightFeatureControl.selectStyle:"";
        layerLimites.drawFeature(feature, style)
        var ll = layerLimites.map.getLonLatFromPixel(app.currentPixelPos);
        app.popupInfo = new OpenLayers.Popup.FramedCloud("popupLimites",
                                 ll,
                                 null,
                                 feature.data["html"],
                                 null,
                                 false, 
                                 null);
        app.popupInfo.panMapIfOutOfView = false;
        app.popupInfo.closeOnMove = false; 
        feature.popup = app.popupInfo;   	    
        layerLimites.map.addPopup(app.popupInfo);
        app.popupInfo.show();	        
    }else{
        if(feature.attributes) {
            var atributos = feature.attributes;
            var popup = null;
            var popup_info = "";
            popup_info = "<div class='callout_big'><div class='callout_desc'><div><h1>"+atributos.designacao+"</h1></br></br><p><span>"+atributos.morada+"</span></br></br><span>"+atributos.lugar+"</span></p></div></div></div>";
            popup_info += "<div style='border: 0px none ; overflow: hidden; position: absolute; top: 7px; left: 196px; width: 20px; height: 15px;'><a href='javascript:onPopupClose()'><img src='images/popup/bot_fechar.gif' title='Fechar'/></a></div>";

            app.popupInfo = new Municipia.Popup.Top("FeatureInfo",
                                            feature.geometry.getBounds().getCenterLonLat(),
                                            new OpenLayers.Size(214,180),
                                            popup_info,
                                            null,
                                            false);
            app.popupInfo.autoSize = false;         
            app.popupInfo.closeOnMove = false;         
            app.popupInfo.panMapIfOutOfView = true; 
            app.popupInfo.overClass = "featureMouseOver";                           
            app.popupInfo.setBackgroundColor('Transparent');
            feature.popup = app.popupInfo;
            //if(popup.closeDiv!=null)
               //this.popup.closeDiv.className = "olPopupDetalheCloseBox"; 
            feature.layer.map.addPopup(app.popupInfo);
            app.popupInfo.show();
        }
    }
    
}

function onFeatureUnselect(feature) {
    feature.layer.map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;   
    app.selectedFeature = null;
    app.popupInfo = null;
}

function addGetFeatureInfoWFS(){
    for(var i=0; i<app.map.getNumLayers(); i++) {
        if((app.map.layers[i].CLASS_NAME === "OpenLayers.Layer.WFS" && app.map.layers[i].featureClass === null) || 
        (app.map.layers[i].CLASS_NAME === "OpenLayers.Layer.Vector" && app.map.layers[i].id_layer != null)) {
            app.layersSelectable.push(app.map.layers[i]);
        }
    }
}

function onPopupClose() {
    if(app.selectedFeature !== null && app.selectedFeature.layer !== null){
        app.selectFeatureControl.unselect(app.selectedFeature);
        return;
    }
    
    if (app.popupInfo !== null) {
        app.map.removePopup(app.popupInfo);
        app.popupInfo.destroy();
        app.popupInfo = null;
        app.selectedFeature = null;
    }  
    
}


function addControls2Mapa(){
    // CONTROLS
    app.map.addControl(new OpenLayers.Control.Footer());
    app.map.addControl( new OpenLayers.Control.Copyright({'text': OpenLayers.i18n('Text copyright')}));
    
    if(app.controls!=null && app.controls.tab_estatisticos){
        app.map.addControl( new OpenLayers.Control.InfoAdicional({'text': app.comment_print}));
    }
    
    app.map.addControl(new Municipia.Control.PanZoomBar({zoomStopHeight: 10}));
    app.map.addControl(new OpenLayers.Control.Navigation({'zoomWheelEnabled': false}));
	//app.map.addControl(new OpenLayers.Control.KeyboardDefaults());
	//app.map.addControl( new OpenLayers.Control.LayerSwitcher({ascending: true}) );
	app.map.addControl( new OpenLayers.Control.MousePosition());
	app.map.addControl( new OpenLayers.Control.DatumDisplayCoordinates());
	
	//app.map.addControl(new OpenLayers.Control.Scale('scaleLine'));
	
	//app.map.addControl(new OpenLayers.Control.OverviewMap());
	if(app.controls !== null && app.controls.scalebar){
        app.map.addControl(new OpenLayers.Control.ScaleBar({abbreviateLabel: true, align: 'right', singleLine:false, scaleText: OpenLayers.i18n("Scale 1:")}));
    }
    
    if(app.controls !== null && app.controls.overview){
        var optionsOM = {};
        optionsOM.controls = [];
        if(app.maxResolutionReferenceMap !== ''){
            optionsOM.maxResolution = app.maxResolutionReferenceMap;
        }
        if(app.llMaxExtent !== '' && app.lbMaxExtent !== '' && app.urMaxExtent !== '' && app.utMaxExtent !== ''){
            optionsOM.maxExtent = new OpenLayers.Bounds(app.llMaxExtent, app.lbMaxExtent, app.urMaxExtent, app.utMaxExtent);
        }
        if(app.llRestrictedExtent !== '' && app.lbRestrictedExtent !== '' && app.urRestrictedExtent !== '' && app.utRestrictedExtent !== ''){
            optionsOM.restrictedExtent = new OpenLayers.Bounds(app.llRestrictedExtent, app.lbRestrictedExtent, app.urRestrictedExtent, app.utRestrictedExtent);        
        }
        optionsOM.size = new OpenLayers.Size(215, 115);
        
        //app.overviewPanel = new Municipia.Control.OverviewMap({map: app.map,layers: [app.map.layers[1].clone()], mapOptions: optionsOM});
        //app.overviewPanel = new Municipia.Control.OverviewMap({map: app.map, mapOptions: optionsOM, x: 80,y:100, minRatio: 300,maxRatio: 300});
        app.overviewPanel = new Municipia.Control.OverviewMap({map: app.map, mapOptions: optionsOM, x: 80,y:140, minRatio: 300,maxRatio: 300});
        app.map.addControl(app.overviewPanel);
    }    
}

function renderGeometryObras(idObra, xmin, ymin, xmax, ymax, datum, filterTable, filterColumn, filterValue, tipoidLayer, tipo){
    try {
        var charset = "UTF-8";
        var params = OpenLayers.Util.applyDefaults({
            //appID: app.appID
            //url: this.config.createURL,
            //spec: specTxt
        }, this.params);
        
        //alert(((app.urlApp.lastIndexOf('/')==app.urlApp.length-1)? app.urlApp : (app.urlApp+"/")) + 'MunWebGis.asmx/getMapasPlantasLocalizacao');
        OpenLayers.Request.POST({
            url: 'MunWebGis.asmx/getGeometryProcessoObra',
            data: "{\"appID\":\""+app.appID+"\", \"tema\": \""+app.namespaceGeoServer+":"+filterTable.toUpperCase()+"\", \"idObra\": \""+idObra+"\"}",
            params: params,
            headers: {
                'Content-type': "application/json",
                'Content-length': 1,
                'Connection': "close"
            },
            callback: function(request) {
                if (request.status >= 200 && request.status < 300) {
                    var json = new OpenLayers.Format.JSON();
                    var answer = json.read(eval(request.responseText));
                    if (answer) {
                        var map = app.map;
                        // desenhar o processo de obra
                        if(answer.totalRegistos==1 && answer.processoObra && app.vectorsLayer){
                            app.vectorsLayer.destroyFeatures();
                            // desenhar o polygon
                            if(Proj4js.defs[datum]){
                                var proj = new OpenLayers.Projection(datum);
                                var in_options = {
                                    'internalProjection': map.baseLayer.projection,
                                    'externalProjection': new OpenLayers.Projection(datum)
                                }; 
                                var wkt = new OpenLayers.Format.WKT(in_options);
                                var processo = answer.processoObra[0];
                                var featureWKT = processo.geom;
                                var features = wkt.read(featureWKT);
                                if(features){
                                    var bounds;
                                    if(features.constructor != Array) {
                                        features = [features];
                                    }
                                    for(var i=0; i<features.length; ++i) {
                                        features[i].attributes=processo;
                                        features[i].state = OpenLayers.State.UPDATE;
                                        if (!bounds) {
                                            bounds = features[i].geometry.getBounds();
                                        } else {
                                            bounds.extend(features[i].geometry.getBounds());
                                        }

                                    }
                                    
                                    // activar o layer do tema associado
                                    var layerTema = null;
                                    if(tipoidLayer){
                                        layerTema = getLayerByProperty(tipoidLayer,'tipoid');
                                    }
                                    if(layerTema !== null){
                                        // FALTA VERFIFICAR OS LIMITES DE ESCALA PARA N EFECTUAR ZOOM E A LAYER ESTAR DISABLE
                                        zoom = layerTema.minScale !== "" ? map.getZoomForResolution(OpenLayers.Util.getResolutionFromScale(layerTema.maxScale,map.baseLayer.units), true): null;
                                        if(bounds !== null && (map.getZoomForExtent(bounds, true) < zoom)){
                                            zoom = map.getZoomForExtent(bounds, true);
                                        }
                                        // adiconar a obra
                                        var layeredition = map.getLayersByName("edition")[0];
                                        if(layeredition){
                                            layeredition.removeFeatures(layeredition.features, true);
                                            layeredition.addFeatures(features);
                                            var ctrl = map.getControlsBy("id", "ctrlModifyPolygon")[0];
                                            if(app.toolbar != undefined){
                                                app.toolbar.getButtonForControl(ctrl).setDisabled(false); 
                                                //app.toolbar.activateControl(ctrl); 
                                            }
                                        }
                                        
                                        if(bounds !== null && bounds != undefined){
                                            // limitar o zoom aos niveis de visualização da layer do Tema associada
                                            bounds.left = bounds.left - 50;
                                            bounds.right = bounds.right + 50;
                                            bounds.top = bounds.top + 50;
                                            bounds.bottom = bounds.bottom - 50;
                                            if(zoom !== null){
                                                map.setCenter(bounds.getCenterLonLat(), zoom, null, true);
                                            }else{
                                                app.map.zoomToExtent(bounds);
                                            }
                                        }           
                                        // colocar visivel a layer do tema seleccionado
                                        layerTema.setVisibility(true);
                                    }
                                    
                                    // preencher os dados alfanumericos caso o perfil permita editar
                                    if(Ext.getCmp('processosobras-update-form')!='undefined' && getURLParam("servicename").toLowerCase()=='geobras' && app.userRoles!="" && !compareRole(app.userRoles,'guest')){
                                        var formProcessosUpdate = Ext.getCmp('processosobras-update-form');
                                        var params = {};
                                        params.numero = processo.numero;
                                        params.idtipoprocesso = processo.idtipoprocesso;
                                        params.descricaoid = processo.descricaoid;
                                        params.observacoes = processo.observacoes;
                                        formProcessosUpdate.actualizarCampos(params);
                                    }
                                    
                                }
                            }
                            
                        }
                    }else {
                        Ext.MessageBox.alert('Erro', 'Não foi possivel carregar o processo de obra.');
                    }
                } else {
                    Ext.MessageBox.alert('Erro', 'Não foi possivel carregar o processo de obra.');
                }
            },
            scope: this
        });
        
    } catch (err) {
        OpenLayers.Console.warn(
                "Cannot request the print service by AJAX. You must set " +
                "the 'OpenLayers.ProxyHost' variable. Fallback to GET method");

    }
}

function zoomToFeature(xmin, ymin, xmax, ymax, datum, filterTable, filterColumn, filterValue, tipoidLayer, tipo){
    var pointToCenter = null;
    var boundsZoom = null;
    var size = null;
    var offset = null;
    var icon = null;

    if(Proj4js.defs[datum]){
        var xymin = new OpenLayers.LonLat(parseFloat(xmin.replace(",",".")), parseFloat(ymin.replace(",",".")));
        var xymax = new OpenLayers.LonLat(parseFloat(xmax.replace(",",".")), parseFloat(ymax.replace(",",".")));
        var bounds = new OpenLayers.Bounds(xymin.lon, xymin.lat, xymax.lon, xymax.lat);   
        var proj = new OpenLayers.Projection(datum);
        
        if(xmin==xmax && ymin==ymax){
            pointToCenter = bounds.getCenterLonLat().transform(proj, new OpenLayers.Projection(app.srsGlobal));
            // DEVE SER RETIRADO O OFFSET E CORRIGIR A CONVERSÃO DE COORDENADAS !!!!!!!
            if(new OpenLayers.Projection(app.srsGlobal)==new OpenLayers.Projection("EPSG:4326")){
                //var offsetY = 0.000668; 
                pointToCenter.lon = pointToCenter.lon + 0.000668;  
            }
        }else{
            boundsZoom = bounds.transform(proj, new OpenLayers.Projection(app.srsGlobal));
        }
    }
    
    //var resolution = OpenLayers.Util.getResolutionFromScale(scale, app.map.baseLayer.units);
    //var zoom = app.map.getZoomForResolution(resolution, true);
    var map = app.map;
    if(map !== null){
        // definir o filtro p a layer de higthligth
        var layerHL = null;
        var layerTema = null;
        var zoom = null;
        if(filterColumn!="undefined" &&  filterColumn !== "" && filterValue!="undefined" && filterValue !== ""){
            if(tipo=="WFS"){
                layerHL = getLayerHighlight(tipo);
                if(layerHL === null){
                    return;
                }
                size = new Municipia.Size(26,26);
                offset = new Municipia.Pixel(-(size.w/2), -(size.h/2));
                icon = new OpenLayers.Icon('images/mapa/temas/20x20/temasHighlight.gif',size,offset);
                layerHL.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(pointToCenter.lon,pointToCenter.lat),icon));
                    
            }else{
                        
                var listCol = filterColumn.split(';');
                
                var listVal = filterValue.split(';');
                if(listCol.length==listVal.length){
                    var featureid = '';
                    var tipoid = '';
                    var filter='';
                    if(filterTable && filterTable.indexOf('.')){
                        filterTable = filterTable.substring(filterTable.indexOf('.')+1,filterTable.length);
                    }
                    if(listCol[0].toUpperCase()=="OBJECTID"){
                        featureid = filterTable.toUpperCase()+'.'+listVal[0];
                        tipoid = listVal[1];
                        //filter = "(<ogc:Filter xmlns:ogc='http://www.opengis.net/ogc' >";
                        //filter += "<ogc:FeatureId fid="+filterTable.toUpperCase()+'.'+listVal[0]+"/>";
                        //filter += "</ogc:Filter>)";
                    }else{
                        filter = "(<ogc:Filter xmlns:ogc='http://www.opengis.net/ogc' >";
                        if(listCol.length>1){
                            filter += "<And>";
                        }
                        for (var i=0, len=listCol.length; i<len; i++) {
                            filter += "<PropertyIsEqualTo>";
                            filter += "<PropertyName>";
                            filter += listCol[i];
                            filter += "</PropertyName>";
                            filter += "<Literal>";
                            filter += listVal[i];
                            filter += "</Literal>";
                            filter += "</PropertyIsEqualTo>";
                        }
                        if(listCol.length>1){
                            filter += "</And>";
                        }
                        filter += "</ogc:Filter>)";
                    }
                    
                    layerHL = getLayerHighlight(tipo, null, ((app.namespaceGeoServer !== "" ? (app.namespaceGeoServer+':') : app.namespaceGeoServer)+filterTable.toUpperCase()), filter, tipoid, featureid);
                    
                }
            }

            if(tipoidLayer){
                layerTema = getLayerByProperty(tipoidLayer,'tipoid');
            }
                            
            if(layerHL !== null && layerTema !== null){
                // adicionar o evento à layer do tema correspondente
                layerTema.events.register("visibilitychanged", layerTema, onLayerHigthligthChanged);
                layerTema.events.register("loadend", layerTema, onLayerHigthligthLoaded);
                // FALTA VERFIFICAR OS LIMITES DE ESCALA PARA N EFECTUAR ZOOM E A LAYER ESTAR DISABLE
                zoom = layerTema.minScale !== "" ? map.getZoomForResolution(OpenLayers.Util.getResolutionFromScale(layerTema.maxScale,map.baseLayer.units), true): null;
                if(boundsZoom !== null && map.getZoomForExtent(boundsZoom, true)<zoom){
                    zoom = map.getZoomForExtent(boundsZoom, true);
                }            
                var index = map.getLayerIndex(layerTema);
                layerHL.setVisibility(false);
                map.addLayer(layerHL);
                if(Municipia.Util.getProperty(layerTema,'index_highlight') !==  1){ // caso onde se pretende que o Higthligth seja coloca acima da layer do tema correspondente
                    map.setLayerIndex(layerHL, index);
                }                    
                // colocar visivel a layer do tema seleccionado
                layerTema.setVisibility(true);
            }
            
        }else if(tipo=='WFS'){  // caso onde pretendo efectuar zoom p um ponto e marcar esse ponto no mapa
            layerHL = getLayerHighlight(tipo);
            if(layerHL === null){
                return;
            }
            
            if(tipoidLayer){
                layerTema = getLayerByProperty(tipoidLayer,'tipoid');
            }                
            if(layerHL !== null && layerTema !== null){
                // colocar visivel a layer do tema seleccionado
                if(!layerTema.isBaseLayer){
                    layerTema.events.register("visibilitychanged", layerTema, onLayerHigthligthChanged);
                    // colocar visivel a layer do tema seleccionado
                    layerTema.setVisibility(true);
                }else{
                    map.setBaseLayer(layerTema);
                }
                
            }
            size = new Municipia.Size(20,20);
            offset = new Municipia.Pixel(-(size.w/2), -(size.h/2));
            icon = new OpenLayers.Icon('images/mapa/arrow_pointer.png',size,offset);
            if(pointToCenter==null){
                pointToCenter = boundsZoom.getCenterLonLat();
            }
            layerHL.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(pointToCenter.lon,pointToCenter.lat),icon));
            layerHL.setVisibility(true);
            map.addLayer(layerHL);
           
        }

        if(pointToCenter !== null){
            map.setCenter(pointToCenter, (zoom !== null ? zoom : map.getNumZoomLevels()-2), null, true);
        }else if(boundsZoom !== null){
            // limitar o zoom aos niveis de visualização da layer do Tema associada
            if(zoom !== null){
                map.setCenter(boundsZoom.getCenterLonLat(), zoom, null, true);
            }else{
                app.map.zoomToExtent(boundsZoom);
            }
        }else{
            map.zoomToMaxExtent();
        }
           
    }
    //app.map.setCenter(new OpenLayers.LonLat(parseFloat(lon),parseFloat(lat)),zoom);
}

function openPopupProximidade(xmin, ymin, xmax, ymax, datum, filterTable, filterColumn, filterValue, tipoidLayer, tipo, id, tipoEvento){
    var layerHL = app.map.getLayersBy('id', 'highlight');
    if(layerHL !== null && layerHL.length>0){
        layerHL = layerHL[0];  
        var markers = layerHL.markers;
        for(var i=0; i<markers.length; ++i) {
            var marker = markers[i];
            if(marker.attributes && marker.attributes.id && marker.attributes.id==id){
                // open popup marker
                var element = marker.events.element;
                if(tipoEvento=="mouseout"){
                    element = marker.popup.events.element;
                }
                                
                if(document.createEvent){
                    // dispatch for firefox + others
                    var evt = document.createEvent("HTMLEvents");
                    evt.initEvent(tipoEvento, true, true ); // event type,bubbling,cancelable
                    return !element.dispatchEvent(evt);
                }
                else{
                    // dispatch for IE
                    var evt = document.createEventObject();
                    return element.fireEvent('on'+tipoEvento,evt)
                }
            }
        }
    }
}

function onLayerHigthligthChanged(evt)
{
    var layer = evt.object;
    if (layer !== null) {
        var checked = layer.getVisibility();    
        var map = layer.map;
        if(checked){
            var layerHL = map.getLayersBy('id', 'highlight');
            if(layerHL.length>0){
                layerHL = layerHL[0];  
                layerHL.setVisibility(checked);         
            }
        }else{
            removeLayerHighlight();
        }
    }
}

function onLayerHigthligthLoaded(evt)
{
    var layer = evt.object;
    if (layer !== null) {
        var map = layer.map;
        var layerHL = map.getLayersBy('id', 'highlight');
        if(layerHL.length>0){
            layerHL = layerHL[0];  
            //layerHL.setVisibility(false);  // forçar o redraw da imagem
            layerHL.setVisibility(true); 
        }
    }
}
    
function openJanelaDetalhe(themeId, objectId) {
     
     var win = new Ext.Window({
         width: 532
         //,id:'detalhePOI'
         ,modal: false
         ,autoHeight: false
         ,height: 221
         ,resizable: false
         ,autoScroll:false 
         ,autoLoad:{
            url:'util/detalhePOI.aspx?appID='+app.appID+'&themeId='+themeId+'&objectId='+objectId,
            scripts: true
         }
         ,title: OpenLayers.i18n('Title Detail Window')
         ,listeners:{show:function() {
             this.loadMask = new Ext.LoadMask(this.body, {
                msg: OpenLayers.i18n('Loading...')
             });
         }}
     });
     
    win.show();
    //events
    win.on( "close", onCloseWinInfo, this );

  
}

function onCloseWinInfo(){
    // remover os popups do mapa
    var map = app.map;
    if(map !== null && map.currentPopup  !== null && map.popups.length>0 && map.currentPopup.visible()){
        map.currentPopup.hide();
    }
}


function removeLayerHighlight(){
    var layerHL = app.map.getLayersBy('id', 'highlight');
    if(layerHL !== null && layerHL.length>0){
        layerHL = layerHL[0];  
        app.map.removeLayer(layerHL);
    }
}
function getLayerHighlight(tipo, url, layers, filter, tipoid, featureid){
    // é necessário remover o layer se este já existir!!
    removeLayerHighlight();        
    var highlightLayer = null;
    if(tipo=="WMS"){
        url = (url===null)?app.urlWMS:url;
		var style = (tipoid===null)?'':(tipoid==16?'lugaresHighlight':(tipoid==95?'eixosViaHighlight':''));
        highlightLayer = new OpenLayers.Layer.WMS(
            "highlight",
            url,
            {
               layers: layers,
               //styles: style,
               sld: app.baseUrl+'sld/highlight.xml', //MUDAR ISTO !!!!!!!!!!!!!!!
               srs: app.srsLocal,
               transparent: true,
               format: 'image/png',
               actualtipoid: '',
               aleatorio: Math.random(),
               filter: filter,
               featureid: featureid
            },
            {
                opacity: 1.0,
                displayInLayerSwitcher: false,
                isBaseLayer: false,
                wrapDateLine: true,
                reproject: true,
                visibility: false,
                singleTile: true,
                ratio: 1.5
            }
        );
    
    }else if(tipo=="WFS"){
        //var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
        //layer_style.fillOpacity = 1;
        //layer_style.graphicOpacity = 1;
        //highlightLayer = new OpenLayers.Layer.Vector("highlight", {style: layer_style});
        
        highlightLayer = new OpenLayers.Layer.Markers( "highlight", {'isBaseLayer': false, 'displayInLayerSwitcher':false});
    }
    if(highlightLayer !== null){
        highlightLayer.id = 'highlight';
            
        highlightLayer.events.register("loadstart", highlightLayer, function() {
             layerLoading(true, 'highlight');
        });
                
        highlightLayer.events.register("loadend", highlightLayer, function() {
             layerLoading(false, 'highlight');       
        });
        
    }
    return highlightLayer;       
}


function pedidoPlantas(idnatobra, contribuinte, natobra, data, nome, local, featurewkt, datum){
        var map = app.map;
        var vectorLayer = app.vectorsLayer;
        
        if(map && vectorLayer){
            var in_options = {
                'internalProjection': map.baseLayer.projection,
                'externalProjection': new OpenLayers.Projection(datum)
            }; 
            
            var formatWKT = new OpenLayers.Format.WKT(in_options);
            
            var features = formatWKT.read(featurewkt);
            var bounds;
            if(features) {
                if(features.constructor  !==  Array) {
                    features = [features];
                }
                
                for(var i=0; i<features.length; ++i) {
                    var feature = features[i];
                    if (!bounds) {
                        bounds = feature.geometry.getBounds();
                    } else {
                        bounds.extend(feature.geometry.getBounds());
                    }
                    var params = {};
                    params.nome = nome;
                    params.contribuinte = contribuinte;
                    params.local = local;
                    params.natobra = natobra;
                    params.idNatObra = idnatobra;
                    params.dataemissao = data;
                    OpenLayers.Util.extend(feature.attributes, params);

                }
                vectorLayer.destroyFeatures();
                vectorLayer.addFeatures(features);
                map.zoomToExtent(bounds);
            } else {
                //alert(OpenLayers.i18n('plantas.pedidos.errorFeatureWKT'));
                Ext.MessageBox.alert(OpenLayers.i18n('print.information'), OpenLayers.i18n('plantas.pedidos.errorFeatureWKT'), null);
            }
        }

}
