/********************************
	geocodeFunctions.js
	
	Author: Vito Rifino
********************************/

// parsing risultati della richiesta di geocoding
//MC 
    coord_x=new Array();
		coord_y=new Array();
		var mem_x;
		var mem_y;
function parseGeocodeResults(theReply) {
	//prompt("",theReply);
    GCscore.length=1; 
	var tempPos = -1;  
		var solo_indirizzo=new Array();     
    var pos = theReply.indexOf("<GCCOUNT count=");
    var lpos = 0;
    var intWasFound = 1;
    var startpos = pos + 16;
    var startpos2=0;
    var endpos = theReply.indexOf(dQuote,startpos);
    var endposForNoName = -1;
    var fString = theReply.substring(startpos,endpos);
    GCpointCount = parseInt(fString);
    var gcCount=0;
    var flagRisultatoOk = true;
   var desc=""
      score_ini=0;
    //aggiunto per effettuare il post dei risultati nella pagina resultGeocode.asp
    var risultati="";
    
    if (GCpointCount > 0){
        pos = theReply.indexOf("<FEATURE");
		if (pos != -1) {
			while ( pos != -1 ) {
				lpos = theReply.indexOf("<FIELD",pos);				
				if ( lpos != -1 ) {
					startpos2 = theReply.indexOf('name="SCORE"',lpos);
					startpos = theReply.indexOf("FIELDVALUE valuestring=",startpos2);
					startpos = startpos + 24;
					endpos = theReply.indexOf(dQuote,startpos);
					GCscore[gcCount] = theReply.substring(startpos,endpos);
				if (GCscore[gcCount]>=score_ini){
					score_ini=GCscore[gcCount]
					startpos2 = theReply.indexOf('name="ADDRESSFOUND"',lpos);
					startpos = theReply.indexOf("FIELDVALUE valuestring=",startpos2);										
					startpos = startpos + 24;
					endpos = theReply.indexOf(dQuote,startpos);
					GCaddress[gcCount] = theReply.substring(startpos,endpos);
					
					//Elimino la dicitura No name, 
					endposForNoName = GCaddress[gcCount].indexOf("No name, ",0);
					if ( endposForNoName != -1 ) {
						endposForNoName += 9;
						GCaddress[gcCount] = GCaddress[gcCount].substring(endposForNoName,GCaddress[gcCount].length);
					}
					
					//Modifico la dicitura No name in senza nome 
					endposForNoNameAndReplace = GCaddress[gcCount].indexOf("No name",0);
					if ( endposForNoNameAndReplace != -1 ) {						
						GCaddress[gcCount] = GCaddress[gcCount].replace("No name","senza nome");
					}
					
					//Sostituisco and con e
					endposForAnd = GCaddress[gcCount].indexOf("and",0);
					if ( endposForAnd != -1 ) {						
						GCaddress[gcCount] = GCaddress[gcCount].replace("and","e");
					}
					//name indirizzo
					
					
					
					startpos2 = theReply.indexOf('name="Name"',lpos);
					startpos = theReply.indexOf("FIELDVALUE valuestring=",startpos2);										
					startpos = startpos + 24;
					endpos = theReply.indexOf(dQuote,startpos);
					solo_indirizzo[gcCount] = theReply.substring(startpos,endpos);
					//end name
					
					//numero civico: non è presente in tutte le risposte
					startpos2 = theReply.indexOf('name="House Range"',lpos);
					startpos = theReply.indexOf("FIELDVALUE valuestring=",startpos2);
					
					startpos = startpos + 24;
					endpos = theReply.indexOf(dQuote,startpos);
				 
					GCCivico[gcCount] = theReply.substring(startpos,endpos);
				
					tempPos = GCCivico[gcCount].indexOf('-',0);
					flagRisultatoOk_civico=false
					if ( tempPos == -1 ) {
							flagRisultatoOk_civico=true
						 GCCivico[gcCount] = "";
						
					}else{
						tempPos = GCCivico[gcCount].indexOf(' - ',0);
						
						tempPos = GCCivico[gcCount].indexOf(' ',tempPos + 3);
						if (cerca[2]!="") {
							 
					  		nl=(GCCivico[gcCount].substring(0,tempPos)).split(" - ")
					  		nr=(GCCivico[gcCount].substring(tempPos + 1,GCCivico[gcCount].length)).split(" - ")
					  		if ((cerca[2]<nl[0] && cerca[2]>nl[1]) || (cerca[2]>nl[0] && cerca[2]<nl[1]) || (cerca[2]<nr[0] && cerca[2]>nr[1]) || (cerca[2]>nr[0] && cerca[2]<nr[1]))
					  		  flagRisultatoOk_civico=true 
					  }
						GCCivico[gcCount] = "Lato sinistro: " + GCCivico[gcCount].substring(0,tempPos) + " Lato destro:" + GCCivico[gcCount].substring(tempPos + 1,GCCivico[gcCount].length);						
					 
					}
					
					startpos2 = theReply.indexOf('name="SHAPEFIELD"',lpos);
					startpos = theReply.indexOf("<POINT x=",startpos2);
					startpos += 10;
					endpos = theReply.indexOf(dQuote,startpos);
					GCpointX[gcCount] = theReply.substring(startpos,endpos);
					startpos = theReply.indexOf("y=",endpos);
					startpos = startpos + 3;
					endpos = theReply.indexOf(dQuote,startpos);
					GCpointY[gcCount] = theReply.substring(startpos,endpos);										
					gcCount++;	
					
					//Se si tratta di un servizio di geocodifica indirizzo
					//controllo se l'indirizzo contiene la via esatta					
					if (flagAddressGeocodingByCandidates){
						if (String(GCaddress[gcCount-1]).indexOf(viaAddressGeocoding,0) == -1 || String(GCaddress[gcCount-1]).indexOf(comuneAddressGeocoding,0) == -1){
							gcCount--;
							flagRisultatoOk = false;
						}else{
							flagRisultatoOk = true;
						}						
					}else{
						flagRisultatoOk = true;						
					}
					if (flagRisultatoOk || (cerca[2]!="" && flagRisultatoOk_civico) ){
						risultati += "indirizzo" + String(gcCount-1) + "&" + GCaddress[gcCount-1] + "&";
						risultati += "civico" + String(gcCount-1) + "&" + GCCivico[gcCount-1] + "&";
						risultati += "score" + String(gcCount-1) + "&" + GCscore[gcCount-1] + "&";
						risultati += "x" + String(gcCount-1) + "&" + GCpointX[gcCount-1] + "&";
						risultati += "y" + String(gcCount-1) + "&" + GCpointY[gcCount-1] + "&";	
						
						if (GCscore[gcCount-1]>=score_ini)	{
							score_ini=GCscore[gcCount-1]
						 	mem_x=	GCpointX[gcCount-1]
						 	mem_y=	GCpointY[gcCount-1]
						 
						}
							
					}
				}		
			}
				pos = theReply.indexOf("<FEATURE",endpos);
			}
		
			risultati += "gcCount" + "&" + String(gcCount)+ "&";
			if (flagAddressGeocodingByCandidates){
				risultati += "strada" + "&" + String(viaAddressGeocoding)+ "&";
				risultati += "stradaToShow" + "&" + String(viaAddressGeocodingToShow)+ "&";	
			 if (mem_x){
				coord_x[coord_x.length]=mem_x
				coord_y[coord_y.length]=mem_y		
			}	
			}
		}
		else{
			GCpointCount = 1;      
			GCaddress[0] = "Lat: " + parseFloat(GCLayers[0].input.GCvalue[0]) + "  Long:" + parseFloat(GCLayers[0].input.GCvalue[1]);
			GCpointY[0]  = parseFloat(GCLayers[0].input.GCvalue[0]);
			GCpointX[0]  = parseFloat(GCLayers[0].input.GCvalue[1]);
		}
        // display results
		currentGeocodePointIndex = 0;
		                
    }
    else {
		//nessun risultato
		intWasFound = 0;			
	}
		
	if (1 == intWasFound){
  		for (var intI =0; intI < GCLayers[GCActiveLayer].input.GCvalue.length; intI++ ){
  			GCLayers[GCActiveLayer].input.GCvalue[intI] = "";	
  		}
	} 	
	okToSend = true;
	
	if (flagAddressGeocodingByCandidates){
		
		flagAddressGeocodingByCandidates = false;
	}	
	
	if (!flagReverseGeocodingForRouting && geocoding==1){
		//resultGeocode = window.open("about:blank",nameResultGeocode,featureResultGeocode);
		//createAndSubmitFormPost("RoutingGeocoding/resultGeocode.asp",risultati,"formData","resultGeocode");
		//mc 17/05/07 rimepire la riga della tab con i risultati	
		/*var objDiv = document.getElementById("divResultGeocoding");
		var objDivIframe = document.getElementById("ifrmResultGeocoding");
		objDivIframe.style.display = "";		
		objDivIframe.src = "about:blank";
		document.getElementById("divResultRouting").style.display = "none";
		//document.getElementById("divResultCapAndVia").style.display = "none";
		objDiv.style.display = "";
		objDiv.style.height="300px";
		objDiv.style.width="250px";*/
			var X = GCpointX[0];
			var Y = GCpointY[0];
		
			charge_ris(risultati,X,Y)		
		//createAndSubmitFormPost("RoutingGeocoding/divResultGeocode.asp",risultati,"formData","ifrmResultGeocoding");	
		//end MC	
	/*}else if (!flagReverseGeocodingForRouting && geocoding==0){
		var objDiv = document.getElementById("divResultGeocoding");
		var objDivIframe = document.getElementById("ifrmResultGeocoding");
		objDivIframe.style.display = "";		
		objDivIframe.src = "about:blank";
		document.getElementById("divResultRouting").style.display = "none";
		//document.getElementById("divResultCapAndVia").style.display = "none";
		objDiv.style.display = "";
		objDiv.style.height="300px";
		objDiv.style.width="250px";			
		createAndSubmitFormPost("RoutingGeocoding/divResultGeocode.asp",risultati,"formData","ifrmResultGeocoding");		
	*/}
	else{
		if (intWasFound == 0){
		
			alert(GCLang[RTLang][6])	
		}else{
			
			var X = GCpointX[0];
			var Y = GCpointY[0];
		  if (!flagReverseGeocodingForRouting && geocoding==1)
					charge_ris(GCaddress[0],X,Y)	
			
			var desc = GCaddress[0];
			address_split=desc.split(",")
			indirizzo_solo=address_split[0]
			if (address_split.length>=3)
				n_civico=indirizzo_solo.slice(solo_indirizzo[0].length,indirizzo_solo.length)
			else
				n_civico=""
			endpos = desc.indexOf("No name, ",0);
			if ( endpos != -1 ) {
				endpos += 9;
				desc = desc.substring(endpos,desc.length);
			}
			var controlla = false;
			flagReverseGeocodingForRouting = false;			
		
			switch(typeReverseGeocodingForRouting){
				case "P":						
					addPartenza(X,Y,controlla,desc,null,n_civico);					
				break;
				case "A":	
					addArrivo(X,Y,controlla,desc,null,n_civico);
				break;
				case "PS":	
					addPassaggio(X,Y,controlla,desc,null,n_civico);
				break;
				case "B":	
					addBarriera(X,Y,controlla,desc,null);
				break;
			}			
		}		
	}
}

