var server = document.location.host;

if (server == "gondor.icc.local")
{
	 var parametres = {
	   	 baseWmsServerICC: "http://lupito.icc.local/tilecache/tilecache.py?",	   	 
	   	 baseWmsServerICC_ov: "http://lupito.icc.local/tilecache/tilecache.py?",
	   	 
	   	 urlWmsQuerySLD: "http://" + servidorWMS + "/arcgis/services/guia_catalunya_montsant/MapServer/WMSServer?",
	   	 
	   	 urPhpSLD: "http://" + server + "/website/guia/php/f_sld.php?par=",
	   	 
	   	 urlGeocodificador: "http://" + servidorJava + "/geocodificador/json",		 

	   	 urlPOIsearch: "http://" + servidorJava + "/poissearch/",	   	 
	   	 urlLlogaretssearch: "http://" + servidorJava + "/llogaretssearch/getLlogaretsMatch",
	   	 urlSpatialsearch: "http://" + servidorJava + "/spatialsearch/",	   	 
	   	 urlCruillessearch: "http://" + servidorJava + "/cruillessearch/getCruillesProx",   	 
	     	 // Serveis Java (via mod_jk)
	     	 urlPrint: "http://" + server + "/serveisGuiaCarrers/mapSnapshot",
	    	 urlPrintPath: "http://" + server + "/serveisGuiaCarrers/",
		 urlSave: "http://" + server + "/website/guia/php/save3.php?url=",
		 urlSendMail: "http://" + server + "/serveisGuiaCarrers/SendMail"			 
	   } 
}
else
{
	 var parametres = {
	   	 baseWmsServerICC: "http://centaurus.icc.cat/tilecache/tilecache.py?",
	   	 baseWmsServerICC_ov: "http://centaurus.icc.cat/tilecache/tilecache.py?",
	   	 
	   	 urlWmsQuerySLD: "http://" + servidorWMS + "/arcgis/services/guia_catalunya/MapServer/WMSServer?",
	   	 
	   	 urPhpSLD: "http://mercuri.icc.cat/website/guia/php/f_sld.php?par=",
	   	 
	   	 urlGeocodificador: "http://" + servidorJava + "/geocodificador/json",		 
		 
		 urlPOIsearch: "http://" + servidorJava + "/poissearch/",
	   	 urlLlogaretssearch: "http://" + servidorJava + "/llogaretssearch/getLlogaretsMatch",
	   	 urlSpatialsearch: "http://" + servidorJava + "/spatialsearch/",  
	   	 urlCruillessearch: "http://" + servidorJava + "/cruillessearch/getCruillesProx",	   	   	  	 
	         urlPrint: "http://mercuri.icc.cat/serveisGuiaCarrers/mapSnapshot",
	         urlPrintPath: "http://mercuri.icc.cat/serveisGuiaCarrers/",
		 urlSave: "http://mercuri.icc.cat/website/guia/php/save3.php?url=",
		 urlSendMail: "http://mercuri.icc.cat/serveisGuiaCarrers/SendMail"			   
	   } 
}	

//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;

	// 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;
	
	var nomPOI = new Array();
	var acronimPOI = new Array();
	var descPOI = new Array();
	var nameLayerWMS = new Array();
	
    //----------------
    function init(){
    //----------------  
    var args = OpenLayers.Util.getParameters();		  
 
    OpenLayers.ProxyHost ="php/proxy.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"},
			{buffer:0, transitionEffect:'resize'} )				 			 		 			
	/*		new OpenLayers.Layer.WMS(
			"Ortofoto", parametres.baseWmsServer,
			{layers: 'orto', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			{buffer:0, transitionEffect:'resize'} )
			new OpenLayers.Layer.WMS(
			"Topogràfica", parametres.baseWmsServer,
			{layers: 'topost', format:"image/jpeg", exceptions:"application/vnd.ogc.se_xml"},
			{buffer:0, transitionEffect:'resize'} )		*/			
		];			      

// embeded
	var bounds = new OpenLayers.Bounds(258000,4485000,536000,4752000);
	var resolutions = [550,275,100,50,25,10,5,2,1,0.5];
