
function inviaEmailEnter(evt){
    if (evt.type == "keyup" && evt.keyCode == 13) {
            inviaEmail();
    }
}

/**
 * questa funzione crea il corpo della email
 */
function creaBodyEmail() {
	  /*
	   var url = urlSardegnaMappe + "mappa.html?";
	
	   var body = '';
	   if (addr!=null && addr.geocodedAddr!=null && addr.geocodedAddr!='') {  
	   	    url += 'r=1';   	   	
		   	body +=  'Indirizzo:\r ' + addr.geocodedAddr.officialname + '\r';
		   	if (addr.geocodedAddr.postalcode!=null) {
		   		body += addr.geocodedAddr.postalcode;	   		
		   	}
		   	if (addr.geocodedAddr.municipality!=null) {
		   		body += ' ' + addr.geocodedAddr.municipality; 
		   	}
		   	if (addr.geocodedAddr.countrysecondarysubdivision!=null) {
		   		body += ' ' +  addr.geocodedAddr.countrysecondarysubdivision; 
		   	}	
	     	if (document.getElementById('addrSel').value!='') {
				url += '&textSel=' +  encodeURI(decodeParameters(document.getElementById('addrSel').value));
			}
			if (document.getElementById('addrInput').value!='') {
				url += '&text=' +  encodeURI(document.getElementById('addrInput').value);
			}	
			body +=	'\r\r';   
	   }
	   if (objects!=null && objects.size()>0)	{
	    	 var ris = objects.get('risultati')[0]; 
			 if (ris!=null ) {	 	    		
			 	if (ris['type']!=null && ris['type']!='' && ris['input']!=null && ris['input']!='') {
			  		if (ris['type']=='POI') {
			  			body += 'Punti d\'interesse:\r\r'; 
			  		} else if (ris['type']=='TOP') {
			  			body += 'Località:\r\r'; 
			  		}			  				    						  	
			  	}    						  
			  	if (ris['start']!=null && ris['start']!='' && ris['end']!=null && ris['end']!='' && ris['numrisultati']!=null && ris['numrisultati']!='') {
			  			body += 'Risultati ' + ris['start'] +  '-' + ris['end'] + ' di '+ ris['numrisultati'] + ' trovati\r\r'; 		    						  	
			  	}    						  	
			 }      		    
		     for (i=1;i<objects.size();i++) {		       
		      	  var object= objects.get(i+'')[0]; 
				  if (object!=null ) {	
			         if (i==1) {
   			          	body +=  'A. ';
   			          }
   			          if (i==2) {
   			          	body +=  'B. ';
   			          }
   			          if (i==3) {
   			          	body +=  'C. ';
   			          }
   			          if (i==4) {
   			          	body +=  'D. ';
   			          }
   			          if (i==5) {
   			          	body +=  'E. ';
   			          }
   			          if (i==6) {
   			          	body +=  'F. ';
   			          }
   			          if (i==7) {
   			          	body +=  'G. ';
   			          }
   			          if (i==8) {
   			          	body += 'H. ';
   			          }
   			          if (i==9) {
   			          	body +=  'I. ';
   			          }
   			          if (i==10) {
   			          	body +=  'L. ';
   			          }
				      if (object['name']!=null && object['name']!='') {				      		
				      			body +=  object['name'] + '\r';	   		
				      } 
				      if (object['address']!=null && object['address']!='') {				      		
				      			body += object['address'];	   			      		
				      } 
				      if (object['country']!=null && object['country']!='') {				      		
			      		    if (object['address']!=null && object['address']!='') {
			      		     	body += ', ' + object['country'];	
			      		    } else {
			      		    	body += object['country'];	
			      		    } 					      		
				      }
				      body += '\r\r';      		 						       	    							         							      
				  }     							                    			      
		      }
		      if (ris!=null ) {	 	    						  
			  	if (ris['type']!=null && ris['type']!='' && ris['input']!=null && ris['input']!='') {
			  		if (ris['type']=='POI') {
			  			url += 'r=3&text=' +  encodeURI(ris['input']); 
			  		} else {
			  			url += 'r=2&text=' +  encodeURI(ris['input']); 
			  		}	
			  		if (ris['numPagina']!=null && ris['numPagina']!='' && ris['numPagina']!=null && ris['numPagina']!='') {
				  		url += '&page=' +  ris['numPagina']; 				  					  				  				    						  	
			  		}    					  				  				    						  	
			  	}    						  	
			 }		      
	   }
	   
	   if (dirs!=null) {  
	   	     
   	     	var geocodes = dirs.getGeocodes();
			var routeinstructions = dirs.getRouteInstructions();
			var indexInstruction = 0;
			var text = "";
			
			if (geocodes!=null && geocodes.length>0 && routeinstructions!=null && routeinstructions.getInstructions()!=null && routeinstructions.getInstructions().length>0) {
				body += 'Indicazioni Stradali:\r\r';
				
				var start = "";
				if (geocodes[0].getTypePrefix() != null)
				{
					start += geocodes[0].getTypePrefix() + " ";
				}
				if (geocodes[0].getOfficialName() != null)
				{
					start += geocodes[0].getOfficialName() + " ";
				}
				if (geocodes[0].getBuildingNumber() != null)
				{
					start += geocodes[0].getBuildingNumber() + " ";
				}
				if (geocodes[0].getMunicipality() != null)
				{
					start = start + "(" + geocodes[0].getMunicipality() + ") ";
				}
				
				body += 'Itinerario da ' + start + ' a ';
				var end  = "";
				if (geocodes[dirs.getNumGeocodes()-1].getTypePrefix() != null)
				{
					end += geocodes[dirs.getNumGeocodes()-1].getTypePrefix() + " ";
				}
				if (geocodes[dirs.getNumGeocodes()-1].getOfficialName() != null)
				{
					end += geocodes[dirs.getNumGeocodes()-1].getOfficialName() + " ";
				}
				if (geocodes[dirs.getNumGeocodes()-1].getBuildingNumber() != null)
				{
					end += geocodes[dirs.getNumGeocodes()-1].getBuildingNumber() + " ";
				}
				if (geocodes[dirs.getNumGeocodes()-1].getMunicipality() != null)
				{
					end = end + "(" + geocodes[dirs.getNumGeocodes()-1].getMunicipality() + ") ";
				}
				body += end;
				
				addrGeocode = "";
				for (var i = 1; i<dirs.getNumGeocodes()-1; i++)
				{
					if (geocodes[i].getTypePrefix() != null)
					{
						addrGeocode += geocodes[i].getTypePrefix() + " ";
					}
					if (geocodes[i].getOfficialName() != null)
					{
						addrGeocode += geocodes[i].getOfficialName() + " ";
					}
					if (geocodes[i].getBuildingNumber() != null)
					{
						addrGeocode += geocodes[i].getBuildingNumber() + " ";
					}
					if (i<dirs.getNumGeocodes()-2)
					{
						addrGeocode += "- ";
					}
				}
				if (addrGeocode!='') {
					body += '\rTappe: ' + addrGeocode;
				}
			    
			    var routePreference = dirs.getRoutePreference();
			    if (routePreference == "Shortest")
			    {
					routePreference = "in auto itinerario piu' corto";
			    }
			    else if (routePreference == "Fastest")
			    {
					routePreference = "in auto itinerario piu' veloce";
			    }
			    else
			    {
					routePreference = "a piedi";
			    }
                body += '\r' + calculateDistance(dirs) + " - circa " + calculateTime(dirs) + " - " + routePreference + '\r\r';
			
			    /*						
			   	var instructions = routeinstructions.getInstructions();
				for (i=0;i<geocodes.length;i++) {
					var geocode = geocodes[i];
					var municipality = geocode.getOfficialName();
					var countrySecondarySusbdivision = geocode.getCountrySecondarySusbdivision();
				    if (municipality!=null) {
				      
				       body += '\r\r';
				       
				       if (i==0) {
				       		body += 'Da ';
				       } else  if (i==(geocodes.length-1)) {
				       		body += 'A ';
				       } else if (i==1) { 
				       		body += 'Tappa ';
				       } else if (i==2) { 
				       		body += 'Tappa ';
				       }		 
				       body +=  municipality; 
				       if (countrySecondarySusbdivision!=null) {
				           body += '(' + countrySecondarySusbdivision + ')';
				       }					   		      
				       body += '\r';
				       
				       if (i<instructions.length) {
				       	 var routeinstruction = instructions[i];
				       	 if (routeinstruction!=null) {
				       	     for (j=0;j<routeinstruction.length;j++) {
								var rinstruction = routeinstruction[j];
								indexInstruction++;
								var instruction = rinstruction.getInstruction();
							    body += '\r';
							    instruction = eliminaSpan(instruction);			    
							    body +=  indexInstruction + '. '+ instruction + ' - ';  
								var distance = 	rinstruction.getDistance();
								if (distance!=null) {
									var valore = distance.getValue();
									var uom = distance.getUom();				
									if (valore!=null && uom !=null) {
										if (valore < 1 && uom.toLowerCase() == "km")
										{
											body += valore * 1000 + "m";
										} else {
											body += valore+uom.toLowerCase();
										}
									}
								}																					
							 }	
				       	 }						       
				       }
				       										    
				    } 
				}
				* * /
				url += 'r=4';
				
				
				if (document.getElementById('startSel').value!='') {
					url += '&startSel=' +  encodeURI(decodeParameters(document.getElementById('startSel').value));
				}
				url += '&start=' +  encodeURI(document.getElementById('partenza').value);
			
				
				if (document.getElementById('endSel').value!='') {
					url += '&endSel=' +   encodeURI(decodeParameters(document.getElementById('endSel').value));
				}
			    url += '&end=' +   encodeURI(document.getElementById('arrivo').value);
				
				if (document.getElementById('viaPoint1Sel').value!='') {
					url += '&viaPoint1=' +  encodeURI(decodeParameters(document.getElementById('viaPoint1Sel').value));
				}
				else if (document.getElementById('viaPoint1').value!='') {
					url += '&viaPoint1=' +  encodeURI(document.getElementById('viaPoint1').value);
				}
				if (document.getElementById('viaPoint2Sel').value!='') {
					url += '&viaPoint2=' +  encodeURI(decodeParameters(document.getElementById('viaPoint2Sel').value));
				}
				else if (document.getElementById('viaPoint2').value!='') {
					url += '&viaPoint2=' +  encodeURI(document.getElementById('viaPoint2').value);
				}			
				
				url += '&routePreference=' + dirs.getRoutePreference();		
		   }				
	   }
	   */
	   //if (body=='') {
	   	
	   	var url = creaLink();
	   	
	   	 //  var bounds = map.getExtent();
	   	 //  body = 'Ciao, vorrei condividere un link di Sardegna Mappe con te.\r\rLink:\r'+ url + '&minx=' + bounds.left + '&miny=' + bounds.bottom + '&maxx=' + bounds.right + '&maxy=' + bounds.top;     	  
	   	   body = 'Ciao, vorrei condividere un link di Sardegna Mappe con te.\r\rLink:\r'+ url;     	  
	   /*} else {   
	   	   body = body + 'Link:\r'+ url; 	  
	   }*/
	   body = body + '\r\r' + 'Questa email ti e\' stata inviata da un utente in Sardegna Mappe (sardegnamappe.it)'; 
	   return body;
	    
}


