//numero dei layer che devono essere interrogati -1
 var numThMultipla = 12;
 
 var actualLyr = 0;
 var theReplyArray = new Array(); //array delle risposte
 var pageFormat = true;           // se è true scrivo l'intestazione della pagina dei risultati
 
 var strLyrVisibileMult = "";     //contiene la stringa per visualizzare i layer che devono essere
                                  //resi visibili con la multipla
 var strPointMultipla = "";
 var leftTemp; 
 var rightTemp ; 
 var bottomTemp ; 
 var topTemp ;		
 					  
//Array contenente gli indici(come appaiono su axl) dei layers che devono essere interrogati 
//in questo ordine
 var multLayerIndex = new Array();
     multLayerIndex[0] = 3;       //Sistemi 
     multLayerIndex[1] = 15;       //subsistemi
     multLayerIndex[2] = 16;       //UTOE  
     multLayerIndex[3] = 17;       //pertinenze
	 
     multLayerIndex[4] = 12;       //tessitura agraria
	 multLayerIndex[5] = 13;       //emergenze paesaggistiche
	 multLayerIndex[6] = 4;       //uso del suolo
	 
	 multLayerIndex[7] = 9;       //vulnerabilità degli acquiferi
	 multLayerIndex[8] = 11;       //pericolosità geologica
	 multLayerIndex[9] = 10;       //pericolosità idrica
	 
	 multLayerIndex[10] = 6;       //sic
	 multLayerIndex[11] = 7;       //riserve naturali
	 multLayerIndex[12] = 8;       //rispetto superstrada
	 
 
 var WinMult;
 var frame;
 
function multipla(a,b,c,d){
   actualLyr = 0;
   getMapXY(a,b);
   var T_primoX = mapX; 
   var T_primoY = mapY; 

   getMapXY(c,d);
   var T_secondoX = mapX; 
   var T_secondoY = mapY; 

   var T_minX = Math.min(T_primoX,T_secondoX);
   var T_maxX = Math.max(T_primoX,T_secondoX);
   var T_minY = Math.min(T_primoY,T_secondoY);
   var T_maxY = Math.max(T_primoY,T_secondoY);

   clickPointX[0] = T_minX;
   clickPointX[1] = T_maxX;
   clickPointX[2] = T_maxX;
   clickPointX[3] = T_minX;

   clickPointY[0] = T_minY;
   clickPointY[1] = T_minY;
   clickPointY[2] = T_maxY;
   clickPointY[3] = T_maxY;

   nPunti = 4;
   
   //Richiesta degli elementi selezionati
   beginRecord = 1;
   scriviXMLMultipla();
   
}

function scriviXMLMultipla(){
    
	 var index = multLayerIndex[actualLyr];
	 //var orderIndex = ordinaLayer(index);
	 setActiveLayer(index);
	 var strXML = writeXML('Polygon');
	 startDataLoading();
	 sendToServer(imsURL + CustomService,strXML,5);
}

function addMultipla(theReply){
   theReplyArray[actualLyr] = '\n'+theReply;
   if (actualLyr < numThMultipla){
     actualLyr += 1;
	 scriviXMLMultipla();
   }else{
     displayMultipla();
   }

}

