 //var urlCentresEnsenyament = "http://www.cat365.net/Inici/Ciutadans/EducacioFormacio/FerPreinscripcio/V09_128_CentresParticDet.htm?ruta=%2FChannels%2FAutors%2FInici%2FCiutadans%2FEducacioFormacio%2FFerPreinscripcio%2FV09%5F128%5FCentresPartic&CTIS=&NomUA=&PCgNomUA=&SCgNomUA=&NomVC=&PCgNomVC=&SCgNomVC=&I=1&CC=";
var urlCentresEnsenyament = "http://www.cat365.net/Inici/Ciutadans/EducacioFormacio/AnarEscola/V09_ConsultaCentresDetall.htm?ruta=%2FChannels%2FAutors%2FInici%2FCiutadans%2FEducacioFormacio%2FAnarEscola%2FV09%5FConsultaCentres&I=1&CodiCentre=";
if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) 
{
		var cursors = {
		arrastrar:  'url("http://' +  document.location.host + '/website/guia/img/cursors/ma_agafant.cur"),default',
		esborrar:  'url("http://' +  document.location.host + '/website/guia/img/cursors/esborrar.cur"),default',
		zoomcaixa:  'url("http://' +  document.location.host + '/website/guia/img/cursors/ampliar.cur"),default', 
		creu:  'url("http://' +  document.location.host + '/website/guia/img/cursors/cursor.cur"),default',
		pan: 'url("http://' +  document.location.host + '/website/guia/img/cursors/Pan.cur"),default'		
		}
}
else
{		var cursors = {
		arrastrar:  'url("http://' +  document.location.host + '/website/guia/img/cursors/ma_agafant.ico") 12 12,default',
		esborrar:  'url("http://' +  document.location.host + '/website/guia/img/cursors/esborrar.ico") 12 12,default',
		zoomcaixa:  'url("http://' +  document.location.host + '/website/guia/img/cursors/ampliar.ico") 12 12,default', 
		creu:  'url("http://' +  document.location.host + '/website/guia/img/cursors/cursor.ico") 12 12,default',
		pan: 'url("http://' +  document.location.host + '/website/guia/img/cursors/Pan.cur") 16 16,default'		
		}
} 	

  var map;
  var actualZoom = 444;
	// Capes (WMS) de base
	var layer_base_mapa,layer_base_orto;
	var layer_topo_transp;
	var layer_topo_transp_nomscarrers;
	var layer_topo_transp_numscarrers;
	var topofons, ortofons;
	
	//Capa (WMS) per ressaltar: Municipis,Comarques,Trams
	var layer_ressaltar;
	
	//Capa (WMS) per identificar POI i mostrar maptips 
	var layer_poi;
	
	// Capa (markers) per mostrar maptip
	var layer_marker_maptip;	
	
	// Capa (markers) per mostrar punt indicat
	var layer_marker_indicaPunt;
	
	// Capa (markers) per mostrar POI seleccionat
	var layer_marker_mostrarFitxa;	
	var layer_marker_mostrarFitxa_cerca;	
	
	//Capa (markers) per mostrar punt indicat en el mapa de referència
	var layer_marker_indicaPunt_ref;
	var marker_punt;
	
	// Capa de dibuix
	var	layer_edit;
	
	var url_imatge_mapa;

	var marker_punt,popup_punt,feature_punt;
	
	
    //----------------
    function init(){
    //----------------  
    var args = OpenLayers.Util.getParameters();		  
 
    OpenLayers.ProxyHost ="php/proxy3.php?url=";	
    OpenLayers.IMAGE_RELOAD_ATTEMPTS  = 2;

	  var layers = [
		new OpenLayers.Layer.WMS(
			"Ortofoto", parametres.baseWmsServerICC,
			{layers: 'orto', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			//{layers: 'topostcom', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			//{layers: 'topost1600', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			{buffer:0, transitionEffect:'resize'} ),
		new OpenLayers.Layer.WMS(
			"Topografica", parametres.baseWmsServerICC,
			{layers: 'topost', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			//{layers: 'prova17', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			{buffer:0, transitionEffect:'resize'} )				 			 		 			
		];			      


  	var bounds = new OpenLayers.Bounds(258000,4485000,536000,4752000);
	  var resolutions = [550,275,100,50,25,10,5,2,1,0.5];
	        
    var controls = [];     		
    var genericMapOptions = {projection: "EPSG:23031", units: 'm', maxExtent: bounds};
    var mapOptions = OpenLayers.Util.extend({
            resolutions: resolutions,
            zoom: -1, // Hack: Força "zoom" per pintar SceneInfo en inicialitzar
            controls: controls,
            restrictedExtent: bounds // per limitar mostra el mapa fora de Catalunya
          }, genericMapOptions);            

	map = new OpenLayers.Map('map',mapOptions);		

	map.addLayers(layers);

	layer_base_orto = map.layers[0];	
	layer_base_mapa = map.layers[1];

	
	var img_options = {resolutions:resolutions, transparent:true };		
 	//var boundsfons = new OpenLayers.Bounds(535600,4485000,788050,4752000); 
 	//var boundsfons = new OpenLayers.Bounds(535000,4485000,540000,4752000); 
	var boundsfons = new OpenLayers.Bounds(525000,4485000,540000,4752000); 
	topofons = new OpenLayers.Layer.Image(
                                'topofons',
                                'img/integracioOL/fonsgris.jpg',
								//'img/integracioOL/fonsvermell.gif',
                                //'../../css/img/bg_caja.gif',                                                            
                                boundsfons,                               
                                //new OpenLayers.Size(400,400),
                                img_options);
	topofons.isBaseLayer = false;	
	topofons.setVisibility(true);
	topofons.displayInLayerSwitcher=false;	
	map.addLayer(topofons);
		 	
	afegirMapaRef();
	
	var controlPermalink = new Vissir.PermalinkWindow('permalink');
	map.addControl(controlPermalink);  
	
	// maptip	
	var controlHover = new Vissir.Hover( {handlerOptions: {'delay': 1000} } );   	    
	map.addControl(controlHover);              
	controlHover.activate();  
	/*
	// vora groga bt25/mtc10
    layer_vora7 = new OpenLayers.Layer.WMS(
	    "vora7", parametres.urlWmsQuerySLD,
     	{
			   transparent:'true',
			   //layers: 'NumcarrersD,NumcarrersE',
			   layers: '49',
			   format:"image/gif"
		},
	    {singleTile: true, ratio:1, resolutions :[5]}
	    );
	        
	layer_vora7.isBaseLayer = false;
	layer_vora7.setVisibility(true);
	layer_vora7.displayInLayerSwitcher=false;	
    map.addLayer(layer_vora7);  
	
	// vora groga bt25/mtc10
    layer_vora8 = new OpenLayers.Layer.WMS(
	    "vora8", parametres.urlWmsQuerySLD,
     	{
			   transparent:'true',
			   //layers: 'NumcarrersD,NumcarrersE',
			   layers: '50',
			   format:"image/gif"
		},
	    {singleTile: true, ratio:1, resolutions :[2]}
	    );
	        
	layer_vora8.isBaseLayer = false;
	layer_vora8.setVisibility(true);
	layer_vora8.displayInLayerSwitcher=false;	
    map.addLayer(layer_vora8);  
	*/
	// numeracio i noms de carrers
    layer_numeracio = new OpenLayers.Layer.WMS(
	    "NumeracioCarrer", parametres.urlWmsQuerySLD,
     	{
			   transparent:'true',
			   //layers: 'NumcarrersD,NumcarrersE',
			   layers: '5,4',
			   format:"image/gif"
		},
	    {singleTile: true, ratio:1, resolutions :[1,0.5]}
	    );
	        
	layer_numeracio.isBaseLayer = false;
	layer_numeracio.setVisibility(true);
	layer_numeracio.displayInLayerSwitcher=false;	
    map.addLayer(layer_numeracio);  
       
    // Noms de carrers
    layer_nomscarrers = new OpenLayers.Layer.WMS(
    "NomsCarrer", parametres.urlWmsQuerySLD,
    	{
		   transparent:'true',
		   //layers: 'Nomscarrers',
		   layers: '3',
		   format:"image/gif"
		},
	    {singleTile: true, ratio:1, resolutions :[2,1,0.5]}
	    );
	        
	layer_nomscarrers.isBaseLayer = false;	
	layer_nomscarrers.setVisibility(true);
	layer_nomscarrers.displayInLayerSwitcher=false;
    map.addLayer(layer_nomscarrers);  
         	
	if (args.base) {
		if (args.base == "m")
			map.setBaseLayer(layer_base_mapa);
		else
			map.setBaseLayer(layer_base_orto);
	}
	else
		map.setBaseLayer(layer_base_mapa);
	
// Capes per a fer transparència  
	layer_topo_transp = new Vissir.WMS(
		"Topografica", parametres.baseWmsServerICC,
		{layers: 'topost', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
		{buffer:0, transitionEffect:'resize'} )	;
	        
	layer_topo_transp.isBaseLayer = false;	
	layer_topo_transp.setVisibility(false);
	layer_topo_transp.setOpacity(0);
	layer_topo_transp.displayInLayerSwitcher=false;
	map.addLayer(layer_topo_transp);  

	layer_topo_transp_nomscarrers = new Vissir.WMS(
    "NomsCarrer", parametres.urlWmsQuerySLD,
    	{
		   transparent:'true',
		   //layers: 'Nomscarrers',
		   layers: '3',
		   format:"image/gif"
		},
	    {singleTile: true, ratio:1, resolutions :[2,1,0.5]}
	    );
	        
	layer_topo_transp_nomscarrers.isBaseLayer = false;	
	layer_topo_transp_nomscarrers.setVisibility(false);
	layer_topo_transp_nomscarrers.setOpacity(0);
	layer_topo_transp_nomscarrers.displayInLayerSwitcher=false;
	map.addLayer(layer_topo_transp_nomscarrers);  
	
	layer_topo_transp_numscarrers = new Vissir.WMS(
	    "NumeracioCarrer", parametres.urlWmsQuerySLD,
     	{
			   transparent:'true',
			   //layers: 'NumcarrersD,NumcarrersE',
			   layers: '5,4',
			   format:"image/gif"
		},
	    {singleTile: true, ratio:1, resolutions :[1,0.5]}
	    );
	        
	layer_topo_transp_numscarrers.isBaseLayer = false;	
	layer_topo_transp_numscarrers.setVisibility(false);
	layer_topo_transp_numscarrers.setOpacity(0);
	layer_topo_transp_numscarrers.displayInLayerSwitcher=false;
	map.addLayer(layer_topo_transp_numscarrers);      

	// --------------------------------------------
	// -- 3. Afegir capa de dibuix (Vector) al mapa
	// --------------------------------------------
	// simbolitzacio capa per editar   
	// problema amb estil elements temporals (no utilitza temporary...)	

	var defStyle = new OpenLayers.Style({
	    externalGraphic: "css/integracioOL/avancades/img/fletxa.gif",
	    graphicWidth:23, 
	    graphicHeight:23,
	    fillColor: "#a2332c", 
	    fillOpacity: 1, 
	    strokeColor: "#a2332c", 
	    strokeWidth: "3"
	});
	var tempStyle = new OpenLayers.Style({	    
	    strokeColor: "#a2332c", 
	    strokeWidth: "1"
	});
	
	var styleMap = new OpenLayers.StyleMap({
	    "default": defStyle,
	    "temporary": tempStyle,
	    "select": tempStyle
	});
              
	layer_edit = new OpenLayers.Layer.Vector("Capa de dibuix", {styleMap: styleMap});	
	layer_edit.displayInLayerSwitcher=false;
	map.addLayer(layer_edit);

	// ------------------------------------------------------
	// -- 4. Afegir el control. "layer" obligatori;
	//       "div" opcional (per posar botonera fora del mapa).
	// ------------------------------------------------------
	var controlOptions = {
        	dialeg: null
        };          

   map.addControl(new OpenLayers.Control.GeneraHTML(controlOptions));
	 map.addControl(new OpenLayers.Control.DesaParametres(controlOptions));
   map.addControl(new OpenLayers.Control.Coordenades(controlOptions));
	 map.addControl(new OpenLayers.Control.Esborra(layer_edit, controlOptions));
   map.addControl(new OpenLayers.Control.Linia(layer_edit, controlOptions));
	 map.addControl(new OpenLayers.Control.Texte(controlOptions));
   map.addControl(new OpenLayers.Control.Marca(layer_edit, controlOptions));

     // Elements a ressaltar   
     layer_ressaltar = new OpenLayers.Layer.WMS(
	    "Ressaltar", parametres.urlWmsQuerySLD,
	    {
			   //layers: 'Municipis,Comarques,Trams',
			   layers: '1,0,2',
			   format:"image/gif",			   
			   transparent:'true',
			   styles:'munid,comid,tramid',			   
			   sld: parametres.urPhpSLD
	    },
	    {singleTile: true, ratio:1}											  
	    );	    
	    	        	      
	layer_ressaltar.isBaseLayer = false;	
	layer_ressaltar.setVisibility(false); 
	layer_ressaltar.displayInLayerSwitcher = false;
  layer_ressaltar.setOpacity(0.5);
  map.addLayer(layer_ressaltar);                
                
    // Punts d'interès (per identificar i mostrar maptip)
    layer_poi = new OpenLayers.Layer.WMS(
    "POI",parametres.urlWmsQuerySLD,
    {
            //layers: 'Ajuntaments',
            layers: '39',
            format:"image/gif",bgcolor:'0xff0000', transparent:'true'
    },
    {singleTile: true, ratio: 1}
    );
      	
    layer_poi.addOptions({isBaseLayer: false}); 
    layer_poi.displayInLayerSwitcher = false;	
    layer_poi.setVisibility(false);                        			      	      
    map.addLayer(layer_poi);
	
	for( var i = 0; i < acronimPOI.length; i++) { 			
		addPOI(nameLayerWMS[i],nomPOI[i],acronimPOI[i],i);
	} 			
				                                    
    map.addControl(new Vissir.Click());
    map.addControl(new Vissir.ClickIndica());
    map.addControl(new OpenLayers.Control.Navigation());
    map.addControl(new Vissir.PanZoomBar({div: document.getElementById("olZoomTools")}));   
    
	    
    // boto tornar enrere
	navHistory = new OpenLayers.Control.NavigationHistory();
	map.addControl(navHistory);
	var panelHistory = new OpenLayers.Control.Panel( {div: document.getElementById("olLastExtent")});
	panelHistory.addControls([navHistory.previous]);
	map.addControl(panelHistory);               
  map.getControlsByClass("Vissir.Click")[0].activate();
	
	layer_marker_maptip = new OpenLayers.Layer.Markers( "Markers" );
	layer_marker_maptip.displayInLayerSwitcher = false;
	map.addLayer(layer_marker_maptip);    
  		    		    
	layer_marker_indicaPunt = new OpenLayers.Layer.Markers( "Markers" );
	layer_marker_indicaPunt.displayInLayerSwitcher = false;
	map.addLayer(layer_marker_indicaPunt);  
	   
	layer_marker_mostrarFitxa = new OpenLayers.Layer.Markers( "Markers" );
	layer_marker_mostrarFitxa.displayInLayerSwitcher = false;
	map.addLayer(layer_marker_mostrarFitxa);     		

	layer_marker_mostrarFitxa_cerca = new OpenLayers.Layer.Markers( "Markers" );
	layer_marker_mostrarFitxa_cerca.displayInLayerSwitcher = false;
	map.addLayer(layer_marker_mostrarFitxa_cerca);     	
    
    // per inicialitzar en cas de retornar d'un enllaç de web/mes_informacio d'un POI
   //cercadorM.novaCercaTotal()
      
   //gestio dels parametres url
	if (args.mun) {
		VeureMapa=1;		
	    cercadorM.getZoomMunicipi(args.mun);
	}
	if (args.com) {
		VeureMapa=1;
	    cercadorM.getZoomComarca(args.com);
	}
    if ((args.xyaddress) || (args.xy)) {             
		if (args.xyaddress)
			var xyBox = args.xyaddress.split(":");
		else
			var xyBox = args.xy.split(":");
		if (xyBox.length==2) 
		{			
			var txyaddress_x = parseFloat(xyBox[0]);
			var txyaddress_y = parseFloat(xyBox[1]);					
			var tcenter = new OpenLayers.LonLat(parseFloat(txyaddress_x),
	                                            parseFloat(txyaddress_y));
	                if (args.zoom) {
	                    var tzoom = parseInt(args.zoom);
				     }
	                else 
	                {
		                if (args.xyaddress)
			                var tzoom = 6;
		                else
			                var tzoom = 9;
		            }
	                map.setCenter(tcenter,tzoom);
	                if (args.ident) 
	                {
		                resultat.puntualFilAriadna = true;
		                resultat.puntual = true;
						resultat.x = txyaddress_x;
						resultat.y = txyaddress_y;
						xResultatFilAriadna = txyaddress_x;
						yResultatFilAriadna = txyaddress_y;
						document.getElementById("a_FilAriadna3").innerHTML = args.ident;
					}
					if (args.t_nom) 
	                {
		                resultat.puntualFilAriadna = true;
		                resultat.puntual = true;
						resultat.x = txyaddress_x;
						resultat.y = txyaddress_y;
						resultat.tipus = "turisme";	
						var t_nom = "";						
						var t_adr = "";		
						var t_cp = "";		
						var t_mun = "";		
						var t_tel = "";		
						var t_fax = "";		
						var t_web = "";
						if (args.t_nom) t_nom = args.t_nom;
						if (args.t_adr) t_adr = args.t_adr;
						if (args.t_cp) t_cp = args.t_cp;
						if (args.t_mun) t_mun = args.t_mun;
						if (args.t_tel) t_tel = args.t_tel;
						if (args.t_fax) t_fax = args.t_fax;
						if (args.t_web) t_web = args.t_web;
						resultat.turisme = construir_popup(t_nom,t_adr,t_cp,t_mun,t_tel,t_fax,t_web);
						xResultatFilAriadna = txyaddress_x;
						yResultatFilAriadna = txyaddress_y;
						document.getElementById("a_FilAriadna3").innerHTML = args.t_nom;						
					}

		}
    }
    
  	 /**************
     * Embedded!  *
     **************/
     if(args.embedded) {
	       $('dv_colEsquerra').toggle();
	       $('FW_contingut2').toggle();
	       $('idTitol').toggle();
	       $('capcalera').toggle();
		   $('tipusPlanol').toggle();
	       
	       document.getElementsByClassName("FW_mZonaToolbar")[0].toggle();
	       document.getElementsByClassName("FW_mBarraIconsHoritzontal3")[0].toggle();
	       document.getElementsByClassName("FW_mBarraIconsVertical")[0].toggle();
	       document.getElementById("peu").style.display = "none";
	       document.getElementsByClassName("FW_mBarraCursorHoritzontal")[0].toggle();
	       document.getElementsByClassName("FW_mIconCursorLateralLeft")[0].toggle();
	       document.getElementsByClassName("FW_mIconCursorLateralRight")[0].toggle();
	       document.getElementsByClassName("FW_mBarraCursorHoritzontal_bottom")[0].toggle();
	       document.getElementsByClassName("FW_sFloatLeft FW_sLink FW_sLinkCartografic")[0].toggle();
	       $('ovHider').toggle();	       
	       
	       document.getElementsByClassName("FW_mMapa")[0].style.position="absolute";
	       document.getElementsByClassName("FW_mMapa")[0].style.top="0px";
               document.getElementsByClassName("FW_mMapa")[0].style.left="0px";                              
           
         $('map').style.top="0px";
	       $('map').style.left="0px";	   
	       $('map').style.position="absolute";
	       if (args.sizew)
	       {		       		       
		       $('map').style.width= args.sizew + "px";
		       document.getElementsByClassName("FW_mMapa")[0].style.width= args.sizew + "px";
				 }   else
				 {
		       $('map').style.width="200px";
		       document.getElementsByClassName("FW_mMapa")[0].style.width="200px";
		     }
	       if (args.sizeh)
	       {
		       $('map').style.height= args.sizeh + "px";
		       document.getElementsByClassName("FW_mMapa")[0].style.height=args.sizeh + "px";
				 }   else		       
				 {       
				 	  $('map').style.height="200px";
						document.getElementsByClassName("FW_mMapa")[0].style.height="200px";
				 }
		    document.getElementsByClassName("FW_mMapa")[0].style.border= "0px";
	      $('overview').toggle();
	     }
		   if (args.zoom) 
		   {             
				map.zoomTo(parseInt(args.zoom));					
		   }

		   if (args.consulta) 
		   {
		   	while (args.consulta.indexOf('%E0') != -1 ) 
		                {
		                    args.consulta = args.consulta.replace('%E0','&agrave;');
		                }
		    	args.ident = args.consulta;
		    }            
			 if (args.ident) 
			 {			    
				if (tcenter)
				{	
					resultat.x = tcenter.lon;
					resultat.y = tcenter.lat;		
					resultat.puntual = true;	
					if (args.tipus)
					{
						// cerca POI 
						tipusPOI = args.tipus;
						resultat.taula = args.tipus;
						resultat.adreca = args.ident;
						resultat.tipus = "puntsI";
						mostraFitxaPOI_CridaParametritzada(tcenter,"map", args.tipus,args.ident);				
					}
					else
					{
						actRessaltar(args.ident); 		
					}
				}
			  }
			  if ((args.t_nom)  && ((args.xyaddress) || (args.xy)))
			 {
				procesFitxa_turisme(args.t_nom,resultat.turisme); 	
			 }
				if (args.adreca) 
				{			    
					if (tcenter)
					{	
					xyResultatPuntualFilAriadna = 1;
					xResultatFilAriadna = tcenter.lon;
					yResultatFilAriadna = tcenter.lat;
					fzResultat = 8;		
					}
					resultat.adreca = args.adreca;
					cercadorM.actFilAriadna3();
				}
		
				if (args.selectComarca) 
				{
					selectComarca = args.selectComarca; 
					actRessaltar();
				}
				if (args.selectMunicipi) 
				{	
					selectMunicipi = args.selectMunicipi;
			 	    	actRessaltar();
				}	  
				if (args.selectCarrer) 
				{	
					selectCarrer = args.selectCarrer;
			 	    	actRessaltar();
				}	    
				if (!map.getCenter()) 
				{
					//map.zoomToMaxExtent();
					//map.zoomTo(0);					
					map.setCenter(new OpenLayers.LonLat(401000,4613000),0);
					//map.zoomTo(0);
				}

				mapa.capturaEvents();
				mapa.setupEstils();
				zonaInfo.setupEstils();
				zonaInfo.capturaEvents();	
}


   	//-----------------------
	function addPOI(nameLayerWMS,nameLayerTOC,acronim,index) {			
    nameLayer = new OpenLayers.Layer.WMS(
		nameLayerTOC, parametres.urlWmsQuerySLD,
		{
				layers: nameLayerWMS,
				format:"image/gif",bgcolor:'0xff0000', transparent:'true'
		},
		{singleTile: true, ratio: 1, maxResolution:100}
		);
			           	          	
		nameLayer.addOptions({isBaseLayer: false}); 	                        			      	      
		nameLayer.addOptions({minResolution:0.5, maxResolution:50}); 	
		map.addLayer(nameLayer);
		if ((nameLayerTOC == "metrotmb") || (nameLayerTOC == "autobustmb"))
		{
			nameLayer.setVisibility(true);
		}
		else
			nameLayer.setVisibility(false);	
	}

    //-----------------------
    function canviTipusPlanol(key) {
        switch (key)
        {
            case "orto":
				map.setBaseLayer(layer_base_orto);				
				layer_topo_transp.setVisibility(false);		// topo 2	
				layer_topo_transp_nomscarrers.setVisibility(false);		// topo 2	
				layer_topo_transp_numscarrers.setVisibility(false);		// topo 2
				layer_numeracio.setVisibility(false);
				layer_nomscarrers.setVisibility(false);
				$('FW_iconPlanolFoto').className = 'FW_iconPlanolSeleccionat';
				$('FW_iconPlanolMapa').className = 'FW_iconPlanol';
				$('FW_iconPlanolHibrid').className = 'FW_iconPlanol';
				$('FW_textPlanolMapa').className = 'FW_sLink_TipusMapa';
				$('FW_textPlanolFoto').className = 'FW_sLink_TipusMapa_Sel';
				$('FW_textPlanolHibrid').className = 'FW_sLink_TipusMapa';
				$('FW_iconPlanolMapa').title = 'Mostra el pl\u00E0nol mapa';
				$('FW_iconPlanolFoto').title = "S'est\u00E0 mostrant el pl\u00E0nol foto";
				$('FW_iconPlanolHibrid').title = 'Mostra el pl\u00E0nol h\u00EDbrid';
				$('FW_aPlanolMapa').className = 'FW_sLink';
				$('FW_aPlanolFoto').className = 'FW_sLink2';
				$('FW_aPlanolHibrid').className = 'FW_sLink';										
			break;
            case "mapa":
				map.setBaseLayer(layer_base_mapa);			
				layer_topo_transp.setVisibility(false);		// topo 2
				layer_topo_transp_nomscarrers.setVisibility(false);		// topo 2	
				layer_topo_transp_numscarrers.setVisibility(false);		// topo 2
				layer_numeracio.setVisibility(true);
				layer_nomscarrers.setVisibility(true);				
				$('FW_iconPlanolMapa').className = 'FW_iconPlanolSeleccionat';
				$('FW_iconPlanolFoto').className = 'FW_iconPlanol';
				$('FW_iconPlanolHibrid').className = 'FW_iconPlanol';
				$('FW_textPlanolMapa').className = 'FW_sLink_TipusMapa_Sel';
				$('FW_textPlanolFoto').className = 'FW_sLink_TipusMapa';
				$('FW_textPlanolHibrid').className = 'FW_sLink_TipusMapa';
				$('FW_iconPlanolMapa').title = "S'est\u00E0 mostrant el pl\u00E0nol mapa";
				$('FW_iconPlanolFoto').title = 'Mostra el pl\u00E0nol foto';
				$('FW_iconPlanolHibrid').title = 'Mostra el pl\u00E0nol h\u00EDbrid';
				$('FW_aPlanolFoto').className = 'FW_sLink';
				$('FW_aPlanolMapa').className = 'FW_sLink2';
				$('FW_aPlanolHibrid').className = 'FW_sLink';								
			break;
			case "hibrid": 
				map.setBaseLayer(layer_base_orto);
				layer_base_orto.setVisibility(true);		// orto
				layer_base_mapa.setVisibility(false);	    // topo 1
				
				layer_topo_transp.setVisibility(true);		// topo 2
				layer_topo_transp.setOpacity(0.7);		
				layer_topo_transp.setClip(280,200);	
				layer_topo_transp_nomscarrers.setVisibility(true);		// topo 2
				layer_topo_transp_nomscarrers.setOpacity(0.7);					
				layer_topo_transp_nomscarrers.setClip(280,200);	
				
				layer_topo_transp_numscarrers.setVisibility(true);		// topo 2
				layer_topo_transp_numscarrers.setOpacity(0.7);					
				layer_topo_transp_numscarrers.setClip(280,200);	
				
				layer_numeracio.setVisibility(false);
				layer_nomscarrers.setVisibility(false);
				$('FW_iconPlanolMapa').className = 'FW_iconPlanol';
				$('FW_iconPlanolFoto').className = 'FW_iconPlanol';
				$('FW_iconPlanolHibrid').className = 'FW_iconPlanolSeleccionat';
				$('FW_textPlanolMapa').className = 'FW_sLink_TipusMapa';
				$('FW_textPlanolFoto').className = 'FW_sLink_TipusMapa';
				$('FW_textPlanolHibrid').className = 'FW_sLink_TipusMapa_Sel';
				$('FW_iconPlanolMapa').title = "Mostra el pl\u00E0nol mapa";
				$('FW_iconPlanolFoto').title = 'Mostra el pl\u00E0nol foto';
				$('FW_iconPlanolHibrid').title = "S'est\u00E0 mostrant el pl\u00E0nol h\u00EDbrid";					
				$('FW_aPlanolHibrid').className = 'FW_sLink2';
				$('FW_aPlanolMapa').className = 'FW_sLink';
				$('FW_aPlanolFoto').className = 'FW_sLink';							
			break;	
        }         		
	}
 
    //-----------------------
    function afegirMapaRef(){
		// mapa de referencia	(amb mapa generat dinamicament)			 
		layer_base_gc_maparef =    new OpenLayers.Layer.WMS(
			"Topografica", parametres.baseWmsServerICC_ov,
			{layers: 'maparefgc', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			//{buffer:0, transitionEffect:'resize', resolutions :[4400,2200,1100,550,275,100,50,25,10,5,2,1,0.5]}
			{buffer:0, transitionEffect:'resize', resolutions :[2200,400,200,100,25,10]}
			 );	
	    var overviewMapSize = new OpenLayers.Size(126,107);
	    var mapOptions_ov = {
	            maxExtent: new OpenLayers.Bounds(258000,4485000,536000,4752000), 
	            projection: "EPSG:23031",
	            units: "m"
	        };
	    var bounds = new OpenLayers.Bounds(258000,4485000,536000,4752000); // Limits 250 000 arrodonits	          
		  	        
		var controlOptions_ov = {
	        mapOptions: mapOptions_ov,
			layers: [layer_base_gc_maparef],						
		    size: overviewMapSize,
		    projection: "EPSG:23031", 
		    units: 'm',
		    div: $('overview'),
			//The default minRatio is 8 and the default maxRatio is 32
	        minRatio: 8, maxRatio: 32
		    //minRatio: 10, maxRatio: 10
	        }	
		var ovControl = new OpenLayers.Control.OverviewMap(controlOptions_ov);
		//Afegim la capa per pintar el punt localitzat al mapa de referència
		if (ovControl.ovmap!=null)
		{		
			layer_marker_indicaPunt_ref = new OpenLayers.Layer.Markers( "Markers" );
			layer_marker_indicaPunt_ref.displayInLayerSwitcher = false;	
			ovControl.ovmap.addLayer(layer_marker_indicaPunt_ref); 
		}
		
		ovControl.isSuitableOverview = function() {
	        return false;
	    };
	    ovControl.updateOverview = function() {	  
			actRessaltar();
			loc = document.getElementById("versio_ajax").href;
	    	if (map)
				{
					var nz = map.getZoom() + 1;
					var ccenter = map.getExtent().getCenterLonLat();
					document.getElementById("versio_ajax").href = loc.substr(0,loc.indexOf("?")) + "?cercadorMunicipis&zoom="+ nz + "&cx=" + ccenter.lon + "&cy=" + ccenter.lat;
			  }
			  else
					document.getElementById("versio_ajax").href = loc;
	if (selectMunicipi != "") 
	{ 
		$("versio_ajax").href += "&idmuni="+selectMunicipi;
		if (resultat.municipi != "")$("versio_ajax").href += "&ctl_municipi="+resultat.municipi;
	}
		
	if (selectCarrer != "") $("versio_ajax").href += "&tipus_cerca=adreca&idvia="+selectCarrer + "&idmuni="+resultat.idmunicipi;
	if (selectNum != "") $("versio_ajax").href += "&tipus_cerca=adreca&ctl_num="+selectNum;
	if (selectToponim != "") $("versio_ajax").href += "&tipus_cerca=toponim&seltoponim="+selectToponim+"&muniTrobat_t="+resultat.municipi+"&cx="+resultat.x+"&cy="+resultat.y;
	if (selectPoi != "") $("versio_ajax").href += "&tipus_cerca=poi&selpoi="+selectPoi.replace("'"," ")+"&muniTrobat_p="+resultat.municipi+"&cx="+resultat.x+"&cy="+resultat.y;
	
	    	var loc = location.href;
				if(loc[loc.length-1] == "#")
				loc = loc.substr(0,loc.length-1);
				if(loc.indexOf("?") >= 0)
				loc = loc.substr(0,loc.indexOf("?"));	
				
	    		
  		if (map.getZoom() >= zonaInfo.maxZoomVis) 
	    	{				
				//mapa.mostraMissatgeAvis(true,"Feu zoom per visualitzar els punts d'inter&egrave;s seleccionats.",false);
				mapa.tancaMissatgeAvis();										 
	    	}
	    	else
		    	if (zonaInfo.obtenirNombreVisiblesPI()	> 0) 
		    	{				
					mapa.mostraMissatgeAvis(true,"Feu zoom per visualitzar els punts d'inter&egrave;s seleccionats.",false);									 
		    	}
		zonaInfo.mostraPestanya("tab6");		
	        var mapRes = this.map.getResolution();	  
	        var mapZoom = this.map.getZoomForResolution(mapRes);
	        if (mapZoom == 0)  var ovmapZoom = 0;
	        if (mapZoom == 1)  var ovmapZoom = 0;
	        if (mapZoom == 2)  var ovmapZoom = 0;
	        if (mapZoom == 3)  var ovmapZoom = 1;
	        if (mapZoom == 4)  var ovmapZoom = 1;
	        if (mapZoom == 5)  var ovmapZoom = 2;
	        if (mapZoom == 6)  var ovmapZoom = 3;
	        if (mapZoom == 7)  var ovmapZoom = 3;
	        if (mapZoom == 8)  var ovmapZoom = 4;
	        if (mapZoom == 9)  var ovmapZoom = 5;
	        
	       if (ovmapZoom < 0) ovmapZoom = 0; 
	       if (ovmapZoom == 0)                
				this.ovmap.setCenter(this.map.getMaxExtent().getCenterLonLat(), ovmapZoom);	 
		   else
		   		this.ovmap.setCenter(this.map.center, ovmapZoom);	 		   
	        this.updateRectToMap();	        
	        if (resultat.puntual  && resultat.x!=0 && resultat.y!=0) {
						this.addPuntMarker();
					}
					else {
						if (layer_marker_indicaPunt_ref)
						{
							layer_marker_indicaPunt_ref.clearMarkers();	  
						}
					}
    	};   
    	
    	ovControl.updateRectToMap = function() {
        // The base layer for overview map needs to be in the same projection
        // as the base layer for the main map.  This should be made more robust.
        if(this.map.units != 'degrees') {
            if(this.ovmap.getProjection() && (this.map.getProjection() != this.ovmap.getProjection())) {
                alert(OpenLayers.i18n("sameProjection"));
            }
        }
        if (this.map.getResolution() == 550)
	        this.extentRectangle.style.visibility = "hidden";
	    else
		    this.extentRectangle.style.visibility = "visible";
        var pxBounds = this.getRectBoundsFromMapBounds(this.map.getExtent());
        if (pxBounds) {
            this.setRectPxBounds(pxBounds);
        }
    };
    
    //Funció per dibuixar el punt al mapa de referència
     ovControl.addPuntMarker = function() {
        	
    		var size = new OpenLayers.Size(15,15);	
    		var icon = new OpenLayers.Icon("img/punt.png",size);
    		var lonlat=new OpenLayers.LonLat(resultat.x,resultat.y);
    		//if (marker_punt && layer_marker_indicaPunt_ref) layer_marker_indicaPunt_ref.removeMarker(marker_punt);	 
    		marker_punt = new OpenLayers.Marker(lonlat,icon);
    		if (layer_marker_indicaPunt_ref)
    		{
    			layer_marker_indicaPunt_ref.clearMarkers();
    		}	  
    		else {
    			layer_marker_indicaPunt_ref = new OpenLayers.Layer.Markers( "Markers" );
    			layer_marker_indicaPunt_ref.displayInLayerSwitcher = false;	
    			this.ovmap.addLayer(layer_marker_indicaPunt_ref);
    		}
    		layer_marker_indicaPunt_ref.addMarker(marker_punt);    
    			//layer_marker_indicaPunt_ref.addMarker(new OpenLayers.Marker(lonlat,icon));
    	//	this.ovmap.addLayer(layer_marker_indicaPunt_ref); 
    		
      
    };
        ovControl.draw = function() {
        OpenLayers.Control.prototype.draw.apply(this, arguments);
        if(!(this.layers.length > 0)) {
            if (this.map.baseLayer) {
                var layer = this.map.baseLayer.clone();
                this.layers = [layer];
            } else {
                this.map.events.register("changebaselayer", this, this.baseLayerDraw);
                return this.div;
            }
        }

        // create overview map DOM elements
        this.element = document.createElement('div');
        this.element.className = this.displayClass + 'Element';
        this.element.style.display = 'none';

        this.mapDiv = document.createElement('div');
        this.mapDiv.style.width = this.size.w + 'px';
        this.mapDiv.style.height = this.size.h + 'px';
        this.mapDiv.style.position = 'relative';
        this.mapDiv.style.overflow = 'hidden';
        this.mapDiv.id = OpenLayers.Util.createUniqueID('overviewMap');
        
        this.extentRectangle = document.createElement('div');
        this.extentRectangle.style.position = 'absolute';
        this.extentRectangle.style.zIndex = 1000;  //HACK
        this.extentRectangle.className = this.displayClass+'ExtentRectangle';
        this.mapDiv.appendChild(this.extentRectangle);

        this.element.appendChild(this.mapDiv);  

        this.div.appendChild(this.element);

        // Optionally add min/max buttons if the control will go in the
        // map viewport.
        if(!this.outsideViewport) {
            this.div.className += " " + this.displayClass + 'Container';
            var imgLocation = OpenLayers.Util.getImagesLocation();
            // maximize button div
            //var img = imgLocation + 'layer-switcher-maximize.png';
            var img = imgLocation + 'integracioOL/icMapGuia_2_act.gif';
            this.maximizeDiv = OpenLayers.Util.createAlphaImageDiv(
                                        this.displayClass + 'MaximizeButton', 
                                        null, 
                                        new OpenLayers.Size(18,18), 
                                        img, 
                                        'absolute');
            this.maximizeDiv.style.display = 'none';
            this.maximizeDiv.className = this.displayClass + 'MaximizeButton';            
            OpenLayers.Event.observe(this.maximizeDiv, 'click', 
                OpenLayers.Function.bindAsEventListener(this.maximizeControl,
                                                        this)
            );
            this.div.appendChild(this.maximizeDiv);
    
            // minimize button div
            //var img = imgLocation + 'layer-switcher-minimize.png';
            var img = imgLocation + 'integracioOL/icMapGuia_1.gif';
            this.minimizeDiv = OpenLayers.Util.createAlphaImageDiv(
                                        'OpenLayers_Control_minimizeDiv', 
                                        null, 
                                        new OpenLayers.Size(18,18), 
                                        img, 
                                        'absolute');
            this.minimizeDiv.style.display = 'none';
            this.minimizeDiv.className = this.displayClass + 'MinimizeButton';
            OpenLayers.Event.observe(this.minimizeDiv, 'click', 
                OpenLayers.Function.bindAsEventListener(this.minimizeControl,
                                                        this)
            );
            this.div.appendChild(this.minimizeDiv);
            
            var eventsToStop = ['dblclick','mousedown'];
            
            for (var i = 0; i < eventsToStop.length; i++) {

                OpenLayers.Event.observe(this.maximizeDiv, 
                                         eventsToStop[i], 
                                         OpenLayers.Event.stop);

                OpenLayers.Event.observe(this.minimizeDiv,
                                         eventsToStop[i], 
                                         OpenLayers.Event.stop);
            }
            
            this.minimizeControl();
        } else {
            // show the overview map
            this.element.style.display = '';
        }
        if(this.map.getExtent()) {
            this.update();
        }
        
        this.map.events.register('moveend', this, this.update);

        return this.div;
    };
           	
	
// Customitzacio per a Guia de carrers
// veure comentari a OpenLayers/Util.js
// veure comentari a OpenLayers/Handler/Drag.js
// veure comentari a OpenLayers/Handler/Box.js     	    
// veure comentari a OpenLayers/Popup.js    
		map.addControl(ovControl);  		 
} 

	//-----------------------
    function toggleOverview() {
		$('overview').toggle();
		$('ovHider').firstDescendant().src = $('overview').visible() ? 'img/integracioOL/icMapGuia_1.gif' : 'img/integracioOL/icMapGuia_2_act.gif';
		if ($('overview').visible()) 
		{
			$('ovHider').firstDescendant().title = "Tanca mapa de referencia";	
			$('ovHider').firstDescendant().alt = "Tanca mapa de referencia";	
		}
		else
		{
			$('ovHider').firstDescendant().title = "Obre mapa de referencia";
			$('ovHider').firstDescendant().alt = "Obre mapa de referencia";		
		}
      }

	//---------------------------- 
	function actRessaltar(text_ident) {
	//---------------------------- 
	// s'ha de cridar abans d'actualitzar el mapa 
	if ((!resultat.puntual) && (!resultat.puntualFilAriadna)) layer_marker_indicaPunt.clearMarkers();
	if (layer_ressaltar) 
	{
		var tempVis = true;			
		if ((selectCarrer != '') && (!resultat.puntual))
		{
			layer_ressaltar.addOptions({minResolution:0.5, maxResolution:550});
			layer_ressaltar.mergeNewParams({styles:',,tram'+selectCarrer,sld: parametres.urPhpSLD + selectCarrer }); 
			//layer_ressaltar.mergeNewParams({styles:',,tram'+selectCarrer,sld: parametres.urPhpSLD  }); 
		}
		else {
				
				if (selectMunicipi != '') 
				{
					layer_ressaltar.addOptions({minResolution:10, maxResolution:550});
					layer_ressaltar.mergeNewParams({styles:'mun' +selectMunicipi + ',,',sld: parametres.urPhpSLD +  selectMunicipi }); 
				}
				else if (selectComarca != '') 
				{
					layer_ressaltar.addOptions({minResolution:50, maxResolution:550});
					layer_ressaltar.mergeNewParams({styles:',com' +selectComarca + ',',sld: parametres.urPhpSLD +  selectComarca }); 
				}
				else
					tempVis = false;
				if (map.zoom >= 6) tempVis = false;
			 }				
		if (tempVis) 
			layer_ressaltar.setVisibility(true); 					
		else
			layer_ressaltar.setVisibility(false); 
	}
	else
		layer_ressaltar.setVisibility(false); 
	/*if (popup_punt != null) {                 
                 map.removePopup(popup_punt); 
                 popup_punt.destroy(); 
                 popup_punt = null; 
         }*/
	if (resultat.puntual)
	{		
		if (resultat.tipus == "puntsI") 
		{
				procesFitxa_cerca(locSeleccionat,true);
		}
		else
		{
		var ndiv0 = document.getElementById("dv_mapaPrint_detallPI");
		while(ndiv0.hasChildNodes()) {
			ndiv0.removeChild(ndiv0.firstChild);}
		ll = new OpenLayers.LonLat(resultat.x,resultat.y);
		var temp_text = text_ident;

		if ((!temp_text) && (resultat.tipus != "municipi_gestionaInfoPunt"))
		{
			temp_text = resultat.adreca;
		}	
		if (!temp_text) return;				
      
		ll = new OpenLayers.LonLat(resultat.x,resultat.y);
																			
		popupContentHTML = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
		popupContentHTML += '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ca"> ';
		popupContentHTML += '<head> ';
		popupContentHTML += '	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ';
		popupContentHTML += '	<meta http-equiv="Content-Script-Type" content="text/javascript; charset=UTF-8" />';
		popupContentHTML += '	<title>Prototip Carrerer</title>';
		popupContentHTML += '	<link href="css/carrerer/FW_capPeu.css" rel="stylesheet" type="text/css" />';
		popupContentHTML += '	<link href="css/carrerer/FW_blocs.css" rel="stylesheet" type="text/css" />';
		popupContentHTML += '	<link href="css/carrerer/FW_estils.css" rel="stylesheet" type="text/css" />';
		popupContentHTML += '	<link href="css/carrerer/FW_carrerer.css" rel="stylesheet" type="text/css" />';
		popupContentHTML += '	<link href="css/carrerer/tabuladors.css" rel="stylesheet" type="text/css" />';
		popupContentHTML += '	<!-- <link href="css/carrerer/FW_minWidthIE.css" rel="stylesheet" type="text/css" /> -->';
		popupContentHTML += '	<!-- <link href="css/carrerer/FW_print_detallPI.css" rel="stylesheet" type="text/css" media="print" /> -->';
		popupContentHTML += '</head>';
		popupContentHTML += '<body>';		
		popupContentHTML += '  <div class="FW_sMissatgeCol2b" >';
		popupContentHTML += '      <div style="background:white">';
		popupContentHTML += '          ';
		popupContentHTML += '          <div class="FW_sMarginEsq12 FW_sMarginRight12 FW_sMarginTop5 FW_sMarginBottom5">';
		popupContentHTML += '              <span><strong>' + temp_text + '</strong></span>';
		popupContentHTML += '          </div>';         		
		popupContentHTML += '      </div>';
		popupContentHTML += '</div>';
		popupContentHTML += '</body></html>';
		var icon_img = "img/punt.png";	
		addMarkerPunt(ll, popupContentHTML, true, true,icon_img);
		}	
	}
}

	//----------------------------
	function mousedown_marker_punt(evt) {
            if (popup_punt != null)  popup_punt.toggle();  
            OpenLayers.Event.stop(evt);
	} 
	//----------------------------
	function mouseover_marker_punt(evt) {
	            map.div.style.cursor = "pointer";          
	}			
	
	//----------------------------
	function mouseout_marker_punt(evt) {
	        map.div.style.cursor = cursors.pan;          
	}        
                       
	//----------------------------
	function addMarkerPunt(ll, popupContentHTML, closeBox, overflow, icon_img) {			   					       			   			
			var size = new OpenLayers.Size(15,15);	
			feature_punt = new OpenLayers.Feature(layer_poi,ll,{icon:new OpenLayers.Icon(icon_img,size)});
			FramedCloud = OpenLayers.Class(OpenLayers.Popup.SmallPopup, 
        	{       
 		       'minSize': new OpenLayers.Size(120,80),
 		       'maxSize': new OpenLayers.Size(300,380),
 		       'autoSize': true,
 		       'panMapIfOutOfView': false,
	 		   'keepInMap': false 
 	       }); 	   	        
			feature_punt.popupClass = FramedCloud;
      marker_punt = feature_punt.createMarker();         
      if (layer_marker_indicaPunt) layer_marker_indicaPunt.clearMarkers();	  
      layer_marker_indicaPunt.addMarker(marker_punt);      
                   
      marker_punt.events.register("mousedown", marker_punt, mousedown_marker_punt);              
      marker_punt.events.register("mouseover", marker_punt, mouseover_marker_punt);
      marker_punt.events.register("mouseout", marker_punt, mouseout_marker_punt);      
 	                             
      if (popup_punt != null) {                 
               map.removePopup(popup_punt); 
               popup_punt.destroy(); 
               popup_punt = null; 
       } 

      popup_punt = feature_punt.createPopup(true);         
            
      popup_punt.setContentHTML(popupContentHTML);                     				
      map.addPopup(popup_punt);         
}
   
OpenLayers.Handler.Box.prototype.startBox = function (xy) {
        this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
                                                 this.dragHandler.start);
        this.zoomBox.className = this.boxDivClassName;                                         
        this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
        this.map.viewPortDiv.appendChild(this.zoomBox);

        // TBD: use CSS classes instead
        //this.map.div.style.cursor = "crosshair";
        //cursor definit per a Guia de carrers        
        if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) 
        	this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/ampliar.cur"),default'; 
        else
        	this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/ampliar.ico") 0 0,default';         
        
};

OpenLayers.Handler.Box.prototype.endBox = function (end) {
        var result;
        if (Math.abs(this.dragHandler.start.x - end.x) > 5 ||    
            Math.abs(this.dragHandler.start.y - end.y) > 5) {   
            var start = this.dragHandler.start;
            var top = Math.min(start.y, end.y);
            var bottom = Math.max(start.y, end.y);
            var left = Math.min(start.x, end.x);
            var right = Math.max(start.x, end.x);
            result = new OpenLayers.Bounds(left, bottom, right, top);
        } else {
            result = this.dragHandler.start.clone(); // i.e. OL.Pixel
        } 
        this.removeBox();
        // TBD: use CSS classes instead
        //this.map.div.style.cursor = "";
        //cursor definit per a Guia de carrers
        if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) 
        	this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/Pan.cur"),default'; 
        else
        	this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/Pan.cur") 16 16,default';         

        this.callback("done", [result]);
    };

OpenLayers.Handler.Drag.prototype.mousedown = function (evt) {
        var propagate = true;
        this.dragging = false;
        if (this.checkModifiers(evt) && OpenLayers.Event.isLeftClick(evt)) {
            this.started = true;
            this.start = evt.xy;
            this.last = evt.xy;
            // TBD replace with CSS classes
            //this.map.div.style.cursor = "move";       
            //this.map.div.style.cursor = mapa.cursors.arrastrar;               
           if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) 
		this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/ma_agafant.cur"),default';
	    else
		this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/ma_agafant.ico") 12 12,default';
                 
            this.down(evt);
            this.callback("down", [evt.xy]);
            OpenLayers.Event.stop(evt);
            
            if(!this.oldOnselectstart) {
                this.oldOnselectstart = (document.onselectstart) ? document.onselectstart : function() { return true; };
                document.onselectstart = function() {return false;};
            }
            
            propagate = !this.stopDown;
        } else {
            this.started = false;
            this.start = null;
            this.last = null;
        }
        return propagate;
    };
    
    OpenLayers.Handler.Drag.prototype.mouseup = function (evt) {
    	        if (this.started) {
            var dragged = (this.start != this.last);
            this.started = false;
            this.dragging = false;
            // TBD replace with CSS classes
            this.map.div.style.cursor = "";
            //cursor definit per a Guia de carrers           
            if (mapa.iconsActius[7]) 
            // si l'eina activa es 'mostrar coordenades', mantenir el cursor especial		    
							this.map.div.style.cursor = cursors.creu;
				    else
				    	{		    
								if (mapa.iconsActius[6]) 
	            // si l'eina activa es 'esborrar', mantenir el cursor especial		    
									this.map.div.style.cursor = cursors.esborrar;
					      else		    
					    		this.map.div.style.cursor = cursors.pan;
				    }
		   
            this.up(evt);
            this.callback("up", [evt.xy]);
            if(dragged) {
                this.callback("done", [evt.xy]);
            }
            document.onselectstart = this.oldOnselectstart;
        }
        return true;
    };
    
        OpenLayers.Control.prototype.defaultMouseDown = function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) {
            return;
        }
        this.mouseDragStart = evt.xy.clone();
        this.performedDrag = false;
        this.startViaKeyboard = false;
        if (evt.shiftKey && this.mode !="zoombox") {
            this.switchModeTo("zoombox");
            this.startViaKeyboard = true;
        } else if (evt.altKey && this.mode !="measure") {
            this.switchModeTo("measure");
        } else if (!this.mode) {
            this.switchModeTo("pan");
        }
        switch (this.mode) {
            case "zoombox":
                this.map.div.style.cursor = "crosshair";
                this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
                                                         this.mouseDragStart,
                                                         null,
                                                         null,
                                                         "absolute",
                                                         "2px solid red");
                this.zoomBox.style.backgroundColor = "white";
                //this.zoomBox.style.filter = "alpha(opacity=50)"; // IE
                //this.zoomBox.style.opacity = "0.50";
                this.zoomBox.style.fontSize = "1px";
                this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.viewPortDiv.appendChild(this.zoomBox);
                this.performedDrag = true;
                break;
            case "measure":
                var distance = "";
                if (this.measureStart) {
                    var measureEnd = this.map.getLonLatFromViewPortPx(this.mouseDragStart);
                    distance = OpenLayers.Util.distVincenty(this.measureStart, measureEnd);
                    distance = Math.round(distance * 100) / 100;
                    distance = distance + "km";
                    this.measureStartBox = this.measureBox;
                }    
                this.measureStart = this.map.getLonLatFromViewPortPx(this.mouseDragStart);;
                this.measureBox = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           -2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");
                this.measureBox.style.width="4px";
                this.measureBox.style.height="4px";
                this.measureBox.style.fontSize = "1px";
                this.measureBox.style.backgroundColor="red";
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                if (distance) {
                    this.measureBoxDistance = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");
                    
                    this.measureBoxDistance.innerHTML = distance;
                    this.measureBoxDistance.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                    this.map.layerContainerDiv.appendChild(this.measureBoxDistance);
                    this.measureDivs.push(this.measureBoxDistance);
                }
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                this.measureDivs.push(this.measureBox);
                break;
            default:
                this.map.div.style.cursor = "move";
                break;
        }
        document.onselectstart = function() { return false; };
        OpenLayers.Event.stop(evt);
    };

    
    OpenLayers.Control.ArgParser.prototype.setMap = function(map) {
        OpenLayers.Control.prototype.setMap.apply(this, arguments);

        //make sure we dont already have an arg parser attached
        for(var i=0; i< this.map.controls.length; i++) {
            var control = this.map.controls[i];
            if ( (control != this) &&
                 (control.CLASS_NAME == "OpenLayers.Control.ArgParser") ) {
                
                // If a second argparser is added to the map, then we 
                // override the displayProjection to be the one added to the
                // map. 
                if (control.displayProjection != this.displayProjection) {
                    this.displayProjection = control.displayProjection;
                }    
                
                break;
            }
        }
        /*if (i == this.map.controls.length) {

            var args = OpenLayers.Util.getParameters();
            // Be careful to set layer first, to not trigger unnecessary layer loads
            if (args.layers) {
                this.layers = args.layers;
    
                // when we add a new layer, set its visibility 
                this.map.events.register('addlayer', this, 
                                         this.configureLayers);
                this.configureLayers();
            }
            if (args.lat && args.lon) {
                this.center = new OpenLayers.LonLat(parseFloat(args.lon),
                                                    parseFloat(args.lat));
                if (args.zoom) {
                    this.zoom = parseInt(args.zoom);
                }
    
                // when we add a new baselayer to see when we can set the center
                this.map.events.register('changebaselayer', this, 
                                         this.setCenter);
                this.setCenter();
            }
        }*/
    };
    
 // Canvi per a evitar mostrar imatge de color rosa quan un layer no esta disponible
    OpenLayers.Util.onImageLoadError = function() {
    this._attempts = (this._attempts) ? (this._attempts + 1) : 1;
    if(this._attempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS) {
        this.src = this.src;
    } else {
        //this.style.backgroundColor = OpenLayers.Util.onImageLoadErrorColor;
        this.style.backgroundColor = null;
    }
    this.style.display = "";
	};
 

    OpenLayers.Util.getRenderedDimensions = function(contentHTML, size) {   
    var w, h; 
    // create temp container div with restricted size
    var container = document.createElement("div");
    //container.style.overflow= "";
    container.style.overflow="hidden";
    
    container.style.position = "absolute";
    //container.style.left = "-9999px";
    container.style.left = "0px";
     container.style.top = "0px";
    //fix a dimension, if specified.    
    if (size) {
        if (size.w) {
            	w = size.w;          	
            	container.style.width = w + "px";             	
        } else if (size.h) {

            	h = size.h;
            	container.style.height = h + "px";             	
        } 
    }
    // create temp content div and assign content
    var content = document.createElement("div");
    content.innerHTML = contentHTML;
    content.style.height="auto";
    content.style.overflow="hidden";   
    
    // add content to restricted container 
    container.appendChild(content);
    
    // append container to body for rendering
    //document.body.appendChild(container);
    document.getElementById("id_bMarc").appendChild(container);
    
    // calculate scroll width of content and add corners and shadow width
    if (!w) {
        w = parseInt(content.scrollWidth);
        // update container width to allow height to adjust
        container.style.width = w + "px";
    }        
    // capture height and add shadow and corner image widths
    if (!h) {
        h = parseInt(content.scrollHeight);
        if (h==0) h = parseInt(content.offsetHeight);
        container.style.height = h + "px";
    }
    // remove elements
    container.removeChild(content);
    //document.body.removeChild(container);
    document.getElementById("id_bMarc").removeChild(container);
    return new OpenLayers.Size(w, h);
};
  