/**
 * funzione per invio email
 * apre client posta installato su pc
 */
function inviaEmail() {
      
       showHideDiv('containerEmail',false); 
       var email = document.getElementById('email').value;
       var from = document.getElementById('from').value;
       var messaggio = document.getElementById('messaggio').value;
       var nome = document.getElementById('nome').value;
       var cognome = document.getElementById('cognome').value;
	 
	   if (email=="") {
	   	 alert("Inserire un indirizzo email valido per il destinatario.");
	   	 return;
	   }
	   
	   if (from=="") {
	   	 alert("Inserire un indirizzo email valido per il mittente.");
	   	 return;
	   }
	
	  var persona = '';
	  
	  if (nome!='') {
	  	persona = nome + ' ';
	  } 
	  if (cognome!='') {
	  	persona = persona + cognome + ' ';
	  } 
	  
	  if (persona =='') {
	  	persona = from + ' ';
	  }
	   
	   var href = "mailto:" + email + "?subject=" + persona + "ti ha inviato questo messaggio con Sardegna Mappe (sardegnamappe.it)&body=";
	  
	  messaggio = replaceAll(messaggio,document.getElementById('caratterea').value,"a'");
      messaggio = replaceAll(messaggio,document.getElementById('caratteree').value,"e'");
      messaggio = replaceAll(messaggio,document.getElementById('caratterei').value,"i'");
      messaggio = replaceAll(messaggio,document.getElementById('carattereo').value,"o'");
      messaggio = replaceAll(messaggio,document.getElementById('carattereu').value,"u'");
	   messaggio = encodeURI(messaggio);
	   messaggio = replaceAll(messaggio,"&","%26");
	   messaggio = replaceAll(messaggio,"?","%3F");
	 	     
	   location.href = href + messaggio;	 
	   // sendMail(email,'Sardegna Mappe',body); 
}