//stampa i risultati inseriti in theReplyArray
function displayMultipla(){
  //alert('theReplyArray='+theReplyArray);
  if (resultsWindow){
	      WinMult = window.open("","QueryWindow","width=600,height=400,scrollbars=yes,resizable=yes");
	      frame = 'opener.parent.MapFrame';
  }else{
	      WinMult = parent.textFrame;
		  frame = 'parent.MapFrame';
  }	  	  
  WinMult.document.open();
  WinMult.document.writeln('<html><head><title>Elementi selezionati</title>');
  WinMult.document.writeln('</head>');
  WinMult.document.writeln('<LINK href="'+path+'PianoStrutturale.css" type=text/css rel=stylesheet>');
  WinMult.document.writeln('<body onload="window.focus()">');
 
  WinMult.document.writeln('<DIV align="center" >');
  WinMult.document.write('<font class="grassettoRosso">Elenco dei tematismi trovati nel punto  </strong></font>');
  WinMult.document.write('<img SRC="'+appDir+'images/freccia.gif" >');
  sisTer=false;
  compPaes=false;
  compGeo=false;
  compVinc=false;
 // WinMult.document.writeln('<br><br>');
 // WinMult.document.writeln('<font face="Verdana" size="4"><b>Componente dei Sistemi Territoriali :</b> </font>');
  for(var i=0; i <= 3; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	 sisTer = true;	      
	 }
  }
  if(sisTer == true){ 
  		WinMult.document.writeln('<br><br>');
  		WinMult.document.writeln('<font class="grassetto">Componente dei Sistemi Territoriali :</font><br>');
		sisTer = false;
  }		 
  //for(var i=0;i<=numThMultipla;i++){
  for(var i=0; i <= 3; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	      var index = multLayerIndex[i];
		  WinMult.document.writeln('<br>');
          WinMult.document.writeln('<font class="grassettonomeLayer">'+layerName[index] + ' </font>');
		  
	      memEnvelopeMultipla(theReplyArray[i],i);
		  displayDataMultipla(theReplyArray[i],i);
	 }
  }
  for(var i=4; i <= 6; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	 compPaes = true;	      
	 }
  }
  if(compPaes == true){ 
  		WinMult.document.writeln('<br><br>');
  		WinMult.document.writeln('<font class="grassetto">Componente paesaggistica :</font><br>');
		compPaes = false;
  }
  for(var i=4; i <= 6; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	      var index = multLayerIndex[i];
		  WinMult.document.writeln('<br>');
          WinMult.document.writeln('<font class="grassettonomeLayer>"'+layerName[index] + ' </b> </font>');
		  
	      memEnvelopeMultipla(theReplyArray[i],i);
		  displayDataMultipla(theReplyArray[i],i);
	 }
  }
  for(var i=7; i <= 9; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	 compGeo = true;	      
	 }
  }
  if(compGeo == true){ 
  		WinMult.document.writeln('<br><br>');
  		WinMult.document.writeln('<font class="grassetto">Componente geologico/idraulica :</b> </font><br>');
		compGeo = false;
  }		
  for(var i=7; i <= 9; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	      var index = multLayerIndex[i];
		  WinMult.document.writeln('<br>');
          WinMult.document.writeln('<font class="grassettonomeLayer">'+layerName[index] + '  </font>');
		  
	      memEnvelopeMultipla(theReplyArray[i],i);
		  displayDataMultipla(theReplyArray[i],i);
	 }
  }
  
  for(var i=10; i <= 12; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	 compVinc = true;	      
	 }
  } 
  
  if(compVinc == true){
  		WinMult.document.writeln('<br><br>');
  		WinMult.document.writeln('<font class="grassetto">Componente Vincoli  e rispetti : </font><br>');
		compVinc = false;
  }		
  
  for(var i=10; i <= 12; i++){
     //alert('theReplyArray['+i+']='+theReplyArray[i]);
     var jgfc = justGetFeatureCount(theReplyArray[i]);
	 if (jgfc != 0 ){
	      var index = multLayerIndex[i];
		  WinMult.document.writeln('<br><br>');
          WinMult.document.writeln('<font class="grassettonomeLayer">'+layerName[index] + '</font>');
		  
	      memEnvelopeMultipla(theReplyArray[i],i);
		  displayDataMultipla(theReplyArray[i],i);
	 }
  }
 
  WinMult.document.writeln('</DIV>');
  WinMult.document.writeln('</body></html>');
  WinMult.document.close();
  //azzeratheReplyArray();
  
  startMapLoading();
  strPointMultipla = addPointMultipla();