// parsing dei layer per il geocode
function parseGeocodeLayers(theReply) {
	//alert(theReply);
	var pos = 0;
	var startpos = 0;
	var endpos = 0;
	var lpos = 0;
	var rCount = 0;
	GCLayers.length=1;
	GCLayerCount=0;
	//prompt("",theReply)
	pos = theReply.indexOf("<LAYERINFO",endpos);

	var strLayerName = "";
	var strLayerId = "";
	var strLayerType = "";
	var strLayerStyle = "";
		
	while (pos!=-1) {
		lpos = theReply.indexOf('name=',pos);
		if (lpos!=-1) {						
			startpos = lpos + 6;
			endpos = theReply.indexOf(dQuote,startpos);
			strLayerName = theReply.substring(startpos,endpos);
			
			startpos = theReply.indexOf('id=',endpos);
			if (startpos!=-1) {
				startpos += 4;
				endpos = theReply.indexOf(dQuote,startpos);
				strLayerId = theReply.substring(startpos,endpos);
			}
			startpos = theReply.indexOf("<GCSTYLE name=",endpos);
			if (startpos!=-1) {
				startpos += 15;
				endpos = theReply.indexOf(dQuote,startpos);
				strLayerStyle = theReply.substring(startpos,endpos);				
			}
			pos = theReply.indexOf("<LAYERINFO",endpos);
			GCLayers[GCLayerCount] = new GCLayerSetup(strLayerName, strLayerId, "" , strLayerStyle);
			
			GCLayerCount=GCLayerCount+1;
			
		} else {			
			pos =-1;
		}
	}
}