//	var resolutions = [600,275,100,50,25,10,5,2,1,0.5];
	//var resolutions = [800,600,400,200,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); 
	topofons = new OpenLayers.Layer.Image(
                                'topofons',
                                'img/fonsgris.jpg',
                                //'../../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();  
	
	// 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);      

/*			      
    layer_topo_transp_nomscarrers = layer_nomscarrers.clone();
	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 = layer_numeracio.clone();
	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).
	// ------------------------------------------------------
   	//map.addControl( new OpenLayers.Control.BotoneraFuncionsAvancades(layer_edit, {div: $('botonera')}));	
	//if (!map.getCenter()) {
	//	map.zoomToMaxExtent();
	//}
	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, resolutions :[550,275,100,50,25,10,5,2,1,0.5]}
	    {singleTile: true, ratio:1}											  
	    );	    
	    	        	      
	layer_ressaltar.isBaseLayer = false;	
	layer_ressaltar.setVisibility(false); 
	layer_ressaltar.displayInLayerSwitcher = false;
    layer_ressaltar.setOpacity(0.5);
    //layer_ressaltar.addOptions({minResolution:10, maxResolution:550}); 	
    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);

	/*// Punts d'interès (per taula de continguts)
	if (args.capes) 
	{
		var argcapes = args.capes;
		argcapes = argcapes.toString().toUpperCase();				
	}
	else
		var argcapes = "";	
	*/
	
	nomPOI[0] = "ajuntaments"; 
	nomPOI[1] = "delegacions";
	nomPOI[2] = "oficatencioc";
	nomPOI[3] = "hotels"; 
	nomPOI[4] = "mercats";
	nomPOI[5] = "biblioteques";
	nomPOI[6] = "museus";
	nomPOI[7] = "colleccions";
	nomPOI[8] = "llibgen"; 
	nomPOI[9] = "centres_ensenyament";
	nomPOI[10] = "eoi"; 
	nomPOI[11] = "cme"; 
	nomPOI[12] = "bombers"; 
	nomPOI[13] = "cambrescom"; 
	nomPOI[14] = "delcidem";
	nomPOI[15] = "oficgestio";
	nomPOI[16] = "entcol"; 
	nomPOI[17] = "oficliquidadores"; 
	nomPOI[18] = "borses"; 	
	nomPOI[19] = "cambresprop"; 
	nomPOI[20] = "oficatencioac";  
	nomPOI[21] = "servorijurid"; 
	nomPOI[22] = "oficcatala"; 
	nomPOI[23] = "centresnorma";
	nomPOI[24] = "oficaca"; 
	nomPOI[25] = "itv"; 	
	nomPOI[26] = "hospitals";	
	nomPOI[27] = "caps";
	nomPOI[28] = "caps24"; 
	nomPOI[29] = "equipatencio"; 	
	nomPOI[30] = "capsd"; 
	nomPOI[31] = "centresdia"; 
	nomPOI[32] = "casalscivics";
	nomPOI[33] = "casalsgentgran"; 
	nomPOI[34] = "oficaccio"; 
	nomPOI[35] = "oficinfodones"; 
	nomPOI[36] = "residencies"; 
	nomPOI[37] = "telecentres"; 	
	nomPOI[38] = "ofictreball"; 
	nomPOI[39] = "oficturisme"; 
	nomPOI[40] = "xanascat"; 	  
	
	nameLayerWMS[0] = "6"; 
	nameLayerWMS[1] = "7";
	nameLayerWMS[2] = "8";
	nameLayerWMS[3] = "9"; 
	nameLayerWMS[4] = "10";
	nameLayerWMS[5] = "11";
	nameLayerWMS[6] = "12";
	nameLayerWMS[7] = "13";
	nameLayerWMS[8] = "14"; 
	nameLayerWMS[9] = "15";
	nameLayerWMS[10] = "16"; 
	nameLayerWMS[11] = "17"; 
	nameLayerWMS[12] = "18"; 
	nameLayerWMS[13] = "19"; 
	nameLayerWMS[14] = "20";
	nameLayerWMS[15] = "21";
	nameLayerWMS[16] = "22"; 
	nameLayerWMS[17] = "23"; 
	nameLayerWMS[18] = "24"; 	
	nameLayerWMS[19] = "25"; 
	nameLayerWMS[20] = "26";  
	nameLayerWMS[21] = "27"; 
	nameLayerWMS[22] = "28"; 
	nameLayerWMS[23] = "29";
	nameLayerWMS[24] = "30"; 
	nameLayerWMS[25] = "31"; 	
	nameLayerWMS[26] = "32";	
	nameLayerWMS[27] = "33";
	nameLayerWMS[28] = "34"; 
	nameLayerWMS[29] = "35"; 	
	nameLayerWMS[30] = "36"; 
	nameLayerWMS[31] = "37"; 
	nameLayerWMS[32] = "38";
	nameLayerWMS[33] = "39"; 
	nameLayerWMS[34] = "40"; 
	nameLayerWMS[35] = "41"; 
	nameLayerWMS[36] = "42"; 
	nameLayerWMS[37] = "43"; 	
	nameLayerWMS[38] = "44"; 
	nameLayerWMS[39] = "45"; 
	nameLayerWMS[40] = "46"; 	  

	descPOI[0] = "Ajuntaments";
	descPOI[1] = "Consells comarcals";
	descPOI[2] = "Oficines d'Atenci&oacute; Ciutadana";
	descPOI[3] = "Hotels d'entitats";	
	descPOI[4] = "Mercats";
	descPOI[5] = "Biblioteques";
	descPOI[6] = "Museus";
	descPOI[7] = "Col&middot;leccions";
	descPOI[8] = "Llibreries de la Generalitat";
	descPOI[9] = "Centres d'ensenyament";
	descPOI[10] = "Escoles Oficials d'Idiomes";	
	descPOI[11] = "Comissaries de Mossos d'Esquadra";
	descPOI[12] = "Parcs de Bombers";
	descPOI[13] = "Cambres de Comer&ccedil;, Ind&uacute;stria i Navegaci&oacute;";
	descPOI[14] = "Delegacions del CIDEM";
	descPOI[15] = "Oficines de Gesti&oacute; Empresarial";
	descPOI[16] = "Entitats Col&middot;laboradores de l'Administraci&oacute;";
	descPOI[17] = "Oficines liquidadores";
	descPOI[18] = "Borses Joves d'Habitatge";
	descPOI[19] = "Cambres de la Propietat Urbana";
	descPOI[20] = "Oficines d'Atenci&oacute; al Ciutad&agrave;";	
	descPOI[21] = "Serveis d'Orientaci&oacute; Jur&iacute;dica";
	descPOI[22] = "Oficines de Catal&agrave;";
	descPOI[23] = "Centres de Normalitzaci&oacute; Ling&uuml;&iacute;stica";
	descPOI[24] = "Oficines de l'Ag&egrave;ncia Catalana de l'Aigua";
	descPOI[25] = "Estacions d'ITV";
	descPOI[26] = "Hospitals";
	descPOI[27] = "Centres d'atenci&oacute; prim&agrave;ria";
	descPOI[28] = "Centres d'atenci&oacute; prim&agrave;ria - 24 hores";
	descPOI[29] = "Equips d'Atenci&oacute; a la Inf&agrave;ncia i Adolesc&egrave;ncia";
	descPOI[30] = "Centres d'atenci&oacute; a persones disminu&iuml;des";
	descPOI[31] = "Centres de dia per a gent gran";
	descPOI[32] = "Casals C&iacute;vics";
	descPOI[33] = "Casals de gent gran";	
	descPOI[34] = "Oficines d'Acci&oacute; Ciutadana";
	descPOI[35] = "Punts d'informaci&oacute; a les dones";
	descPOI[36] = "Resid&egrave;ncies per a gent gran";
	descPOI[37] = "Telecentres";
	descPOI[38] = "Oficines de Treball de la Generalitat";
	descPOI[39] = "Oficines de turisme";			
	descPOI[40] = "Xarxa Nacional d'Albergs Socials de Catalunya (XANASCAT)";

	acronimPOI[0] = "AJT";
	acronimPOI[1] = "CCS";
	acronimPOI[2] = "OAC";
	acronimPOI[3] = "HENT";
	acronimPOI[4] = "MRC";
	acronimPOI[5] = "BLT";
	acronimPOI[6] = "MSS";
	acronimPOI[7] = "CLC";
	acronimPOI[8] = "LLIB";
	acronimPOI[9] = "CES";
	acronimPOI[10] = "EOI";
	acronimPOI[11] = "CME";
	acronimPOI[12] = "BOM"; 
	acronimPOI[13] = "CCOM";
	acronimPOI[14] = "CIDEM";
	acronimPOI[15] = "OGES";
	acronimPOI[16] = "ECA"; 
	acronimPOI[17] = "OLIQ"; 
	acronimPOI[18] = "BJH"; 	
	acronimPOI[19] = "CPROP"; 
	acronimPOI[20] = "OAAC";  
	acronimPOI[21] = "SOJ"; 
	acronimPOI[22] = "OCAT"; 
	acronimPOI[23] = "CNL";
	acronimPOI[24] = "OACA"; 
	acronimPOI[25] = "ITV"; 	
	acronimPOI[26] = "HOSP";	
	acronimPOI[27] = "CAP";
	acronimPOI[28] = "CAP24"; 
	acronimPOI[29] = "EAIA"; 	
	acronimPOI[30] = "CAD"; 
	acronimPOI[31] = "CDIA"; 
	acronimPOI[32] = "CCIV";
	acronimPOI[33] = "CGRAN"; 
	acronimPOI[34] = "OACCIO"; 
	acronimPOI[35] = "ODONA"; 
	acronimPOI[36] = "RES"; 
	acronimPOI[37] = "TEL"; 	
	acronimPOI[38] = "OTG"; 
	acronimPOI[39] = "OTUR"; 
	acronimPOI[40] = "XANASCAT"; 	  	
	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 OpenLayers.Control.LoadingPanel({minSize: new OpenLayers.Size(600, 600)}));
    //map.addControl(new Vissir.PanZoomBar({div: OpenLayers.Util.getElement('olZoomTools')}));
    map.addControl(new Vissir.PanZoomBar({div: document.getElementById("olZoomTools")}));   
    
    /*controlArgParser = new Vissir.ArgParser();
	map.addControl(controlArgParser);*/
	    
    // 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;		
	    _loader.getZoomMunicipi(args.mun);
	}
	if (args.com) {
		VeureMapa=1;
	    _loader.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 = canviZoom_GC2OL(args.zoom);
	                    var tzoom = args.zoom;
				     }
	                else 
	                {
		                if (args.xyaddress)
			                var tzoom = 6;
		                else
			                var tzoom = 9;
		            }
	                map.setCenter(tcenter,tzoom);
	                if (args.ident) 
	                {
		                xyResultatPuntualFilAriadna = 1;
		                xyResultatPuntual = 1;
				xResultat = txyaddress_x;
				yResultat = txyaddress_y;
				xResultatFilAriadna = txyaddress_x;
				yResultatFilAriadna = txyaddress_y;
				document.getElementById("a_FilAriadna3").innerHTML = args.ident;
				nomFilAriadna3 = args.ident;
			}

		}
    }
    
    	     /**************
	     * Embedded!  *
	     **************/
		//var panZoom = new Vissir.PanZoomBar({div: $('panZoomBar'), slideFactor: 256});
	     if(args.embedded) {
	       $('dv_colEsquerra').toggle();
	       $('FW_contingut2').toggle();
	       $('idTitol').toggle();
	       $('capcalera').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();
		
	       /*$('sceneInfo').toggle();
	       $('footer').style.height="16px";
	       $('footer').style.left="0";
	       $('scaleBar').toggle();
	       $('ovHider').toggle();
	       $('overview').toggle();
	       $('position').toggle();
	       $('tiny').toggle();
	       //S'elimina estil de la barra de zoom
	       $('panZoomBar').style.backgroundImage="none";
	       $('panZoomBar').style.border="0px solid #000";
	       
	       $$('.bottomright').each(function(item){item.toggle()});*/
	       
	       //panZoom = new OpenLayers.Control.PanZoom({div: $('panZoomBar'), slideFactor: 128});
	       
	      // ajustaMapaIE();
	     }
    if (args.zoom) {             
		//var tzoom = canviZoom_GC2OL(args.zoom);
		map.zoomTo(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)
		{	
		xyResultatPuntual = 1;
		xResultat = tcenter.lon;
		yResultat = tcenter.lat;
		actRessaltar(args.ident);  
		}
	}
	if (args.adreca) {			    
		nomFilAriadna3 = args.adreca;
		if (tcenter)
		{	
		xyResultatPuntualFilAriadna = 1;
		xResultatFilAriadna = tcenter.lon;
		yResultatFilAriadna = tcenter.lat;
		fzResultat = 8;		
		}
		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);
	}