/**
 * metodo loadComuni carica i nomi dei comuni per l'url di comunas
 * che serve inserire nel baloon dei poi e dei toponimi
 */

function sendMail(mailTo,mailSubject,mailBody) {
   var url = urlSendEmail;	
   /*
   if (Roja.Proxy && urlSendEmail.startsWith("http")) {
		url = Roja.Proxy + Roja.Util.escapeUri(urlSendEmail);
	}*/
	var par =  '&mailProtocol=' + mailProtocol + '&mailHost=' + mailHost + '&mailFrom=' + mailFrom+
	 '&mailTo=' + mailTo +  '&mailSubject=' + mailSubject + '&mailBody=' + mailBody;
	
	new OpenLayers.Ajax.Request(url + par,
	                         {   method: 'post',
	                             parameters: null,
	                             onComplete: successSendMail,
	                             onFailure: failureSendMail
	                          }
	 );  
}

/**
 * metodo successSendMail che invia l'email
 */
function successSendMail(request)
{   	    
	    if (request.responseXML == null){
	        return;
	    }
	    var xmlResponse = request.responseXML;
	    if (!xmlResponse || request.fileType!="XML") { //for IE compatibility
	        xmlResponse = OpenLayers.parseXMLString(request.responseText);       
	    }	
	    showHideDiv('esito',true);
	    var errore = xmlResponse.getElementsByTagName('Errore')[0];
	    if (errore==null) {
	    	document.getElementById('esito').innerHTML = '<font style="color:red;">L\'email è stata inviata correttamente</font>'; 
	    } else {
	    	document.getElementById('esito').innerHTML = '<font style="color:red;">Si è verificato un problema nell\'invio email.</font>'; 
	    }	 
	     showHideDiv('containerEmail',false); 
}

/**
 * failureSendMail in caso di fallimento nell'invio email
 */
function failureSendMail(request)
{   	    
	   alert('Impossibile inviare l\'email');
}

/**
 * calcola il tempo per percorrere il percorso 
 */
function calculateTime(dirs)
{
	var totalTime = (dirs.getTotalTime().getHours() * 3600)*1 + (dirs.getTotalTime().getMinutes() * 60)*1 + (dirs.getTotalTime().getSeconds())*1;
	var timeString;
	if (totalTime < 60)
	{
		timeString = totalTime + " secondi";
	}
	else if (totalTime < 3600)
	{
		timeString = Math.round(totalTime/60) + " minuti";
	}
	else
	{
		timeString = Math.floor(totalTime/3600) + " ore" + " e " + Math.floor((totalTime*1 - Math.floor(totalTime/3600) * 3600)/60) + " minuti" ;
	}
	return timeString;
}
/**
 * calcola la distanza del percorso
 */
function calculateDistance(dirs)
{
	var distanceString;
	if (dirs.getTotalDistance().getValue() < 1 && dirs.getTotalDistance().getUom() == "KM")
	{
		distanceString = dirs.getTotalDistance().getValue() * 1000 + "m";
	}
	else
	{
		distanceString = Math.floor(dirs.getTotalDistance().getValue()) + dirs.getTotalDistance().getUom().toLowerCase();
	}
	return distanceString;
}
/**
 * elimina i tag span dalle istruzioni del percorso
 */