OpenLayers.Util.modifyAlphaImageDiv = function(div, id, px, sz, imgURL, 
                                               position, border, sizing, 
                                               opacity) {

    OpenLayers.Util.modifyDOMElement(div, id, px, sz, 
                                     null, null, null, opacity);

    var img = div.childNodes[0];

    if (imgURL) {
        img.src = imgURL;
    }
    OpenLayers.Util.modifyDOMElement(img, div.id + "_innerImage", null, sz, 
                                     "relative", border);
    
    if (OpenLayers.Util.alphaHack()) {

        div.style.display = "inline-block";
        if (sizing == null) {
            sizing = "scale";
        }
        
        div.style.filter = "progid:DXImageTransform.Microsoft" +
                           ".AlphaImageLoader(src='" + img.src + "', " +
                           "sizingMethod='" + sizing + "')";
        if (parseFloat(div.style.opacity) >= 0.0 && 
            parseFloat(div.style.opacity) < 1.0) {
            div.style.filter += " alpha(opacity=" + div.style.opacity * 100 + ")";
        }
		
		// Customitzacio per a Guia de carrers
		// Es comenta la linia per integracio OpenLayers - css maqueta 
		// (si no, a IE les imatges transparents no apareixen)
        //img.style.filter = "alpha(opacity=0)";
    }
};
OpenLayers.Util.getParameters = function(url) {
    // if no url specified, take it from the location bar
    url = url || window.location.href;

    //parse out parameters portion of url string
    var paramsString = "";
    if (OpenLayers.String.contains(url, '?')) {
        var start = url.indexOf('?') + 1;
        var end = OpenLayers.String.contains(url, "#") ?
                    url.indexOf('#') : url.length;
        paramsString = url.substring(start, end);
    }
        
    var parameters = {};
    var pairs = paramsString.split(/[&;]/);
    for(var i = 0; i < pairs.length; ++i) {
        var keyValue = pairs[i].split('=');
        if (keyValue[0]) {
            // canvi per convertir a minuscules
            var key = decodeURIComponent(keyValue[0]).toLowerCase();
            var value = keyValue[1] || ''; //empty string if no value

            //decode individual values
            value = value.split(",");
            for(var j=0; j < value.length; j++) {
            	var temp = value[j];
                //value[j] = decodeURIComponent(value[j]);
                try {
		value[j] = decodeURIComponent(temp);
		} catch (error) {
		value[j] = decodeURIComponent(unescape(temp));
		}
            }

            //if there's only one value, do not return as array                    
            if (value.length == 1) {
                value = value[0];
            }                
            
            parameters[key] = value;
         }
     }
    return parameters;
};

    OpenLayers.Popup.prototype.setOpacity = function(opacity) { 
        if (opacity != undefined) {
            this.opacity = opacity; 
        }
        
        if (this.div != null) {
            // for Mozilla and Safari
            this.div.style.opacity = this.opacity;

            // for IE
            // Customitzacio per a Guia de carrers
            //this.div.style.filter = 'alpha(opacity=' + this.opacity*100 + ')';
        }
    };
    
    OpenLayers.Ajax.Request.prototype.initialize = function(url, options) {
        OpenLayers.Ajax.Base.prototype.initialize.apply(this, [options]);
        
        if (OpenLayers.ProxyHost && OpenLayers.String.startsWith(url, "http")) {
            if (url != parametres.urlPrint)
            	url = OpenLayers.ProxyHost + encodeURIComponent(url);          
        }
        this.transport = OpenLayers.Ajax.getTransport();
        this.request(url);
    };
    
    
 