// parsing dei parametri per ogni layer per il geocode
function parseGeocodeParams(theReply,theLayer, intLayerNum) {
	var pos = 0;
	var startpos = 0;
	var endpos = 0;
	var lpos = 0;
	var strTemp = "";
	var strLayer = "";
	var intPos = 0;
	var intEnd = 0; 
	var intId  = 0;
	var flagpos= 0;
	
	// cancella le vecchie informazioni sui parametri
	GCLayers[intLayerNum].input.GCid.length=0;
	GCLayers[intLayerNum].input.GClabel.length=0;
	GCLayers[intLayerNum].input.GCdesc.length=0;
	GCidCount=0;
	strLayerId = "";
	  
	var theName = 'name="' + theLayer + '"'
	pos 		= theReply.indexOf(theName,flagpos);
	   	
	if (pos == -1) return false;
	
	while (pos!=-1){
		intId 		= theReply.indexOf("id=", pos) + 4;
		strLayerId  = theReply.substring(intId, theReply.indexOf("\"", intId));
		if (strLayerId == GCLayers[intLayerNum].layerId ){
     			
     			
     	   	lpos     	= theReply.indexOf("</LAYERINFO>", pos);
          strLayer    = theReply.substring(pos, lpos);

     		startpos    = strLayer.indexOf("<GCINPUT id=",startpos);

     		// trova tutti i tag GIINPUT
     		while ((startpos!=-1)) {
         		startpos = strLayer.indexOf("<GCINPUT id=",startpos);
         		intEnd   = strLayer.indexOf("/",startpos);
         		
     			strTemp  = strLayer.substring(startpos, intEnd)
     			//	Prendi id,	
     			startpos += 13;
     			intPos = strTemp.indexOf("id=", 0) + 4;
     			endpos = strTemp.indexOf(dQuote,intPos); 
     			GCLayers[intLayerNum].input.GCid[GCidCount] = strTemp.substring(intPos,endpos);
     			// description, 
     			startpos = strTemp.indexOf("description=", 0);
     			startpos += 13;
     			endpos = strTemp.indexOf(dQuote,startpos); 
     			GCLayers[intLayerNum].input.GCdesc[GCidCount] = strTemp.substring(startpos,endpos);
     			// e label
     			startpos = strTemp.indexOf("label=", 0);
     			startpos = startpos + 7;
     			endpos = strTemp.indexOf(dQuote,startpos); 
     			GCLayers[intLayerNum].input.GClabel[GCidCount] = strTemp.substring(startpos,endpos);
     			GCLayers[intLayerNum].input.GCvalue[GCidCount] = "";
     			GCidCount=GCidCount+1;
     		
			   	// prova a trovare un altro tag GIINPUT
               	startpos = strLayer.indexOf("<GCINPUT id=",intEnd);
            			
            }
			return true;     		
		}
	flagpos   = pos + 1;
	pos 	 = theReply.indexOf(theName,flagpos);
	if (-1 == pos) return false;
	}
}


