var svgns   = "http://www.w3.org/2000/svg";
var xlinkns = "http://www.w3.org/1999/xlink";

//var tipoArea = "SVG";
//var tipoArea = "VML";
var tipoArea = "valoreDiDefault";	//viene cambiato a runtime leggendo un parametro dell'ini

var defs;
var rect;
var svgRoot;
var svgDocument;
var upnetRequired = false;		//indica se upnet ? installato e se la relativa form deve essere aggiornata con la geometria attiva

//var stoMuovendo = new Array();
//var puntoMosso = 0;

var documentoSVG;
var evtSVG;
var numeroPoligoniDisegnati = 0;
var numeroPolylineDisegnate = 0;
var numeroMultipointDisegnati = 0;

/*
function creaPunto(x, y) {
    var use1 = svgDocument.createElementNS(svgns, "use");
    use1.setAttributeNS(null, "x", x);
    use1.setAttributeNS(null, "y", y);
    use1.setAttributeNS(xlinkns, "xlink:href", "#rect");
    svgRoot.appendChild(use1);
}
*/


function disegnaAreaAXL(evt) {	 
	var allSVGPath = ' ';	
//	alert("mappaWidth= " + mappaWidth);
//	alert("mappaHeight= " + mappaHeight);	
	
	axl = getGeometriaAttiva();
	
	//svg disabilitato per il momento
	//var svgDocument = window.document.canvasSvg.getSVGDocument();
	var svgDocument;
	
	//var svgRoot = svgDocument.documentElement;	
	var svgRoot;
	
	if (tipoArea == "SVG") {	
		//cancello tutti i polygoni 
		alert("numero poligoni SVG gia' disegnati = " + numeroPoligoniDisegnati);
		for (var indicePol = 0; indicePol < numeroPoligoniDisegnati; indicePol++) {
			svgDocument.documentElement.removeChild(svgDocument.documentElement.getElementById('polygon'+indicePol));		
		}
		
		//alert("numero polyline SVG gia' disegnate = " + numeroPolylineDisegnate);
		for (var indicePolyline = 0; indicePolyline < numeroPolylineDisegnate; indicePolyline++) {
			svgDocument.documentElement.removeChild(svgDocument.documentElement.getElementById('polyline'+indicePolyline));
		}				
		numeroPolylineDisegnate = 0;
		
		//alert("numero multipoint SVG gia' disegnati = " + numeroMultipointDisegnati);
		for (var indiceMultipoint = 0; indiceMultipoint < numeroMultipointDisegnati; indiceMultipoint++) {
			svgDocument.documentElement.removeChild(svgDocument.documentElement.getElementById('multipoint'+indiceMultipoint));
		}			
	} else {
		//VML
		nascondiVML();
	}	
	
	if ((axl != null) && (axl !="") && (axl.length > 1) ) {
		//alert("axl = " + axl);
		//instantiate the W3C DOM Parser
		var parser = new DOMImplementation();
	
		//load the XML into the parser and get the DOMDocument
		var domDoc = parser.loadXML(axl);	
	
		//get the root node
		var docRoot = domDoc.getDocumentElement();	
		
		var elementoAXLGLOBO = docRoot.getElementsByTagName("AXLGLOBO").item(0);
		var elementoRESPONSE = elementoAXLGLOBO.getElementsByTagName("RESPONSE").item(0);		
		var elementoFEATURES = elementoRESPONSE.getElementsByTagName("FEATURES").item(0);			
		var numeroNodiFeature = elementoFEATURES.getElementsByTagName("FEATURE").getLength();			
		//alert("numero feature = " + numeroNodiFeature);
		
		//inizializzo la div con il codice VML		
		var testoVML = '';		
		testoVML += '<div id="areaSelezionata" STYLE="overflow:hidden">';		
		
		for (var indiceFeature = 0; indiceFeature < numeroNodiFeature; indiceFeature++) {
			//disegno ogni singola feature		
			
			var elementoFEATURE = elementoFEATURES.getElementsByTagName("FEATURE").item(indiceFeature);			
	
			
			//analizzo i nodi FIELDS/FIELD per costruire il tooltip delle geometria		
			var tooltipFeature = "tooltip di prova";
			
			//controllo se esiste il nodo FIELDS
			var numeroFields = elementoFEATURE.getElementsByTagName("FIELDS").getLength();
			if (numeroFields == 1) {
				var elementoFIELDS = elementoFEATURE.getElementsByTagName("FIELDS").item(0);
				var numeroField = elementoFIELDS.getElementsByTagName("FIELD").getLength();
				var comune="";
				var sezione="";
				var particella="";
				var foglio="";
				for (var indiceField = 0; indiceField < numeroField; indiceField++) {
					var elementFIELD = elementoFIELDS.getElementsByTagName("FIELD").item(indiceField);
					var attributo = elementFIELD.getAttributes().item(indiceField);
					//devo creare 2 funzioni per estrarre il nome ed il valore dell'attributo
					
					//da completare
					//nomeAttributo = getAttributeName(attributo);
					//valoreAttributo = getAttributoValue(attributo);			
					//if (nomeAttributo == "name") {				
					//}
					//alert("nomeAttributo = " + 
				}	
			
			}
			
			//////////////////////////////////
			// MULTIPOLYGON					//
			//////////////////////////////////				
			//cerco ogni polygon all'interno della feature
			var numeroPolygon = elementoFEATURE.getElementsByTagName("POLYGON").getLength();
			//alert("numero Polygon = " + numeroPolygon);
			var poligono = new Array();		
			for (var indicePolygon = 0; indicePolygon < numeroPolygon; indicePolygon++) {
				var elementoPOLYGON = elementoFEATURE.getElementsByTagName("POLYGON").item(indicePolygon);			
				var dStringSVG = "";	//stringa che comprende i punti di tutti i ring e tutti gli hole
				var dStringVML='<v:shape style="filter:alpha(opacity=70);position:absolute;width:1000;height:1000" strokecolor="blue" strokeweight="1" fillcolor="#00ffff"><v:path v="';		
				var numeroRing = elementoPOLYGON.getElementsByTagName("RING").getLength();		
				for (var indiceRing = 0; indiceRing < numeroRing; indiceRing++) {
					var pathStringSVG = "";	//stringa che comprende i punti di questo ring
					var pathStringVML = "";
					var elementoRING = elementoPOLYGON.getElementsByTagName("RING").item(indiceRing);			
					var numeroPoint = elementoRING.getElementsByTagName("POINT").getLength();					
					for (var indicePoint = 0; indicePoint < numeroPoint; indicePoint++) {
						var elementoPOINT = elementoRING.getElementsByTagName("POINT").item(indicePoint);			
						var attributoX = elementoPOINT.getAttributes().item(0).getXML();
						var attributoY = elementoPOINT.getAttributes().item(1).getXML();
						var xReale = attributoX.substring(3, ((attributoX.length)-1));
						var yReale = attributoY.substring(3, ((attributoY.length)-1));
	
						var coordinateMappa = null;
						coordinateMappa = converti(xReale, yReale);
						//la stringa SVG devo calcolarla in ogni caso
						if (pathStringSVG == "" ) {
							pathStringSVG = "M " + coordinateMappa[0] + ", " + coordinateMappa[1];
						} else {		
							pathStringSVG = pathStringSVG + " L " + coordinateMappa[0] + ", " + coordinateMappa[1];
						}
	
						if (tipoArea == "VML") {							
							if (pathStringVML == "" ) {
								//primo punto
								pathStringVML = "m " + coordinateMappa[0] + ", " + coordinateMappa[1];
							} else if (pathStringVML.indexOf("l") == -1)  {		
								//secondo punto
								pathStringVML = pathStringVML + " l " + coordinateMappa[0] + ", " + coordinateMappa[1];
							} else {
								//punti successivi
								pathStringVML = pathStringVML + ", " + coordinateMappa[0] + ", " + coordinateMappa[1];
							}
						} //fine aggiunta del punto corrente a pathStringVML
						
					} //fine ciclo sui punti delle'elemento RING
					
					//chiudo la stringa con i punti del RING
					pathStringSVG += " Z ";					
					//aggiungo a dString i punti del RING
					dStringSVG += pathStringSVG;				
					
					if (tipoArea == "VML") {
						pathStringVML += 	" x e";
						dStringVML += pathStringVML;					
					}
					
					//ciclo su ogni HOLE del RING attuale
					var numeroHole = elementoRING.getElementsByTagName("HOLE").getLength();		
					//alert("numeroHole = " + numeroHole);
					for (var indiceHole = 0; indiceHole < numeroHole; indiceHole++) {
						pathStringSVG = "";	
						pathStringVML = "";
						var elementoHOLE = elementoRING.getElementsByTagName("HOLE").item(indiceHole);			
						var numeroPoint = elementoHOLE.getElementsByTagName("POINT").getLength();					
						for (var indicePoint = 0; indicePoint < numeroPoint; indicePoint++) {				
							var elementoPOINT = elementoHOLE.getElementsByTagName("POINT").item(indicePoint);			
							var attributoX = elementoPOINT.getAttributes().item(0).getXML();
							var attributoY = elementoPOINT.getAttributes().item(1).getXML();
							var xReale = attributoX.substring(3, ((attributoX.length)-1));
							var yReale = attributoY.substring(3, ((attributoY.length)-1));
							var coordinateMappa = null;
							coordinateMappa = converti(xReale, yReale);
							if (pathStringSVG == "" ) {
								pathStringSVG = "M " + coordinateMappa[0] + ", " + coordinateMappa[1];
							} else {		
								pathStringSVG = pathStringSVG + " L " + coordinateMappa[0] + ", " + coordinateMappa[1];
							}
						}
						pathStringSVG += "Z ";
						
						//aggiungo i punti di questo HOLE
						////////////////////////////    da dove salta fuori pathRing ????????
						dStringSVG += pathRing;	
									
					} //fine ciclo su tutti gli hole
	
				} // fine ciclo su tutti i ring
					
				if (tipoArea == "SVG") {
					poligono[indicePolygon] = svgDocument.createElementNS(svgns, "path");			    
					poligono[indicePolygon].setAttributeNS(null, "d", dStringSVG);			    
					poligono[indicePolygon].setAttributeNS(null, "fill", "#00ffff");
					poligono[indicePolygon].setAttributeNS(null, "stroke", "blue");
					poligono[indicePolygon].setAttributeNS(null, "stroke-width", "1");
					poligono[indicePolygon].setAttributeNS(null, "opacity", "0.7");
					poligono[indicePolygon].setAttributeNS(null, "id", "polygon"+indicePolygon);			
					//poligono[indicePolygon].setAttributeNS(null, "onmousemove", "ShowTooltip(evt)"); //"showMsg('" + tooltipFeature + "')");  			
					//poligono[indicePolygon].setAttributeNS(null, "onmouseover", "ShowTooltip(evt)"); //"showMsg('" + tooltipFeature + "')");  						
					//poligono[indicePolygon].setAttributeNS(null, "onmouseout", "HideTooltip()"); 
					//poligono[indicePolygon].setAttributeNS(null, "title", "asdfasdfadsfasdfas");  						    
					svgDocument.documentElement.appendChild(poligono[indicePolygon]);			
				}
								
				if (allSVGPath.length < 2) {
					allSVGPath = "multipolygon@" + dStringSVG + "@";
				} else {
					allSVGPath += "multipolygon@" + dStringSVG+ "@";
				}
				dStringVML += '"/></v:shape>';				
				testoVML += dStringVML;
				
			}  //fine ciclo sui polygon
			numeroPoligoniDisegnati = numeroPolygon;
			//alert("numeroPoligoniDisegnati = " + numeroPoligoniDisegnati);			

			//alert("dopo multipolygon: " + testoVML);

			//////////////////////////////////
			// POLYLINE 					//
			//////////////////////////////////	
			
			var polylineStringSVG = "";
			var polylineStringVML = "";
			///////////var indicePathGlobale = 0; //numeroPathTotali + indicePathDiPolylineCorrente;			
			//cerco ogni polyline all'interno della feature
			var numeroPolyline = elementoFEATURE.getElementsByTagName("POLYLINE").getLength();						
			var polyline = new Array();
			////////////var numeroPathTotali = 0;	//ogni path va disegnato come oggetto singolo		
			for (var indicePolyline = 0; indicePolyline < numeroPolyline; indicePolyline++) {
				polylineStringSVG += '<v:path v="';
				var elementoPOLYLINE = elementoFEATURE.getElementsByTagName("POLYLINE").item(indicePolyline);			
				var numeroPath = elementoPOLYLINE.getElementsByTagName("PATH").getLength();						
				var pathStringSVG = "";
				for (var indicePathDiPolylineCorrente = 0; indicePathDiPolylineCorrente < numeroPath; indicePathDiPolylineCorrente++) {												
					var elementoPATH = elementoPOLYLINE.getElementsByTagName("PATH").item(indicePathDiPolylineCorrente);			
					var numeroPoint = elementoPATH.getElementsByTagName("POINT").getLength();					
					var singlePathStringSVG = "";
					var singlePathStringVML = '<v:polyline strokecolor="blue" strokeweight="2" filled="false" points="';
					for (var indicePoint = 0; indicePoint < numeroPoint; indicePoint++) {
						var elementoPOINT = elementoPATH.getElementsByTagName("POINT").item(indicePoint);			
						var attributoX = elementoPOINT.getAttributes().item(0).getXML();
						var attributoY = elementoPOINT.getAttributes().item(1).getXML();
						var xReale = attributoX.substring(3, ((attributoX.length)-1));
						var yReale = attributoY.substring(3, ((attributoY.length)-1));
						/*xMappa = convertiX (xReale);	
						yMappa = convertiY (yReale); */
						var coordinateMappa = null;
						coordinateMappa = converti(xReale, yReale);
						
						//if (tipoArea == "SVG") {						
						if (singlePathStringSVG == "" ) {
							singlePathStringSVG = "M " + coordinateMappa[0] + ", " + coordinateMappa[1];
						} else {		
							singlePathStringSVG = singlePathStringSVG + " L " + coordinateMappa[0] + ", " + coordinateMappa[1];
						}							
						
						if (tipoArea == "VML") {	
							singlePathStringVML += 	coordinateMappa[0] + "," + coordinateMappa[1] + " ";									
						} //fine aggiunta del punto corrente a pathString
					} //fine ciclo sui point di un PATH
					singlePathStringVML += '"></v:polyline>';
					
					testoVML += singlePathStringVML;
					if (allSVGPath == "") {
						allSVGPath = "POLYLINE@" + singlePathStringSVG + "@";
					} else {
						allSVGPath += "POLYLINE@" + singlePathStringSVG + "@";
					}
				    
				    //var indice = numeroPathTotali -1;
				    
					if 	(tipoArea == "SVG") {
						polyline[numeroPolylineDisegnate] = svgDocument.createElementNS(svgns, "path");			    
					    polyline[numeroPolylineDisegnate].setAttributeNS(null, "d", singlePathStringSVG);			    
					    polyline[numeroPolylineDisegnate].setAttributeNS(null, "fill", "none");
					    polyline[numeroPolylineDisegnate].setAttributeNS(null, "stroke", "blue");
					    polyline[numeroPolylineDisegnate].setAttributeNS(null, "stroke-width", "2");					    
					    polyline[numeroPolylineDisegnate].setAttributeNS(null, "id", "polyline" + numeroPolylineDisegnate);
					    svgDocument.documentElement.appendChild(polyline[numeroPolylineDisegnate]);									
					    //var pippo = svgDocument.documentElement.getElementById("prova").nodeValue;
				    	//document.carotaggio.coordinateSVG.value = pippo;
					    //alert("b3");
					}
					numeroPolylineDisegnate++;
				}  //fine ciclo sui PATH
				///////////numeroPathTotali += numeroPath;
				//alert("pathString " + pathString);
				
				////polylineStringSVG += pathStringSVG;
				////polylineStringVML += pathStringVML;				
				//alert("polylineString = " +polylineString);
				
			}  //fine ciclo sulle polyline
			//alert(polylineString);
			
			//numeroPolylineDisegnate = numeroPolyline;
			//numeroPolylineDisegnate = numeroPathTotali;
				
				
	
			//////////////////////////////////
			// MULTIPOINT					//
			//////////////////////////////////	
			//cerco ogni multiPoint all'interno della feature
			dStringSVG = "";
			dStringVML = "";
			var numeroMultipoint = elementoFEATURE.getElementsByTagName("MULTIPOINT").getLength();			
			//alert("numeroMultipoint: " + numeroMultipoint);
			var multipoint = new Array();		
			for (var indiceMultipoint = 0; indiceMultipoint < numeroMultipoint; indiceMultipoint++) {
				var elementoMULTIPOINT = elementoFEATURE.getElementsByTagName("MULTIPOINT").item(indiceMultipoint);			
				//var pointsStringSVG = '<v:path v="';
				var pointsStringSVG = '';
				var pointsStringVML = '<v:shape style="filter:alpha(opacity=70);position:ABSOLUTE;width:1000;height:1000" strokecolor="blue" strokeweight="1" fillcolor="#00ffff"><v:path v="';				
				//alert("pointsStringVML " + pointsStringVML);
				
				var numeroPoint = elementoMULTIPOINT.getElementsByTagName("POINT").getLength();										
				for (var indicePoint = 0; indicePoint < numeroPoint; indicePoint++) {
					var elementoPOINT = elementoMULTIPOINT.getElementsByTagName("POINT").item(indicePoint);			
					var attributoX = elementoPOINT.getAttributes().item(0).getXML();
					var attributoY = elementoPOINT.getAttributes().item(1).getXML();
					var xReale = attributoX.substring(3, ((attributoX.length)-1));			
					var yReale = attributoY.substring(3, ((attributoY.length)-1));
					/*xMappa = convertiX (xReale);	
					yMappa = convertiY (yReale);*/
							
					var coordinateMappa = null;
					coordinateMappa = converti(xReale, yReale);											

					pointsStringSVG += "M " + (coordinateMappa[0] - 3) + ", " + (coordinateMappa[1] - 3) ;
					pointsStringSVG += " L " + (coordinateMappa[0] + 3) + ", " + (coordinateMappa[1] - 3) ;					
					pointsStringSVG += " L " + (coordinateMappa[0] + 3) + ", " + (coordinateMappa[1] + 3) ;
					pointsStringSVG += " L " + (coordinateMappa[0] - 3) + ", " + (coordinateMappa[1] + 3) + " ";
					
					if (tipoArea == "VML") {					
						pointsStringVML += "M " + (coordinateMappa[0] - 3) + ", " + (coordinateMappa[1] - 3) ;
						pointsStringVML += " L " + (coordinateMappa[0] + 3) + ", " + (coordinateMappa[1] - 3) ;					
						pointsStringVML += ", " + (coordinateMappa[0] + 3) + ", " + (coordinateMappa[1] + 3) ;
						pointsStringVML += ", " + (coordinateMappa[0] - 3) + ", " + (coordinateMappa[1] + 3) + " ";										
					}
				} //fine ciclo sui punti

				//chiusura della stringa dei punti
				pointsStringSVG += 'Z ';	
				dStringSVG += pointsStringSVG;				
				
				if (tipoArea == "VML") {
					pointsStringVML += 'x e">';					
					dStringVML += pointsStringVML + '</v:shape>';	
				}

				if (tipoArea == "SVG") {				
					//alert("dStringSVG = " + dStringSVG);	
					//alert(indiceMultipoint);			
					multipoint[indiceMultipoint] = svgDocument.createElementNS(svgns, "path");			    
					multipoint[indiceMultipoint].setAttributeNS(null, "d", dStringSVG);			    
					//multipoint[indiceMultipoint].setAttributeNS(null, "d", "M 300, 300 L 330, 330 L 350, 300 Z");			    
//																			M 335, 299 L 341, 299 L 341, 305 L 335, 305 Z 
					multipoint[indiceMultipoint].setAttributeNS(null, "fill", "#00ffff");
					multipoint[indiceMultipoint].setAttributeNS(null, "stroke", "blue");
					multipoint[indiceMultipoint].setAttributeNS(null, "stroke-width", "1");
					multipoint[indiceMultipoint].setAttributeNS(null, "opacity", "0.7");
					multipoint[indiceMultipoint].setAttributeNS(null, "id", "multipoint"+indiceMultipoint);			
					svgDocument.documentElement.appendChild(multipoint[indiceMultipoint]);							
				}
				
			}  //fine ciclo sui MULTIPOINT
			
			if(numeroMultipoint > 0) {
				if (allSVGPath.length < 2) {
					allSVGPath = "MULTIPOINT@" + dStringSVG + "@";
				} else {	
					allSVGPath += "MULTIPOINT@" + dStringSVG + "@";
				}				
			}
			
			if (tipoArea == "VML") {			
				testoVML += dStringVML;	
			}		
			numeroMultipointDisegnati = numeroMultipoint;
			
		}  //fine ciclo su tutte le feature

		//testoVML += dStringVML; + "</DIV>";	
		if (tipoArea == "VML") {			
			testoVML += "</DIV>";	

			//dopo aver ciclato su tutte le feature, chiudo l'elemento shape e aggiungo la DIV alla pagina jsp
			//alert("testoVML = " + testoVML);
			this.theMap.insertAdjacentHTML('afterBegin', testoVML);			
		}			
	} 	
	
	if (upnetRequired == true) {
		document.carotaggio.coordinateSVG.value = allSVGPath;		
	}

	
} //fine funzione disegnaAXL