function eliminaSpan(text) {		
	var inizio = text.indexOf('<');
	while (inizio!=-1) {
		fine = text.indexOf('>');
		if (fine!=-1) {
			text = text.substring(0,inizio) + text.substring(fine+1);
		}
		inizio = text.indexOf('<');
	}	
	return text;
}

/**
 * funzione che:
 *  - 	seleziona il base layer sfondo di partenza. Accetta i valori:
 * 		Stradale, Aerea, Ibrida (in tutti gli altri casi, restituisce la Stradale) 
 *  - 	effettua lo switch al layer "Aerea" 
 * 		se conferma la presenza di un layer wms in url
 * 
 */
function checkBaseLayerByURL(map) {	
    var wmsUrl 		= null;
    var url 		= location.search;
    url 			= decodeURI(url);
	url 			= decodeParameters(url);
	var baseLayer 	= null;
	var mapname		= null;
	var backgroundColor = null;
	var okWMS		= null;
	var okMapName	= null;
	
	var pos = url.indexOf('wmsUrl=');
	if(pos != -1) {
	    wmsUrl = url.substring(pos + 'wmsUrl='.length);
	    pos = wmsUrl.indexOf('&');
	    if (pos!=-1) {
			wmsUrl = wmsUrl.substring(0,pos);
			okWMS = 1;
		}
	}
	
	//questa verifica permette di capire se attivare o meno "tematismi"
	var pos = url.indexOf('mapname=');
	if(pos != -1) {
		
		/*mapName = url.substring(pos + 'mapName='.length);
	    pos = mapName.indexOf('&');
	    alert('mapname'+mapName);
	    if (pos!=-1) {
			mapName = mapName.substring(0,pos);
			alert('mapname'+mapName);
			if (mapName != null && mapName != 'SardegnaMappe'){
			document.getElementById('tematismi_titolo').innerHTML= mapName;
			}
		}*/
	okMapName = 1;
	mapname = getConfMapName();
	if (mapname != null && mapname != 'SardegnaMappe'){
		document.getElementById('tematismi_titolo').innerHTML = mapname;
		}
	}
	
	var pos = url.indexOf('baselayer=');
	if(pos != -1) {
	    baseLayer = url.substring(pos + 'baselayer='.length);
	    pos = baseLayer.indexOf('&');
	    if (pos!=-1) {
			baseLayer = baseLayer.substring(0,pos);
		}
	}
	var pos = url.indexOf('backgroundColor=');
	if(pos != -1) {
	    backgroundColor = url.substring(pos + 'backgroundColor='.length);
	    pos = backgroundColor.indexOf('&');
	    if (pos!=-1) {
			backgroundColor = backgroundColor.substring(0,pos);
		}
	}
	/*
	if(baseLayer != null) {
	    var layer = map.getLayersBy('name',baseLayer)[0];
	    if(layer != null) {
	        layer.setVisibility(true);
	        map.setBaseLayer(layer);
	        if(layer.backgroundColor) {
	         //map.viewPortDiv.style.backgroundColor = layer.backgroundColor;
	         layer.map.div.style.backgroundColor = layer.backgroundColor;
	        }
	    }
	} */
	
  SwitchLayer(baseLayer,backgroundColor);

/*	switch(baseLayer) {
        
	        case 'Stradale':
	            SwitchLayer('Stradale');
	            //toggleSideBarOutput('tematismi');
	            break;
	        
	        case 'Aerea':
	            SwitchLayer('Aerea');
	            //toggleSideBarOutput('tematismi');
	            break;
	        
	        case 'Ibrida':
	            SwitchLayer('Ibrida');
	           // toggleSideBarOutput('tematismi');
	            break;	
	            	
	        default:
	            SwitchLayer(baseLayer,backgroundColor);
	           // toggleSideBarOutput('tematismi');
	            break;		
		}
*/
	
	//se abbiamo un WMS URL, cambio la label su tematismi
	if (okWMS == 1 || okMapName == 1){
		toggleSideBarOutput('tematismi');
	}
}





function addWMSbyURL(map) {
    
    var wmsLogicalName = null;
    var wmsUrl = null;
    var wmsPhysicalName = null;
    var wmsFormat = null;
    var wmsBBox = null;     
    
    
    var url = location.search;
    url = decodeURI(url);
	url = decodeParameters(url);
	
	
	var pos = url.indexOf('wmsLogicalName=');
	if(pos != -1) {
	    wmsLogicalName = url.substring(pos + 'wmsLogicalName='.length);
	    pos = wmsLogicalName.indexOf('&');
	    if (pos!=-1) {
			wmsLogicalName = wmsLogicalName.substring(0,pos);
		}
	}
	
	
	var pos = url.indexOf('wmsUrl=');
	if(pos != -1) {
	    wmsUrl = url.substring(pos + 'wmsUrl='.length);
	    pos = wmsUrl.indexOf('&');
	    if (pos!=-1) {
			wmsUrl = wmsUrl.substring(0,pos);
		}
	}
	
	var pos = url.indexOf('wmsPhysicalName=');
	if(pos != -1) {
	    wmsPhysicalName = url.substring(pos + 'wmsPhysicalName='.length);
	    pos = wmsPhysicalName.indexOf('&');
	    if (pos!=-1) {
			wmsPhysicalName = wmsPhysicalName.substring(0,pos);
		}
	}
	
	var pos = url.indexOf('wmsFormat=');
	if(pos != -1) {
	    wmsFormat = url.substring(pos + 'wmsFormat='.length);
	    pos = wmsFormat.indexOf('&');
	    if (pos!=-1) {
			wmsFormat = wmsFormat.substring(0,pos);
		}
	}
	
	
	
	if(wmsPhysicalName != null) {
       var layer = new OpenLayers.Layer.WMS(wmsLogicalName,wmsUrl,
                {layers: wmsPhysicalName, format: wmsFormat,transparent: 'true'},{isBaseLayer:false}  );
       layer.setVisibility(true);
       map.addLayer(layer);
       /*if(wmsBBox != null) {
           var bounds = new OpenLayers.Bounds(wmsBBox);
           map.zoomToExtent(bounds);
           return 
       }*/
       
	}
	
	return null
}