//Serve se è possibile selezionare il tipo di geocodifica
function setGCActiveLayer() {
	var s = document.getElementById("theLayer");	
	GCActiveLayer = s.selectedIndex;
	
	changeGcSelect();
}


//Costruisci la geocode query
function sendGeocodeQuery() {
	if (GCLayers.length > 0){
		
		var numeroParametri = GCLayers[GCActiveLayer].input.GCid.length;
		var contatoreParametriVisibili = 0;
		if (numeroParametri > 0){
			if (!flagReverseGeocodingByClick){
				for ( var i = 0; i < numeroParametri; i++ ){
					if (controllaVisibilitaParametro(GCLayers[GCActiveLayer].input.GClabel[i],GCLayers[GCActiveLayer].layerName)){
						//GCLayers[GCActiveLayer].input.GCvalue[i] = document.getElementById("input" + contatoreParametriVisibili).value;
					  
						GCLayers[GCActiveLayer].input.GCvalue[i]=cerca[i]
						
						contatoreParametriVisibili++;
					}
				}
			}	        
			// test sui campi
			for ( var i = 0; i < numeroParametri; i++ ){
					
				if (controllaVisibilitaParametro(GCLayers[GCActiveLayer].input.GClabel[i],GCLayers[GCActiveLayer].layerName)){
					
					if ( GCLayers[GCActiveLayer].input.GCvalue[i] != ""){						
						if (flagReverseGeocoding){			
						
							//Se si tratta di un servizio di reverse geocoding
							//converte le coordinate in lat/lon
							coordInput.length = 0;	
											
							coordInput[0] = GCLayers[indexReverseService].input.GCvalue[indexCoordInput[0]];
							coordInput[1] = GCLayers[indexReverseService].input.GCvalue[indexCoordInput[1]];
							flagReverseGeocodingByClick = false;							
							if (coordInput[0] != "" && coordInput[1] != ""){
								sendCoordToServer(coordInput[0],coordInput[1],"parseCoordTransform");	
								break;
							}else{
								//alert("Specificare entrambe le coordinate");
										alert(GCLang[RTLang][7])
								return;
							}
						}else if (GCActiveLayer == indexAddressService){
							//var inputPrefix = document.getElementById("prefix").value;		
							//MC 18/10/07 var inputPrefix = "";
							comuneAddressGeocoding	= makeXMLsafe(String(GCLayers[GCActiveLayer].input.GCvalue[1]).toUpperCase());
							
							sendViaAndComuneToServer(GCLayers[GCActiveLayer].input.GCvalue[0],GCLayers[GCActiveLayer].input.GCvalue[1],inputPrefix,"parseCapAndVia");
							break;
						}else{							
							var theText = writeGeocodeXML(GCActiveLayer); 
							sendToServer(imsGeoCoderURL, theText, 5004 );
							break;
						}
					}
				}
				if (i == numeroParametri-1){
					//alert("Specificare almeno un campo per la ricerca");
					alert(GCLang[RTLang][8])
					return; // tutti i campi sono vuoti
				}
			}	    		
		}
		else{
			//alert("In questo servizio non ci sono parametri per impostare la ricerca");
			alert(GCLang[RTLang][9])
			return;
		}
	}
	
			

}

//riceve il risultato della ricerca cap e via e invia la richiesta
//di geocode modificata
function parseCapAndVia(risultati,numRisultati){	

	numRisultati = parseInt(numRisultati)
	okToSend = true;
	if (numRisultati > 0 || numRisultati == 0){
	  if (validate==1){
	       
				 // name_geo="Geocoding"

					var objDiv = document.getElementById("divResultCapAndVia");	
					var objDivIframe = document.getElementById("ifrmResultCapAndVia");
					
					objDivIframe.style.display = "";
				
					objDivIframe.src = "RoutingGeocoding/validation.asp";
				
					objDiv.style.display = "";
		
					//prompt("form",risultati)	
					createAndSubmitFormPost("RoutingGeocoding/validation.asp",risultati,"formData","ifrmResultCapAndVia");
				
		
		//MC
	}
	
	}else{
	
		sendAddressQuery(risultati);
	}
}

