
// Variabili per la selezione
    var maxFeaturesReturned = 25;
    var nPunti = 0;
    var strPoly = "";
	var strSingleZoom = ""; 
//Variabile per il margine di una selezione
    var selectMargin = 0.2;
// Variabili per il rendering	
	var lineThema = '<SIMPLELINESYMBOL transparency="0.5" type="solid" width="3" captype="round" jointype="round" color="255,255,0" />\n';
    var pointThema = ' <SIMPLEMARKERSYMBOL color="255,255,0" width="10" />\n' ;
	var polygonThema = ' <SIMPLEPOLYGONSYMBOL fillcolor="255,255,0" filltype="solid" transparency="0.2" boundarycolor="255,255,0" />\n';

    var lineThemaLight = '<SIMPLELINESYMBOL transparency="1.0" type="solid" width="3" captype="round" jointype="round" color="255,0,0" />\n';
    var pointThemaLight = ' <SIMPLEMARKERSYMBOL color="255,0,0" width="10" />\n' ;
	var polygonThemaLight = ' <SIMPLEPOLYGONSYMBOL fillcolor="255,0,0" filltype="fdiagonal"  fillinterval ="5" transparency="1.0" boundarycolor="255,0,0" />\n';

// Variabile per l'attivazione della finestra dei risultati	
    var resultsWindow = false;
	var apriHelpSingleSelect=true;
	//salvataggio scala selezione layer singolo
	var LastScale=0;
	var LastTop=0;
	var LastLeft=0;
	var LastRight=0;
	var LastBottom=0;
	var LastTipo="";
	var LastSelected="";
// Calcola le coords territoriali e le invia a writeXML('Polygon') inserendo la stringa strPoly
function arrayrett(primoX,primoY,secondoX,secondoY) {

getMapXY(primoX,primoY);
var T_primoX = mapX; 
var T_primoY = mapY; 

getMapXY(secondoX,secondoY);
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;

strPoly = addPolygon();

	
//Richiesta degli elementi selezionati
//startMapLoading();
startDataLoading();
beginRecord = 1;
var strXML = writeXML('Polygon');
sendToServer(imsURL + CustomService,strXML,3);

}

function pointSelection(primoX,primoY,secondoX,secondoY) {

getMapXY(primoX,primoY);
var T_primoX = mapX; 
var T_primoY = mapY; 

getMapXY(secondoX,secondoY);
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;
strPoly = addPoint();

	
//Richiesta degli elementi selezionati
//startMapLoading();
startDataLoading();
beginRecord = 1;
var strXML = writeXML('Polygon');
sendToServer(imsURL + CustomService,strXML,3);

}

function addPolygon() {
    delSelection();
    var theString = '<LAYER type="acetate" name="acetate" id="acetate">\n'; 
    theString += '<OBJECT units="database">\n';
    theString += '      <LINE coords="';
    
    for (var i=0;i<nPunti;i++){
			theString += clickPointX[i] + ' ' + clickPointY[i];
		    theString += ';';
    }
    if(!useKm) theString += clickPointX[0] + ' ' + clickPointY[0];
				
    theString += '">\n';
    theString += '<SIMPLELINESYMBOL type="solid" color="0,0,255" width="2"  />\n';
    theString += '      </LINE>\n';
    
    theString += '  </OBJECT>\n';
    theString += '</LAYER>\n';
    
    if(!useKm) theString +=  addSelection();
    // alert(theString);
    return theString;
}



function addPoint() {
   delSelection();
   if (layerType[activeLayerIndex] != "point") { 
         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 += '<SIMPLEMARKERSYMBOL color="0,0,255" width="9" type="triangle"  />\n';
         theString += '      </POINT>\n';
         theString += '  </OBJECT>\n';
         theString += '</LAYER>\n';
         if(!useKm) theString +=  addSelection();
   }else{
	     if(!useKm) var theString =  addSelection();
   }	 
   //alert("addPoint"+theString);
 
   return theString;
}