/*	cercadorM.setupEstils();
	cercadorM.capturaEvents();*/
	mapa.capturaEvents();
	mapa.setupEstils();
	zonaInfo.setupEstils();
	zonaInfo.capturaEvents();	
}
	//----------------------- 
	function canviZoom_GC2OL(tzoom) {
		switch (tzoom) {
			case 0:
				tzoom = 9; 
				break;
			case 1:
				tzoom = 9; 
				break;		
			case 2:
				tzoom = 8; 
				break;	
			case 3:
				tzoom = 7; 
				break;
			case 4:
				tzoom = 8; 
				break;		
			case 5:
				tzoom = 5; 
				break;	
			case 6:
				tzoom = 4; 
				break;
			case 7:
				tzoom = 3; 
				break;		
			case 8:
				tzoom = 2; 
				break;									
			case 9:
				tzoom = 1; 
				break;
			case 10:
				tzoom = 0; 
				break;		
			case 11:
				tzoom = 0; 
				break;	
		}
		return tzoom;
	}    
		//----------------------- 
	function canviZoom_OL2GC(tzoom) {
		switch (tzoom) {
			case 0:
				tzoom = 10; 
				break;
			case 1:
				tzoom = 9; 
				break;		
			case 2:
				tzoom = 8; 
				break;	
			case 3:
				tzoom = 7; 
				break;
			case 4:
				tzoom = 6; 
				break;		
			case 5:
				tzoom = 5; 
				break;	
			case 6:
				tzoom = 4; 
				break;
			case 7:
				tzoom = 3; 
				break;		
			case 8:
				tzoom = 2; 
				break;									
			case 9:
				tzoom = 1; 
				break;
			case 10:
				tzoom = 0; 
				break;		
			case 11:
				tzoom = 0; 
				break;	
		}
		return tzoom;
	}    
   	//-----------------------
	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);
		nameLayer.setVisibility(false);
	   	/*if (argcapes.indexOf(acronim) != -1 )
	   	{   	    
		    nameLayer.setVisibility(true); 
		    var id = "ch_" + index;			    
		    if (document.getElementById(id) != null) document.getElementById(id).checked = 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';
				$('FW_textPlanolFoto').className = '';
				$('FW_textPlanolHibrid').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_textPlanolFoto').className = 'FW_sLink';
				$('FW_textPlanolHibrid').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';
				$('FW_textPlanolFoto').className = 'FW_sLink';
				$('FW_textPlanolHibrid').className = '';					
			break;	
        }         		
	}
 
    //-----------------------
    function afegirMapaRef(){
		// mapa de referencia	(amb mapa generat dinamicament)			 
		layer_base_gc_maparef =    new OpenLayers.Layer.WMS(
			"Topografica", parametres.baseWmsServerICC_ov,
			{layers: 'gcmaparef', 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() {	  
  		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 (xyResultatPuntual!=0 && xResultat!=0 && yResultat!=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(xResultat,yResultat);
    		//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 + '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 + '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/icMapGuia_1.gif' : 'img/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 (layer_ressaltar) 
	{
		var tempVis = true;			
		if (selectCarrer != '')
		{
			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 (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 (xyResultatPuntual != 0)
	{		
		if ( $('ctl_puntsI').value != "") 
		{
				procesFitxa_cerca(locSeleccionat,true);
		}
		else
		{
		var ndiv0 = document.getElementById("dv_mapaPrint_detallPI");
		while(ndiv0.hasChildNodes()) {
			ndiv0.removeChild(ndiv0.firstChild);}
		ll = new OpenLayers.LonLat(xResultat,yResultat);
		var temp_text = text_ident;

		if (!temp_text)
                {
	                if ( $('ctl_num').value != "")
	                	temp_text = $('ctl_carrer').value + ", " + $('ctl_num').value;
	                else
	                {
		                if ( $('ctl_cruilla').value != "")
		                   	temp_text = $('ctl_carrer').value + " amb " + $('ctl_cruilla').value;
		                else
		                	{
		                	if ( $('ctl_indret').value != "")
								temp_text = $('ctl_indret').value;
							else
								temp_text = $('ctl_puntsI').value;
							}
	                } 
                }	
		if (!temp_text) return;				
            
		ll = new OpenLayers.LonLat(xResultat,yResultat);
																			
		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)});
			popupClass = OpenLayers.Class(OpenLayers.Popup.Anchored, 
	        {	        
	        'minSize': new OpenLayers.Size(120,80),
	        'autoSize': true,    
	        'maxSize': new OpenLayers.Size(300,300)
	        });	
			feature_punt.popupClass = popupClass;
            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);      
 	       
 	       //per a utilitzar la classe FramedCloud amb singleFile=false, 
 	       //ha  calgut afegir img/cloud-popup-relative.png 
 	       
 	       // per a que funcioni autosize = true, 
 	       // ha calgut fer canvis a OpenLayers/lib/OpenLayers/Util.js, funcio OpenLayers.Util.getRenderedDimensions
			FramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, 
        	{       
 		       'minSize': new OpenLayers.Size(120,85),
 		       'autoSize': true  ,
 		       'panMapIfOutOfView': false,
               'maxSize': new OpenLayers.Size(300,300)    
 	        }); 	                    
			feature_punt.popupClass = FramedCloud;
            
            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.iconToolsActiu == 6) 
            {
            // si l'eina activa es 'esborrar', mantenir el cursor especial
		    if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) 
			this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/esborrar.cur"),default';
		    else
			this.map.div.style.cursor = 'url("http://' +  document.location.host + '/website/guia/img/cursors/esborrar.ico") 12 12,default';
	    }
	    else
	    {
		    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.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);
    };
    
    