//////////////////////////////////////////////////////////////////////////////////
//					FUNZIONI DI EDITING DEI PUNTI E DEI POLIGONI				//
//////////////////////////////////////////////////////////////////////////////////


function premoPunto(indicePunto) {
	stoMuovendo[indicePunto] = true;
	puntoMosso = indicePunto;	
}


/*
function muovoPunto(evt) {
//alert("puntoMosso = " + puntoMosso);
	if (stoMuovendo[puntoMosso]) {		
		var svgDocument = evt.getTarget().ownerDocument;
		
		var myQua = svgDocument.getElementById("qua"+puntoMosso);		
		//myQua.setAttributeNS(null, "style", "fill: red");
		var deltaX = (eval(myQua.getAttribute("x"))) - evt.clientX;
		var deltaY = (eval(myQua.getAttribute("y"))) - evt.clientX;
		
//		myQua.setAttributeNS(null, "x", evt.clientX - deltaX);
//		myQua.setAttributeNS(null, "y", evt.clientY - deltaY);
		myQua.setAttributeNS(null, "x", evt.clientX - 10);
		myQua.setAttributeNS(null, "y", evt.clientY - 10);
		
		
		
		//var myBordo = svgDocument.getElementById("bordo");		
		//myBordo.setAttributeNS(null, "stroke", "black");		
		
		//alert("ho cambiato il colore di qua" + puntoMosso);

	}
}

function rilascioPunto(indicePunto) {
	stoMuovendo[indicePunto] = false;
	//alert("Ho rilasciato il quadrato " + indicePunto);
}
*/
	