// funzione che riempie la stringa che disegna gli eventuali elementi selezionati  

function addSelection() {
var theString = '<LAYER type="featureclass" name="selezione" id="selezione">\n'; 
    theString += '<DATASET fromlayer="' + ID + '" />\n';
    theString += '<SPATIALQUERY>\n';
    theString += '<SPATIALFILTER relation="area_intersection">\n';
    theString += '<POLYGON>';
    theString += '<RING>\n';
       for (var i=0;i<nPunti;i++){
		    theString += '<POINT x="';
			theString += clickPointX[i] + '" y="' + clickPointY[i];
			theString += '" />\n';
       }
    theString += '<POINT x="';
	theString += clickPointX[0] + '" y="' + clickPointY[0];
	theString += '" />\n';
			
	theString += '</RING>';			
    theString += '</POLYGON>\n';
    theString += '</SPATIALFILTER>\n';
    theString += '</SPATIALQUERY>\n';
    theString += '<SIMPLERENDERER>\n';
	switch (lyrThematization){
	   case "line" :
	            theString += lineThema;
	   case "point" :
	            theString += pointThema;
	   case "polygon" :
	            theString += polygonThema;
	}
	
	theString += '</SIMPLERENDERER>\n';
    
    theString += '</LAYER>\n';
    
  return theString;
}



//Svuota tutta le variabili globali che selezionano.
function delSelection() {
    strPoly = "";
    strSingleZoom = "";
	strPointMultipla = "";
	strStradario="";
	//alert(strStradario);
	useMultiplaStampa = false;
	//alert("disattivaStradario");
	disattivaStradario();
	//alert("disattivaStradario");
    parent.textFrame.location = path+'blank.htm';
}


//Memorizzazione dello sviluppo degli elementi
//in 4 array (env_minx,env_miny,env_maxx,env_maxy)
function memEnvelope(theR,num) {
    theString = theR.toUpperCase();
	var tempString = "";
	var startpos;
	var endpos;
	
	//Get the start of the ENVELOPE element
	var pos = theString.indexOf("ENVELOPE",startpos);
	var successivo = false;
	if (pos!=-1) {
		for(var i=0;i<num;i++) {
		if (successivo) pos = theString.indexOf("ENVELOPE",startpos); else successivo = true;
		pos = pos + 8;
		
					//Extract minx
					startpos = theString.indexOf("MINX=",pos);
					startpos += 6;
					var endpos = theString.indexOf(dQuote,startpos);
					tempString = theString.substring(startpos,endpos);
					leftEnv[i] = parseFloat(tempString); 
					
					//Extract miny
					startpos = theString.indexOf("MINY=",pos);
					startpos += 6;
					endpos = theString.indexOf(dQuote,startpos);
					tempString = theString.substring(startpos,endpos);
					bottomEnv[i] = parseFloat(tempString); 
		
					//Extract maxx
					startpos = theString.indexOf("MAXX=",pos);
					startpos += 6;
					endpos = theString.indexOf(dQuote,startpos);
					tempString = theString.substring(startpos,endpos);
					rightEnv[i] = parseFloat(tempString); 
		
					//Extract maxy
					startpos = theString.indexOf("MAXY=",pos);
					startpos += 6;
					endpos = theString.indexOf(dQuote,startpos);
					tempString = theString.substring(startpos,endpos);
					topEnv[i] = parseFloat(tempString); 
		}
	} else {
		alert(theR);
		}
	

}