function sendAddressQuery(risultati){
	flagAddressGeocodingByCandidates = true;
	var tmpResult = new Array();
	var tmpCap = "";
	var tmpVia = "";
	//prompt("",risultati)
	tmpResult = risultati.split('&');
	tmpCap = tmpResult[1];
	tmpVia = tmpResult[3];
	tmpComune= tmpResult[5];
	//viaAddressGeocoding = String(document.getElementById("input0").value).toUpperCase();
  
	viaAddressGeocoding =makeXMLsafe(String(cerca[0]).toUpperCase())
	viaAddressGeocodingToShow = makeXMLsafe(tmpVia); 	
	//document.getElementById("inputCivic").value=""
	//MC 04/12/07
	comuneAddressGeocoding=makeXMLsafe(tmpComune)
	//GCLayers[GCActiveLayer].input.GCvalue[0] = tmpVia + " " + document.getElementById("inputCivic").value;

  if (tmpVia!="  ")
			GCLayers[GCActiveLayer].input.GCvalue[0] = tmpVia + " " + cerca[2];
	GCLayers[GCActiveLayer].input.GCvalue[1] = tmpComune;	
	aParsNameGcService[indexAParsNameGC].aParsNameGcParameter[2].defaultValue = tmpCap;
	var theText = writeGeocodeXML(GCActiveLayer);  
  
  sendToServer(imsGeoCoderURL, theText, 5004 );
}