//alert(strPointMultipla);
  
  //Quando faccio l'interrogazione multipla devono riapparire tutti i layer interrogabili.
  //Li setto adesso
  // true se il layer deve essere visibile (come nel file axl)
	layerVisible[0]=false;//DTM
	layerVisible[1]=false;//toponimi
	layerVisible[2]=false;//conf_com
	layerVisible[3]=true;//st1
	layerVisible[4]=false;//uso_suolo
	layerVisible[5]=true;//pee_stor_att
	layerVisible[6]=false;//sic
	layerVisible[7]=false;//ris_nat
	layerVisible[8]=false;//risp_superstrada
	layerVisible[9]=false;//vulnerabilità
	layerVisible[10]=false;//cp_idr
	layerVisible[11]=false;//cp_geo
	layerVisible[12]=false;//tessitura
	layerVisible[13]=false;//terrazzi
	layerVisible[14]=false;//st
	layerVisible[15]=true;//sbt
	layerVisible[16]=true;//utoe
	layerVisible[17]=true;//pert
	layerVisible[18]=true;//ctr2000_taglio
	layerVisible[19]=true;//ctr10000_taglio
	layerVisible[20]=true;//ctr10000
	layerVisible[21]=true;//ctr25000
	layerVisible[22]=true;//cenuc
  
  strLyrVisibileMult = ' <LAYERLIST> ';
	   for (var i=0; i<numLayerField ; i++){
	       var orderIndex = ordinaLayer(i);
           strLyrVisibileMult += '  <LAYERDEF id="'+layerID[orderIndex]+'" visible="'+layerVisible[orderIndex]+'" />';
       }
	   strLyrVisibileMult += '</LAYERLIST>';
  strLyrVisibile = strLyrVisibileMult; 
  
  // memorizzo l'estensione precedente
    leftTemp = left; 
    rightTemp = right; 
    bottomTemp = bottom ; 
    topTemp = top ;
	//alert("leftTemp="+leftTemp+";rightTemp="+rightTemp+";bottomTemp="+bottomTemp+";topTemp="+topTemp);
	
//risetto lo zoom_in dopo l'interrogazione multipla
  parent.toolFrame.setToolPic('Zoom In');
  //parent.toolFrame.chiamaRet(3);
    
  controlla_fattore();
  //stopMapLoading();
}