//visualizza la risposta
function displayData(risposta,num) {
	//alert(risposta);
	//alert(num);
	stillMore = false;
	if(beginRecord==1) stillPrevious = false;
	if (num == featureLimit){
	     stillMore = true;
	}
	var pos = 1
	xmlEndPos = 1
	
	if (resultsWindow){
	      var Win1 = window.open("","QueryWindow","width=600,height=400,scrollbars=yes,resizable=yes");
	      var frame = 'opener.parent.MapFrame';
	}else{
	      var Win1 = parent.textFrame;
		  var frame = 'parent.MapFrame';
	}	  	  
	Win1.document.open();
	Win1.document.writeln('<html><head><title>Elementi selezionati</title><LINK href="'+path+'PianoStrutturale.css" type=text/css rel=stylesheet>');
	Win1.document.writeln('</head>');
	Win1.document.writeln('<body onload="window.focus()">');
		Win1.document.writeln('<DIV align="center"><br><font class="grassettonomeLayer">');
	Win1.document.writeln(layerName[activeLayerIndex].toLowerCase() + '</font>');
	Win1.document.writeln('<br>');
	
	
	var fieldValuesTemp = parseRecordString(risposta,pos); 
	var fName1 = getFieldNames(fieldValuesTemp);
	if (useAlias) {
	      var fAlias1 = loadAlias(fName1,activeLayerIndex);
	}
		
	Win1.document.writeln('<table border="1" bordercolor="White" cellspacing="2" cellpadding="1" align="center">');
	Win1.document.writeln('<tr><td class=tbnome>Zoom</td>');
	
	for (var i=0; i<fName1.length; i++){
	  if((fName1[i] != "#SHAPE#")&&(fName1[i] != "#ID#")){
	     if (useAlias){
	         Win1.document.writeln('<td  class=tbnome>'+ fAlias1[i]+'</td>');
	     }else{
	         Win1.document.writeln('<td class=tbnome>'+ fName1[i].toLowerCase()+'</td>');
	     }
	  } 	
	}
	
	Win1.document.writeln('</tr>');	
	
	//alert(fName1+'-------'+fValue1);
	
	for (var i=0;i<num;i++) {
	
	        var fieldValues = parseRecordString(risposta,pos); 
			//alert("fieldValues"+fieldValues);
	        var fValue1 = getFieldValues(fieldValues);
			pos = xmlEndPos;
			
			// Inserisco i valori dei campi #ID# o OBJECTID 
			selectPoints[i] = getIdValue(fName1,fValue1);
			
			// Inserisco i valore "SHAPE" o "SDE"
			selectFieldID[i] = getFieldID(fName1);
			
		    Win1.document.writeln('<tr>');
			
			Win1.document.writeln('<td class=tbvalore><a href="javascript:'+frame+'.singleZoom(' + i + ')" >');
			Win1.document.write(i+beginRecord+ '.');
			Win1.document.writeln('</a></td>');
			for (var ii=0; ii<fName1.length; ii++){
			  if((fName1[ii] != "#SHAPE#")&&(fName1[ii] != "#ID#")){
			     if(fName1[ii]=="COD_NTA"){
				   if(fValue1[ii]=="&nbsp;") Win1.document.writeln('<td class=tbvalore>Non prevista dal Piano Strutt.</td>');
				   else Win1.document.writeln('<td class=tbvalore><a target="new" href="'+path+fValue1[ii]+'">Leggi Norma</a></td>');
				 
}else{
				   Win1.document.writeln('<td class=tbvalore>'+fValue1[ii]+'</td>');
			     }
			  }	 
			}     
			Win1.document.writeln('</tr>');	
    }	
	//alert('selectPoints='+selectPoints);
	//alert('selectFieldID='+selectFieldID);
		
	Win1.document.writeln('</table>');
	if ( (LastSelected!='')){
		Win1.document.writeln('<table border="0" cellspacing="2" cellpadding="2"  bordercolor="Black" align="center">');	
		Win1.document.writeln('<td><input type="button" class="button" value="Ripristina" onmousedown="javascript:'+frame+'.ripristinaSelezione();"></td>');	
		Win1.document.writeln('</td></table>');}
	
	Win1.document.writeln('<P>');
	if (stillPrevious){
	     Win1.document.writeln('<INPUT type=button class="button" value="Precedenti elementi" onclick="'+frame+'.addPrevious('+num+');"  > ');
	} 
	if (stillMore){
	     Win1.document.writeln('<INPUT type=button class="button" value="Successivi elementi" onclick="'+frame+'.addMore();"  > ');
	
	}
	Win1.document.writeln('</DIV>');
	Win1.document.writeln('</body></html>');
	Win1.document.close();
		
}