/**
 * funzione che restituisce il nome della mappa di configurazione da caricare
 */
function getConfMapName() {
    var url = location.search;
    url = decodeURI(url);
	url = decodeParameters(url);
	
	var mapName = null;
	var pos = url.indexOf('mapname=');
	if(pos != -1) {
	    mapName = url.substring(pos + 8);
	    pos = mapName.indexOf('&');
	    if (pos!=-1) {
			mapName = mapName.substring(0,pos);
		}
	}
	return mapName;   
}

/**
 * questa funzione controlla se ci sono 
 * parametri nell'url di sardegnamappe
 * se ci sono allora effettua la ricerca in base ai parametri
 * passati all'url
 */
function checkUrl(url) {

	var r = '';
	var text = '';
	var textSel = '';
	var page = '';
	var start = '';
	var end = '';
	var startSel = '';
	var endSel = '';
	var viaPoint1 = '';
	var viaPoint2 = '';
	var type = '';
	var minx = '';
	var miny = '';
	var maxx = '';
	var maxy = '';
	var small = '';
	var lat = '';
	var lon = '';
	var baselayer = '';
	var overlay = '';
	url = decodeURI(url);
	url = decodeParameters(url);
	//parametro r 
	//r=1 ricerca indirizzo
	//r=2 ricerca toponimi
	//r=3 ricerca poi
	//r=4 ricerca percorsi
	var pos = url.indexOf('r=');
	if (pos!=-1) {
		r = url.substring(pos+2);
		pos = r.indexOf('&');
		if (pos!=-1) {
			r = r.substring(0,pos);
		}	 
	}
	//testo da cercare nel caso di ricerca indirizzo
	//di ricerca toponimi e di ricerca poi
	pos = url.indexOf('text=');	
	if (pos!=-1) {
		text = url.substring(pos+5);
		pos = text.indexOf('&');
		if (pos!=-1) {
			text = text.substring(0,pos);
		}	 
	}
	//testo in formato xml da cercare nel caso di ricerca indirizzo
	pos = url.indexOf('textSel=');	
	if (pos!=-1) {
		textSel = url.substring(pos+8);
		pos = textSel.indexOf('&');
		if (pos!=-1) {
			textSel = textSel.substring(0,pos);
		}	 
	}
	//numero di pagina che si vuole visualizzare nella ricerca del poi
	//e del toponimo
	pos = url.indexOf('page=');	
	if (pos!=-1) {
		page = url.substring(pos+5);
		pos = page.indexOf('&');
		if (pos!=-1) {
			page = page.substring(0,pos);
		}	 
	}
	//start: indirizzo di partenza per la ricerca percorso
	pos = url.indexOf('start=');	
	if (pos!=-1) {
		start = url.substring(pos+6);
		pos = start.indexOf('&');
		if (pos!=-1) {
			start = start.substring(0,pos);
		}	 
	}
	//end: indirizzo di destinazione per la ricerca percorso
	pos = url.indexOf('end=');	
	if (pos!=-1) {
		end = url.substring(pos+4);
		pos = end.indexOf('&');
		if (pos!=-1) {
			end = end.substring(0,pos);
		}	 
	}
	//start in formato xml per i percorsi
	pos = url.indexOf('startSel=');	
	if (pos!=-1) {
		startSel = url.substring(pos+9);
		pos = startSel.indexOf('&');
		if (pos!=-1) {
			startSel = startSel.substring(0,pos);
		}	 
	}
	//end in formato xml per i percorsi
	pos = url.indexOf('endSel=');	
	if (pos!=-1) {
		endSel = url.substring(pos+7);
		pos = endSel.indexOf('&');
		if (pos!=-1) {
			endSel = endSel.substring(0,pos);
		}	 
	}
	//tappa intermedia per ricerca percorsi 
	pos = url.indexOf('viaPoint1=');	
	if (pos!=-1) {
		viaPoint1 = url.substring(pos+10);
		pos = viaPoint1.indexOf('&');
		if (pos!=-1) {
			viaPoint1 = viaPoint1.substring(0,pos);
		}	 
	}
	//tappa intermedia per ricerca percorsi 
	pos = url.indexOf('viaPoint2=');
	if (pos!=-1) {
		viaPoint2 = url.substring(pos+10);
		pos = viaPoint2.indexOf('&');
		if (pos!=-1) {
			viaPoint2 = viaPoint2.substring(0,pos);
		}	 
	}
	//tipo di percorso (a piedi, in auto ecc..)
	pos = url.indexOf('routePreference=');
	if (pos!=-1) {
		type = url.substring(pos+16);
		pos = type.indexOf('&');
		if (pos!=-1) {
			type = type.substring(0,pos);
		}	 
	}
	
	
	//minx per zoom
	pos = url.indexOf('minx=');	
	if (pos!=-1) {
		minx = url.substring(pos+5);
		pos = minx.indexOf('&');
		if (pos!=-1) {
			minx = minx.substring(0,pos);
		}	 
	}
	//miny per zoom
	pos = url.indexOf('miny=');	
	if (pos!=-1) {
		miny = url.substring(pos+5);
		pos = miny.indexOf('&');
		if (pos!=-1) {
			miny = miny.substring(0,pos);
		}	 
	}
	//maxx per zoom
	pos = url.indexOf('maxx=');
	if (pos!=-1) {
		maxx = url.substring(pos+5);
		pos = maxx.indexOf('&');
		if (pos!=-1) {
			maxx = maxx.substring(0,pos);
		}	 
	}
	//maxy per zoom
	pos = url.indexOf('maxy=');	
	if (pos!=-1) {
		maxy = url.substring(pos+5);
		pos = maxy.indexOf('&');
		if (pos!=-1) {
			maxy = maxy.substring(0,pos);
		}	 
	}
	

	//overlay
	pos = url.indexOf('baselayer=');	
	if (pos!=-1) {
		baselayer = url.substring(pos+10);
		pos = baselayer.indexOf('&');
		if (pos!=-1) {
			baselayer = baselayer.substring(0,pos);
		}	 
	}

	//overlay
	pos = url.indexOf('overlay=');	
	if (pos!=-1) {
		overlay = url.substring(pos+8);
		pos = overlay.indexOf('&');
		if (pos!=-1) {
			overlay = overlay.substring(0,pos);
		}	 
	}

	//maxy per zoom
	pos = url.indexOf('small=');	
	if (pos!=-1) {
		small = url.substring(pos+6);
		pos = small.indexOf('&');
		if (pos!=-1) {
			small = small.substring(0,pos);
		}	 
	}
	
	//lat per coordinata punto
	pos = url.indexOf('lat=');	
	if (pos!=-1) {
		lat = url.substring(pos+4);
		pos = lat.indexOf('&');
		if (pos!=-1) {
			lat = lat.substring(0,pos);
		}	 
	}
	
	//lon per coordinata punto
	pos = url.indexOf('lon=');	
	if (pos!=-1) {
		lon = url.substring(pos+4);
		pos = lon.indexOf('&');
		if (pos!=-1) {
			lon = lon.substring(0,pos);
		}	 
	}
	
	if (r==1) {
		if (text!='') {
			 reset_init('address');
			  document.getElementById('searchInput').value = text;	
			  if (textSel!='') {
			    document.getElementById('addrSel').value = textSel;			  
			  }			 
			  document.getElementById('optionsSearch').value = 1;
			  if (small!='' && small==1) {
					 showHideDiv('header',false); 
					 showHideDiv('cerca',false); 
					 showHideDiv('lineaHr',false); 
					 showHideDiv('lower-footer',false); 
					 //showHideDiv('risultatiricerca',false);		 
					 toggleSideBar('close');  
					 document.getElementById('map').style.top = '0px';
					 document.getElementById('map').style.left = '0px';
					 showHideDiv('button',false); 
					 showHideDiv('output',false); 	
					 showHideDiv('indicazioni',false); 
				}
			  addr.load(text);	
			  nero();			  
		}
		
	}
	
	if (r==2) {
		if (text!='') {
			reset_init('address');
			document.getElementById('searchInput').value = text;			
			document.getElementById('optionsSearch').value = 2;
			if (small!='' && small==1) {
				 showHideDiv('header',false); 
				 showHideDiv('cerca',false); 
				 showHideDiv('lineaHr',false); 
				 showHideDiv('lower-footer',false); 
				 //showHideDiv('risultatiricerca',false);		 
				 toggleSideBar('close');  
				 document.getElementById('map').style.top = '0px';
				 document.getElementById('map').style.left = '0px';
				 showHideDiv('button',false); 
				 showHideDiv('output',false); 	
				 showHideDiv('indicazioni',false); 	
			}
			if (page!='') {
				 gazetteerSearch((new Number(page)).valueOf());		  
			} else {
				gazetteerSearch(1);	
			}	
			nero();		  			  
		}		
	}
	
	if (r==3) {
		if (text!='') {
			reset_init('address');
			document.getElementById('searchInput').value = text;				
			document.getElementById('optionsSearch').value = 3;
			if (small!='' && small==1) {
				  showHideDiv('header',false); 
				 showHideDiv('cerca',false); 
				 showHideDiv('lineaHr',false); 
				 showHideDiv('lower-footer',false); 
				 //showHideDiv('risultatiricerca',false);		 
				 toggleSideBar('close');  
				 document.getElementById('map').style.top = '0px';
				 document.getElementById('map').style.left = '0px';
				 showHideDiv('button',false); 
				 showHideDiv('output',false); 	
				 showHideDiv('indicazioni',false); 		 
			}
			if (page!='') {
				 poiSearch((new Number(page)).valueOf());		  
			} else {
				poiSearch(1);	
			}	
			nero();			  
		}
		
	}
	
	if (r==4) {
		if (start!='' && end!='') {
			reset_init('route');
			document.getElementById('start').value = start;	
			document.getElementById('end').value = end;	
			document.getElementById('startSel').value = startSel;	
			document.getElementById('endSel').value = endSel;	
			document.getElementById('viaPoint1').value = viaPoint1;	
			document.getElementById('viaPoint2').value = viaPoint2;		
			if (type!='') {
   			    if (type == 'Fastest')
				{
					document.getElementById('type').options.selectedIndex = 0;
				}
				if (type == 'Shortest')
				{
					document.getElementById('type').options.selectedIndex = 1;
				}
				if (type == 'Pedestrian')
				{
					document.getElementById('type').options.selectedIndex = 2;
				}
   			  				
			}
			if (small!='' && small==1) {
				 showHideDiv('header',false); 
				 showHideDiv('cerca',false); 
				 showHideDiv('lineaHr',false); 
				 showHideDiv('lower-footer',false); 
				 //showHideDiv('risultatiricerca',false);		 
				 toggleSideBar('close');  
				 document.getElementById('map').style.top = '0px';
				 document.getElementById('map').style.left = '0px';
				 showHideDiv('button',false); 
				 showHideDiv('output',false); 	
				 showHideDiv('indicazioni',false); 
			}		
			routeXSL();
			nero();		
		}		
	}
	
	if (minx!='' && miny!='' && maxx!='' && maxy!='') {
		var bounds = new OpenLayers.Bounds((new Number(minx)).valueOf(),(new Number(miny)).valueOf(),(new Number(maxx)).valueOf(),(new Number(maxy)).valueOf());
	    map.zoomToExtent(bounds);   	
	}

	if (lat!='' && lon!='') {
		lonlat = new OpenLayers.LonLat(lon,lat);
		coordinateButton.addMarker(lonlat);
	}
	

     /* gestione sfondo */
   	  if (baselayer!='') {   
	      
	      for (i=0;i<map.layers.length;i++) {
	  			if(this.map.layers[i].visibility 
	   				&& this.map.layers[i].CLASS_NAME == "OpenLayers.Layer.TMS") {
	   				map.layers[i].setVisibility(false);		   				}
   	   	   }
	
	      var elem=baselayer.split(",")
	      for (i=0;i<elem.length;i++) {
	      	map.layers[elem[i]].setVisibility(true);
	      	if (map.layers[elem[i]].isBaseLayer == true)
				map.setBaseLayer(map.layers[elem[i]]);
	   	    }
	   	   	
		}


	
	if (small!='' && small==1) {
		 showHideDiv('header',false); 
		 showHideDiv('cerca',false); 
		 showHideDiv('lineaHr',false); 
		 showHideDiv('lower-footer',false); 
		 //showHideDiv('risultatiricerca',false);		 
		 toggleSideBar('close');  
		 document.getElementById('map').style.top = '0px';
		 document.getElementById('map').style.left = '0px';
		 showHideDiv('button',false); 
		 showHideDiv('output',false); 	
		 showHideDiv('indicazioni',false); 
		 map.removeControl(overview);
					 
	}		
	
}	