//invia alla pagina searchCapAndVia.asp comune e nome via
//e poi richiama la funzione functionToProcessResponce
function sendViaAndComuneToServer(via,comune,prefisso,functionToProcessResponce){	

	if (okToSend) {	
	  //MC 22/10/07
		if (makeStrSafeForPost(comune)!=""){
			okToSend = false;	
			via=via.replace(/,/g," ")
			via=via.replace(/'/g,"-")
			comune=comune.replace(/'/g,"-")
      
			risultati = "via&" + makeStrSafeForPost(via) + "&comune&" + makeStrSafeForPost(comune) + "&prefisso&" + makeStrSafeForPost(prefisso) + "&idLayer&" + GCLayers[indexAddressService].layerId+"&civico&"+cerca[2] ;
			//prompt("",risultati)	
	   if (validate==1){
	   	risultati += "&functionToProcessResponce&parent." + functionToProcessResponce;	
	   	var objDiv = document.getElementById("divResultCapAndVia");	
					var objDivIframe = document.getElementById("ifrmResultCapAndVia");
					
					objDivIframe.style.display = "";
				
					objDivIframe.src = "RoutingGeocoding/validate_noroute.asp";
					//objDivIframe.src = "RoutingGeocoding/validation.asp";
					//objDiv.style.display = "";
					okToSend = true;	
			    createAndSubmitFormPost("RoutingGeocoding/validate_noroute.asp",risultati,"formData","ifrmResultCapAndVia");
			    //createAndSubmitFormPost("RoutingGeocoding/validation.asp",risultati,"formData","ifrmResultCapAndVia");
	
			//createAndSubmitFormPost("RoutingGeocoding/searchCapAndVia.asp",risultati,"formData",functionToProcessResponce);
			}else{
		
				arrParametri=risultati.split('&');
				stringConDati=""
		  	for (indiceArrParametri=0;indiceArrParametri<arrParametri.length-1;indiceArrParametri=indiceArrParametri+2){					
					stringConDati+=arrParametri[indiceArrParametri]+"=" + (arrParametri[indiceArrParametri+1]) + "&";
					
				}
			  //if (cerca[2]!="") stringConDati+="civico="+cerca[2]+ "&";	
			 if (map){ 
				if (map.getLayerIndex(newl)!=-1){
							map.removeLayer(map.layers[0])
							newl=""
				}
			
			 		url_geo=indirizzo_base+"/pk_geocoding_form.asp?"+stringConDati.slice(0,stringConDati.length-1)
			 		//prompt("",url_geo)
			 		add_georss(url_geo)
				}else{
					//modulo3d
					url_geo=indirizzo_base+"/Modulo_3D/box_geocoding.asp?"+stringConDati.slice(0,stringConDati.length-1)
					url_georss=indirizzo_base+"/pk_geocoding_form.asp?"+stringConDati.slice(0,stringConDati.length-1)
					add_box_ricerca(url_geo);
				}
				
				okToSend = true;	
			}
		}else{
			//alert("Specificare meglio i parametri di ricerca" );	
				alert(GCLang[RTLang][10])		
		}
	}
	else {
		//alert("Attendere" );
		alert(GCLang[RTLang][11])		
	}
}

//riceve la risposta della trasformazione di coordinate
//da wgs84 utm33 a lat/lon
function parseCoordTransform(lon,lat){	
	okToSend = true;
	GCLayers[GCActiveLayer].input.GCvalue[indexCoordInput[0]] = String(lon);
	GCLayers[GCActiveLayer].input.GCvalue[indexCoordInput[1]] = String(lat);	
	
	var theText = writeGeocodeXML(GCActiveLayer);    
 // prompt("",theText)
 	
 	sendToServer(imsGeoCoderURL, theText, 5004 );
}


//invia alla pagina coordTransform.asp le coordinate in wgs84 lat/lon 
//e poi richiama la funzione functionToProcessResponce
function sendCoordToServer(x,y,functionToProcessResponce){	
	if (okToSend) {	
		okToSend = false;	
	/*	risultati = "parConvFrom&" + parConvFrom + "&parConvTo&" + parConvTo;
		risultati += "&parDatumIn&" + parDatumIn + "&parDatumOut&" + parDatumOut;
		risultati += "&parFuseIn&" + parFuseIn + "&parFuseOut&" + parFuseOut;
		risultati += "&xIn&" + String(x) + "&yIn&" + String(y);
		risultati += "&functionToProcessResponce&parent." + functionToProcessResponce;
		//if (geocoding!="1")	createAndSubmitFormPost("RoutingGeocoding/coordTransform.asp",risultati,"formData","ifrmRoutingGeocoding");
		*/
		//MC-17
	
		parseCoordTransform(x,y)
		
	}
	else {
		//alert("Attendere" );
		alert(GCLang[RTLang][11])		
	}
}

// compone la richiesta XML di geocode
function writeGeocodeXML(indexLayerGeocode) {
	//il mingeocodescore lo legge dalla slider
	
	//MC 17/05/07 elimino lo slider
	//minGeocodeScore = "" + document.getElementById("VITransparency").value;	
	//minGeocodeScore = minGeocodeScore.replace("%","");		
	minGeocodeScore=60
	//end MC

	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_GEOCODE';
	if (!flagReverseGeocoding || !flagReverseGeocodingForRouting){
		theString += ' spellingsensitivity="' + spellingSensitivity + '"';
	}
	theString += ' maxcandidates="' + maxGeocodeCandidates + '" minscore="' + minGeocodeScore + '"';
	theString += '>\n';	
	theString += '<LAYER id="' + GCLayers[indexLayerGeocode].layerId + '" />\n';
	theString += '<ADDRESS>\n';
	var value = '';		
	
	for (var i=0;i<GCLayers[indexLayerGeocode].input.GCid.length;i++) {
		if (controllaVisibilitaParametro(GCLayers[indexLayerGeocode].input.GClabel[i],GCLayers[indexLayerGeocode].layerName)){			
			value = GCLayers[indexLayerGeocode].input.GCvalue[i];
			//alert(GCLayers[indexLayerGeocode].input.GCvalue[i])
			if ((value!=null) && (value!="")) {
				value = makeXMLsafe(value);
				theString += '<GCTAG id="' + GCLayers[indexLayerGeocode].input.GCid[i] + '" value="' + value + '"/>\n';
			}
		}else{
			value = makeXMLsafe(returnDefaultValue(GCLayers[indexLayerGeocode].input.GClabel[i],GCLayers[indexLayerGeocode].layerName));
			if (value != ""){				
				theString += '<GCTAG id="' + GCLayers[indexLayerGeocode].input.GCid[i] + '" value="' + value + '"/>\n';
			}
		}
	}	

	if (!flagReverseGeocodingForRouting && flagReverseGeocoding){
		var reverseStyle = "";
		//MC 17/05/07 eliminare il contenuto e settare solo il tipo indirizzo
		//reverseStyle = document.getElementById("selectReverseType").options[document.getElementById("selectReverseType").selectedIndex].value;	
		reverseStyle="address"
		//end MC
		theString += '<GCTAG id="Style" value="' + reverseStyle + '"/>\n';
	}else if(flagReverseGeocodingForRouting){
		theString += '<GCTAG id="Style" value="address"/>\n';
	}
	theString += '</ADDRESS>\n';
	theString += '<FEATURECOORDSYS id="' + FEATURECOORDSYS + '" />\n';
  theString += '<FILTERCOORDSYS id="' + FILTERCOORDSYS + '" />\n';
	theString += '</GET_GEOCODE>\n</REQUEST>\n</ARCXML>\n';	
	//prompt("",theString);
	
	return theString;
}

function populateSelectGcService() {
	/*marianna al momento non serve
	
	var s = document.getElementById("theLayer");
	
	s.options.length=0;*/
	for ( var i = 0; i < GCLayers.length; i++ ){
			
		for (var j = 0; j < aParsNameGcService.length; j++ ){
			if (GCLayers[i].layerName == aParsNameGcService[j].serviceName){
				switch(aParsNameGcService[j].type){
					case "N":
					break;
					
					case "R":
						//Settaggio indice del servizio di geocode reverse
						//e indice dei parametri delle coordinate						
						indexReverseService = i;
						indexCoordInput.length = 0;
						indexCoordInput[0] = -1;
						indexCoordInput[1] = -1;
						//alert( GCLayers[indexReverseService].input.GCid.length)
						for (var k=0;k<GCLayers[indexReverseService].input.GCid.length;k++) {
							var typeReverseParameter = "";
							typeReverseParameter = whatReverseParameterIs(GCLayers[indexReverseService].input.GClabel[k],j);
							
							if (typeReverseParameter == "X"){						
								indexCoordInput[0] = k;
							}else if (typeReverseParameter == "Y"){						
								indexCoordInput[1] = k;
							}		
						}
						if (indexCoordInput[0] == -1 || indexCoordInput[1] == -1){
							alert("Impostare correttamente il file routeParameter.js per il servizio di geocode reverse");
							return;
						}						
					break;
					
					case "A":					
						//Settaggio indice del servizio di geocode reverse						
						indexAddressService = i;		
						indexAParsNameGC = j;
					break;
					
					default:
					break;
				}
			}			
		}
		
	/*	mc non serve
	 var option = new Option(parseNameGcService(GCLayers[i].layerName),parseNameGcService(GCLayers[i].layerName));		
		s.options.add(option, i);			*/				
	}	
}
//mc ho inserito i commenti
function changeGcSelect(){	
	//alert(GCActiveLayer)
	//var tdCampi = document.getElementById("tdCampi");
	var tdIn = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
	var contatoreParametriVisibili = 0;
	
	switch(GCActiveLayer){
		case indexReverseService:	
			setUpServiceFlagAndHtmlElement("R");							
		break;
		
		case indexAddressService:
			setUpServiceFlagAndHtmlElement("A");			
		break;
		
		default:
			setUpServiceFlagAndHtmlElement("");							
		break;
	}
	
	for ( var i = 0; i < GCLayers[GCActiveLayer].input.GCid.length; i++ ){
		if (controllaVisibilitaParametro(GCLayers[GCActiveLayer].input.GClabel[i],GCLayers[GCActiveLayer].layerName)){					
			tdIn += "<tr width=\"100%\"><TD class=\"box_td_line_left_bottom\" align=\"left\" width=\"30%\">" + parseNameGcInput(GCLayers[GCActiveLayer].input.GClabel[i],GCLayers[GCActiveLayer].layerName) + ":&nbsp;</td>";
			tdIn += "<TD class=\"box_td_line_bottom\" align=\"right\" width=\"70%\"><input type=\"text\" name=\"input" + contatoreParametriVisibili + "\" id=\"input" + contatoreParametriVisibili + "\" size=\"24\" class=\"txtfld\">&nbsp;</td></tr>";
			if(flagAddressGeocoding && parseNameGcInput(GCLayers[GCActiveLayer].input.GClabel[i],GCLayers[GCActiveLayer].layerName) == objExtraParameter.nameGcParameter){
				tdIn += "<tr width=\"100%\"><TD class=\"box_td_line_left_bottom\" align=\"left\" width=\"30%\">" + objExtraParameter.civic + ":&nbsp;</td>";
				tdIn += "<TD class=\"box_td_line_bottom\" align=\"right\" width=\"70%\"><input type=\"text\" name=\"inputCivic\" id=\"inputCivic\" size=\"24\" class=\"txtfld\">&nbsp;</td></tr>";
			}
			contatoreParametriVisibili++;
		}
	}	
	tdIn += "</table>";
//	tdCampi.innerHTML = tdIn;	
}

//Function per reimpostare i flag sui servizi
//mc ho commentato alcune cose
function setUpServiceFlagAndHtmlElement(type){
	switch(type){
		case "R":	
			flagReverseGeocoding = true;
			flagAddressGeocoding = false;
		/*	document.getElementById("reverseButton").style.display = "inline";
			document.getElementById("reverseType").style.display = "inline";
			document.getElementById("addressType").style.display = "none";*/
		break;
		
		case "A":	
			flagReverseGeocoding = false;
			flagAddressGeocoding = true;
			/*document.getElementById("addressType").style.display = "inline";
			document.getElementById("reverseType").style.display = "none";
			document.getElementById("reverseButton").style.display = "none";*/
		break;
		
		default:
			flagReverseGeocoding = false;
			flagAddressGeocoding = false;
		/*	document.getElementById("reverseButton").style.display = "none";
			document.getElementById("reverseType").style.display = "none";
			document.getElementById("addressType").style.display = "none";*/
		//	newmode('noMode');			
		break;		
	}
}

//Eventuale parsing dei nomi dei servizi di geocoding
//Deve essere stato creato il vettore delle corrispondenze in routeParameters.js
//Se son si trova la corrispondenza viene visualizzato il nome restituito da ArcIms
function parseNameGcService(name){
	var parsedName = name;
	
	for ( var i = 0; i < aParsNameGcService.length; i++ ){
		if(parsedName == aParsNameGcService[i].serviceName){
			parsedName = aParsNameGcService[i].parseServiceName;
			break;		
		}
	}	
	return parsedName;
}

//Eventuale parsing dei parametri dei servizi di geocoding
//Deve essere stato creato il vettore delle corrispondenze in routeParameters.js
//Se son si trova la corrispondenza viene visualizzato il nome restituito da ArcIms
function parseNameGcInput(name,serviceName){
	var parsedName = name;
	
	for ( var i = 0; i < aParsNameGcService.length; i++ ){
		for (var j = 0; j < aParsNameGcService[i].aParsNameGcParameter.length; j++ ){
			if(name == aParsNameGcService[i].aParsNameGcParameter[j].parameterName && serviceName == aParsNameGcService[i].serviceName){
				parsedName = aParsNameGcService[i].aParsNameGcParameter[j].parseParameterName;
				break;
			}
		}
	}	
	return parsedName;
}

//Controllo della visibilità del parametro
//Deve essere stato creato il vettore delle corrispondenze in routeParameters.js
//Se non si trova la corrispondenza viene inteso che si tratta di un parametro visibile
function controllaVisibilitaParametro(name,serviceName){
	for ( var i = 0; i < aParsNameGcService.length; i++ ){
		for (var j = 0; j < aParsNameGcService[i].aParsNameGcParameter.length; j++ ){			
			if(name == aParsNameGcService[i].aParsNameGcParameter[j].parameterName && serviceName == aParsNameGcService[i].serviceName){
				if(aParsNameGcService[i].aParsNameGcParameter[j].visibility){
					return true;
				}else{
					return false;
				}
			}
		}
	}			
	return true;
}
	
//Ritorna il valore di default per un parametro che si è deciso di non visualizzare
//Deve essere stato creato il vettore delle corrispondenze in routeParameters.js
function returnDefaultValue(name,serviceName){
	var defaultValue = "";
	
	for ( var i = 0; i < aParsNameGcService.length; i++ ){
		for (var j = 0; j < aParsNameGcService[i].aParsNameGcParameter.length; j++ ){
			if(name == aParsNameGcService[i].aParsNameGcParameter[j].parameterName && serviceName == aParsNameGcService[i].serviceName){
				defaultValue = aParsNameGcService[i].aParsNameGcParameter[j].defaultValue;
				break;
			}
		}
	}	
	return defaultValue;
}

//Ritorna che tipo di coordinata rappresenta il parametro associato ad un sevizio di geocodifica inversa
function whatReverseParameterIs(parameterName,indexParse){
	var coord = "";
	for (var j = 0; j < aParsNameGcService[indexParse].aParsNameGcParameter.length; j++ ){
		if(parameterName == aParsNameGcService[indexParse].aParsNameGcParameter[j].parameterName){
			coord = aParsNameGcService[indexParse].aParsNameGcParameter[j].coord;
			break;
		}
	}
	return coord;
}

function zoomDaEnvelope(tlx,tly,brx,bry){
	if((tlx==brx)&&(tly==bry)){//se si tratta di un punto		
	//	top.imageMovetoCoordTrasformAndScale(parseFloat(tlx),parseFloat(tly),scaleG);
	  if (map)
	   	map.setCenter(new OpenLayers.LonLat(tlx,tly),10)
	  else
	   		C3d.GoToPos(tlx,tly,700,700,100,8);	
	} else {//è un poligono
	/*	var widthPoligonM = brx - tlx;
		var heighPoligonM = tly - bry;		
		var minHW = minScaleR / 4;
		if(widthPoligonM<= minHW && heighPoligonM<=minHW){
			centroXPoligono=widthPoligonM/2+tlx;
			centroYPoligono=bry+heighPoligonM/2;
			map.setCenter(new OpenLayers.LonLat(centroXPoligono,centroYPoligono),10)
			//top.imageMovetoCoordTrasformAndScale(parseFloat(centroXPoligono),parseFloat(centroYPoligono),minScaleR);			
		} else {//altrimenti realizzo lo zoom sull'envelope del poligono*/
			moveAExtent(tlx,brx,bry,tly);//xxx da centrare
		//}
	}
}

function moveAExtent(minX,maxX,minY,maxY){
	tlx = minX; 
	tly = maxY; 
	brx = maxX;
	bry = minY;
	if (map){
		var extent = new OpenLayers.Bounds(minX,minY,maxX,maxY);
                                  
    map.zoomToExtent(extent);
  }else
  	{
  		C3d.SetView(tlx,tly,brx,bry);
  	}
	//document.ECWView1.SetExtents(tlx, tly, brx, bry); 

}

	 
function charge_ris(risultati,XUtm,YUtm,numRisultati){
	
	if (risultati=="") {
		alert("Nessun risultato valido")
	}else{
		
		 
		 	
		
			YGeo=(UTM2LL(XUtm,YUtm,33))[0]
			XGeo=(UTM2LL(XUtm,YUtm,33))[1]
			/*XUtm=(LL2UTM(YGeo,XGeo,33))[0]
			YUtm=(LL2UTM(YGeo,XGeo,33))[1]*/
			//fine conversione
			//alert(risultati)
			coord_utm=new OpenLayers.LonLat(XUtm, YUtm)
		 //	add_marker_indirizzo(coord_utm,risultati,XGeo,YGeo)
			add_marker_geo(coord_utm,risultati,XGeo,YGeo)
	}
}

function add_marker_indirizzo(coord_utm){
	   		markers = new OpenLayers.Layer.Markers("indirizzo");
		    map.addLayer(markers);
		  //  map.setLayerIndex(markers,2)
		    icon = OpenLayers.Marker.defaultIcon("PK_layout/img/BandierinaGiallaMappa.gif");
		    marker = new OpenLayers.Marker(coord_utm,icon);
		    markers.addMarker(marker);
}