function addMore(){
     stillPrevious = true;
	 beginRecord = beginRecord + featureLimit;
	 startDataLoading();
	 //alert(toponimo+'---'+beginRecord);
	 if (toponimo!=""){
	   cercaToponimo(toponimo);
	 }else{
	   var strXML = writeXML('Polygon');
	   sendToServer(imsURL + CustomService,strXML,3);
	 }
	
}

function addPrevious(prec){
     //alert(prec);
	 stillMore = true;
	 beginRecord -= (featureLimit);
	 if(beginRecord==1) stillPrevious = false;
	 startDataLoading();
	 if (toponimo!=""){
	   cercaToponimo(toponimo);
	 }else{
	   var strXML = writeXML('Polygon');
	   sendToServer(imsURL + CustomService,strXML,3);
	 }
	 
	
}




function singleZoom(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") {
	
			larg_Margin = converti(10000) * larghezza / 2;
			alt_Margin = converti(10000) * altezza / 2;
			//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 = addSingleZoom(i);
    //alert('strSingleZoom'+strSingleZoom);
    left = leftEnv[i] - larg_Margin; 
    right = rightEnv[i] + larg_Margin; 
    bottom = bottomEnv[i] - alt_Margin; 
    top = topEnv[i]  + alt_Margin;
	
    controlla_fattore();

}


function addSingleZoom(i) {

    //alert(useMultipla);
	var theString = '<LAYER type="featureclass" name="zoom" id="zoom">\n'; 
    theString += '<DATASET fromlayer="' + ID + '" />\n';
    theString += '<QUERY where="'+selectFieldID[i]+' = ' +selectPoints[i] + '"/>\n';
    theString += '<SIMPLERENDERER>\n';
	//alert(lyrThematization);
	if (lyrThematization == "line")
	     theString += lineThemaLight;
    if (lyrThematization == "point")
	     theString += pointThemaLight ;
	if (lyrThematization == "polygon")	 
	     theString += polygonThemaLight;
    
	theString += '</SIMPLERENDERER>\n';
    
    theString += '</LAYER>\n';
    //alert('addSingleZoom'+theString);
	
  return theString;


} 
function ripristinaSelezione(){
	var numSel = LastSelected;
	parent.selectFrame.document.forms[0].elements[0].selectedIndex=LastSelected;
	var selOpt=parent.selectFrame.document.forms[0].elements[0].options[numSel].value;

	for(var i=0;i<numLayerField;i++){
		  parent.MapFrame.layerVisible[i] = false;
	 }
	layerVisible[selOpt] = true;
	aggiornaToc();

	 strLyrVisibile = ' <LAYERLIST> ';
    for (var i=0; i<numLayerField ; i++){
		 var orderIndex = ordinaLayer(i);
		 strLyrVisibile += '  <LAYERDEF id="'+layerID[orderIndex]+'" visible="'+layerVisible[orderIndex]+'" />';
    }
    strLyrVisibile += '</LAYERLIST>';
	
	parent.MapFrame.setActiveLayer(selOpt);
	parent.toolFrame.setToolPic(LastTipo);
	parent.toolFrame.document.form_scala.text_scala.value=LastScale;
	top=LastTop;
	left=LastLeft;
	right=LastRight;
	bottom=LastBottom;
	var strXML = writeXML('Polygon');
	sendToServer(imsURL + CustomService,strXML,3);
	//}else{
	//	alert('E\' stato modificato il tematismo relativo alla ricerca fatta.\nRisulta impossibile ripristinare la mappa.');
	//}
}
//end cristina