// funzione che memorizza l'envelope
function memEnvelopeMultipla(theR,featureIndex) {
    theString = theR.toUpperCase();
	var tempString = "";
	var startpos=0;
	var endpos;
	
	//Get the start of the ENVELOPE element
	var pos = theString.indexOf("ENVELOPE",startpos);
	if (pos!=-1) {
	    pos = pos + 8;
		
		//Extract minx
		startpos = theString.indexOf("MINX=",pos);
		startpos += 6;
		var endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		leftEnv[featureIndex] = parseFloat(tempString); 
					
		//Extract miny
		startpos = theString.indexOf("MINY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		bottomEnv[featureIndex] = parseFloat(tempString); 
		
		//Extract maxx
		startpos = theString.indexOf("MAXX=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		rightEnv[featureIndex] = parseFloat(tempString); 
		
		//Extract maxy
		startpos = theString.indexOf("MAXY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		topEnv[featureIndex] = parseFloat(tempString); 
		
	} else {
		alert('Errore: impossibile trovare "ENVELOPE"');
		}
	

}

//stampa i valori di theReplyArray[i]
function displayDataMultipla(risposta,featureIndex) {
	
	var pos = 1;
	xmlEndPos = 1;
	
	var fieldValuesTemp = parseRecordString(risposta,pos); 
	var fName1 = getFieldNames(fieldValuesTemp);
	var index = multLayerIndex[featureIndex];
	if (useAlias) {
	      var fAlias1 = loadAlias(fName1,index);
	}
	WinMult.document.writeln('<table border="1" bordercolor="White" cellspacing="2" cellpadding="1"  align="center">');
	WinMult.document.writeln('<tr>');
	for (var i=0; i<fName1.length; i++){
	  if((fName1[i] != "#SHAPE#") && (fName1[i] != "#ID#")){
	     if (useAlias){
		   WinMult.document.writeln('<td class=tbnome>'+ fAlias1[i]+'</td>');
	     }else{
	       WinMult.document.writeln('<td class=tbnome>'+ fName1[i].toLowerCase()+'</td>');
	     }	
	  }  
	}
	
	WinMult.document.writeln('</tr>');	
	
	var fieldValues = parseRecordString(risposta,pos); 
	var fValue1 = getFieldValues(fieldValues);
	pos = xmlEndPos;
	
	// Inserisco i valori dei campi #ID# o OBJECTID 
	selectPoints[featureIndex] = getIdValue(fName1,fValue1);
			
	// Inserisco i valore "SHAPE" o "SDE"
	selectFieldID[featureIndex] = getFieldID(fName1);
			
	WinMult.document.writeln('<tr>');
	for (var ii=0; ii<fName1.length; ii++){
	   if((fName1[ii] != "#SHAPE#")&&(fName1[ii] != "#ID#")){
			 
			if(fName1[ii]=="COD_NTA"){
			
			       if(fValue1[ii]=="&nbsp;") WinMult.document.writeln('<td class=tbvalore>Non prevista dal Piano Strutt.</td>');
				   else WinMult.document.writeln('<td class=tbvalore><a target="new" href="'+path+fValue1[ii]+'">Leggi Norma</a></td>');
				 
			}else{
				   WinMult.document.writeln('<td class=tbvalore>'+fValue1[ii]+'</td>');
		    }
	   }
	}     
	WinMult.document.writeln('</tr>');	
    WinMult.document.writeln('</font></table>');
	WinMult.document.writeln('<div align="center">');
	WinMult.document.writeln('<table border="0" cellspacing="2" cellpadding="2"  bordercolor="Black" align="center">');	
	/*
	WinMult.document.writeln('<td><img src="'+appDir+'bottoni/zoom_in_page_1.gif" width="19" height="19" border="0" alt="Zoom su questo elemento" onmousedown="javascript:'+frame+'.singleZoomMultipla(' + featureIndex + ')"></td>');	
	WinMult.document.writeln('<td><img src="'+appDir+'bottoni/mostra.gif" width="19" height="19" border="0" alt="Mostra solo questo tematismo" onmousedown="javascript:parent.MapFrame.mostraUnico('+featureIndex+');"></td>');	
	WinMult.document.writeln('<td><img src="'+appDir+'bottoni/ripristina.gif" width="19" height="19" border="0" alt="Ripristina" onmousedown="javascript:parent.MapFrame.ripristina();"></td>');	
	*/
	WinMult.document.writeln('<td> <input type="button" class="button" value="Zoom su elemento" onmousedown="javascript:'+frame+'.singleZoomMultipla(' + featureIndex + ')"></td>');	
	WinMult.document.writeln('<td><input type="button" class="button" value="Mostra solo questo tematismo" onmousedown="javascript:'+frame+'.mostraUnico('+featureIndex+');"></td>');	
	WinMult.document.writeln('<td><input type="button" class="button" value="Ripristina" onmousedown="javascript:'+frame+'.ripristina();"></td>');	
	WinMult.document.writeln('</td></table>');
	
}

function addPointMultipla() {
   strPoly = "";
   strSingleZoom = "";
   var theString = '<LAYER type="acetate" name="acetate" id="acetate">\n'; 
   theString += '<OBJECT units="database">\n';
   theString += '      <POINT coords="'+clickPointX[0]+' '+clickPointY[0];
   theString += '">\n';
   theString += '      <RASTERMARKERSYMBOL overlap="false" url="'+path+'images/freccia_gialla.gif"  image="C:/ArcIMS/'+appDir+'images/freccia_gialla.gif" />\n';
   theString += '      </POINT>\n';
   theString += '  </OBJECT>\n';
   theString += '</LAYER>\n';
   //alert("addPoint"+theString);
   return theString;
}

function ripristina(){
  tuttoIlPiano();
  strLyrVisibile = strLyrVisibileMult; 
  strSingleZoom = "";
  left = leftTemp;
  right = rightTemp; 
  bottom = bottomTemp ; 
  top = topTemp ; 
  if (parent.tocFrame.document.location == parent.MapFrame.path + "toc.htm") {
	       aggiornaToc();
    }		   
  controlla_fattore();
}

function mostraUnico(i){

    strSingleZoom = addSingleZoomMultipla(i);
    left = startLeft;
    right = startRight;
    bottom = startBottom;
    top = startTop;
	
	for (var ii=0; ii<numLayerField; ii++){
	  var orderIndex = ordinaLayer(ii);
	  layerVisible[orderIndex]=false;
	}
	
	// devo fare vedere solo il tematismo matchato + lo sfondo
	layerVisible[ordinaLayer(i)]=true;
	//Inserire qui eventuali combinazioni
	/*layerVisible[8]=true;//ctr5000
    layerVisible[9]=true;//ctr25000
    layerVisible[10]=true;//centri e nuclei*/
	
	
	strLyrVisibile = ' <LAYERLIST> ';
	   for (var i=0; i<numLayerField ; i++){
	       var orderIndex = ordinaLayer(i);
           strLyrVisibile += '  <LAYERDEF id="'+layerID[orderIndex]+'" visible="'+layerVisible[orderIndex]+'" />';
       }
	   strLyrVisibile += '</LAYERLIST>';
	if (parent.tocFrame.document.location == parent.MapFrame.path + "toc.htm") {
	       aggiornaToc();
    }		   
  controlla_fattore();
}




function singleZoomMultipla(i){
    
	var t_larg = rightEnv[i] - leftEnv[i];
	var t_alt = topEnv[i] - bottomEnv[i];
	var larg_Margin = 0;
	var alt_Margin = 0;

	if(lyrThematization == "point") {
	
			var MapFactor = getMapScaleFactor();
			larg_Margin = MapFactor * larghezza / 2;
			alt_Margin = MapFactor * altezza / 2;
	} else {
		   larg_Margin = t_larg * selectMargin;
		   alt_Margin = t_alt * selectMargin; 
	}
    strSingleZoom = addSingleZoomMultipla(i);
	left = leftEnv[i] - larg_Margin/8; 
    right = rightEnv[i] + larg_Margin/8; 
    bottom = bottomEnv[i] - alt_Margin/8; 
    top = topEnv[i]  + alt_Margin/8;
	
	for (var ii=0; ii<numLayerField; ii++){
	  var orderIndex = ordinaLayer(ii);
	  layerVisible[orderIndex]=false;
	}
	// devo fare vedere solo il tematismo matchato + lo sfondo
	layerVisible[ordinaLayer(i)]=true;
	//Inserire qui eventuali combinazioni
	/*layerVisible[8]=true;//ctr5000
    layerVisible[9]=true;//ctr25000
    layerVisible[10]=true;//centri e nuclei*/
	
	
	
	strLyrVisibile = ' <LAYERLIST> ';
	   for (var i=0; i<numLayerField ; i++){
	       var orderIndex = ordinaLayer(i);
           strLyrVisibile += '  <LAYERDEF id="'+layerID[orderIndex]+'" visible="'+layerVisible[orderIndex]+'" />';
       }
	   strLyrVisibile += '</LAYERLIST>';
	if (parent.tocFrame.document.location == parent.MapFrame.path + "toc.htm") {
	       aggiornaToc();
    }		      
    controlla_fattore();

}

function addSingleZoomMultipla(i) {

    var theString = '<LAYER type="featureclass" name="zoom" id="zoom">\n'; 
    var ii = multLayerIndex[i];
	theString += '<DATASET fromlayer="' + layerID[ii] + '" />\n';
	theString += '<QUERY where="'+selectFieldID[i]+' = ' +selectPoints[i] + '"/>\n';
    theString += '<SIMPLERENDERER>\n';
	if (layerType[ii] == "line")
	     theString += lineThemaLight;
    if (layerType[ii] == "point")
	     theString += pointThemaLight ;
	if (layerType[ii] == "polygon")	 
	     theString += polygonThemaLight;
    
	theString += '</SIMPLERENDERER>\n';
    
    theString += '</LAYER>\n';
    //alert('addSingleZoom'+theString);
	
  return theString;
} 

function azzeratheReplyArray(){
 
  for(var i=0;i<theReplyArray.length;i++) {
       theReplyArray[i]="";
  }
  theReplyArray.length=0;
}