/**
 * questa funzione crea il link per la mappa
 * e crea anche un html da inserire nel proprio sito web 
 */
function creaLink(lonlat) {
	
	   var url = urlSardegnaMappe + "mappa.html?";
	  
	    var bounds = map.getExtent();
	    
	    
	    var baseLayer = map.baseLayer;
	    	    
	  
	   if (addr!=null && addr.geocodedAddr!=null && addr.geocodedAddr!='') {  
	   	    url += 'r=1';   	   	
		   	if (document.getElementById('addrSel').value!='') {
				url += '&textSel=' +  encodeURI(decodeParameters(document.getElementById('addrSel').value));
			}
			if (document.getElementById('addrInput').value!='') {
				url += '&text=' + encodeURI(document.getElementById('addrInput').value);
			}			  
	   } else if (objects!=null && objects.size()>0)	{
	    	 var ris = objects.get('risultati')[0]; 			
		      if (ris!=null ) {	 	    						  
			  	if (ris['type']!=null && ris['type']!='' && ris['input']!=null && ris['input']!='') {
			  		if (ris['type']=='POI') {
			  			url += 'r=3&text=' +  encodeURI(ris['input']); 
			  		} else {
			  			url += 'r=2&text=' +  encodeURI(ris['input']); 
			  		}	
			  		if (ris['numPagina']!=null && ris['numPagina']!='' && ris['numPagina']!=null && ris['numPagina']!='') {
				  		url += '&page=' +  ris['numPagina']; 				  					  				  				    						  	
			  		}    					  				  				    						  	
			  	}    						  	
			 }		      
	   } else if (dirs!=null) {  
	   	     
   	     	var geocodes = dirs.getGeocodes();
			var routeinstructions = dirs.getRouteInstructions();
			var indexInstruction = 0;
			var text = "";
			
			if (geocodes!=null && geocodes.length>0 && routeinstructions!=null &&
			 routeinstructions.getInstructions()!=null && routeinstructions.getInstructions().length>0) {
			
				url += 'r=4';				
				
				if (document.getElementById('startSel').value!='') {
					url += '&startSel=' +  encodeURI(decodeParameters(document.getElementById('startSel').value));
				}
				url += '&start=' +  encodeURI(document.getElementById('partenza').value);
			
				
				if (document.getElementById('endSel').value!='') {
					url += '&endSel=' +   encodeURI(decodeParameters(document.getElementById('endSel').value));
				}
			    url += '&end=' +   encodeURI(document.getElementById('arrivo').value);
				
				if (document.getElementById('viaPoint1Sel').value!='') {
					url += '&viaPoint1=' +  encodeURI(decodeParameters(document.getElementById('viaPoint1Sel').value));
				}
				else if (document.getElementById('viaPoint1').value!='') {
					url += '&viaPoint1=' +  encodeURI(document.getElementById('viaPoint1').value);
				}
				if (document.getElementById('viaPoint2Sel').value!='') {
					url += '&viaPoint2=' +  encodeURI(decodeParameters(document.getElementById('viaPoint2Sel').value));
				}
				else if (document.getElementById('viaPoint2').value!='') {
					url += '&viaPoint2=' +  encodeURI(document.getElementById('viaPoint2').value);
				}			
				
				url += '&routePreference=' + dirs.getRoutePreference();		
		   } else {
		   	   url += 'minx=' + bounds.left + '&miny=' + bounds.bottom + '&maxx=' + bounds.right + '&maxy=' + bounds.top;
		   }				
	   } else {
	   	 url += 'minx=' + bounds.left + '&miny=' + bounds.bottom + '&maxx=' + bounds.right + '&maxy=' + bounds.top;    	   
	   }
	   
      /* gestione sfondo */
      var flag = false;
      var numlayer;
      for (i=0;i<map.layers.length;i++) {
  			if(this.map.layers[i].visibility 
   				&& this.map.layers[i].CLASS_NAME == "OpenLayers.Layer.TMS") {
   					if (flag) {
   						numlayer = numlayer+","+i;
   					}
   					else {
   					    numlayer = i;
   					    flag = true;
   					}   				}
   	   	}
   	   	
   	   	      url += '&baselayer=' + numlayer;

       
       url += '&backgroundColor=' + baseLayer.backgroundColor.substring(1);	   
	   
	   // controllo la presenza di una configurazione
	   var mapName = getConfMapName();
	   if(mapName != null && mapName != '') {
	       url += '&mapname='+ mapName;
	   }
	   
	   //controllo condivisione punto
	   //giambattista
               
	   var checkCoord = document.getElementById('checkcoord');  	 	
	   var resultCoord = document.getElementById('resultCoord');  	 	
	   if (checkCoord.checked && lonlat)
	   {
      		url += '&lon=' + roundNumber(lonlat.lon,0)+'&lat='+roundNumber(lonlat.lat,0);	   
       }
       else if(resultCoord.value) {
       	    var elem=resultCoord.value.split(" , ")
      		url += '&lon=' +elem[0]+'&lat='+elem[1];	   
       }
        	

    	 		   
	   //controllo la presenza di parametri WMS
	    var locationURL = location.search;
        locationURL = decodeURI(locationURL);
    	locationURL = decodeParameters(locationURL);
    	
    	
    	var pos = locationURL.indexOf('wmsLogicalName=');
    	if(pos != -1) {
    	    wmsLogicalName = locationURL.substring(pos + 'wmsLogicalName='.length);
    	    pos = wmsLogicalName.indexOf('&');
    	    if (pos!=-1) {
    			wmsLogicalName = wmsLogicalName.substring(0,pos);
    		}
    		url += '&wmsLogicalName=' + wmsLogicalName;
    	}
    	
    	
    	pos = locationURL.indexOf('wmsUrl=');
    	if(pos != -1) {
    	    wmsUrl = locationURL.substring(pos + 'wmsUrl='.length);
    	    pos = wmsUrl.indexOf('&');
    	    if (pos!=-1) {
    			wmsUrl = wmsUrl.substring(0,pos);
    		}
    		url += '&wmsUrl=' + wmsUrl;
    	}
    	
    	pos = locationURL.indexOf('wmsPhysicalName=');
    	if(pos != -1) {
    	    wmsPhysicalName = locationURL.substring(pos + 'wmsPhysicalName='.length);
    	    pos = wmsPhysicalName.indexOf('&');
    	    if (pos!=-1) {
    			wmsPhysicalName = wmsPhysicalName.substring(0,pos);
    		}
    		url += '&wmsPhysicalName=' + wmsPhysicalName; 
    	}
    	
    	pos = locationURL.indexOf('wmsFormat=');
    	if(pos != -1) {
    	    wmsFormat = locationURL.substring(pos + 'wmsFormat='.length);
    	    pos = wmsFormat.indexOf('&');
    	    if (pos!=-1) {
    			wmsFormat = wmsFormat.substring(0,pos);
    		}
    		url += '&wmsFormat=' + wmsFormat;
    	}
    	   	
    		   
	   
	   document.getElementById('link').value = url;
	   document.getElementById('htmlMappa').value = '<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' + url + '&small=1"></iframe>'+
	   '<br/><a style="font-size:0.8em;color:#666666;font-family:Verdana,Arial,Geneva,Helvetica,sans-serif;text-decoration:none;"' +
	   ' onMouseOver="style.color=\'#F39E00\'; style.textDecoration =\'underline\';"  onMouseOut="style.color=\'#666666\'; style.textDecoration =\'none\';" href="' + url + '" class="link">Visualizzazione ingrandita della mappa</a>';
	   
		
		document.getElementById('resultLink').value =  url;
		document.getElementById('link').value = url;
	   
      	return url;
 
	// document.getElementById('link').select();
	 //document.getElementById('htmlMappa').select();
}
      