/*	
//da cancellare	
function convertiX(xReale) {
	xReale = xReale.replace(',', '.');
	xValutato = eval(xReale);
	//var xM = (xValutato / 100000)|0 ;
	var xM = xValutato - 49500;
 	return xM;
}


//da cancellare
function convertiY(yReale) {
 	yReale = yReale.replace(',', '.');
	yValutato = eval(yReale);
	//var yM = (yValutato / 100000)|0 ;
	var yM = yValutato - 59800 ;
 	return yM;
}		
*/

function converti(xReale, yReale) {
	var coordinate = null;
	var g_extent = mapGetExtent();
	coordinate = mapGetCoordinateMonitor(xReale, yReale, mappaWidth, mappaHeight, g_extent);		
	return coordinate;
}


//serve a settare se si usa SVG o VML
function setTipoArea(nuovoTipoArea) {		
	if ((nuovoTipoArea == "SVG") || (nuovoTipoArea == "VML"))  {		
		tipoArea = nuovoTipoArea;
	} else {
		alert("E' stata settata un tipo di area non valido: " + nuovoTipoArea + ". I valori validi sono 'SVG' e 'VML'.");
	}	
}

function setUpnetRequired(upnet) {	
	upnetRequired = upnet;
}


//setta l'axl di una o piu' features (richiamata per esempio da catviewRicercaParticelle)
//function setAXLFeatures(axl) {
//	document.carotaggio.axlGeometria.value = axl;
//} 
