// 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'));  
    
    // 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();

   /*
    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;
    }
        
    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);

    // 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;
    if(app.llExtent !== null && app.lbExtent !== null && app.urExtent !== null && app.utExtent !== null){
        //app.map.zoomToExtent(new OpenLayers.Bounds(app.llExtent, app.lbExtent, app.urExtent, app.utExtent));         
		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, false); 
	    //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(app.nameModule.toLowerCase() === 'roteiro')
    {
        addGetFeatureInfoWFS();
    }
    
    // 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("vectorsLayer",{styleMap:getStyleMeasure()});
    app.map.addLayer(app.vectorsLayer);
    
    
    
}

function addGetFeatureInfoWFS(){

    var layers = [];
    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].events.on({
                "featureselected": function(e) {
                    alert(123);
                },
                "featureunselected": function(e) {
                    alert(1234);
                }
            });
            */
            layers.push(app.map.layers[i]);
        }
    }
    
    /*
    var listLayers = getOverLayers();
    for(var i=0; i<listLayers.length; i++) {
        if(listLayers.CLASS_NAME == "OpenLayers.Layer.WFS" && listLayers.featureClass==null) {
            layers.push(listLayers[i]);
        }
    }
    */
    if(layers.length>0){
        /*
        OpenLayers.Feature.Vector.style = {
            'selectPOI': {
                fillColor: "#ee9900",
                fillOpacity: 0.4, 
                hoverFillColor: "white",
                hoverFillOpacity: 0.8,
                strokeColor: "#ee9900",
                strokeOpacity: 1,
                strokeWidth: 1,
                strokeLinecap: "round",
                strokeDashstyle: "solid",
                hoverStrokeColor: "red",
                hoverStrokeOpacity: 1,
                hoverStrokeWidth: 0.2,
                pointRadius: 6,
                hoverPointRadius: 5,
                hoverPointUnit: "%",
                pointerEvents: "visiblePainted",
                cursor: "inherit"
           }
        }; 
        */
        var selectOptions = 
        {
            multiple: false,
            clickout: true,
            toggle: true,
            hover: true,
            //selectStyle: "selectPOI",
            onSelect: function(feature) {                           
                onPopupClose();
                app.selectedFeature = feature;
                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();
                }                       
            },
            onUnselect: function(feature) {
                feature.layer.map.removePopup(feature.popup);
                feature.popup.destroy();
                feature.popup = null;   
                app.selectedFeature = null;
                app.popupInfo = null;
            }
        };
    
        app.selectFeatureControl = new OpenLayers.Control.SelectFeature(layers, selectOptions);
        app.map.addControl(app.selectFeatureControl);
        app.selectFeatureControl.activate();
    }
}

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 OpenLayers.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});
        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+"/")) + 'GeocidMadeira.asmx/getMapasPlantasLocalizacao');
        OpenLayers.Request.POST({
            url: 'GeocidMadeira.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 featureWKT = answer.processoObra[0].geom;
                                var features = wkt.read(featureWKT);
                                if(features){
                                    var bounds;
                                    if(features.constructor != Array) {
                                        features = [features];
                                    }
                                    for(var i=0; i<features.length; ++i) {
                                        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
                                        app.vectorsLayer.addFeatures(features);
                                        
                                        if(bounds !== null){
                                            // limitar o zoom aos niveis de visualização da layer do Tema associada
                                            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);
                                    }
                                    
                                }
                            }
                            
                        }
                    }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);
            }
        }

}
