

// Definizione oggetti Applicazione
function rule(name,url){
	this.name=name;
	this.url=url;
} 

function layer(titolo,name,url,tipo,legImg,legTipo,queryable,infoOutput,infoUrl,sldUrl,scMin,scMax,ordine,stato,trasp,numClassi,rules,livHidden,tipoGeom,styleCurrent,grouped,uid,col_label,des_label,filtro,logoImg,urlWmsEcw,nameWmsEcw,srs,getFeatureInfoUrl){
	this.titolo=titolo;
	this.name=name;
	this.url=url;
	this.tipo=tipo;
	this.legImg=legImg;	
	this.legTipo=legTipo;
	this.queryable=queryable;
	this.infoOutput=infoOutput;
	this.infoUrl=infoUrl;
	this.sldUrl=sldUrl;
	this.scMin=scMin;
	this.scMax=scMax;
	this.ordine=ordine;
	this.stato=stato;
	this.trasp=trasp;
	this.numClassi=numClassi;
	this.rules=rules;
	this.livHidden=livHidden;
	this.tipoGeom=tipoGeom;
	this.styleCurrent=styleCurrent;
	this.grouped=grouped;
	this.uid=uid;
	this.col_label=col_label;
	this.des_label=des_label;
	this.filtro=filtro;
	this.logoImg=logoImg;
	this.urlWmsEcw=urlWmsEcw;
	this.nameWmsEcw=nameWmsEcw;
	this.srs=srs;
	this.getFeatureInfoUrl=getFeatureInfoUrl;
} 

function param(name,value){
	this.name=name;
	this.value=value;
} 

listaParam = new Array();

// definizione variabili
var livAttivo=-1;
var indiceClassi=0;
var bottoneAttivo='pan';
var flagInit=0;
var tMapTimer=null;
var strScala=0;
var numClick=0;
var numDiv=0;
var dWorldTLXPre=0;
var dWorldTLYPre=0;
var dWorldBRXPre=0;
var dWorldBRYPre=0;
var livFind2='';
var livFind2SldUrl='';
var livInfo='';
var livInfoSldUrl='';
var flgAttesaLiv=0;
var percentComplete=0;
//clickY = new Array();
clickXWorld = new Array();
clickYWorld = new Array();
var shiftGBtoSPHx = 40;
var shiftGBtoSPHy = 230;


function livFind(titolo,url){
	this.titolo=titolo;
	this.url=url;
} 
listaLivFind = new Array();


function livSelezione(titolo,url){
	this.titolo=titolo;
	this.url=url;
} 

listaLivSelezione = new Array();

var altezzaLogo=-1;

var widthBase;
var heightBase;

// array per memorizzare l'history degli zoom e relativo indice
function storiaZoom(TLX,TLY,BRX,BRY){
		this.TLX=TLX;
		this.TLY=TLY;
		this.BRX=BRX;
		this.BRY=BRY;
}
listaStoriaZoom = new Array();
var indiceStoriaZoom = 0; 
var flagScorriZoom = false;

// definizione variabili globali per versione OpenLayers
var SRS_OL = 'EPSG:900913';
var map = null;
var vectorLayer = null;
var mappaIngombroBboxGB = null;
var mappaIngombroBboxArrayGB = null;
var maxZoomLevel = null;
var flagSfondoVisibile = 0;
//-----------------------------------------------------------------------------------------	

if (parseFloat(navigator.appVersion) < 4.0) {
	document.location = '/ecwplugins/sorry.htm';
}
//ECWCheckPlugin();
// There is a major bug in Mozilla where the onLoad event for the body gets called before the
// plugins on the page are loaded, this seems to work around it.
var tOnLoadTimer = null;

function onUnloadCB() {
	if(tipoMappa!='OL')
		deleteCookie('NCSPluginInstallMethod');
}

// Funzione di caricamento viene eseguita sull'onLoad del BODY e chiama inizializza
function onLoadCB() {
//alert(document.getElementById("mapConfig").value);

	if(tipoMappa!='OL')
		tOnLoadTimer = setTimeout('inizializzaECW()', 500);
	else
		inizializzaOL();

	
}

function timedRefresh() {
	alert('ciao');
}

function bboxTransform(oldBounds,fromEPSG,toEPSG) 
{
// è necessario un aggiustamento delle coordinate nella trasformazione (no matrice)

	oldBounds.transform(new OpenLayers.Projection(fromEPSG), new OpenLayers.Projection(toEPSG));
    bbox = oldBounds.toBBOX();
	bboxArray=bbox.split(',');
    if ((fromEPSG=='EPSG:3003')&&(toEPSG=='EPSG:900913'))
    {
	    bboxArray[0] = parseInt(bboxArray[0])-parseInt(shiftGBtoSPHx);
	    bboxArray[2] = parseInt(bboxArray[2])-parseInt(shiftGBtoSPHx);
	    bboxArray[1] = parseInt(bboxArray[1])+parseInt(shiftGBtoSPHy);
	    bboxArray[3] = parseInt(bboxArray[3])+parseInt(shiftGBtoSPHy);
    }
    if ((fromEPSG=='EPSG:900913')&&(toEPSG=='EPSG:3003'))
    {
	    bboxArray[0] = parseInt(bboxArray[0])+parseInt(shiftGBtoSPHx);
	    bboxArray[2] = parseInt(bboxArray[2])+parseInt(shiftGBtoSPHx);
	    bboxArray[1] = parseInt(bboxArray[1])-parseInt(shiftGBtoSPHy);
	    bboxArray[3] = parseInt(bboxArray[3])-parseInt(shiftGBtoSPHy);
    }   
    bbox=bboxArray[0]+","+bboxArray[1]+","+bboxArray[2]+","+bboxArray[3]
    var newBounds = OpenLayers.Bounds.fromString(bbox)
    return newBounds;

}

// Gestisce l'inizializzazione del sistema nel caso di mappa tipo OpenLayers
function inizializzaOL() 
{
// setto i parametri comuni tra versione ECW e versione OpenLayers
	setParametri();

// memorizzo l'ingombro in GB prima di convertire i BBox in SHP
	mappaIngombroBboxGB = mappaIngombroBbox;
	mappaIngombroBboxArrayGB=mappaIngombroBboxGB.split(',');
// converto i bounding bbox da Gauss-Boaga a Sferico Mercatore
	var bounds = OpenLayers.Bounds.fromString(bbox)
    bounds = bboxTransform(bounds,'EPSG:3003','EPSG:900913');
    bbox = bounds.toBBOX();
	bboxArray=bbox.split(',');
// 
	var ov_bounds = OpenLayers.Bounds.fromString(ov_bbox)
	ov_bounds.transform(new OpenLayers.Projection('EPSG:3003'), new OpenLayers.Projection('EPSG:900913'));
	ov_bbox = ov_bounds.toBBOX();
	ov_bboxArray=ov_bbox.split(',');
//
	var mappaIngombro_bounds = OpenLayers.Bounds.fromString(mappaIngombroBbox)
	mappaIngombro_bounds.transform(new OpenLayers.Projection('EPSG:3003'), new OpenLayers.Projection('EPSG:900913'));
	mappaIngombroBbox = mappaIngombro_bounds.toBBOX();
	mappaIngombroBboxArray=mappaIngombroBbox.split(',');
//

/* 
	var ov_bounds = OpenLayers.Bounds.fromString(ov_bbox)
    ov_bounds = bboxTransform(ov_bounds,'EPSG:3003','EPSG:900913');
	ov_bbox = ov_bounds.toBBOX();
	ov_bboxArray=ov_bbox.split(',');

	var mappaIngombro_bounds = OpenLayers.Bounds.fromString(mappaIngombroBbox)
    mappaIngombro_bounds = bboxTransform(mappaIngombro_bounds,'EPSG:3003','EPSG:900913');
	mappaIngombroBbox = mappaIngombro_bounds.toBBOX();
	mappaIngombroBboxArray=mappaIngombroBbox.split(',');

	mappaIngombroBboxGB = mappaIngombroBbox;
	mappaIngombroBboxArrayGB=mappaIngombroBboxGB.split(',');
*/

// carico la mappa
	var options = {
		projection: SRS_OL,
		displayProjection:SRS,
		units: "m",
		maxResolution: 156543.0339,
		maxExtent: mappaIngombro_bounds,
		restrictedExtent: mappaIngombro_bounds,
		controls: [] 
	};
	map = new OpenLayers.Map('map',options);
	map.fractionalZoom=true;
// imposto il numero degli zoom
	map.numZoomLevels=20;
// carico i controlli
	map.addControl(new OpenLayers.Control.Navigation());
	map.addControl(new OpenLayers.Control.KeyboardDefaults());
//	map.addControl(new OpenLayers.Control.ScaleLine());
//	map.addControl(new OpenLayers.Control.LayerSwitcher());
// carico gli sfondi google
    var gphy = new OpenLayers.Layer.Google(
        "Google Terreno",
        {type: G_PHYSICAL_MAP,"sphericalMercator": true}
    );
    var gmap = new OpenLayers.Layer.Google(
        "Google Stradario",
        {"sphericalMercator": true}
    );
    var ghyb = new OpenLayers.Layer.Google(
        "Google Ibrida",
        {type: G_HYBRID_MAP,"sphericalMercator": true}
    );
    var gsat = new OpenLayers.Layer.Google(
        "Google Satellite",
        {type: G_SATELLITE_MAP,"sphericalMercator": true}
    );
// carico un base layer vuoto 
	var layerBaseVuoto = new OpenLayers.Layer.Vector("Nessuno", {
		isBaseLayer: true
	});
//   map.addLayers([gsat,gmap,ghyb,gphy,layerBaseVuoto]);
   map.addLayers([layerBaseVuoto]);

// carico i livelli WMS
	caricaLivelliWMS(listaLayer);

// carico il livello per il disegno (misure ecc....)
	vectorLayer = new OpenLayers.Layer.Vector("Vector Layer");
    map.addLayers([vectorLayer]);
	vectorLayer.displayInLayerSwitcher=false;

// carico i controlli per il disegno e quelli che richiedono una "attivazione"
    var options = {handlerOptions: {freehand: false}};
    drawControls = {
        point: new OpenLayers.Control.DrawFeature(vectorLayer,
                    OpenLayers.Handler.Point),
        line: new OpenLayers.Control.DrawFeature(vectorLayer,
                    OpenLayers.Handler.Path, options),
        polygon: new OpenLayers.Control.DrawFeature(vectorLayer,
                    OpenLayers.Handler.Polygon, options),
		zoombox: new OpenLayers.Control.ZoomBox({alwaysZoom:true})
    };
    for(var key in drawControls) {
        map.addControl(drawControls[key]);
    }

// centro la mappa al fit all e calcolo il relativo livello di zoom (livello di zoom massimo
	setMapCenter(ov_bbox); 
	var fitAllBounds = map.getExtent();
	maxZoomLevel = map.getZoomForExtent(fitAllBounds,true); 

// centro la mappa
	setMapCenter(bbox); 
	
// attivo la gestione dell'evento click (definito nella libOL.js: al momento gestisce il getFeatureInfo)
	var click = new OpenLayers.Control.Click();
	map.addControl(click);
	click.activate();

// attivo la funzione onExtentsChangeCb sull'evento di moveend
	map.events.register( 'moveend', this, function() { 
		var newBounds = map.getExtent();
		var dWorldTLX = newBounds.left;
		var dWorldTLY = newBounds.top;
		var dWorldBRX = newBounds.right;
		var dWorldBRY = newBounds.bottom;
		onExtentsChangeCb(dWorldTLX, dWorldTLY, dWorldBRX,dWorldBRY);
	}); 

// scrivo la scala
	strScala=map.getScale();
	strScala = Math.round(strScala/100)*100;
	document.Scala.Scala.value = strScala;
// scrivo la legenda
	scriviLegenda();

// altezza base dei div del logo
	altezzaLogo=15;
// imposto i valori 
	var newBounds = map.getExtent();
	dWorldTLXPre = newBounds.left;
	dWorldTLYPre = newBounds.top;
	dWorldBRXPre = newBounds.right;
	dWorldBRYPre = newBounds.bottom;
//alert(dWorldTLXPre);


// se è impostata la variabile strComandoBottone eseguo il comando		
//	if (typeof(strComandoBottone)=='string') {
	if ((typeof(strComandoBottone)==='string')&&(strComandoBottone.length>0)) {
        var eseguiComando = eval('(' + strComandoBottone + ')');
	}
// 
	var comandoBottone = valoreParametro('comandoBottone');
	if ((typeof(comandoBottone)==='string')&&(comandoBottone.length>0)) {
		var eseguiComando = eval('(' + comandoBottone + ')');
	}

}

// funzione per attivare un determinato controllo (p.e. le funzionalità di disegno di linee ecc.....)
// input: key del controllo:
//	- point
//  - line
//  - polygon
// - 
function toggleDrawControl(geomType) {

	if(tipoMappa!='OL')
	 return;

    for(key in drawControls) {
        var control = drawControls[key];
        if(geomType == key) {
            control.activate();
        } else {
            control.deactivate();
        }
    }

}



function caricaLivelliWMS(listaLayer)
{
	for (i = 0; i < listaLayer.length; i++) {
		if ((listaLayer[i].tipoGeom=='Raster')&&(listaLayer[i].livHidden=='0')) {
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
				var str = 'REQUEST=GetMap';	
				if (listaLayer[i].tipo=='ECW') {
//alert(listaLayer[i].nameWmsEcw + ' ' + listaLayer[i].urlWmsEcw);
					var urlWmsServer = listaLayer[i].urlWmsEcw.substring(0,listaLayer[i].urlWmsEcw.indexOf(str));
					var layerName = listaLayer[i].titolo;	
					var layerNameWMS = listaLayer[i].nameWmsEcw;	
				}
				else {
					var urlWmsServer = listaLayer[i].url.substring(0,listaLayer[i].url.indexOf(str));
					var layerName = listaLayer[i].titolo;	
					var layerNameWMS = listaLayer[i].name;	
				}
//				alert(layerName + ' ' + listaLayer[i].url + urlWmsServer);
				var urlSLD = '';
				caricaLivelloWMS(urlWmsServer,layerName,layerNameWMS,urlSLD,'image/pngRGB');
				SetLayerTransparency(layerName,'#',listaLayer[i].trasp/100);
			}
		}
	}
	for (i = 0; i < listaLayer.length; i++) {
		if ((listaLayer[i].tipoGeom!='Raster')&&(listaLayer[i].livHidden=='0')) {
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
				var str = 'REQUEST=GetMap';	
				if (listaLayer[i].tipo=='ECW') {
					var urlWmsServer = listaLayer[i].urlWmsEcw.substring(0,listaLayer[i].urlWmsEcw.indexOf(str));
					var layerName = listaLayer[i].titolo;	
					var layerNameWMS = listaLayer[i].nameWmsEcw;	
					var urlSLD = '';			
				}
				else {
					var urlWmsServer = listaLayer[i].url.substring(0,listaLayer[i].url.indexOf(str));
					var layerName = listaLayer[i].titolo;	
					var layerNameWMS = listaLayer[i].name;	
					var urlSLD = listaLayer[i].sldUrl;			
				}
				caricaLivelloWMS(urlWmsServer,layerName,layerNameWMS,urlSLD,'image/png');
				SetLayerTransparency(layerName,'#',listaLayer[i].trasp/100);
			}
		}
	}
}


// funzione di refresh dei livelli wms OpenLayers
function refreshLivelloWMS(layerName)
{
// ATTENZIONE: layerName è listaLayer[i].titolo
	var layers = map.getLayersByName(layerName);
	layers[0].mergeNewParams({'version':Math.random()})		
    layers[0].moveTo(layers[0].map.getExtent(), true);
}


// funzione di caricamento dei livelli wms          
function  caricaLivelloWMS(urlWmsServer,layerName,layerNameWMS,urlSLD,wmsFormat)
{           
// se il livello e un tematismo levo la stringa dal nome del layer 
	var str = "__TEMA_TEMATISMO";
	var posStr = layerNameWMS.indexOf(str);
	if (posStr > 0 )
		layerNameWMS = layerNameWMS.substring(0,posStr);
// controllo che il layer non esista già 
	var layers = map.getLayersByName(layerName);
	if (layers.length==0)
	{
		if (urlSLD!="")
		{
			layerWMS = new OpenLayers.Layer.WMS( 
						layerName,
						urlWmsServer,
						{
							layers: layerNameWMS, 
							srs: SRS_OL,
							transparent: "true",
							format: wmsFormat,
							sld: urlSLD
						}
						// setto il singleTile a true 
						, {singleTile: true}
						, {reproject: true}
			);
		}
		else
		{
			layerWMS = new OpenLayers.Layer.WMS( 
						layerName,
						urlWmsServer,
						{
							layers: layerNameWMS, 
							srs: SRS_OL,
							transparent: "true",
							format: wmsFormat
						}
						// setto il singleTile a true 
						, {singleTile: true}
						, {reproject: true}
			);
		}
		layerWMS.displayInLayerSwitcher=false;
		
// registro gli eventi associati al layer
		registerEvents(layerWMS);
// aggiungo il layer alla mappa
		map.addLayer(layerWMS);

// debug javascript
	    if (debug) {
		    Opzioni = 'status=yes, toolbar=yes, menubar=no, width=1000, height=486, resizable=yes, scrollbars=yes';
		    WinAlert = window.open('', 'alert', Opzioni)
            var bounds = OpenLayers.Bounds.fromString(bbox);
		    WinAlert.document.write('<b>caricaLivelloWMS:</b><br> livello: '+ layerNameWMS + ' (' + layerName + ')<br>url:    ' + layerWMS.getURL(bounds) + '<br>sld: ' + urlSLD + '<br>');
        }

	}
}


// gestione eventi layer
function registerEvents(layer) {
// --- gestione log
    layer.logEvent = function(event) {
    }
// --- Evento "loadstart"
    layer.events.register("loadstart", layer, function() {
// gestione div "attendere"
		var myDiv = document.getElementById("ATTENDERE");
		myDiv.style.display='block';
		flgAttesaLiv ++;
    });
// --- Evento "tileloaded"
    layer.events.register("tileloaded", layer, function() {
    });
// --- Evento "loadend"
    layer.events.register("loadend", layer, function() {
// gestione div "attendere"
		flgAttesaLiv -- ;		
		if((flgAttesaLiv == 0)) {
			document.getElementById('ATTENDERE').style.display='none';
		}
    });
}



// centra la mappa nel bbox
function setMapCenter(Bbox,transform)
{

	var bounds = OpenLayers.Bounds.fromString(Bbox);
	if (transform)
	{
	    bounds = bboxTransform(bounds,'EPSG:3003','EPSG:900913');
	}
	var lonlat = 	bounds.getCenterLonLat(); 
//	console.log (lonlat);
	var zoomLevel = map.getZoomForExtent(bounds); 
	map.setCenter(lonlat, zoomLevel);
	
}


// setto i parametri comuni tra versione ECW e versione OpenLayers
function setParametri()
{
	    if (debug) {
		    Opzioni = 'status=yes, toolbar=yes, menubar=no, width=1000, height=486, resizable=yes, scrollbars=yes';
		    WinAlert = window.open('', 'alert', Opzioni)
		    WinAlert.document.write('<b>INIZIALIZZAZIONE</b><br><br>');
        }

// flag di inizializzazione
	flagInit=1;
// width e height di base (partenza)
	widthBase=width;
	heightBase=height;
// resize della mappa
	if (typeof(window.opener)=='object') resizeMappa();
// imposto la visibilità dei DIV
	document.getElementById('RICERCALOCALITADIV').style.display='none';
	document.getElementById('SERVIZIODIV').style.display='none';
	document.getElementById('MEASUREPOINTDIV').style.display='none';
	document.getElementById('MEASUREPOINTDIV').innerHTML='Coordinate: ';
	document.getElementById('MEASURELINEDIV').style.display='none';
	document.getElementById('MEASURELINEDIV').innerHTML='Distanza (m): ';
	document.getElementById('MEASUREAREADIV').style.display='none';
	document.getElementById('MEASUREAREADIV').innerHTML='Area (m^2): ';
	document.getElementById('MEASURERESET').style.display='none';
	document.getElementById('DRAWCIRCLEDIV').style.display='none';
	document.getElementById('RAGGIOCERCHIODIV').style.display='none';
// Calcolo la scala di partenza
	strScala = parseInt(3780 * (bboxArray[2] - bboxArray[0])/ width);
	strScalaFitAll = parseInt(9600 * (mappaIngombroBboxArray[2] - mappaIngombroBboxArray[0])/ (width * 2.54) + 0.5);
// inizializzo i livelli vettoriali
	livAttivo=-1;
	for (i = 0; i < listaLayer.length; i++){
		if (listaLayer[i].scMin == 0) 
			listaLayer[i].scMin=1;
		if (listaLayer[i].tipo!='ECW') {
			if(tipoMappa!='OL')
				inizializzaVettoriale(listaLayer[i].titolo,listaLayer[i].name);
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))&&(listaLayer[i].queryable==1))
				livAttivo=i;
		}
// inizializzo l'array contentente lo stato dei livelli (acceso/spento)
// 0 = Livello Non Visibile
// 1 = Livello Visibile
// 2 = Livello Fuoriscala Non Visibile
// 3 = Livello Fuoriscala Visibile
//alert(listaLayer[i].titolo + ' ' + listaLayer[i].stato);
		if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
			if ((listaLayer[i].livHidden=='0'))
				listaLayer[i].stato=1;
			else
				listaLayer[i].stato=0;
		}
		else {
			if ((listaLayer[i].livHidden=='0'))
				listaLayer[i].stato=3;
			else
				listaLayer[i].stato=2;
		}
	
// nel caso di mappa OpenLayers non imposto la trasparenza
		if(tipoMappa!='OL')
		{		
			impostaTrasparenza(i,listaLayer[i].titolo,listaLayer[i].name,listaLayer[i].trasp);
		}
	}


// se viene passato un parametro di nome "filtro" imposto il relativo attributo del layer
	var codice_livello_temp = valoreParametro('codice_livello_temp');
	var filtro_temp = valoreParametro('filtro_temp');
 	for (i = 0; i < listaLayer.length; i++){
		if (listaLayer[i].name=="L"+codice_livello_temp) {
			listaLayer[i].filtro=filtro_temp;
		}
	}



	if ((puntoX>0)&&(puntoY>0)) {
		var strPunti = puntoX + "," + puntoY + "|" + parseInt(puntoX-3) + "," + parseInt(puntoY-3);
		var vecObject = "linewidth=7;color=#FF0000;fillcolor=#FF0000;"
		vecObject += "filledcircle1=" + strPunti + ";"
		document.ECWView1.SetLayerParameter("VectorOverlay2", vecObject);
	}

    inizializzaLogo();
}


// Gestisce l'inizializzazione del sistema
function inizializzaECW() {
// Force the native plugin (ActiveX/NetscapePlugin)
	setCookie("NCSPluginInstallMethod", "NATIVE");
	clearTimeout(tOnLoadTimer);
// Carico un raster vuoto di sfondo e lo rendo trasparente
	if (document.ECWView1.GetLayerIndex('sfondo') < 1 )
	{
		fileSfondo = "/CartoWebNET/sfondo.ecw"
		indirizzoSfondo = "ecwp://" + document.location.host + fileSfondo
		if (document.ECWView1.AddLayer("ECW",indirizzoSfondo,"sfondo", "") < 0 ) {
			alert('Caricamento Raster Sfondo: ' + indirizzoSfondo + ' - '+ document.ECWView1.GetLastErrorText());
			return false;
		}
		SetLayerTransparency("sfondo","#",0);
		document.ECWView1.SetBackGroundColor("#FFFFFF");
	}
// Carico layer per il disegno vettoriale delle misure ecc...
    if (document.ECWView1.AddLayer("simplevector", "", "VectorOverlay", ";") < 0) {
		alert(document.ECWView1.GetLastErrorText());
	}
	else {
		ECWVectorLayer = new NCSVectorLayer(document.ECWView1, "VectorOverlay");
	}
// Carico layer per il disegno vettoriale dei punti in ingresso
    if (document.ECWView1.AddLayer("simplevector", "", "VectorOverlay2", ";") < 0) {
		alert(document.ECWView1.GetLastErrorText());
	}
	else {
		ECWVectorLayer = new NCSVectorLayer(document.ECWView1, "VectorOverlay");
	}
// setto i parametri comuni tra versione ECW e versione OpenLayers
	setParametri();

	

// faccio lo zoom al rettangolo si ingombro iniziale (metto un leggero time-out)
	tOnLoadTimer = setTimeout('setExtentIniziale()', 1);
	
//	setExtentsControllo(bboxArray[0],bboxArray[3],bboxArray[2],bboxArray[1]);

	if (modo=='STAMPA') {
		document.ECWView1.SetPointerMode(2);
	}

// se è impostata la variabile strComandoBottone eseguo il comando		
	if (typeof(strComandoBottone)=='string') {
        var eseguiComando = eval('(' + strComandoBottone + ')');
	}
// 
	var comandoBottone = valoreParametro('comandoBottone');
	if ((typeof(comandoBottone)=='string')&&(comandoBottone)) {
		var eseguiComando = eval('(' + comandoBottone + ')');
	}

}

function setExtentIniziale()
{
	setExtentsControllo(bboxArray[0],bboxArray[3],bboxArray[2],bboxArray[1]);
}

function caricaRaster(urlFile,nomeLayer,trasp) {
//alert('caricaraster ' + document.location.host + urlFile);
	if (document.ECWView1.GetLayerIndex(nomeLayer) < 0 )
	{
		if (document.ECWView1.AddLayer("ECW","ecwp://" + document.location.host + urlFile,nomeLayer, "") < 0 ) {
			alert('Caricamento Raster: ' + nomeLayer + ' - Url: '+ document.location.host + urlFile + '\nErrore ' + document.ECWView1.GetLastErrorText());
			return false;
		}
		SetLayerTransparency(nomeLayer,'#FFFFFF',0);
		SetLayerTransparency(nomeLayer,'#',trasp/100);
	}
	return true;
}


function inizializzaVettoriale(nomeLayer,titoloLayer) {

		if (tipoMappa=='OL')
			return;

		if (document.ECWView1.GetLayerIndex(nomeLayer) < 1 )
		{
			if (document.ECWView1.AddLayer("GISOverlay", "", nomeLayer,"") < 0 ) {
				alert('Inizializzazione Vettoriale ' + document.ECWView1.GetLastErrorText());
				return false;
			}
		}
// inizializzo i livelli Find
		for (k = 0; k < listaLivFind.length; k++){
//alert(listaLivFind[k].titolo + ' ' + listaLayer[i].name);
			if (listaLivFind[k].titolo==titoloLayer){
				livelloFind = 'find'+listaLivFind[k].titolo;
//alert(livelloFind);
				if (document.ECWView1.GetLayerIndex(livelloFind) < 1 )
				{
					if (document.ECWView1.AddLayer("GISOverlay", "", livelloFind ,"") < 0 ) {
						alert('Inizializzazione Vettoriale Livello Find' + livelloFind + ' ' + document.ECWView1.GetLastErrorText());
						return false;
					}
				}
			}
		}
}


function inizializzaLogo() {
	for (i = 0; i < listaLayer.length; i++)
	{
		if (listaLayer[i].logoImg!='')
		{
//alert(listaLayer[i].titolo + ' ' + listaLayer[i].logoImg);
			livelloLogo = 'LOGO_'+listaLayer[i].titolo;
			if (tipoMappa!='OL') {
				if (document.ECWView1.GetLayerIndex(livelloLogo) < 1 )
				{
					altezzaLogo = altezzaLogo + 20;  
					sParams = "";
					sParams = sParams + "mode=WINABSOLUTE;";
					sParams = sParams + "body=;";
					sParams = sParams + "action=GET;";
					sParams = sParams + "worldTLX=1;";
					sParams = sParams + "worldTLY=1;";
					sParams = sParams + "worldBRX=10;";
					sParams = sParams + "worldBRY=" + (altezzaLogo) + ";";  
					sParams = sParams + "url=http://" + document.location.host + listaLayer[i].logoImg +";";  
	//			    sParams = sParams + "url=http://" + "www.cartografiarl.regione.liguria.it" + listaLayer[i].logoImg +";";  
					if (document.ECWView1.AddLayer("GISOverlay", "", livelloLogo,sParams) < 0 ) {
						alert('Inizializzazione Logo ' + document.ECWView1.GetLastErrorText());
						return false;
					}
					SetLayerTransparency(livelloLogo, "#ff0000", 0.0);
				}
			}
			else {
				altezzaLogo = altezzaLogo + 10;  
//				alert(livelloLogo);
				var checkDiv = document.getElementById(livelloLogo);
				if (checkDiv==null)
				{
					var divLeft = 20;			
					var divTop = altezzaLogo;	
					var mappa = document.getElementById("MAPPA");
					var newdiv = document.createElement('div');
					newdiv.setAttribute('id', livelloLogo);
					newdiv.style.position = "absolute";
					newdiv.style.left = divLeft;
					newdiv.style.top = divTop;
					var html = "<img src='" + listaLayer[i].logoImg + "'>" 
					newdiv.innerHTML = html;
					newdiv.style.display='block';
					mappa.appendChild(newdiv);
				}
			}
		}
	}
}

// trasforma un punto da Gauss-Boaga a WGS84 latlon
// input x e y
// output oggetto Proj4js.Point (con proprietà x e y)
function pointTrasfCoord(x,y,epsgFrom,epsgTo)
{

    if ((epsgFrom=='EPSG:3003')&&(epsgTo=='EPSG:900913'))
    {
	    x = parseInt(x)-parseInt(shiftGBtoSPHx);
	    y = parseInt(y)+parseInt(shiftGBtoSPHy);
    }
    if ((epsgFrom=='EPSG:900913')&&(epsgTo=='EPSG:3003'))
    {
	    x = parseInt(x)+parseInt(shiftGBtoSPHx);
	    y = parseInt(y)-parseInt(shiftGBtoSPHy);
    }  
	var source = new Proj4js.Proj(epsgFrom);    //source coordinates 
	var dest = new Proj4js.Proj(epsgTo);     //destination coordinates 
	var p = new Proj4js.Point(x,y);   //any object will do as long as it has 'x' and 'y' properties
	Proj4js.transform(source, dest, p);      //do the transformation.  x and y are modified in place
	return p;
}

function calcolaWmsUrl(urlFile,nomeLayer,sldUrl,styleCurrent,srs) {


	if ((styleCurrent == '1')&&(sldUrl!='')) {
		sUrl = urlFile + "&SLD=" + sldUrl;
	}
	else {
		sUrl = urlFile;
	}

/*
// se il servizio wms è in WFS84 converto le coordinate per il BBOX 
	if ((srs=='EPSG:4326')||(srs=='EPSG:32632')||(srs=='EPSG:23032'))
	{
// versione che utilizza Proj4js
		var point = new Proj4js.Point();
		var x = parseInt(dWorldTLXPre) ;
		var y = parseInt(dWorldTLYPre);
		point = pointTrasfCoord(x,y,'EPSG:3003',srs);
		var tlx = point.x; 
		var tly = point.y; 	
		var x = parseInt(dWorldBRXPre);
		var y = parseInt(dWorldBRYPre);
		point = pointTrasfCoord(x,y,'EPSG:3003',srs);
		var brx = point.x; 
		var bry = point.y; 	
		sUrl = sUrl + "&BBOX=" + tlx + "," + bry + "," + brx + "," + tly;
	}
	else
	{
*/
		var tlx=dWorldTLXPre;	
		var tly=dWorldTLYPre;	
		var brx=dWorldBRXPre;	
		var bry=dWorldBRYPre;	
		sUrl = sUrl + "&BBOX=" + Math.ceil(tlx) + "," + Math.ceil(bry) + "," + Math.ceil(brx) + "," + Math.ceil(tly);
//	}

//alert(sUrl);

	sUrl = sUrl + "&WIDTH=" + width + "&HEIGHT=" + height;
//	sUrl += "&STYLES="

    return sUrl;
	
}

function caricaVettoriale(urlFile,nomeLayer,sldUrl,styleCurrent,srs) {

    sUrl = calcolaWmsUrl(urlFile,nomeLayer,sldUrl,styleCurrent,srs);
    
//alert(sUrl);

// - Debug Url WMS
	if (debug) {
		Opzioni = 'status=yes, toolbar=yes, menubar=no, width=1000, height=486, resizable=yes, scrollbars=yes';
		WinAlert = window.open('', 'alert', Opzioni)
		WinAlert.document.write('<b>CARICO VETTORIALE:</b> livello '+ nomeLayer + '<br>' + sUrl + '<br>');
	}

	params = "";
	params = params + "mode=0;";
	params = params + "body=;";
	params = params + "action=GET;";
	params = params + "worldTLX=" + dWorldTLXPre + ";";
	params = params + "worldTLY=" + dWorldTLYPre + ";";
	params = params + "worldBRX=" + dWorldBRXPre + ";";
	params = params + "worldBRY=" + dWorldBRYPre + ";"; 
	params = params + "url=" + sUrl + ";";

	//alert('CARICO VETTORIALE: '+ nomeLayer + ' ' + sldUrl);


	if (document.ECWView1.SetLayerParameter(nomeLayer, params) < 0 ) {
		alert('Caricamento Vettoriale ' + document.ECWView1.GetLastErrorText());
		return false;
	}

	var myDiv = document.getElementById("ATTENDERE");
	myDiv.style.display='block';
	flgAttesaLiv ++;
//alert('carico ' + flgAttesaLiv);
	if (nomeLayer=='find') {
		SetLayerTransparency(nomeLayer,'#',0.75);
	}
	SetLayerTransparency(nomeLayer,'#FFFFFF',0);
	return true;
}

function convertiBBox(bbox)
{
	url = "/cartowebNet/CwTrasfCoord.aspx?bbox=" + bbox;
//alert(url);
	xmlhttp=getXMLHttp();
	if (xmlhttp!=null)
	{
		xmlhttp.onreadystatechange=onHTTPResponse;
		xmlhttp.open('GET',url,false);
		xmlhttp.send(null);
	}
	stringaXML = xmlhttp.responseText;	

	if (window.ActiveXObject) 
	{
		var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(stringaXML);
	}
	else
	{
		try
		{
			var parser=new DOMParser();
			var xmlDoc=parser.parseFromString(stringaXML,"text/xml");
		}
		catch(e)	{alert(e.message)}
	}

// gestione errore <WMTException>
	try {
		exception = xmlDoc.getElementsByTagName("Error");
		alert(exception[0].firstChild.nodeValue);
		return "Error";
	}
	catch(err){}

	bboxNode = xmlDoc.getElementsByTagName("Bbox");
	bbox = bboxNode[0].firstChild.nodeValue;
	return bbox;

}



//------------------------
function onHTTPResponse() 
{ 
	if (xmlhttp.readyState==4) 
	{ 
	if (xmlhttp.status!=200) 
		{
			alert('Non riesco a contattare il server WMS - Codice Errore: ' + xmlhttp.status);
		}
	}
}
function getXMLHttp() {
	var xmlhttp = null;
	if (window.ActiveXObject) {
		if (navigator.userAgent.toLowerCase().indexOf("msie 5") != -1) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		else {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
	}
	if (!xmlhttp && typeof(XMLHttpRequest) != 'undefined') {
		xmlhttp = new XMLHttpRequest()
	}
	return xmlhttp
} 


// -------------------------------------------
// Cambia l'area di ingombro aggiorno la mappa
// -------------------------------------------
function onExtentsChangeCb(dWorldTLX, dWorldTLY, dWorldBRX,dWorldBRY) {
	if ((parseInt(dWorldTLX)!=parseInt(dWorldTLXPre))||(parseInt(dWorldTLY) != parseInt(dWorldTLYPre))||(parseInt(dWorldBRX) != parseInt(dWorldBRXPre))||(parseInt(dWorldBRY) != parseInt(dWorldBRYPre))) {

//alert('appo ' + dWorldTLX + ' ' + dWorldBRY + ' ' + dWorldBRX + ' ' + dWorldTLY);
//alert('appoPre ' + dWorldTLXPre + ' ' + dWorldBRYPre + ' ' + dWorldBRXPre + ' ' + dWorldTLYPre);

//alert('appo ' + dWorldTLX + ' ' + dWorldBRY + ' ' + dWorldBRX + ' ' + dWorldTLY);

if ((dWorldTLX=="0")&&(dWorldBRY=="0")&&(dWorldBRX=="0")&&(dWorldTLY=="0"))
{
//	alert('sono qui');
	dWorldTLX=dWorldTLXPre;
	dWorldTLY=dWorldTLYPre;
	dWorldBRX=dWorldBRXPre;
	dWorldBRY=dWorldBRYPre;
}
	
		dWorldTLXPre=dWorldTLX;
		dWorldTLYPre=dWorldTLY;
		dWorldBRXPre=dWorldBRX;
		dWorldBRYPre=dWorldBRY;

		if(tipoMappa!='OL')
		{
			strScala = parseInt(9600 * (dWorldBRX - dWorldTLX)/ (document.ECWView1.GetViewWidth() * 2.54) + 0.5);
		}
		else
		{
			strScala=map.getScale();
		}
		strScala = Math.round(strScala/100)*100;
		document.Scala.Scala.value = strScala;
// temporizzatore per filtrare navigazione (richieste ogni 2 secondo)
		if (tMapTimer != null) 
	        		clearTimeout(tMapTimer);
/*
	if(tipoMappa!='OL')
		tMapTimer = setTimeout('aggiornaLivelliECW(listaLayer)',2000);        
	else
		tMapTimer = setTimeout('aggiornaLivelliOL(listaLayer)',2000);        
*/
	tMapTimer = setTimeout('aggiornaLivelli(listaLayer)',2000);        

// Aggiorno l'ingombro
		spostaDivIngombro(dWorldTLX, dWorldTLY, dWorldBRX,dWorldBRY);
		for (i = 0; i < listaLayer.length; i++){
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))&&(listaLayer[i].tipo=='WMS')) {
				if(tipoMappa!='OL') {
					var myDiv = document.getElementById("ATTENDERE");
					myDiv.style.display='block';
				}
			}
		}
// Controllo livello attivo (Se livello attivo è fuori scala cambio livello attivo)
//alert('CwMappa.js riga 278' + livAttivo);
		if (livAttivo!=-1)
		{
			if (!((listaLayer[livAttivo].scMin<parseInt(strScala))&&(listaLayer[livAttivo].scMax>=parseInt(strScala))&&(listaLayer[livAttivo].tipo=='WMS'))) 
			{
				livAttivo=-1;
				for (i = 0; i < listaLayer.length; i++)
				{
					if (listaLayer[i].scMin == 0) 
					{
						listaLayer[i].scMin=1;
					}
					if (listaLayer[i].tipo!='ECW') 
					{
						if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))&&(listaLayer[i].queryable==1))
							livAttivo=i;
					}
				}
			}
		}
		
// controllo se vado oltre i limiti di fitall
//		if(tipoMappa!='OL')
			controllaLimitiFitAll(parseInt(dWorldTLX),parseInt(dWorldBRX),parseInt(dWorldTLY),parseInt(dWorldBRY));
	}
}

function controllaLimitiFitAll(dWorldTLX,dWorldBRX,dWorldTLY,dWorldBRY)
{

	if(tipoMappa=='OL')
	{
		var bboxAppo = dWorldTLX + "," + dWorldTLY + "," + dWorldBRX + "," + dWorldBRY
		var bounds = OpenLayers.Bounds.fromString(bboxAppo)
//		bounds.transform(new OpenLayers.Projection('EPSG:3003'), new OpenLayers.Projection('EPSG:900913'));
        bounds = bboxTransform(bounds,'EPSG:3003','EPSG:900913');


		var zoomLevel = map.getZoomForExtent(bounds,true); 
		if (zoomLevel < maxZoomLevel) {			
//			alert(maxZoomLevel + ' ' + zoomLevel);
			SetExtentsAll(); 	
		}
		return;
	}

	var flagOltre = false;
	dWorldTLXappo = dWorldTLX;
	dWorldBRXappo = dWorldBRX;
	dWorldTLYappo = dWorldTLY;
	dWorldBRYappo = dWorldBRY;

	if ((dWorldTLX < mappaIngombroBboxArray[0])&&(dWorldBRX > mappaIngombroBboxArray[2]))
	{
//alert('1 ' + dWorldTLX + ' '+ mappaIngombroBboxArray[0] + ' ' + dWorldBRX + ' ' + mappaIngombroBboxArray[2]);
		flagOltre = true;
		dWorldTLXappo = mappaIngombroBboxArray[0];
		dWorldBRXappo = mappaIngombroBboxArray[2];
		dWorldTLYappo = mappaIngombroBboxArray[3];
		dWorldBRYappo = mappaIngombroBboxArray[1];
	}
	else
	{
		if (dWorldTLX < mappaIngombroBboxArray[0]) 
		{
//alert('2 ' + dWorldTLX + ' ' + mappaIngombroBboxArray[0]);
			flagOltre = true;
			dWorldTLXappo = parseInt(mappaIngombroBboxArray[0]);
			dWorldBRXappo = dWorldBRX - parseInt(dWorldTLX - mappaIngombroBboxArray[0]); 
			if (dWorldBRXappo > mappaIngombroBboxArray[2])
				dWorldBRXappo = parseInt(mappaIngombroBboxArray[2]);
		}
		if (dWorldBRX > mappaIngombroBboxArray[2])
		{
//alert('3 ' + dWorldBRX + ' ' + mappaIngombroBboxArray[2]);
			flagOltre = true;
			dWorldBRXappo = parseInt(mappaIngombroBboxArray[2]);
			dWorldTLXappo = dWorldTLX + parseInt(mappaIngombroBboxArray[2] - dWorldBRX);
			if (dWorldTLXappo < mappaIngombroBboxArray[0]) 
				dWorldTLXappo = parseInt(mappaIngombroBboxArray[0]);
		}
		if (dWorldTLY > mappaIngombroBboxArray[3])
		{
//alert('4');
			flagOltre = true;
			dWorldTLYappo = mappaIngombroBboxArray[3];
			dWorldBRYappo = dWorldBRY + parseInt(dWorldTLY - mappaIngombroBboxArray[3]);
			if (dWorldBRYappo < mappaIngombroBboxArray[1])
				dWorldBRYappo = mappaIngombroBboxArray[1];
		}
		if (dWorldBRY < mappaIngombroBboxArray[1])
		{
//alert('5');
			flagOltre = true;
			dWorldBRYappo = mappaIngombroBboxArray[1];
			dWorldTLYappo = parseInt(dWorldTLY) - parseInt(dWorldBRY - mappaIngombroBboxArray[1]);
			if (dWorldTLYappo > mappaIngombroBboxArray[3])
				dWorldTLYappo = mappaIngombroBboxArray[3];
		}

	}
	if (flagOltre)
	{
//alert('appo ' + dWorldTLXappo + ' ' + dWorldBRYappo + ' ' + dWorldBRXappo + ' ' + dWorldTLYappo);
//alert('ingo ' + mappaIngombroBboxArray[0] + ' ' + mappaIngombroBboxArray[1] + ' ' + mappaIngombroBboxArray[2] + ' ' + mappaIngombroBboxArray[3]);
		setExtentsControllo(dWorldTLXappo,dWorldTLYappo,dWorldBRXappo,dWorldBRYappo);
	}
}


// ---------------------------------------
// Imposto la history dello zoom
// ---------------------------------------

function impostaStoriaZoom(TLX,TLY,BRX,BRY) {

//	alert(indiceStoriaZoom + ' '+ TLX);

	if (indiceStoriaZoom < 10)
	{	
		indiceStoriaZoom++; 	
		listaStoriaZoom[indiceStoriaZoom]=new storiaZoom(TLX,TLY,BRX,BRY);
		listaStoriaZoom.length=indiceStoriaZoom+1;
	}
	else
	{
		for(ind=10; ind > 0; ind--)
		{	
			listaStoriaZoom[ind-1]=listaStoriaZoom[ind];
		}
		listaStoriaZoom[indiceStoriaZoom]=new storiaZoom(TLX,TLY,BRX,BRY);
	}

}

function zoomIndietro()
{
	if (indiceStoriaZoom > 1)
	{
		indiceStoriaZoom--;
		flagScorriZoom=true;
		setExtentsControllo(listaStoriaZoom[indiceStoriaZoom].TLX,listaStoriaZoom[indiceStoriaZoom].TLY,listaStoriaZoom[indiceStoriaZoom].BRX,listaStoriaZoom[indiceStoriaZoom].BRY);
	}
}

function zoomAvanti()
{
	if (listaStoriaZoom.length>indiceStoriaZoom+1)
	{
		indiceStoriaZoom++;
		flagScorriZoom=true;
		setExtentsControllo(listaStoriaZoom[indiceStoriaZoom].TLX,listaStoriaZoom[indiceStoriaZoom].TLY,listaStoriaZoom[indiceStoriaZoom].BRX,listaStoriaZoom[indiceStoriaZoom].BRY);
	}
}

// ---------------------------------------
// Aggiorno i livelli  --
// VERSIONE PER COMPATIBILITA' ALL'INDIETRO
// ---------------------------------------
function aggiornaLivelli(listaLayer) {

	if(tipoMappa!='OL')
	{
		aggiornaLivelliECW(listaLayer);
	}
	else
	{
		aggiornaLivelliOL(listaLayer);
	}

}

// ---------------------------------------
// Aggiorno i livelli  --
// VERSIONE VECCHIA 
// ---------------------------------------fin
function aggiornaLivelliOLD(listaLayer) {

	if (flagInit==1){	
// Gestione History degli Zoom
		if (!flagScorriZoom)
		{
				impostaStoriaZoom(dWorldTLXPre,dWorldTLYPre,dWorldBRXPre,dWorldBRYPre);
		}
		else
		{
			flagScorriZoom=false;
		}
		for (i = 0; i < listaLayer.length; i++){
//				if ((listaLayer[i].tipo=='WMS')&&(listaLayer[i].livHidden=='0')) {
			if ((listaLayer[i].tipo=='WMS')) {
//Nel caso di FIND faccio vedere il livello sempre (indipendentemente dalla scala
				for (k = 0; k < listaLivFind.length; k++){
					if (listaLivFind[k].titolo==listaLayer[i].name){
						livelloFind = 'find'+listaLivFind[k].titolo;
						caricaVettoriale(listaLivFind[k].url,livelloFind,'','1');
							if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
								document.ECWView1.SetLayerVisible(livelloFind,true);
							}
					}
				}
//alert('sono qui '+listaLayer[i].titolo+' '+listaLayer[i].url);
				for (k = 0; k < listaLivSelezione.length; k++){
					if (listaLivSelezione[k].titolo==listaLayer[i].name){
						livelloFind = 'find2'+listaLivSelezione[k].titolo;
						caricaVettoriale(listaLivSelezione[k].url,livelloFind,'','1');
							if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
								document.ECWView1.SetLayerVisible(livelloFind,true);
							}
					}
				}
				if (livFind2==listaLayer[i].titolo){
					caricaVettoriale(livFind2Url,'find2',livFind2SldUrl,'1');
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
						document.ECWView1.SetLayerVisible('find2',true);
					}
				}
//				alert(livInfo+ ' '+listaLayer[i].titolo)
				if (livInfo==listaLayer[i].titolo){
					caricaVettoriale(livInfoUrl,'info',livInfoSldUrl,'1');
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
//						alert(livInfo+ ' '+listaLayer[i].titolo)
						document.ECWView1.SetLayerVisible('info',true);
					}
				}
				if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
					caricaVettoriale(listaLayer[i].url,listaLayer[i].titolo,listaLayer[i].sldUrl,listaLayer[i].styleCurrent);
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3))
					{
						document.ECWView1.SetLayerVisible(listaLayer[i].titolo,true);
						listaLayer[i].stato=1;
					}
					else listaLayer[i].stato=0;
					if ((listaLayer[i].livHidden=='1'))
						document.ECWView1.SetLayerVisible(listaLayer[i].titolo,false);
					if (listaLayer[i].logoImg!='')
					{
						if (document.ECWView1.GetLayerParameter(listaLayer[i].titolo,"visibility")== "TRUE") 
							document.ECWView1.SetLayerVisible('LOGO_'+listaLayer[i].titolo,true);
						else 
							document.ECWView1.SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}

				}
				else {
					if (listaLayer[i].logoImg!=''){
						document.ECWView1.SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}
					document.ECWView1.SetLayerVisible(listaLayer[i].titolo,false);
					if ((listaLayer[i].stato==0)||(listaLayer[i].stato==2)){
						listaLayer[i].stato=2;
					}
					else listaLayer[i].stato=3;
					if (livInfo==listaLayer[i].titolo){
							document.ECWView1.SetLayerVisible('info',false);
					}
				}
			}
		}
		
		for (i = 0; i < listaLayer.length; i++){
//		if ((listaLayer[i].tipo=='ECW')&&(listaLayer[i].livHidden=='0')) {
			if ((listaLayer[i].tipo=='ECW')) {
				if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
					if (document.ECWView1.GetLayerIndex(listaLayer[i].titolo)<1) {
						caricaRaster(listaLayer[i].url,listaLayer[i].titolo,listaLayer[i].trasp);			
//alert('sono qui '+document.ECWView1.GetLayerName(0));
//alert('sono qui '+listaLayer[i].titolo+' '+document.ECWView1.GetLayerIndex(listaLayer[i].titolo)+' '+listaLayer[i].ordine);
						document.ECWView1.MoveLayer(document.ECWView1.GetLayerIndex(listaLayer[i].titolo),listaLayer[i].ordine);
					}
//alert('sono qui '+listaLayer[i].titolo+' '+document.ECWView1.GetLayerIndex(listaLayer[i].titolo)+' '+listaLayer[i].ordine);
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
						document.ECWView1.SetLayerVisible(listaLayer[i].titolo,true);
						listaLayer[i].stato=1;
					}
					else listaLayer[i].stato=0;
					if ((listaLayer[i].livHidden=='1'))
						document.ECWView1.SetLayerVisible(listaLayer[i].titolo,false);
// Se livello con logo carico il DIV con il logo
					if (listaLayer[i].logoImg!='')
					{
						if (document.ECWView1.GetLayerParameter(listaLayer[i].titolo,"visibility")== "TRUE") 
							document.ECWView1.SetLayerVisible('LOGO_'+listaLayer[i].titolo,true);
						else 
							document.ECWView1.SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}
				}
				else {
					if (listaLayer[i].logoImg!=''){
						document.ECWView1.SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}
					document.ECWView1.SetLayerVisible(listaLayer[i].titolo,false);
					if ((listaLayer[i].stato==0)||(listaLayer[i].stato==2)){
						listaLayer[i].stato=2;
					}
					else listaLayer[i].stato=3;
				}
			}
		}
	}
	aggiornaOrdine();
	scriviLegenda();
}




// ---------------------------------------
// Aggiorno i livelli 
// ---------------------------------------find
function aggiornaLivelliECW(listaLayer) {

	if (flagInit==1){	
// Gestione History degli Zoom
		if (!flagScorriZoom)
		{
				impostaStoriaZoom(dWorldTLXPre,dWorldTLYPre,dWorldBRXPre,dWorldBRYPre);
		}
		else
		{
			flagScorriZoom=false;
		}
		for (i = 0; i < listaLayer.length; i++){
			if ((listaLayer[i].tipo=='WMS')&&(listaLayer[i].livHidden=='0')) {
//Nel caso di FIND faccio vedere il livello sempre (indipendentemente dalla scala
				for (k = 0; k < listaLivFind.length; k++){
					if (listaLivFind[k].titolo==listaLayer[i].name){
						livelloFind = 'find'+listaLivFind[k].titolo;
							caricaVettoriale(listaLivFind[k].url,livelloFind,'','1');
							if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
								SetLayerVisible(livelloFind,true);
							}
					}
				}
//alert('sono qui '+listaLayer[i].titolo+' '+listaLayer[i].url);
				for (k = 0; k < listaLivSelezione.length; k++){
					if (listaLivSelezione[k].titolo==listaLayer[i].name){
						livelloFind = 'find2'+listaLivSelezione[k].titolo;
							caricaVettoriale(listaLivSelezione[k].url,livelloFind,'','1');
							if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
								SetLayerVisible(livelloFind,true);
							}
					}
				}
				if (livFind2==listaLayer[i].titolo){
						caricaVettoriale(livFind2Url,'find2',livFind2SldUrl,'1');
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
						SetLayerVisible('find2',true);
					}
				}
//				alert(livInfo+ ' '+listaLayer[i].titolo)
				if (livInfo==listaLayer[i].titolo){
						caricaVettoriale(livInfoUrl,'info',livInfoSldUrl,'1');
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
//						alert(livInfo+ ' '+listaLayer[i].titolo)
						SetLayerVisible('info',true);
					}
				}
				if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
//alert('qui');
					caricaVettoriale(listaLayer[i].url,listaLayer[i].titolo,listaLayer[i].sldUrl,listaLayer[i].styleCurrent,listaLayer[i].srs);
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3))
					{
						SetLayerVisible(listaLayer[i].titolo,true);
						listaLayer[i].stato=1;
					}
					else listaLayer[i].stato=0;
					if ((listaLayer[i].livHidden=='1'))
						SetLayerVisible(listaLayer[i].titolo,false);
					if (listaLayer[i].logoImg!='')
					{
						if (document.ECWView1.GetLayerParameter(listaLayer[i].titolo,"visibility")== "TRUE") 
							SetLayerVisible('LOGO_'+listaLayer[i].titolo,true);
						else 
							SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}

				}
				else {
					if (listaLayer[i].logoImg!=''){
						SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}
					SetLayerVisible(listaLayer[i].titolo,false);
					if ((listaLayer[i].stato==0)||(listaLayer[i].stato==2)){
						listaLayer[i].stato=2;
					}
					else listaLayer[i].stato=3;
					if (livInfo==listaLayer[i].titolo){
							SetLayerVisible('info',false);
					}
				}
			}
		}
		
		for (i = 0; i < listaLayer.length; i++){
//		if ((listaLayer[i].tipo=='ECW')&&(listaLayer[i].livHidden=='0')) {
			if ((listaLayer[i].tipo=='ECW')&&(listaLayer[i].livHidden=='0')) {
//alert('aggiornaLivelliECW ' + listaLayer[i].titolo + ' trasp ' + listaLayer[i].trasp);
				if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
					if (document.ECWView1.GetLayerIndex(listaLayer[i].titolo)<1) {
						caricaRaster(listaLayer[i].url,listaLayer[i].titolo,listaLayer[i].trasp);			
						document.ECWView1.MoveLayer(document.ECWView1.GetLayerIndex(listaLayer[i].titolo),listaLayer[i].ordine);
					}
//alert('sono qui '+listaLayer[i].titolo+' '+document.ECWView1.GetLayerIndex(listaLayer[i].titolo)+' '+listaLayer[i].ordine);
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
						SetLayerVisible(listaLayer[i].titolo,true);
						listaLayer[i].stato=1;
					}
					else listaLayer[i].stato=0;
					if ((listaLayer[i].livHidden=='1'))
						SetLayerVisible(listaLayer[i].titolo,false);
// Se livello con logo carico il DIV con il logo
					if (listaLayer[i].logoImg!='')
					{
						if (document.ECWView1.GetLayerParameter(listaLayer[i].titolo,"visibility")== "TRUE") 
							SetLayerVisible('LOGO_'+listaLayer[i].titolo,true);
						else 
							SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}
				}
				else {
					if (listaLayer[i].logoImg!=''){
						SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}
					SetLayerVisible(listaLayer[i].titolo,false);
					if ((listaLayer[i].stato==0)||(listaLayer[i].stato==2)){
						listaLayer[i].stato=2;
					}
					else listaLayer[i].stato=3;
				}
			}
		}
	}
	aggiornaOrdine();
	scriviLegenda();
}


// ---------------------------------------
// Aggiorno i livelli 
// ---------------------------------------find
function aggiornaLivelliOL(listaLayer) {
	
	caricaLivelliWMS(listaLayer);
	
	if (flagInit==1){	
// Gestione History degli Zoom
		if (!flagScorriZoom)
		{
				impostaStoriaZoom(dWorldTLXPre,dWorldTLYPre,dWorldBRXPre,dWorldBRYPre);
		}
		else
		{
			flagScorriZoom=false;
		}
		for (i = 0; i < listaLayer.length; i++){
//Nel caso di FIND faccio vedere il livello sempre (indipendentemente dalla scala
				for (k = 0; k < listaLivFind.length; k++){
					if (listaLivFind[k].titolo==listaLayer[i].name){
						livelloFind = 'find'+listaLivFind[k].titolo;
							if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
								SetLayerVisible(livelloFind,true);
							}
					}
				}
//alert('sono qui '+listaLayer[i].titolo+' '+listaLayer[i].url);
				for (k = 0; k < listaLivSelezione.length; k++){
					if (listaLivSelezione[k].titolo==listaLayer[i].name){
						livelloFind = 'find2'+listaLivSelezione[k].titolo;
							if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
								SetLayerVisible(livelloFind,true);
							}
					}
				}
				if (livFind2==listaLayer[i].titolo){
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
						SetLayerVisible('find2',true);
					}
				}
//				alert(livInfo+ ' '+listaLayer[i].titolo)
				if (livInfo==listaLayer[i].titolo){
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3)){
//						alert(livInfo+ ' '+listaLayer[i].titolo)
						SetLayerVisible('info',true);
					}
				}
				if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
					if ((listaLayer[i].stato==1)||(listaLayer[i].stato==3))
					{
						SetLayerVisible(listaLayer[i].titolo,true);
						listaLayer[i].stato=1;
					}
					else listaLayer[i].stato=0;
					if ((listaLayer[i].livHidden=='1'))
						SetLayerVisible(listaLayer[i].titolo,false);
/*
					if (listaLayer[i].logoImg!='')
					{
						if (document.ECWView1.GetLayerParameter(listaLayer[i].titolo,"visibility")== "TRUE") 
							SetLayerVisible('LOGO_'+listaLayer[i].titolo,true);
						else 
							SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}

*/
				}
				else {
					if (listaLayer[i].logoImg!=''){
						SetLayerVisible('LOGO_'+listaLayer[i].titolo,false);
					}
					SetLayerVisible(listaLayer[i].titolo,false);
					if ((listaLayer[i].stato==0)||(listaLayer[i].stato==2)){
						listaLayer[i].stato=2;
					}
					else listaLayer[i].stato=3;
					if (livInfo==listaLayer[i].titolo){
							SetLayerVisible('info',false);
					}
				}
		}
	}
		
	aggiornaOrdine();
	scriviLegenda();
}



function SetLayerVisible(titolo,visible) {

	if(tipoMappa!='OL')
	{
		document.ECWView1.SetLayerVisible(titolo,visible);
	}
	else
	{
		var layers = map.getLayersByName(titolo);
		if (layers.length>0)
			layers[0].setVisibility(visible);
// gestione layers accessori (logo)
//alert(titolo);
		if (titolo.substring(0,5)=='LOGO_') {
			var logoDiv = document.getElementById(titolo);
			if (visible)
				logoDiv.style.display='block';
			else
				logoDiv.style.display='none';
			
		}
		

	}
}	


function spegniLayerSfondo(visible) {

	var layers = map.getLayersBy('isBaseLayer', true)
	if (layers.length>0)
	{
		for (k = 0; k < layers.length; k++) {
			if (visible) {
				if(flagSfondoVisibile==k) {
					layers[k].setVisibility(visible);
				}											
				layers[k].setVisibility(visible);
			}
			else {
				if(layers[k].getVisibility()) {
					flagSfondoVisibile=k;
					layers[k].setVisibility(visible);
				}											
			}
			
		}
	}
}


function spegniLayer(nomeLayer,visible,i) {

	if (nomeLayer=='Sfondo') {
		spegniLayerSfondo(visible);
		return;
	}
	
	SetLayerVisible(nomeLayer,visible);

	if (visible) {
		listaLayer[i].stato=1;
		if ((listaLayer[i].livHidden=='1'))
			listaLayer[i].livHidden='0';
	}
	else {
		listaLayer[i].stato=0;
	}
	
////--- Gestione Livelli Accessori (FIND/INFO) -------------------------
// gestione Livelli logo
	if (listaLayer[i].logoImg!=''){
		SetLayerVisible('LOGO_'+nomeLayer,visible);
	}
// gestione livello find
	for (k = 0; k < listaLivFind.length; k++){
		if (listaLivFind[k].titolo==listaLayer[i].name){
			livelloFind = 'find'+listaLivFind[k].titolo;
			SetLayerVisible(livelloFind,visible);
		}
	}
// gestione livello selezione oggetti e topologica
	for (k = 0; k < listaLivSelezione.length; k++){
		if (listaLivSelezione[k].titolo==listaLayer[i].name){
			livelloFind = 'find2'+listaLivSelezione[k].titolo;
			SetLayerVisible(livelloFind,visible);
		}
	}
// gestione livello find2 (ricerca interna)
	if (livFind2==nomeLayer){
		SetLayerVisible("find2",visible);
	}
// gestione livello info (highlite info)
	if (livInfo==nomeLayer){
		SetLayerVisible("info",visible);
	}
////--- ---------------------------------------- -------------------------
}


// -----------------------------
// Scrive il frame della Legenda
// -----------------------------
function scriviLegenda() {

	var separatore_decimale = valoreParametro('separatore_decimale');

// Intestazione
	stringaLegenda = '';
	stringaLegenda += '<FORM name=LEGENDA>';
	stringaLegenda += '<TABLE ID=\'LEGTABLE\' WIDTH=200 align=LEFT bgcolor=white STYLE=\'position:absolute; top=0px; left=0px\'>';
// CICLO SUI LIVELLI WMS
	for (i = listaLayer.length-1; i >= 0; i--)
	{
		if (listaLayer[i].tipoGeom!='Raster') {
// non metto in stampa i livelli fuori scala
    	  if ((modo!='STAMPA')||((modo=='STAMPA')&&(listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala)&&(listaLayer[i].livHidden=='0')))) {
			stringaLegenda += '<TR>';
// immagine simbologia
			stringaLegenda += '<TD>';
//alert(listaLayer[i].titolo+'--'+listaLayer[i].legTipo);
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
				switch (listaLayer[i].legTipo) {
// - livello con legenda in pop-up	
					case '1': 
						if (listaLayer[i].legImg!="") { 
							stringaLegenda += '<a href=\'' + listaLayer[i].legImg + '\' TARGET=\'_new\'>';
						}
						else {		
							stringaLegenda += '<a href=\'javascript:apriLegenda(' + i + ');\'>' ;
						}
						if (listaLayer[i].tipoGeom=="Raster") { 
							stringaLegenda += '<img src=\'./images/legenda/raster.gif\'>' ;
						}
						else {
							stringaLegenda += '<img src=\'images/legenda/tema.gif\' >' ;
						}
						stringaLegenda += '</a>' ;
						break; 
					case '2': 
// - No Classi in Legenda (livello diviso in classi ma con una sola voce in legenda) 
						if (listaLayer[i].legImg!="") 
						{ 
							stringaLegenda += '<img src=\'' + listaLayer[i].legImg + '\'>' + '&nbsp;';
						}
						else
						{
							if ((listaLayer[i].styleCurrent == '1')&&(listaLayer[i].sldUrl!='')&&(urlRuleNonImmagine(listaLayer[i].rules[k].url))) {
								sUrl = listaLayer[i].rules[0].url + "&SLD=" + listaLayer[i].sldUrl;
							}
							else {
								sUrl = listaLayer[i].rules[0].url;
							}
							stringaLegenda += '<img src=\'' + sUrl + '\' >' ;
						}
						break; 
					case '0': 
// - livello normale
						if (listaLayer[i].legImg!="") { 
							switch (listaLayer[i].tipoGeom) {
								case 'Raster': 
									stringaLegenda += '<img src=\'./images/legenda/raster.gif\'>' ;
										break; 
								case 'Text': 
									stringaLegenda += '<img src=\'./images/legenda/text.gif\'>' ;
										break; 
								default:
									stringaLegenda += '<img src=\'' + listaLayer[i].legImg + '\'>' + '&nbsp;';
/* per fare in modo che quando le classi sono + di una COMUNQUE venga messo il simbolo del tema anche se è
   impostata la url dell'immagine
									if ((listaLayer[i].numClassi>1))  {
										stringaLegenda += '<img src=\'images/legenda/tema.gif\' >' ;
									}
									else {
										stringaLegenda += '<img src=\'' + listaLayer[i].legImg + '\'>' + '&nbsp;';
									}							
*/
							}
						}
						else {
//alert(listaLayer[i].titolo + ' ' + listaLayer[i].numClassi);
							switch (listaLayer[i].tipoGeom) {
								case 'Raster': 
									stringaLegenda += '<img src=\'./images/legenda/raster.gif\'>' ;
										break; 
								case 'Text': 
									stringaLegenda += '<img src=\'./images/legenda/text.gif\'>' ;
										break; 
								default:
									if ((listaLayer[i].numClassi>1))  {
										stringaLegenda += '<img src=\'images/legenda/tema.gif\' >' ;
									}
									else {
										if ((listaLayer[i].styleCurrent == '1')&&(listaLayer[i].sldUrl!='')&&(urlRuleNonImmagine(listaLayer[i].rules[0].url))) {
											sUrl = listaLayer[i].rules[0].url + "&SLD=" + listaLayer[i].sldUrl;
										}
										else {
											sUrl = listaLayer[i].rules[0].url;
										}
										stringaLegenda += '<img src=\'' + sUrl + '\' >' ;
									}							
							}
						}
	// - Debug Url WMS
//						if (debug) {
//							Opzioni = 'status=yes, toolbar=yes, menubar=no, width=1000, height=486, resizable=yes, scrollbars=yes';
//							WinAlert = window.open('', 'alert', Opzioni)
//							WinAlert.document.write('LEGENDA CLASSI 1:<br> ' + sUrl +'<br>');
//						}
						break; 
// fine switch
					}
//
			}
// BUG Explorer6  
			if(userBrowser=="EXPLORER")
				stringaLegenda += '</TD><TD>';
// check-box per la visibilità
			stringaLegenda += '</TD><TD>';
			if (modo!='STAMPA') {
				if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
					stringaLegenda += '<INPUT TYPE=\'checkbox\' NAME=check VALUE=\'' + listaLayer[i].titolo + '\' onClick=\'spegniLayer(this.value,this.checked,'+i+')\' '
					if ((listaLayer[i].livHidden=='0')&&((listaLayer[i].stato)==1||(listaLayer[i].stato==3))) {
						stringaLegenda += 'CHECKED'; 
					}
					stringaLegenda += ' >' 
				}
				else {
					stringaLegenda += '<img src=\'images/lente.gif\' width=20 height=20 border=0 TITLE=\'Visibile da 1:' + listaLayer[i].scMin + ' a 1:' + listaLayer[i].scMax + '\'>'
				}
			}
// radio-button per il livello attivo
			stringaLegenda += '</TD><TD>';
			if (modo!='STAMPA') {
				if (listaLayer[i].queryable==1){
					if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
						stringaLegenda += '<INPUT TYPE=\'radio\' NAME=attivo VALUE=\'' + listaLayer[i].titolo + '\' ID=\'CHECK_' + listaLayer[i].titolo + '\' onClick=\'attivaLayer(this.value,this.checked,'+i+')\' '
						if ((livAttivo==i)) {
							stringaLegenda += 'CHECKED'; 
						}
						stringaLegenda += ' >' 
					}
				}
			}
// nome del livello
			stringaLegenda += '</TD><TD>';
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
				stringaLegenda += '<b>' + listaLayer[i].titolo.substr(0,80) + '</b>';
			}
			else {
				stringaLegenda += listaLayer[i].titolo.substr(0,80);
			}
// Fine riga
			stringaLegenda += '</TD></TR>';
  		   }
		}
// Se livello tematizzato non in pop-up scrivo le righe per le classi	
   		if ((modo!='STAMPA')||((modo=='STAMPA')&&(listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala)&&(listaLayer[i].livHidden=='0')))) {
			if ((listaLayer[i].legTipo=="0")&&(listaLayer[i].numClassi>1)&&(listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
				for (k = 0; k < listaLayer[i].numClassi; k++) {
					stringaLegenda += '<TR>';
					stringaLegenda += '<TD></TD><TD>';
					if ((listaLayer[i].styleCurrent == '1')&&(listaLayer[i].sldUrl!='')&&(urlRuleNonImmagine(listaLayer[i].rules[k].url))) {
						sUrl = listaLayer[i].rules[k].url + "&SLD=" + listaLayer[i].sldUrl;
					}
					else {
						sUrl = listaLayer[i].rules[k].url;
					}
					stringaLegenda += '<img src=\'' + sUrl + '\' >' ;
					stringaLegenda += '</TD><TD></TD><TD>';
					if (separatore_decimale!='')
						stringaLegenda += formattaNumeri(listaLayer[i].rules[k].name,separatore_decimale);
					else
						stringaLegenda += listaLayer[i].rules[k].name;
					
					stringaLegenda += '</TD></TR>';
	// - Debug Url WMS
					if (debug) {
						Opzioni = 'status=yes, toolbar=yes, menubar=no, width=1000, height=486, resizable=yes, scrollbars=yes';
						WinAlert = window.open('', 'alert', Opzioni)
						WinAlert.document.write('LEGENDA CLASSI 2: <br>' + sUrl +'<br>');
					}
	//
				}
			}
		}

	}
//------------------------------------------------------------------------------------------------------
// CICLO SUI LIVELLI RASTER ECW
	for (i = listaLayer.length-1; i >= 0; i--)
	{
		if (listaLayer[i].tipoGeom=='Raster') {
// non metto in stampa i livelli fuori scala
	   	  if ((modo!='STAMPA')||((modo=='STAMPA')&&(listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala)&&(listaLayer[i].livHidden=='0')))) {
//   		  if ((modo!='STAMPA')||((modo=='STAMPA')&&(listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala)))) {
			stringaLegenda += '<TR>';
	// immagine simbologia
			stringaLegenda += '<TD>';
			
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
				if (listaLayer[i].legTipo=="1") {
					stringaLegenda += '<a href=\'' + listaLayer[i].legImg + '\' TARGET=\'_new\'>';
					stringaLegenda += '<img src=\'./images/legenda/raster.gif\'>' + '&nbsp;';
					stringaLegenda += '</a>';
				}
				else {
					if (listaLayer[i].legImg!="") { 
						stringaLegenda += '<img src=\'' + listaLayer[i].legImg + '\'>' + '&nbsp;';
					}
					else { 
						stringaLegenda += '<img src=\'./images/legenda/raster.gif\'>' + '&nbsp;';
					}
				}
			}
	// check-box
			stringaLegenda += '</TD><TD>';
			if (modo!='STAMPA') {
				if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
					stringaLegenda += '<INPUT TYPE=\'checkbox\' NAME=check VALUE=\'' + listaLayer[i].titolo + '\' onClick=\'spegniLayer(this.value,this.checked,'+i+')\' '
					if ((listaLayer[i].livHidden=='0')&&((listaLayer[i].stato)==1||(listaLayer[i].stato==3))) {
						stringaLegenda += 'CHECKED'; 
					}
					stringaLegenda += ' >' 
				}
				else {
					stringaLegenda += '<img src=\'images/lente.gif\' width=20 height=20 border=0 TITLE=\'Visibile da 1:' + listaLayer[i].scMin + ' a 1:' + listaLayer[i].scMax + '\'>'
				}
			}
	// cella vuota in corrispondenza del radio-button
			stringaLegenda += '</TD><TD>';
	// nome del livello
			stringaLegenda += '</TD><TD>';
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))) {
				stringaLegenda += '<b>' + listaLayer[i].titolo.substr(0,80) + '</b>';
			}
			else {
				stringaLegenda += listaLayer[i].titolo.substr(0,80);
			}
			stringaLegenda += '</TD>';
	// Fine riga
			stringaLegenda += '</TR>';
		   }
   	   	}
	}
// Livello per gli sfondi Google
	//if(tipoMappa=='OL') scriviLivelloSfondo();

// Piede
	stringaLegenda += '</TABLE>';
	stringaLegenda += '</FORM>';
	var legDiv = document.getElementById('LEGENDADIV');
	legDiv.innerHTML = stringaLegenda;	
}


// controlla che la url della rule non sia la url di una immagine jpg o gif o png
// ritorna true se non è un'immagine
function urlRuleNonImmagine(url) {

	returnCode = true;
	estensione = url.substr(url.length-4,4)
	if ((estensione=='.jpg')||(estensione=='.gif')||(estensione=='.gif'))
		returnCode = false;
	estensione = url.substr(url.length-5,5)
	if (estensione=='.jpeg')
		returnCode = false;

	return returnCode;		

}

// formatta i numeri usando la virgola come separatore decimale e il punto come separatore di migliaia
function formattaNumeri(nomeRule,separatore_decimale)
{
// splitto la stringa nelle singole parole 
	var parole=nomeRule.split(' ');
// ciclo sulle parole e se è numerica 

	for (indRule = 0; indRule < parole.length; indRule++) { 
		if (parole.length>1) {
			stringa = parole[indRule];
		}
		else {
			stringa = parole;
		}
		stringa += '';

		if (separatore_decimale==',')
			stringa = stringa.replace(',','.');

		if (!isNaN(stringa))
		{
//alert('ciao');
			if (separatore_decimale==',')
				stringa = stringa.replace('.',',');
			var numeroFormattato = aggiungiSeparatoreMigliaia(stringa,separatore_decimale);
//			alert(numero);
			nomeRule = nomeRule.replace(stringa,numeroFormattato);	
		}
	}
	return nomeRule
}


function aggiungiSeparatoreMigliaia(nStr,separatore_decimale)
{
	if (separatore_decimale==',')
		var separatore_migliaia='.';
	else
		var separatore_migliaia=',';

	nStr += '';
	x = nStr.split(separatore_decimale);
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + separatore_migliaia + '$2');
	}
	return x1 + x2;
}

function scriviLivelloSfondo() {
			stringaLegenda += '<TR>';
	// immagine simbologia
			stringaLegenda += '<TD>';
			stringaLegenda += '<img src=\'./images/legenda/raster.gif\'>' + '&nbsp;';
	// check-box
			stringaLegenda += '</TD><TD>';
			if (modo!='STAMPA') {
				stringaLegenda += '<INPUT TYPE=\'checkbox\' NAME=check VALUE=\'' + 'Sfondo' + '\' onClick=\'spegniLayer(this.value,this.checked,'+i+')\' '
				stringaLegenda += 'CHECKED'; 
				stringaLegenda += ' >' 
			}
	// cella vuota in corrispondenza del radio-button
			stringaLegenda += '</TD><TD>';
	// nome del livello
			stringaLegenda += '</TD><TD>';
			stringaLegenda += '<b>' + 'Sfondo' + '</b>';
			stringaLegenda += '</TD>';
	// Fine riga
			stringaLegenda += '</TR>';
}

function apriLegenda(ind) {
//alert(listaLayer[ind].titolo + ' ' + listaLayer[ind].numClassi);
	Opzioni = 'status=no, toolbar=no, menubar=no, width=300, height=486, resizable=yes, scrollbars=yes';
	WinLeg = window.open('','', Opzioni)
	WinLeg.focus();
	strLeg = ''; 

	strLeg += '<html><head><title>' + listaLayer[ind].titolo + '</title></head>';
	strLeg += '<body>';
	strLeg += '<b>' + listaLayer[ind].titolo+ ' <br><br></b>';
	strLeg += '<TABLE>';
//	for (k = 0; k < listaLayer[ind].numClassi; k++) {
	for (k = listaLayer[ind].numClassi-1; k >= 0; k--) {
		strLeg += '<TR>';
		strLeg += '<TD></TD><TD>';
		if ((listaLayer[ind].styleCurrent == '1')&&(listaLayer[ind].sldUrl!='')) {
			sUrl = listaLayer[ind].rules[k].url + "&SLD=" + listaLayer[ind].sldUrl;
		}
		else {
			sUrl = listaLayer[ind].rules[k].url;
		}
        if (listaLayer[ind].rules[k].url.indexOf('.jpg')>-1)
        {
            sUrl = listaLayer[ind].rules[k].url;
        }
		strLeg += '<img src=\'' + sUrl + '\' >' ;
		strLeg += '</TD><TD></TD><TD>';
		strLeg += listaLayer[ind].rules[k].name;
		strLeg += '</TD></TR>';
	}
	strLeg += '</TABLE>';
	strLeg += '</body></html>';
	WinLeg.document.close();
	WinLeg.document.write(strLeg+'<br>');
	WinLeg.focus();
}

function measure(X,Y){

	if(tipoMappa=='OL')
	{
    	var p = pointTrasfCoord(X,Y,'EPSG:900913','EPSG:3003');
		X = p.x;
		Y = p.y;
	}		

	clickXWorld[numClick]=X;
	clickYWorld[numClick]=Y;
	if (numClick==0){
		switch (bottoneAttivo) {
		case 'selezionecerchio': 
			document.getElementById('RAGGIOCERCHIODIV').style.display='block';
			document.getElementById('RAGGIOCERCHIODIV').style.background='white';
	        break; 
		case 'selezionePuntoBiomass': 
			SelezionePuntoBiomass(X,Y);
			break; 
		}
		disegnaPunto();
	}
	else{
		switch (bottoneAttivo) {
		case 'measureline': 
			disegnaLinea();
	        break; 
		case 'measurearea': 
			disegnaArea();
	        break; 
		case 'segnalazione': 
			disegnaCerchio();
	        break; 
		case 'selezionecerchio': 
			disegnaCerchioSelezione();
	        break; 
		case 'selezionerettangolo': 
			disegnaRettangoloSelezione();
	        break; 
		case 'selezionepoligono': 
			disegnaPoligonoSelezione();
	        break; 
		case 'selezionePoligonoBiomass': 
			SelezionePoligonoBiomass();
	        break; 
		case 'insertcoordinate': 
			disegnaPunto();
	        break; 
		case 'sialInsertPunti': 
			disegnaPunto();
	        break; 
		case 'impostafence': 
			disegnaRettangoloFence();
	        break; 
		}
	}
	numClick++;
	return;
}

function disegnaPuntoCentroMappa(color,size) {

// disegna un punto di colore e dimensioni date al centro della mappa
	if(tipoMappa!='OL') {
	    tlwcx = document.ECWView1.GetTopLeftWorldCoordinateX(); 
	    tlwcy = document.ECWView1.GetTopLeftWorldCoordinateY(); 
	    brwcx = document.ECWView1.GetBottomRightWorldCoordinateX(); 
	    brwcy = document.ECWView1.GetBottomRightWorldCoordinateY(); 
	    puntoX = tlwcx + (brwcx - tlwcx)/2;
	    puntoY = brwcy + (tlwcy - brwcy)/2;
	    var strPunti = puntoX + "," + puntoY + "|" + parseInt(puntoX-3) + "," + parseInt(puntoY-3);
	    var vecObject = "linewidth="+size+";color="+color+";fillcolor="+color+";"
	    vecObject += "filledcircle1=" + strPunti + ";"
	    document.ECWView1.SetLayerParameter("VectorOverlay2", vecObject);	
	}
	else {
		var bounds = map.getExtent();
		tlwcx = bounds.left;
		tlwcy = bounds.top;
		brwcx = bounds.right;
		brwcy = bounds.bottom;
	    puntoX = tlwcx + (brwcx - tlwcx)/2;
	    puntoY = brwcy + (tlwcy - brwcy)/2;
	    var point = new OpenLayers.Geometry.Point(puntoX,puntoY);
	    var feature = new OpenLayers.Feature.Vector(point);
	    var vectorLayer = map.getLayersByName("Vector Layer")[0];
		vectorLayer.destroyFeatures();
		vectorLayer.addFeatures(feature);

	}


}


function disegnaPunto(){

	var strPunti = clickXWorld[numClick] + "," + clickYWorld[numClick] + "|" + parseInt(clickXWorld[numClick]-3) + "," + parseInt(clickYWorld[numClick]-3);
	var vecObject = "linewidth=5;color=#00FF00;fillcolor=#00FF00;"
	vecObject += "filledcircle1=" + strPunti + ";"
	if(tipoMappa!='OL') {
		document.ECWView1.SetLayerParameter("VectorOverlay", vecObject);
	}
	insertCoordX=clickXWorld[numClick];
	insertCoordY=clickYWorld[numClick];

}

function disegnaCerchio(){

	var strPunti = clickXWorld[0] + "," + clickYWorld[0] + "|" + clickXWorld[1] + "," + clickYWorld[1];
	var vecObject = "linewidth=2;color=#00FF00;"
	vecObject += "circle1=" + strPunti + ";"
	document.ECWView1.SetLayerParameter("VectorOverlay", vecObject);

/*

	XWorld=pixel2worldX(clickX[0],width);
	YWorld=pixel2worldY(clickY[0],height);

	QuadLon1Ov=dWorldTLXPre;
	QuadLon2Ov=dWorldBRXPre;
	DimPixelX = (QuadLon2Ov-QuadLon1Ov)/width; 
	QuadLat1Ov=dWorldBRYPre;
	QuadLat2Ov=dWorldTLYPre;
	DimPixelY = (QuadLat2Ov-QuadLat1Ov)/height; 
	raggioWorld=Math.floor(Math.sqrt( Math.pow((clickX[1]-clickX[0])*DimPixelX,2) + Math.pow((clickY[1]-clickY[0])*DimPixelY,2) ));
*/

	raggioMetri=Math.floor(Math.sqrt( Math.pow(clickXWorld[1]-clickXWorld[0],2) + Math.pow(clickYWorld[1]-clickYWorld[0],2) ));

	var strHTML='<A href="javascript:segnalaVariazione(' + clickXWorld[0] + ',' + clickYWorld[0] + ',' + raggioMetri + ');">Conferma</A>';
	document.getElementById('DRAWCIRCLEDIV').style.display='block';
	document.getElementById('DRAWCIRCLEDIV').style.background='white';
	document.getElementById('DRAWCIRCLEDIV').innerHTML=strHTML;
}
	


function disegnaLinea(){
	var strPunti = "";
	var misura = 0;
	for(var i=0;i<clickXWorld.length-1;i++) 
	{ 
		misura += Math.sqrt( Math.pow(clickXWorld[i+1]-clickXWorld[i],2) + Math.pow(clickYWorld[i+1]-clickYWorld[i],2) );
		strPunti += clickXWorld[i] + "," + clickYWorld[i] + "|";
	} 
	strPunti += clickXWorld[clickXWorld.length-1] + "," + clickYWorld[clickXWorld.length-1];
	var strHTML='Distanza (m): ' + Math.round(misura);
	document.getElementById('MEASURELINEDIV').innerHTML=strHTML;
	var vecObject = "linewidth=2;color=#00FF00;fillcolor=#000000;"	
	vecObject += "polyline1=" + strPunti + ";"
	if(tipoMappa!='OL')
	    document.ECWView1.SetLayerParameter("VectorOverlay", vecObject);

}

function disegnaArea(){
	var strPunti = "";
	var misura = 0; 
	for(var i=0;i<clickXWorld.length-1;i++) 
	{ 
		misura += (clickXWorld[i+1]+clickXWorld[i])*(clickYWorld[i+1]-clickYWorld[i]);
		strPunti += clickXWorld[i] + "," + clickYWorld[i] + "|";
	} 
	strPunti += clickXWorld[clickXWorld.length-1] + "," + clickYWorld[clickXWorld.length-1];
	misura += (clickXWorld[0]+clickXWorld[i])*(clickYWorld[0]-clickYWorld[i]);

	var strHTML='Area (m^2): ' + Math.abs(Math.round(misura/2));
	document.getElementById('MEASUREAREADIV').innerHTML=strHTML;

	var vecObject = "linewidth=2;color=#00FF00;fillcolor=#000000;"	
	vecObject += "polygon1=" + strPunti + ";"
	if(tipoMappa!='OL')
	    document.ECWView1.SetLayerParameter("VectorOverlay", vecObject);

}

function disegnaRettangolo(){

	clickXWorld[2]=clickXWorld[1]
	clickYWorld[2]=clickYWorld[1]
	clickXWorld[1]=clickXWorld[0]
	clickXWorld[3]=clickXWorld[2]
	clickYWorld[3]=clickYWorld[0]

	var strPunti = "";
	for(var i=0;i<clickXWorld.length-1;i++) 
	{ 
		strPunti += clickXWorld[i] + "," + clickYWorld[i] + "|";
	} 
	strPunti += clickXWorld[clickXWorld.length-1] + "," + clickYWorld[clickXWorld.length-1];
	var vecObject = "linewidth=2;color=#00FF00;fillcolor=#000000;"	
	vecObject += "polygon1=" + strPunti + ";"
    document.ECWView1.SetLayerParameter("VectorOverlay", vecObject);

}

// converte le coordinate pixel in coordinate geografiche 
function pixel2worldX(offsetX){
	QuadLon1Ov=dWorldTLXPre;
	QuadLon2Ov=dWorldBRXPre;
	DimPixelX = (QuadLon2Ov-QuadLon1Ov)/width; 
     	return Math.ceil(parseInt(QuadLon1Ov) + parseInt(DimPixelX * offsetX)); 
}

function pixel2worldY(offsetY){
	QuadLat1Ov=dWorldBRYPre;
	QuadLat2Ov=dWorldTLYPre;
	DimPixelY = (QuadLat2Ov-QuadLat1Ov)/height; 
     	return Math.ceil(QuadLat2Ov - (DimPixelY * offsetY)); 
}


// Funzione getPositionClick: viene chiamata al click sul div per il pan dalla mappa di ov
function getPositionClick (event) {
	if (browser.isIE) 
	{
		centroX = window.event.offsetX;
		centroY = window.event.offsetY;
	}
	if (browser.isNS) 
	{
		offsetX = document.getElementById('MAPPA_OV').style.left;
		offsetX = offsetX.substring(0,offsetX.length-2);
		offsetY = document.getElementById('MAPPA_OV').style.top;
		offsetY = offsetY.substring(0,offsetY.length-2);
		centroX = parseInt(event.clientX)-parseInt(offsetX);
		centroY = parseInt(event.clientY)-parseInt(offsetY) - parseInt(4)
	}
	if(tipoMappa=='OL') {
		centroX = pixel2worldXOv(centroX);
		centroY = pixel2worldYOv(centroY);
		alert(centroX);
		var lonlat = new OpenLayers.LonLat.fromString(centroX + "," + centroY); 	
		map.setCenter(lonlat);
	}
	else
	{
		spostaMappa(centroX,centroY);
	}
}

// Funzione spostaMappa: effettua il recenter della mappa dalla mappa di OverView
function spostaMappa (offsetX,offsetY) 
{ 
	X = pixel2worldXOv(offsetX,ov_width);
	Y = pixel2worldYOv(offsetY,ov_height);
	xPre = dWorldTLXPre + (dWorldBRXPre - dWorldTLXPre)/2;
	yPre = dWorldBRYPre + (dWorldTLYPre - dWorldBRYPre)/2;
	setExtentsControllo(dWorldTLXPre+X-xPre,dWorldTLYPre+Y-yPre,dWorldBRXPre+X-xPre,dWorldBRYPre+Y-yPre);
	return true;
}
// converte le coordinate pixel in coordinate geografiche 
function pixel2worldXOv(offsetX){
	QuadLon1Ov=mappaIngombroBboxArray[0];
	QuadLon2Ov=mappaIngombroBboxArray[2];
	DimPixelX = (QuadLon2Ov-QuadLon1Ov)/ov_width; 
     	return Math.ceil(parseInt(QuadLon1Ov) + parseInt(DimPixelX * offsetX)); 
}
function pixel2worldYOv(offsetY){
	QuadLat1Ov=mappaIngombroBboxArray[1];
	QuadLat2Ov=mappaIngombroBboxArray[3];
	DimPixelY = (QuadLat2Ov-QuadLat1Ov)/ov_height; 
     	return Math.ceil(QuadLat2Ov - (DimPixelY * offsetY)); 
}


function mappaOvOnOff () {
		var theDiv = document.getElementById('MAPPA_OV');
		accendiSpegni(theDiv);
		var theDiv = document.getElementById('INGOMBRO');
		accendiSpegni(theDiv);
		var theDiv = document.getElementById('MAPPA_OV_CTRL');
		accendiSpegni(theDiv);
		var theDiv = document.getElementById('MAPPA_OV_ON');
		accendiSpegni(theDiv);
		var theDiv = document.getElementById('MAPPA_OV_OFF');
		accendiSpegni(theDiv);
}

function mappaContesto () {
		var theDiv = document.getElementById('MAPPA_OV');
//		alert(theDiv.style.display);
		accendiSpegni(theDiv);
		var theDiv = document.getElementById('INGOMBRO');
		accendiSpegni(theDiv);
		var theDiv = document.getElementById('MAPPA_OV_CTRL');
		accendiSpegni(theDiv);
}

function accendiSpegni(theDiv) {
/*
	if (theDiv.style.display=='block') 
		theDiv.style.display='none';
	else
		theDiv.style.display='block';
*/
	if (theDiv.style.display=='block') 
		theDiv.style.display='none';
	else
		theDiv.style.display='block';
}

// Scrive il frame della mappa di Ingombro
function spostaDivIngombro(dWorldTLX, dWorldTLY, dWorldBRX,dWorldBRY) {
//-- Calcolo la posizione del rettangolo
	ov_width=width/3;
	ov_height=height/3;
	QuadLon1Fit=mappaIngombroBboxArray[0];
	QuadLat1Fit=mappaIngombroBboxArray[1];
	QuadLon2Fit=mappaIngombroBboxArray[2];
	QuadLat2Fit=mappaIngombroBboxArray[3];
	QuadLon1=dWorldTLX;
	QuadLat1=dWorldBRY;
	QuadLon2=dWorldBRX;
	QuadLat2=dWorldTLY;
	divIngombroLeft = (QuadLon1-QuadLon1Fit)*(ov_width/(QuadLon2Fit-QuadLon1Fit))
	divIngombroTop = (QuadLat2Fit-QuadLat2)*(ov_height/(QuadLat2Fit-QuadLat1Fit))
	divIngombroWidth = (QuadLon2-QuadLon1Fit)*(ov_width/(QuadLon2Fit-QuadLon1Fit)) - (QuadLon1-QuadLon1Fit)*(ov_width/(QuadLon2Fit-QuadLon1Fit))
	divIngombroHeight = (QuadLat2Fit-QuadLat1)*(ov_height/(QuadLat2Fit-QuadLat1Fit)) - (QuadLat2Fit-QuadLat2)*(ov_height/(QuadLat2Fit-QuadLat1Fit))
	if (divIngombroWidth < 2) 
		divIngombroWidth = 2;
	if (divIngombroHeight < 2) 
		divIngombroHeight = 2;
	if (divIngombroWidth > ov_width) 
		divIngombroWidth = ov_width;
	if (divIngombroHeight > ov_height) 
		divIngombroHeight = ov_height;
	if (divIngombroHeight +divIngombroTop > ov_height) 
		divIngombroHeight = ov_height - divIngombroTop;
	if (divIngombroWidth +divIngombroLeft > ov_width) 
		divIngombroWidth = ov_width - divIngombroLeft;
	if ((divIngombroTop > ov_height)||(divIngombroLeft > ov_width)) {
		divIngombroTop = 0;
		divIngombroLeft = 0;
		divIngombroWidth = 0;
		divIngombroHeight = 0;
	}
	if (divIngombroTop < 0) 
		divIngombroTop = 0;
	if (divIngombroLeft < 0) 
		divIngombroLeft = 0;

// ----------------------------------------------------------------------------------------------------------------------------
// Se l'altezza del DIV è minore di 10 (BACO EXPLORER????) la posizione viene settata MALE in questo modo metto a posto le cose
	if (divIngombroHeight < 10) 
		divIngombroTop = divIngombroTop-(10-divIngombroHeight);
// ----------------------------------------------------------------------------------------------------------------------------

	var mappaIngombro = document.getElementById('INGOMBRO');
	var imgIngombro = document.getElementById('IMGTRASP');
	mappaIngombro.style.top=divIngombroTop;
	mappaIngombro.style.left=divIngombroLeft;
	mappaIngombro.style.width=divIngombroWidth;
	mappaIngombro.style.height=divIngombroHeight;
	imgIngombro.style.width=divIngombroWidth;
	imgIngombro.style.height=divIngombroHeight;
}

function mouseUp(buttonMask, screenX, screenY, worldX, worldY) {
//alert(bottoneAttivo);
	switch (bottoneAttivo) {
		case 'info': 
			InfoCarota(screenX, screenY, worldX, worldY,'attivo');
	        break; 
		case 'coordinate': 
			Coordinate(worldX, worldY);
	        break; 
		case 'zoomin': 
			Zoomin(worldX, worldY);
	        break; 
		case 'zoomout': 
			Zoomout(worldX, worldY);
	        break; 
		case 'insertPoint': 
			insertPoint(worldX, worldY, screenX, screenY);
	        break; 
		case 'selezioneoggetti': case 'selezionetopologica': case 'selezioneFogli': 
			SelezioneOggetti(bottoneAttivo,screenX, screenY, worldX, worldY);
	        break; 
		case 'schedaIncendi': 
			SelezioneParticella(screenX, screenY, worldX, worldY);
	        break; 
		case 'aggiungiRasterCatastoClick': 
			AggiungiRasterCatastoClick(screenX, screenY, worldX, worldY);
	        break; 
		case 'infocarota': 
			InfoCarota(screenX, screenY, worldX, worldY,'carota');
	        break; 
		case 'measureline': case 'measurearea': case 'segnalazione': case 'selezionecerchio': case 'selezionerettangolo': case 'selezionepoligono': 
		case 'insertcoordinate': case 'sialInsertPunti': case 'impostafence': case 'selezionePuntoBiomass': case 'selezionePoligonoBiomass':
		    measure(worldX, worldY);
	        break; 
	}

}




function Zoomin (X,Y){

	X1 = X - (dWorldBRXPre-dWorldTLXPre)/4;
	X2 = parseInt(X) + parseInt((dWorldBRXPre-dWorldTLXPre)/4);
	Y1 = Y - (dWorldTLYPre-dWorldBRYPre)/4;
	Y2 = parseInt(Y) + parseInt((dWorldTLYPre-dWorldBRYPre)/4);
	setExtentsControllo(X1,Y2,X2,Y1);
	return;
}


function setExtentsControllo(X1,Y2,X2,Y1,transform){
//alert(X1+' '+Y1+' '+X2+' '+Y2 + ' setExtentsControllo');
	if(tipoMappa!='OL') {
		document.ECWView1.SetExtents(X1,Y2,X2,Y1);
	}
	else {

		var strBbox = X1 + ',' + Y1 + ',' + X2 + ',' + Y2;
//console.log(strBbox);
		setMapCenter(strBbox,transform);
	}
}

function insertPoint (X,Y,scrX,scrY){
	
	var strPunti = X + "," + Y + "|" + parseInt(X-300) + "," + parseInt(Y-300);
	var vecObject = "linewidth=2;color=#00FF00;fillcolor=#00FF00;"
	vecObject += "filledcircle1=" + strPunti + ";"
	document.ECWView1.SetLayerParameter("VectorOverlay", vecObject);
	
	Parametri='';
	if (listaParam.length > 0) {
		for (i = 0; i < listaParam.length; i++){
			if (listaParam[i].name == 'AspInsertPoint') {
				Parametri = listaParam[i].value + '&X=' + X + '&Y=' + Y;
			}
		}
	}

	if (Parametri=='') {
		alert('errore: manca parametro AspInsertPoint');
	}
	else{
		Opzioni = 'status=yes, toolbar=yes, menubar=no, width=600, height=486, resizable=yes, scrollbars=yes';
		//alert(Parametri);
		WinInsertPoint = window.open(Parametri, 'InsertPoint', Opzioni)
		WinInsertPoint.focus();
	}
	return;
}

function Zoomout (X,Y){
	X1 = X - (dWorldBRXPre-dWorldTLXPre);
	X2 = parseInt(X) + parseInt((dWorldBRXPre-dWorldTLXPre));
	Y1 = Y - (dWorldTLYPre-dWorldBRYPre);
	Y2 = parseInt(Y) + parseInt((dWorldTLYPre-dWorldBRYPre));
	setExtentsControllo(X1,Y2,X2,Y1);
	return;
}

function Coordinate (X,Y){

	if(tipoMappa=='OL')
	{
    	var p = pointTrasfCoord(X,Y,'EPSG:900913','EPSG:3003');
		X = p.x;
		Y = p.y;
	}		

	var strHTML="Coordinate:  X= " + parseInt(X) + " \nY = " + parseInt(Y);
	document.getElementById('MEASUREPOINTDIV').innerHTML=strHTML;
	return;
}



function pan(direction) {    

	var pansize = 0.50;
	switch (direction) {
		case 'n' : 
			x1 = dWorldTLXPre;
			y1 = parseFloat(dWorldBRYPre)+parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
			x2 = dWorldBRXPre;
			y2 = parseFloat(dWorldTLYPre)+parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
	        break; 
		case 'nw' : 
			x1 = parseFloat(dWorldTLXPre)-parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y1 = parseFloat(dWorldBRYPre)+parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
			y2 = parseFloat(dWorldTLYPre)+parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
			x2 = parseFloat(dWorldBRXPre)-parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
	        break; 
		case 'ne' : 
			x1 = parseFloat(dWorldTLXPre)+parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y1 = parseFloat(dWorldBRYPre)+parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
			x2 = parseFloat(dWorldBRXPre)+parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y2 = parseFloat(dWorldTLYPre)+parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
	        break; 
		case 's' : 
			x1 = dWorldTLXPre;
			y1 = parseFloat(dWorldBRYPre)-parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
			x2 = dWorldBRXPre;
			y2 = parseFloat(dWorldTLYPre)-parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
	        break; 
		case 'sw' : 
			x1 = parseFloat(dWorldTLXPre)-parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y1 = parseFloat(dWorldBRYPre)-parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
			x2 = parseFloat(dWorldBRXPre)-parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y2 = parseFloat(dWorldTLYPre)-parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
	        break; 
		case 'se' : 
			x1 = parseFloat(dWorldTLXPre)+parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y1 = parseFloat(dWorldBRYPre)-parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
			x2 = parseFloat(dWorldBRXPre)+parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y2 = parseFloat(dWorldTLYPre)-parseFloat((dWorldTLYPre-dWorldBRYPre)*pansize);
	        break; 
		case 'e' : 
			x1 = parseFloat(dWorldTLXPre)+parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y1 = dWorldBRYPre;
			x2 = parseFloat(dWorldBRXPre)+parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y2 = dWorldTLYPre;
	        break; 
		case 'w' : 
			x1 = parseFloat(dWorldTLXPre)-parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y1 = dWorldBRYPre;
			x2 = parseFloat(dWorldBRXPre)-parseFloat((dWorldBRXPre-dWorldTLXPre)*pansize);
			y2 = dWorldTLYPre;
	        break; 
	} 	
	setExtentsControllo(x1,y2,x2,y1);
	return;
  }



function helpcarto() {
	var idRichiesta = valoreParametro('idRichiesta');
	sUrlInfo='Help2/CartoHelp.asp?CwContext=' + CwContext + '&CodApplicazione=' + CodApplicazione + '&idRichiesta=' + idRichiesta;
	Opzioni = 'status=yes, toolbar=yes, menubar=no, width=800, height=586, resizable=yes, scrollbars=yes';
	WinHelp = window.open(sUrlInfo, 'Help', Opzioni)
	WinHelp.focus();

}



function attivaLayer(nomeLayer,visible,indice) {
	livAttivo=indice;
//alert(livAttivo);
}


function SetPointerMode(value) {
	document.ECWView1.SetPointerMode(value);

}


function SetExtentsHome() {
	setExtentsControllo(bboxArray[0],bboxArray[3],bboxArray[2],bboxArray[1]);
}

function SetExtentsAll() {
	setExtentsControllo(mappaIngombroBboxArray[0],mappaIngombroBboxArray[3],mappaIngombroBboxArray[2],mappaIngombroBboxArray[1]);
}

function zoomtoscale(scaleIn) {
	if ((scaleIn==null)||(scaleIn==0))
		scale = document.Scala.Scala.value;
	else
		scale = scaleIn;

	if(tipoMappa!='OL')
	{
		tlwcx = document.ECWView1.GetTopLeftWorldCoordinateX(); 
		tlwcy = document.ECWView1.GetTopLeftWorldCoordinateY(); 
		brwcx = document.ECWView1.GetBottomRightWorldCoordinateX(); 
		brwcy = document.ECWView1.GetBottomRightWorldCoordinateY(); 
		if(scale > 1) {
			imageWidth = brwcx - tlwcx; 
			imageHeight = tlwcy - brwcy; 
			widthUnits = (scale / 9600) * (document.ECWView1.GetViewWidth() * 2.54); 
			heightUnits = (scale / 9600) * (document.ECWView1.GetViewHeight()* 2.54); 
			tlx = tlwcx + (imageWidth / 2) - (widthUnits / 2); 
			brx = brwcx - (imageWidth / 2) + (widthUnits / 2); 
			tly = tlwcy - (imageHeight / 2) + (heightUnits / 2); 
			bry = brwcy + (imageHeight / 2) - (heightUnits / 2);
		} else {
			tlx = tlwcx;
			tly = tlwcy;
			brx = brwcx;
			bry = brwcy;
		}
		setExtentsControllo(tlx, tly, brx, bry); 
	}
	else
	{
		map.zoomToScale(scale,true)
	}

}

function onLayerResponseCb(sName, sURL, sBody, sAction, dWorldTLX, dWorldTLY,dWorldBRX, dWorldBRY, sResponse)
{
	if(sResponse != "NCS_OVERLAY_SUCCESS") {
		alert('Errore caricamento layer: \n'+sName+'\n'+sURL+'\n'+sResponse);
		if (debug) {
			Opzioni = 'status=yes, toolbar=yes, menubar=no, width=1000, height=486, resizable=yes, scrollbars=yes';
			WinAlert = window.open('', 'alert', Opzioni)
			WinAlert.document.write('<br>------------------------------ errore caricamento layer -----------<br>'+sResponse+'<br>------------------------------<br>');
		}
	}
	if (sName.substring(0,5)!="LOGO_") {
		flgAttesaLiv -- ;		
//alert('onLayerResponseCb' +  sName + ' ' + flgAttesaLiv);
		if((flgAttesaLiv == 0)) {
			document.getElementById('ATTENDERE').style.display='none';
		}
	}

}


function onPercentCompleteCb(value) {
}



function impostaTrasparenza(i,livello,nomeLiv,valore) {
//alert(livello+' '+valore);
	listaLayer[i].trasp=valore;
	livelloTit = listaLayer[i].titolo;
	if (listaLayer[i].tipo=='ECW')
		livelloName = listaLayer[i].nameWmsEcw;
	else
		livelloName = listaLayer[i].name;
	mask = '#';
	SetLayerTransparency(livelloTit,mask, valore/100);
//alert('sono qui ' + document.ECWView1.GetLayerTransparency(livelloTit, "#" ) + ' ' + valore);

// gestione livello find
	for (k = 0; k < listaLivFind.length; k++){
//alert(listaLivFind[k].titolo + ' ' + nomeLiv);
		if (listaLivFind[k].titolo==nomeLiv){
			livelloFind = 'find'+nomeLiv;
			mask = '#';
			SetLayerTransparency(livelloFind, mask,  valore/133);
		}
	}
// gestione livello selezione oggetti e topologica
	for (k = 0; k < listaLivSelezione.length; k++){
		if (listaLivSelezione[k].titolo==nomeLiv){
			livelloFind = 'find2'+nomeLiv;
			mask = '#';
			SetLayerTransparency(livelloFind,mask,  valore/133);
		}
	}
	if (livFind2==livelloTit){
		mask = '#';
		SetLayerTransparency("find2", mask,  valore/133);
	}
	if (livInfo==livelloTit){
		mask = '#';
		SetLayerTransparency("info",mask, valore/133);
	}
}

function SetLayerTransparency(livelloTit, mask, valore)
{
	if(tipoMappa!='OL')
	{
		document.ECWView1.SetLayerTransparency(livelloTit, mask , valore);
	}
	else
	{
		var layers = map.getLayersByName(livelloTit);
		if (layers.length>0)
		{
			layers[0].setOpacity(valore);
		}
	}
}


function cambiaBottone(bottone,numBott) {

// cambio immagine bottone
// attivo il bottone OpenLayers
	toggleDrawControl(bottone);
	var bottDiv = document.getElementById('BOTTONI');
	var bottoni_tutti = bottDiv.getElementsByTagName('img');
	bottoni = new Array();
	k=0;
	for (i = 0; i < bottoni_tutti.length; i++){
		if (bottoni_tutti[i].id != 'ButtOpenClose'){
			bottoni[k]=bottoni_tutti[i];
			k++;
		}
	}
	for (i = 0; i < bottoni.length; i++) 
	{ 
		if (i==numBott) 
		{ 
			oldSrc = bottoni[i].src;
			if (oldSrc.indexOf('_s') == -1)
			{ 
				newSrc = oldSrc.substr(0,oldSrc.length - 4) + '_s.gif'; 
				bottoni[i].src=newSrc; 
			} 
		}
		else 
		{ 
			oldSrc = bottoni[i].src; 
			if (oldSrc.indexOf('_s') > -1)
			{ 
				newSrc = oldSrc.substr(0,oldSrc.length - 6) + '.gif'; 
				bottoni[i].src=newSrc; 
			} 
		} 
	} 
// ripulisco la grafica delle misure
	pulisciGraficaMisure();
//  imposto la visibilità dei div
	document.getElementById('RICERCALOCALITADIV').style.display='none';
//	document.getElementById('MEASAPPO').style.display='none';
	document.getElementById('MEASUREPOINTDIV').style.display='none';
	document.getElementById('MEASUREPOINTDIV').innerHTML='Coordinate: ';
	document.getElementById('MEASURELINEDIV').style.display='none';
	document.getElementById('MEASURELINEDIV').innerHTML='Distanza (m): ';
	document.getElementById('MEASUREAREADIV').style.display='none';
	document.getElementById('MEASUREAREADIV').innerHTML='Area (m^2): ';
	document.getElementById('MEASURERESET').style.display='none';
	document.getElementById('DRAWCIRCLEDIV').style.display='none';
	document.getElementById('RAGGIOCERCHIODIV').style.display='none';
// impostazione stato puntatore 
	switch (bottone) {
		case 'pan' : 
			value=0;
	        break; 
		case 'zoomdinamico' : 
			value=1;
	        break; 
		case 'zoombox' : 
			value=3;
	        break; 
		case 'coordinate' : 
			initMeasurePoint();
			value=2;
	        break; 
		case 'measureline' : 
			initMeasureLine();
	        break; 
		case 'measurearea' : 
			initMeasureArea();
	        break; 
        case 'segnalazione' : 
			value=2;
			measureInit();
	        break; 
        case 'insertcoordinate' : 
			value=2;
			initInsertCoordinate();
	        break; 
        case 'sialInsertPunti' : 
			value=2;
			sialInit();
	        break; 
        case 'selezionecerchio' : case 'selezionerettangolo' : case 'selezionepoligono' : case 'impostafence' : 
			value=2;
			measureInit();
	        break; 
        case 'selezionePuntoBiomass':
			initMeasureBiomassPunto();
	        break; 
        case 'selezionePoligonoBiomass':
			initMeasureBiomassPoligono();
	        break; 
        case 'selezioneoggetti' : case 'selezionetopologica' : case 'selezioneFogli':
			value=2;
			SelezioneOggetti(bottone,'','','','');
	        break; 
        case 'schedaIncendi' : 
			value=2;
			SelezioneParticella('','','','');
	        break; 
		default : 
			value=2;
	} 	

	bottoneAttivo=bottone;
	if(tipoMappa!='OL')
		document.ECWView1.SetPointerMode(value);
}

function pulisciGraficaMisure()
{	

	if(tipoMappa!='OL')
	{
		ECWVectorLayer.clear();
	}
	else
	{
		var layers = map.getLayersByName("Vector Layer");
		layers[0].destroyFeatures();
	}			
}

function initMeasurePoint()
{
	document.getElementById('MEASUREPOINTDIV').style.display='block';
	document.getElementById('MEASUREPOINTDIV').style.background='white';
	if(tipoMappa=='OL')
	{
		toggleDrawControl('point');
		measureInit();
	}
}


function initMeasureLine()
{			
	document.getElementById('MEASURELINEDIV').style.display='block';
	document.getElementById('MEASURELINEDIV').style.background='white';
	if(tipoMappa!='OL')
	{
		vectorMode = "polygon";
	    ECWVectorLayer.setMode(vectorMode);
		ECWVectorLayer.objectNumPoints = 0;
		value=2;
	}
	else
	{
		toggleDrawControl('line');
	}

	measureInit();

}

function initMeasureArea()
{
	if(tipoMappa=='OL')
	{
		toggleDrawControl('polygon');
	}
	document.getElementById('MEASUREAREADIV').style.display='block';
	document.getElementById('MEASUREAREADIV').style.background='white';
	value=2;
	measureInit();
}
			
function initMeasureBiomassPoligono()
{
	if(tipoMappa=='OL')
	{
		toggleDrawControl('polygon');
	}
	value=2;
	measureInit();
}
			
function initMeasureBiomassPunto()
{
	if(tipoMappa=='OL')
	{
		toggleDrawControl('point');
		measureInit();
	}
	measureInit();
}
			

function showHideButtonGroup(gruppo) {
//alert(gruppo);
// cambio immagine apri/chiudi
	var divTitolo = document.getElementById(gruppo + '_TIT');
	var imgTitolo = divTitolo.getElementsByTagName('img');
	oldSrc = imgTitolo[0].src
	if (oldSrc.indexOf('_close') == -1)
	{ 
		newSrc = oldSrc.substr(0,oldSrc.length - 9) + '_close.gif'; 
		imgTitolo[0].src=newSrc; 
		imgTitolo[0].TITLE='Chiudi'; 
		document.getElementById(gruppo + '_BOT').style.display='block';
			
	} 
	else
	{ 
		newSrc = oldSrc.substr(0,oldSrc.length - 10) + '_open.gif'; 
		imgTitolo[0].src=newSrc; 
		imgTitolo[0].TITLE='Apri'; 
		document.getElementById(gruppo + '_BOT').style.display='none';

	}
}

function measureInit(){

	clickX = new Array();
	clickY = new Array();
	clickXWorld = new Array();
	clickYWorld = new Array();
	numClick=0;

	if(tipoMappa!='OL')
	{
		ECWVectorLayer.clear();
	}
	else
	{
		pulisciGraficaMisure();
	}
	
	document.getElementById('MEASURERESET').style.display='block';
	document.getElementById('MEASURERESET').style.background='white';
//	document.getElementById('MEASAPPO').style.display='block';
	document.getElementById('MEASURELINEDIV').innerHTML='Distanza (m): ';
	document.getElementById('MEASUREAREADIV').innerHTML='Area (m^2): ';
	document.getElementById('DRAWCIRCLEDIV').innerHTML='';
	document.getElementById('RAGGIOCERCHIODIV').style.display='none';
}


	
function gestioneTrasparenza() {


	//strTitolo=joinArray(listaLayer,'titolo');
	var strTitolo = "";
	for(var i=0;i<listaLayer.length;i++){
		titoloLiv = listaLayer[i].titolo;
		rExp = /,/g;
		titoloLiv = titoloLiv.replace(rExp,'**VIRGOLA**');
// -- sostituzione caratteri accentati
// à - 224 - %E0
// è - 232 - %E8
// é - 233 - %E9 
// ì - 236 - %EC
// ò - 242 - %F2
// ù - 249 - %F9
		titoloLiv = titoloLiv.replace(String.fromCharCode(224),'%E0')
		titoloLiv = titoloLiv.replace(String.fromCharCode(232),'%E8')
		titoloLiv = titoloLiv.replace(String.fromCharCode(233),'%E9')
		titoloLiv = titoloLiv.replace(String.fromCharCode(236),'%EC')
		titoloLiv = titoloLiv.replace(String.fromCharCode(242),'%F2')
		titoloLiv = titoloLiv.replace(String.fromCharCode(249),'%F9')
//
		strTitolo = strTitolo + titoloLiv + ",";
	}
	strTitolo=strTitolo.substring(0,strTitolo.length-1);
	//
	strNome=joinArray(listaLayer,'name');
	strTrasp=joinArray(listaLayer,'trasp');
	strTipo=joinArray(listaLayer,'tipo');
	Pagina = 'CWGestioneTrasparenza.asp?Livelli='+strTitolo+'&NomeLiv='+strNome+'&Valore='+strTrasp+'&Tipo='+strTipo+'&Stile='+stile;
	Opzioni = 'status=yes, toolbar=yes, menubar=no, width=600, height=300, resizable=yes, scrollbars=yes';
	WinGestLeg = window.open(Pagina, 'GestioneTrasparenza', Opzioni)
	WinGestLeg.focus();
return;
}

// -- prende in input un array di oggetti e il nome di una proprietà dell'oggetto e costruisce una stringa con il concatenamento delle proprietà con delimitatore la virgola ","
function joinArray(arrayLiv,propr) {
	var strArray = "";
	for(var i=0;i<arrayLiv.length;i++){
		strComando = 'strArray = strArray + arrayLiv[i].' + propr + ' + ",";'
		eval(strComando);
	}
	strArray=strArray.substring(0,strArray.length-1);
	return strArray;
}

// -- prende in input un array di oggetti e il nome di una proprietà dell'oggetto e costruisce una stringa con il concatenamento delle proprietà con delimitatore doppio-pipe "||"
function joinArray2(arrayLiv,propr) {
	var strArray = "";
	for(var i=0;i<arrayLiv.length;i++){
		strComando = 'strArray = strArray + arrayLiv[i].' + propr + ' + "||";'
		eval(strComando);
	}
	strArray=strArray.substring(0,strArray.length-2);
	return strArray;
}
// -------------------------------------------
// Aggiorno l'ordine dei livelli
// -------------------------------------------
function aggiornaOrdine() {
	j=1;
	for (i = 0; i < listaLayer.length; i++){
		if (listaLayer[i].tipoGeom=='Raster'){
			listaLayer[i].ordine=j;
			j=j+1;
		}
		maxIndEcw=j;
	}
	for (i = 0; i < listaLayer.length; i++){
		if (listaLayer[i].tipoGeom!='Raster'){
			listaLayer[i].ordine=j;
			j=j+1;
		}
	}
	for (i = 0; i < listaLayer.length; i++){
		indice = GetLayerIndex(listaLayer[i].titolo,listaLayer[i].name);
		if ((indice!=-1)&&(indice!=listaLayer[i].ordine)) {
			MoveLayer(indice,listaLayer[i].ordine,listaLayer[i].titolo);
		}
	}
	if(tipoMappa!='OL')
	{
		indice=document.ECWView1.GetLayerIndex("VectorOverlay");
		document.ECWView1.MoveLayer(indice,999);
		indice=document.ECWView1.GetLayerIndex("VectorOverlay2");
		document.ECWView1.MoveLayer(indice,998);
	}
}

function GetLayerIndex(titolo,nome)
{
	if(tipoMappa!='OL')
	{
		indiceLayer = document.ECWView1.GetLayerIndex(titolo);
	}
	else
	{
		var layers = map.getLayersByName(titolo);
		indiceLayer = map.getLayerIndex(layers[0]);
	}
	return indiceLayer;

}

function MoveLayer(indice,nuovoIndice,titolo)
{
	if(tipoMappa!='OL')
	{
		document.ECWView1.MoveLayer(indice,nuovoIndice);
	}
	else
	{
		var layers = map.getLayersByName(titolo);
		map.setLayerIndex(layers[0],nuovoIndice);
	}
}

function stampa() {
	StrContext = preparaContext();
	document.Servizio.Context.value = StrContext;
	Pagina =  'CWStampa.asp?tipoMappa=' + tipoMappa;
	Opzioni = 'status=yes, toolbar=yes, menubar=yes, width=800, height=600, resizable=yes, scrollbars=yes';
	WinStampa = window.open(Pagina, 'Stampa', Opzioni)
	WinStampa.focus();
	return;
}

function immagineMappa() {
	gestStampa('IMMAGINE');
}

function creaPDF() {
	gestStampa('PDF');
}

function gestStampa(modo) 
{
//	StrContext = preparaContext();
//	alert(StrContext);
    winWidth = parseInt(width)+parseInt(50)
    winHeight = parseInt(height)+parseInt(50)
	Opzioni = 'status=yes, toolbar=yes, menubar=yes, width=' + winWidth + ', height=' + winHeight + ', resizable=yes, scrollbars=yes';
	WinStampa = window.open('', '', Opzioni)
	WinStampa.document.close();
	var strHtml = "<HTML><BODY onLoad='document.Scheda.submit();'><FORM NAME='Scheda' ACTION='CwStampa.aspx' METHOD=POST><INPUT TYPE=hidden NAME=MODO VALUE='" + modo + "'>";	
//	var strHtml = "<HTML><BODY><FORM NAME='Scheda' ACTION='CwStampa.aspx' METHOD=POST><INPUT TYPE=hidden NAME=MODO VALUE='" + modo + "'>";	
	strHtml += "<INPUT TYPE=hidden NAME=TIPOMAPPA VALUE='" + tipoMappa + "'>";
	strHtml += "<INPUT TYPE=hidden NAME=TITOLO VALUE='" + nomeMappa + "'>";
	strHtml += "<INPUT TYPE=hidden NAME=WIDTH VALUE='" + width + "'>";
	strHtml += "<INPUT TYPE=hidden NAME=HEIGHT VALUE='" + height + "'>";
// versione Plug-In ECW
    if (tipoMappa!='OL') {
	    for (i = 0; i < listaLayer.length; i++){
 		    if ((listaLayer[i].tipo=="ECW")&&(listaLayer[i].stato==1)) {
                sUrl = calcolaWmsUrl(listaLayer[i].urlWmsEcw,listaLayer[i].nameWmsEcw,'','');
        	    strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	    strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
            }
        }
	    for (i = 0; i < listaLayer.length; i++){
 		    if ((listaLayer[i].tipo=="WMS")&&(listaLayer[i].tipoGeom=='Raster')&&(listaLayer[i].stato==1)) {
                sUrl = calcolaWmsUrl(listaLayer[i].url,listaLayer[i].titolo,listaLayer[i].sldUrl,listaLayer[i].styleCurrent);
        	    strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	    strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
            }
        }
	    for (i = 0; i < listaLayer.length; i++){
 		    if ((listaLayer[i].tipo=="WMS")&&(listaLayer[i].tipoGeom!='Raster')&&(listaLayer[i].stato==1)) {
                sUrl = calcolaWmsUrl(listaLayer[i].url,listaLayer[i].titolo,listaLayer[i].sldUrl,listaLayer[i].styleCurrent);
        	    strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	    strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
            }
        }
    }
// versione OL
    else {
// calcolo il bound della mappa
		var bbStr = dWorldTLXPre + "," + dWorldBRYPre + "," + dWorldBRXPre + "," + dWorldTLYPre
		var bounds = OpenLayers.Bounds.fromString(bbStr)
//
	    for (i = 0; i < listaLayer.length; i++){
 		    if ((listaLayer[i].tipo=="ECW")&&(listaLayer[i].stato==1)) {
        		var layers = map.getLayersByName(listaLayer[i].titolo);
                if (layers.length>0) {
        		    sUrl = layers[0].getURL(bounds);
        	        strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	        strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
        	    }
            }
        }
	    for (i = 0; i < listaLayer.length; i++){
 		    if ((listaLayer[i].tipo=="WMS")&&(listaLayer[i].tipoGeom=='Raster')&&(listaLayer[i].stato==1)) {
        		var layers = map.getLayersByName(listaLayer[i].titolo);
                if (layers.length>0) {
        		    sUrl = layers[0].getURL(bounds);
        		    strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	        strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
                }
            }
        }
	    for (i = 0; i < listaLayer.length; i++){
 		    if ((listaLayer[i].tipo=="WMS")&&(listaLayer[i].tipoGeom!='Raster')&&(listaLayer[i].stato==1)) {
        		var layers = map.getLayersByName(listaLayer[i].titolo);
                if (layers.length>0) {
        		    sUrl = layers[0].getURL(bounds);
        		    strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	        strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
                }
// guardo se ci sono layer accessori associati al layer
        		var layers = map.getLayersByName("find");
                if (layers.length>0) {
        		    sUrl = layers[0].getURL(bounds);
        		    strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	        strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
                }
        		var layers = map.getLayersByName("find2");
                if (layers.length>0) {
        		    sUrl = layers[0].getURL(bounds);
        		    strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
        	        strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + listaLayer[i].trasp + "'>";
                }
            }
        }
// layer info
	    var layers = map.getLayersByName("info");
        if (layers.length>0) {
	        sUrl = layers[0].getURL(bounds);
	        infoTrasp = "75";
	        strHtml += "<INPUT TYPE=hidden NAME=IMGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
            strHtml += "<INPUT TYPE=hidden NAME=IMGTRASP VALUE='" + infoTrasp + "'>";
        }
// Compongo la definizione dei tile del layer base 
		strOLBaseLayerTiles = getOLBaseLayerTiles(); 
    	strHtml += "<INPUT TYPE=hidden NAME=strOLBaseLayerTiles VALUE='" + strOLBaseLayerTiles.replace(/'/g,'***APICE***') + "'>"
    }
// Compongo la definizione della leganda 
	strHtml += componiCampiLegenda(); 
	strHtml += "</FORM></BODY></HTML>";
	WinStampa.document.write(strHtml);
	WinStampa.document.close();
	WinStampa.focus();
	return;
}



// compongo i campi HIDDEN per la legenda
function componiCampiLegenda()
{
    var strHMTL = "";
    for (i = 0; i < listaLayer.length; i++){
	    if ((listaLayer[i].tipo=="ECW")&&(listaLayer[i].stato==1)) {
            componiCampiLegendaHTML(i)
        }
    }
    for (i = 0; i < listaLayer.length; i++){
        if ((listaLayer[i].tipo=="WMS")&&(listaLayer[i].tipoGeom=='Raster')&&(listaLayer[i].stato==1)) {
            componiCampiLegendaHTML(i)
        }
    }
    for (i = 0; i < listaLayer.length; i++){
        if ((listaLayer[i].tipo=="WMS")&&(listaLayer[i].tipoGeom!='Raster')&&(listaLayer[i].stato==1)) {
            componiCampiLegendaHTML(i)
        }
    }
    return strHMTL;
}


function componiCampiLegendaHTML(i)
{
// layer ECW
    if (listaLayer[i].tipo=="ECW") {
        if (listaLayer[i].legImg!="") { 
            sUrl = listaLayer[i].legImg;
        }
        else { 
            sUrl = './images/legenda/raster.gif';
        }
    }
// layer WMS
    else
    {
		switch (listaLayer[i].tipoGeom) {
		    case 'Raster': 
                if (listaLayer[i].legImg!="") { 
                    sUrl = listaLayer[i].legImg;
                }
                else { 
                    sUrl = './images/legenda/raster.gif';
                }
				break; 
			case 'Text': 
                sUrl = './images/legenda/text.gif';
				break; 
			default:
                switch (listaLayer[i].legTipo) {
                // - livello con legenda in pop-up	
                    case '1': 
                        sUrl = 'images/legenda/tema.gif';
                        break; 
                    case '2': 
                // - No Classi in Legenda (livello diviso in classi ma con una sola voce in legenda) 
                        if (listaLayer[i].legImg!="") 
                        { 
	                        sUrl = listaLayer[i].legImg;
                        }
                        else
                        {
	                        if ((listaLayer[i].styleCurrent == '1')&&(listaLayer[i].sldUrl!='')&&(urlRuleNonImmagine(listaLayer[i].rules[k].url))) {
		                        sUrl = listaLayer[i].rules[0].url + "&SLD=" + listaLayer[i].sldUrl;
	                        }
	                        else {
		                        sUrl = listaLayer[i].rules[0].url;
	                        }
                        }
                        break; 
                    case '0': 
                // - livello normale
                        if (listaLayer[i].legImg!="") { 
	                        sUrl = listaLayer[i].legImg;
                        }
                        else {
	                        if ((listaLayer[i].numClassi>1))  {
		                        sUrl = 'images/legenda/tema.gif';
	                        }
	                        else {
		                        if ((listaLayer[i].styleCurrent == '1')&&(listaLayer[i].sldUrl!='')&&(urlRuleNonImmagine(listaLayer[i].rules[0].url))) {
			                        sUrl = listaLayer[i].rules[0].url + "&SLD=" + listaLayer[i].sldUrl;
		                        }
		                        else {
			                        sUrl = listaLayer[i].rules[0].url;
		                        }
	                        }							
                        }
                        break; 
                }
		}            
    }    
// scrivo i campi
    sNome = listaLayer[i].titolo.substr(0,80);
    strHMTL = "";
    strHMTL += "<INPUT TYPE=hidden NAME=LEGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
    strHMTL += "<INPUT TYPE=hidden NAME=LEGNOME VALUE='" + 	sNome + "'>";
    strHMTL += "<INPUT TYPE=hidden NAME=LEGCLASSE VALUE='N'>";
// nel caso di livello con + classi e legenda non in pop-up scrivo le righe delle classi
	if ((listaLayer[i].legTipo=="0")&&(listaLayer[i].numClassi>1)) {
		for (k = 0; k < listaLayer[i].numClassi; k++) {
            // url immagine
			if ((listaLayer[i].styleCurrent == '1')&&(listaLayer[i].sldUrl!='')&&(urlRuleNonImmagine(listaLayer[i].rules[k].url))) {
				sUrl = listaLayer[i].rules[k].url + "&SLD=" + listaLayer[i].sldUrl;
			}
			else {
				sUrl = listaLayer[i].rules[k].url;
			}
            // legenda
			if (separatore_decimale!='')
				sNome = formattaNumeri(listaLayer[i].rules[k].name,separatore_decimale);
			else
				sNome = listaLayer[i].rules[k].name;
// scrivo i campi
            strHMTL += "<INPUT TYPE=hidden NAME=LEGURL VALUE='" + sUrl.replace(/,/g,'***VIRGOLA***') + "'>";
            strHMTL += "<INPUT TYPE=hidden NAME=LEGNOME VALUE='" + 	sNome + "'>";
            strHMTL += "<INPUT TYPE=hidden NAME=LEGCLASSE VALUE='S'>";
		}
	}
        
}



function getOLBaseLayerTiles() {
    var mapview  = map;
    var size     = mapview.getSize();
    // go through all layers, and collect a list of objects
    // each object is a tile's URL and the tile's pixel location relative to the viewport
    var tiles = [];
    for (layername in mapview.layers) {
      // if the layer isn't visible at this range, or is turned off, skip it
		var layer = mapview.layers[layername];
		if (!layer.getVisibility()) continue;
		if (!layer.isBaseLayer) continue;
		var layerDiv = document.getElementById(layer.div.id);
//	  document.write(layerDiv.innerHTML);
		var images = layerDiv.getElementsByTagName("img");
		var strXmlOL = "<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>";
		strXmlOL  += '<OLBaseLayer version=\'2.0.0\' xmlns:xlink=\'http://www.w3.org/TR/xlink\' xmlns:sld=\'http://www.opengis.net/sld\'  xmlns:ogc=\'http://www.opengis.net/ogc\'>'	
		strXmlOL  += '<Layer>'	
		for (ind = 0; ind < images.length; ind++)	  {
			if (images[ind].src.indexOf('transparent.png') == -1) {
				rExp = /\&/g;
				urlSrc = images[ind].src.replace(rExp,'***AMP***');
				strXmlOL += '<tile xlink:href=\'' + urlSrc + '\' width=\'' + images[ind].style.width.replace('px','') + '\'  height=\'' + images[ind].style.height.replace('px','') + '\'  left=\'' + images[ind].style.left.replace('px','') + '\' top=\'' + images[ind].style.top.replace('px','') + '\' />';
			}
		}
		strXmlOL += "</Layer>";
		strXmlOL += "</OLBaseLayer>";
    }
//alert(strXmlOL);
    return strXmlOL;
}

function preparaContext(){
// Se mappa OL converto le coordinate da Sferico Mercatore a GB 

	if(tipoMappa!='OL')
	{
		var minx = parseInt(dWorldTLXPre);
		var miny = parseInt(dWorldBRYPre);
		var maxx = parseInt(dWorldBRXPre);
		var maxy = parseInt(dWorldTLYPre);
		var ov_minx = parseInt(ov_bboxArray[0]);
		var ov_miny = parseInt(ov_bboxArray[1]);
		var ov_maxx = parseInt(ov_bboxArray[2]);
		var ov_maxy = parseInt(ov_bboxArray[3]);
	}
	else
	{
		var bbStr = dWorldTLXPre + "," + dWorldBRYPre + "," + dWorldBRXPre + "," + dWorldTLYPre
		var bounds = OpenLayers.Bounds.fromString(bbStr)
		bounds.transform(new OpenLayers.Projection('EPSG:900913'), new OpenLayers.Projection('EPSG:3003'));
		bbStr = bounds.toBBOX();
		bbStrArray=bbStr.split(',');
		var minx = parseInt(bbStrArray[0]);
		var miny = parseInt(bbStrArray[1]);
		var maxx = parseInt(bbStrArray[2]);
		var maxy = parseInt(bbStrArray[3]);
		var bounds = OpenLayers.Bounds.fromString(ov_bbox)
		bounds.transform(new OpenLayers.Projection('EPSG:900913'), new OpenLayers.Projection('EPSG:3003'));
		bbStr = bounds.toBBOX();
		bbStrArray=bbStr.split(',');
		var ov_minx = parseInt(bbStrArray[0]);
		var ov_miny = parseInt(bbStrArray[1]);
		var ov_maxx = parseInt(bbStrArray[2]);
		var ov_maxy = parseInt(bbStrArray[3]);
	}
	strXml = '<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>';
	strXml += '<Cw_Context version=\'2.0.0\' xmlns:xlink=\'http://www.w3.org/TR/xlink\' xmlns:sld=\'http://www.opengis.net/sld\'  xmlns:ogc=\'http://www.opengis.net/ogc\'>'	
	strXml += '<General>' 
	strXml += '	<BoundingBox SRS=\'' + SRS + '\' minx=\'' + minx + '\' miny=\'' + miny + '\' maxx=\'' + maxx + '\' maxy=\'' + maxy + '\'/>'
	strXml += '	<Window width=\'' + width + '\' height=\'' + height + '\'/>'
//alert(nomeMappa.replace(String.fromCharCode(224),'&#224;'));
	strXml += '	<Title>' + sostituisciCaratteriAccentati(nomeMappa) + '</Title>'
	strXml += '	<Stile xlink:href=\'' + stile + '\' xlink:type=\'simple\'/>'
	strXml += '	<OvImg xlink:href=\'' + ov_img + '\' xlink:type=\'simple\' minx=\'' + ov_minx + '\' miny=\'' + ov_miny + '\' maxx=\'' + ov_maxx + '\' maxy=\'' + ov_maxy + '\'/>'
	strXml += '	<BgFileUrl xlink:href=\'' + fileSfondo + '\' xlink:type=\'simple\'/>'
	if (printable == "1")
	{ 
	strXml += '	<PrintOptions titolo=\'' + printTitolo + '\' scala=\'' + printScala + '\' legenda=\'' + printLegenda + '\'/>'
	} 
	strXml += '</General>' 	
	strXml += '<LayerList>' 
	for (i = 0; i < listaLayer.length; i++){
		findable='0';
		if ((listaLayer[i].stato=='0')||(listaLayer[i].stato=='2')) {
			LivHidden='1';			
		}
		else {
			LivHidden='0';			
		}
//alert(listaLayer[i].stato + ' ' + LivHidden);
		strXml += '	<Layer queryable=\'' + listaLayer[i].queryable + '\'  trasparency=\'' + listaLayer[i].trasp + '\' findable= \'' + findable + '\' hidden=\'' + LivHidden + '\' grouped=\'' + listaLayer[i].grouped + '\'>' 
		if (listaLayer[i].tipo=='ECW') {
			serverUrl=listaLayer[i].url.substr(0,listaLayer[i].url.indexOf(listaLayer[i].name));
			formato='image/ecw';
	        if(tipoMappa!='OL')
                formato='image/pngRGB';
		}
		if (listaLayer[i].tipo=='WMS') {
//			serverUrl=listaLayer[i].url.substr(0,parseInt(listaLayer[i].url.indexOf('&'))+parseInt(1)).replace('\&','@');
			serverUrl=listaLayer[i].url.substr(0,parseInt(listaLayer[i].url.indexOf('&')));
			formato='image/png';
		}

        if ((listaLayer[i].tipo=='ECW')&&(tipoMappa=='OL'))
        {
            serverUrl=listaLayer[i].urlWmsEcw.substr(0,parseInt(listaLayer[i].urlWmsEcw.indexOf('&')));
		    strXml += '		<Server service=\'' + listaLayer[i].tipo + '\' version=\'1.1.0\' title=\'\'>'
		    strXml += '			<OnlineResource xlink:href=\'' + serverUrl + '\' xlink:type=\'simple\'/>'
		    strXml += '		</Server>'
		    strXml += '		<Name>' + listaLayer[i].nameWmsEcw + '</Name>'
        }
        else
        {
		    strXml += '		<Server service=\'' + listaLayer[i].tipo + '\' version=\'1.1.0\' title=\'\'>'
		    strXml += '			<OnlineResource xlink:href=\'' + serverUrl + '\' xlink:type=\'simple\'/>'
		    strXml += '		</Server>'
		    strXml += '		<Name>' + listaLayer[i].name + '</Name>'
        }
		strXml += '		<Title>' + sostituisciCaratteriAccentati(listaLayer[i].titolo) + '</Title>'
		strXml += '		<FormatList>'
		strXml += '			<Format current=\'1\'>' + formato + '</Format>'
		strXml += '		</FormatList>'
		strXml += '		<GeometryType>' + listaLayer[i].tipoGeom + '</GeometryType>'
		if ((listaLayer[i].legImg!='')||(listaLayer[i].sldUrl!='')) {
			strXml += '		<StyleList><Style legendPopUp=\'' + listaLayer[i].legTipo + '\' current=\'' + listaLayer[i].styleCurrent + '\'><Name>default</Name><Title>default</Title>'
/*
			if (listaLayer[i].legTipo=='1') {
				strXml += '		<StyleList><Style legendPopUp=\'1\' current=\'' + listaLayer[i].styleCurrent + '\'><Name>default</Name><Title>default</Title>'
			}
			else {
				strXml += '		<StyleList><Style legendPopUp=\'0\' current=\'' + listaLayer[i].styleCurrent + '\'><Name>default</Name><Title>default</Title>'
			}
*/
		}
		if (listaLayer[i].legImg!='') {
			strXml += '		<LegendURL width=\'20\' height=\'20\' format=\'image/gif\'>'
			rExp = /\&/g;
			strXml += '		<OnlineResource xlink:type=\'simple\' xlink:href=\'' + listaLayer[i].legImg.replace(rExp,'@@@') + '\'/>'
			strXml += '		</LegendURL>'
		}
//		else
//		{
			if (listaLayer[i].sldUrl!='') {
				strXml += '		<SLD>'
				strXml += '		<OnlineResource xlink:type=\'simple\' xlink:href=\'' + listaLayer[i].sldUrl + '\'/>'
				strXml += '		</SLD>'
			}
//		}
		if ((listaLayer[i].legImg!='')||(listaLayer[i].sldUrl!='')) {
			strXml += '		</Style></StyleList>'
		}
		if (listaLayer[i].logoImg!=''){
			strXml += '		<LogoImg xlink:href=\'' + listaLayer[i].logoImg + '\' xlink:type=\'simple\'/>'
		}
		else {
			strXml += '		<LogoImg></LogoImg>'
		}
		strXml += '		<MinScale>' + listaLayer[i].scMin + '</MinScale>'
		strXml += '		<MaxScale>' + listaLayer[i].scMax + '</MaxScale>'
		if (listaLayer[i].infoOutput!='') {
			strXml += '		<InfoUrl output=\'' + listaLayer[i].infoOutput + '\' ' 
			if (listaLayer[i].infoUrl!='') {
				strXml += ' xlink:href=\'' + listaLayer[i].infoUrl + '\' '
			}	
			strXml += ' xlink:type=\'simple\'/>'
		}
		//
		if (listaLayer[i].uid!='') {
			strXml += '		<uid>' + listaLayer[i].uid + '</uid>'
		}
		if (listaLayer[i].col_label!='') {
			strXml += '		<col_label>' + listaLayer[i].col_label + '</col_label>'
		}
		else {
			strXml += '		<col_label></col_label>'
		}
		if (listaLayer[i].des_label!='') {
			strXml += '		<des_label>' + listaLayer[i].des_label + '</des_label>'
		}
		else {
			strXml += '		<des_label></des_label>'
		}
		if (listaLayer[i].filtro!='') {
			strXml += '		<filtro>' + listaLayer[i].filtro + '</filtro>'
		}
		else {
			strXml += '		<filtro></filtro>'
		}
//		if (listaLayer[i].logoImg!='') {
//			strXml += '		<logoImg>' + listaLayer[i].logoImg + '</logoImg>'
//		}
//		else {
//			strXml += '		<logoImg></logoImg>'
//		}
// scrivo le rules
		strXml += '	<ClassList legendPopUp=\'' + listaLayer[i].legTipo + '\' >' 
		for (k = 0; k < listaLayer[i].numClassi; k++) {
			ruleName = listaLayer[i].rules[k].name.replace('&agrave;','à')
			rExp = /\&/g;
			ruleUrl = listaLayer[i].rules[k].url.replace(rExp,'@@@')
			strXml += ' <Class><Title>' + ruleName + '</Title><LegendURL><OnlineResource xlink:href=\''+ ruleUrl + '\' xlink:type=\'simple\'/></LegendURL></Class>' 
		}
		strXml += '	</ClassList>' 
// fine layer
		strXml += '	</Layer>' 
	}
	strXml += '</LayerList>' 
	strXml += '</Cw_Context>'

	return strXml;
}


function sostituisciCaratteriAccentati(stringaIn)
{

	stringaIn = stringaIn.replace(String.fromCharCode(224),'&#224;');
	stringaIn = stringaIn.replace(String.fromCharCode(232),'&#232;');
	stringaIn = stringaIn.replace(String.fromCharCode(236),'&#236;');
	stringaIn = stringaIn.replace(String.fromCharCode(242),'&#242;');
	stringaIn = stringaIn.replace(String.fromCharCode(249),'&#249;');

	stringaIn = stringaIn.replace(String.fromCharCode(224),'&#224;');
	stringaIn = stringaIn.replace(String.fromCharCode(232),'&#232;');
	stringaIn = stringaIn.replace(String.fromCharCode(236),'&#236;');
	stringaIn = stringaIn.replace(String.fromCharCode(242),'&#242;');
	stringaIn = stringaIn.replace(String.fromCharCode(249),'&#249;');

	stringaIn = stringaIn.replace(String.fromCharCode(224),'&#224;');
	stringaIn = stringaIn.replace(String.fromCharCode(232),'&#232;');
	stringaIn = stringaIn.replace(String.fromCharCode(236),'&#236;');
	stringaIn = stringaIn.replace(String.fromCharCode(242),'&#242;');
	stringaIn = stringaIn.replace(String.fromCharCode(249),'&#249;');

	stringaIn = stringaIn.replace(String.fromCharCode(224),'&#224;');
	stringaIn = stringaIn.replace(String.fromCharCode(232),'&#232;');
	stringaIn = stringaIn.replace(String.fromCharCode(236),'&#236;');
	stringaIn = stringaIn.replace(String.fromCharCode(242),'&#242;');
	stringaIn = stringaIn.replace(String.fromCharCode(249),'&#249;');

	stringaIn = stringaIn.replace(String.fromCharCode(224),'&#224;');
	stringaIn = stringaIn.replace(String.fromCharCode(232),'&#232;');
	stringaIn = stringaIn.replace(String.fromCharCode(236),'&#236;');
	stringaIn = stringaIn.replace(String.fromCharCode(242),'&#242;');
	stringaIn = stringaIn.replace(String.fromCharCode(249),'&#249;');

	return stringaIn;

}

function segnalaVariazione(Xlon,Ylat,Raggio){
	StrContext = preparaContext();
	document.Servizio.Context.value = StrContext;
//alert(StrContext.length);
//	Pagina =  'CWSegnalaVariazione.asp?Stile='+stile+'&StrContext='+StrContext+'&Xlon='+Xlon+'&Ylat='+Ylat+'&Raggio='+Raggio;
	Pagina =  'CWSegnalaVariazione.asp?Stile='+stile+'&Xlon='+Xlon+'&Ylat='+Ylat+'&Raggio='+Raggio;
	Opzioni = 'status=yes, toolbar=yes, menubar=yes, width=600, height=300, resizable=yes, scrollbars=yes';
	WinSegnala = window.open(Pagina, 'Segnala', Opzioni)
	ECWVectorLayer.clear();
	WinSegnala.focus();
}

function inizializzaInfoLayer(strUrl,nomeLayer) {

	rExp = /&amp;/g;
	livInfoUrl = strUrl.replace(rExp,'&');

	if(tipoMappa!='OL')
	{
		if (document.ECWView1.GetLayerIndex("info") < 1 ) {
			if (document.ECWView1.AddLayer("GISOverlay", "", "info","") < 0 ) {
				alert('Inizializzazione Vettoriale Info' + document.ECWView1.GetLastErrorText());
				return false;
			}
		}
		caricaVettoriale(livInfoUrl,'info','','1');
	}
	else
	{
		var str = '&REQUEST=GetMap';
		var urlWmsServer = livInfoUrl.substring(0,livInfoUrl.indexOf(str));
		var layerName = 'info';	
		var layerNameWMS = nomeLayer + '__INFO';	
		var layers = map.getLayersByName(layerName);
		if (layers.length > 0)
			map.removeLayer(layers[0]);
		var urlSLD = '';			
		caricaLivelloWMS(urlWmsServer,layerName,layerNameWMS,urlSLD,'image/png');
	}

	for (i = 0; i < listaLayer.length; i++){
		if (listaLayer[i].name==nomeLayer)
		{
			var strLayer = listaLayer[i].titolo;
		}

	}
	SetLayerTransparency('info','#',0.75);
	SetLayerVisible('info',true);
	livInfo=strLayer;
	livInfoSldUrl="";
//alert('inizializza ' + livInfo);
}

function inizializzaInfoLayerOLD(SldUrl,nomeLayer) {

	if (document.ECWView1.GetLayerIndex("info") < 1 ) {
		if (document.ECWView1.AddLayer("GISOverlay", "", "info","") < 0 ) {
			alert('Inizializzazione Vettoriale Info' + document.ECWView1.GetLastErrorText());
			return false;
		}
	}

	for (i = 0; i < listaLayer.length; i++){
		if (listaLayer[i].name==nomeLayer)
		{
			var strUrl = listaLayer[i].url;
			var strLayer = listaLayer[i].titolo;
		}

	}
	if(tipoMappa!='OL')
		caricaVettoriale(strUrl,'info',SldUrl,'1');
	SetLayerTransparency('info','#',0.75);
	SetLayerVisible('info',true);
	livInfo=strLayer;
	livInfoSldUrl=SldUrl;
//alert('inizializza ' + livInfo);
}

function pulisciInfoLayer() {

	SetLayerTransparency('info','#',0);
	document.ECWView1.DeleteLayer('info');

}


function valoreParametro(ParamName) {
	var ParamValue = "";
	if (listaParam.length > 0) {
		for (i = 0; i < listaParam.length; i++){
			if (listaParam[i].name.toUpperCase() == ParamName.toUpperCase()) {
				ParamValue = listaParam[i].value;
			}
		}
	}
	return ParamValue;
}

function InfoCarota(screenX, screenY, worldX, worldY,tipo) {
	if ((tipo=='attivo')&&(livAttivo==-1))
	{
		alert('Nessun Livello Interrogabile');
		return;
	}

	if(tipoMappa!='OL') {
		var v = document.ECWView1;
		var dWorldTLX = v.GetTopLeftWorldCoordinateX();
		var dWorldTLY = v.GetTopLeftWorldCoordinateY();
		var dWorldBRX = v.GetBottomRightWorldCoordinateX();
		var dWorldBRY = v.GetBottomRightWorldCoordinateY();
	}
	else {
		var bounds = map.getExtent();
        bounds = bboxTransform(bounds,'EPSG:900913','EPSG:3003');
		var dWorldTLX = bounds.left;
		var dWorldTLY = bounds.top;
		var dWorldBRX = bounds.right;
		var dWorldBRY = bounds.bottom;

    	var point = pointTrasfCoord(worldX,worldY,'EPSG:900913','EPSG:3003');
		worldX = parseInt(point.x); 
		worldY = parseInt(point.y); 
	}

	var bbox = dWorldTLX + "," + dWorldBRY + "," + dWorldBRX + "," + dWorldTLY; 

// calcolo il bbox in WGS84 (per i livelli remoti)
	var point = new Proj4js.Point();
	var x = parseInt(dWorldTLX) ;
	var y = parseInt(dWorldTLY);
	point = pointTrasfCoord(x,y,'EPSG:3003','EPSG:4326');
	var tlx = point.x; 
	var tly = point.y; 	
	var x = parseInt(dWorldBRX);
	var y = parseInt(dWorldBRY);
	point = pointTrasfCoord(x,y,'EPSG:3003','EPSG:4326');
	var brx = point.x; 
	var bry = point.y; 	
	var bbox4326 = tlx + "," + bry + "," + brx + "," + tly; 
// calcolo il bbox in UTM / WGS84 (per i livelli remoti)
	var point = new Proj4js.Point();
	var x = parseInt(dWorldTLX) ;
	var y = parseInt(dWorldTLY);
	point = pointTrasfCoord(x,y,'EPSG:3003','EPSG:32632');
// aggiungo 80 alla x per problemna shift verso est - COMMENTATO DOPO MODIFICA EPSG 26591 --> 3003
//	var tlx = parseInt(point.x) + 80; 
	var tlx = point.x; 
	var tly = point.y; 	
	var x = parseInt(dWorldBRX);
	var y = parseInt(dWorldBRY);
	point = pointTrasfCoord(x,y,'EPSG:3003','EPSG:32632');
// aggiungo 80 alla x per problemna shift verso est - COMMENTATO DOPO MODIFICA EPSG 26591 --> 3003
//	var brx = parseInt(point.x) + 80; 
	var brx = point.x; 
	var bry = point.y; 	
	var bbox32632 = tlx + "," + bry + "," + brx + "," + tly; 
// calcolo il bbox in UTM / ED50 (per i livelli remoti)
	var point = new Proj4js.Point();
	var x = parseInt(dWorldTLX) ;
	var y = parseInt(dWorldTLY);
	point = pointTrasfCoord(x,y,'EPSG:3003','EPSG:23032');
	var tlx = point.x; 
	var tly = point.y; 	
	var x = parseInt(dWorldBRX);
	var y = parseInt(dWorldBRY);
	point = pointTrasfCoord(x,y,'EPSG:3003','EPSG:23032');
	var brx = point.x; 
	var bry = point.y; 	
	var bbox23032 = tlx + "," + bry + "," + brx + "," + tly; 

	if (screenX > width) 
		x = (screenX - width);
	else
		x = screenX;
	y = screenY;
	
	var idRichiesta = valoreParametro('idRichiesta');

	Opzioni = 'status=yes, toolbar=yes, menubar=no, width=400, height=500, resizable=yes, scrollbars=yes';
//	WinInfo = window.open('', 'Info', Opzioni)
	WinInfo = window.open('', '', Opzioni)
	WinInfo.document.write("<html><body>");	

	WinInfo.document.write("<br>Interrogazione in corso...<br>");	
	WinInfo.document.write("<form id='frm' name='frm' method=post action='CwGetFeatureInfoCarota.aspx'>");	
	WinInfo.document.write("<input type=hidden name='bbox' value='" + bbox + "'>");
	WinInfo.document.write("<input type=hidden name='bbox4326' value='" + bbox4326 + "'>");
	WinInfo.document.write("<input type=hidden name='bbox32632' value='" + bbox32632 + "'>");
	WinInfo.document.write("<input type=hidden name='bbox23032' value='" + bbox23032 + "'>");
	WinInfo.document.write("<input type=hidden name='width' value='" + width + "'>");
	WinInfo.document.write("<input type=hidden name='height' value='" + height + "'>");
	WinInfo.document.write("<input type=hidden name='X' value='" + x + "'>");
	WinInfo.document.write("<input type=hidden name='Y' value='" + y + "'>");
	WinInfo.document.write("<input type=hidden name='worldX' value='" + worldX + "'>");
	WinInfo.document.write("<input type=hidden name='worldY' value='" + worldY + "'>");
	WinInfo.document.write("<input type=hidden name='scala' value='" + strScala + "'>");
	WinInfo.document.write("<input type=hidden name='idRichiesta' value='" + idRichiesta + "'>");
	WinInfo.document.write("<input type=hidden name='ambiente' value='" + ambiente + "'>");
	WinInfo.document.write("<input type=hidden name='tipo' value='" + tipo + "'>");
	WinInfo.document.write("<input type=hidden name='stile' value='" + stile + "'>");
	WinInfo.document.write("<input type=hidden name='debug' value='" + debug + "'>");
	WinInfo.document.write("<br><br>");
	// ciclo sui livelli e scrivo i campi

//alert(listaLayer [livAttivo].filtro);
	if (tipo=='attivo')
	{
		rExp = /,/g;
		WinInfo.document.write("<input type=hidden name='titolo' value='" + listaLayer[livAttivo].titolo.replace(rExp,'**VIRGOLA**') + "'>");	
		nomeLiv = listaLayer[livAttivo].name;
		if (nomeLiv.indexOf('__TEMA_') != -1)
			nomeLiv = nomeLiv.substring(0,nomeLiv.indexOf('__TEMA_'));			
		if (nomeLiv.indexOf('__QUERY') != -1)
			nomeLiv = nomeLiv.substring(0,nomeLiv.indexOf('__QUERY'));			
		WinInfo.document.write("<input type=hidden name='Layers' value='" + nomeLiv + "'>");	
		if (listaLayer[livAttivo].getFeatureInfoUrl.length>0)
		{
// 01/10/2010 
// modificato per gestione layer di tipo R (Remote WMS, tipo GenioWeb Provincia)
// probabilmente problemi con WMS remoti aggiunti aggiunti con la funzione apposita
//			var sInfoUrl = listaLayer[livAttivo].getFeatureInfoUrl + "&layers=" + nomeLiv + "&query_layers=" + nomeLiv ;
			var sInfoUrl = listaLayer[livAttivo].getFeatureInfoUrl;
		}
		else
		{
			var sInfoUrl = preparaUrlGetFeatureInfo(listaLayer[livAttivo].url);
		}
		WinInfo.document.write("<input type=hidden name='InfoUrl' value='" + sInfoUrl + "'>");	
		WinInfo.document.write("<input type=hidden name='XslUrl' value='" + listaLayer [livAttivo].infoUrl + "'>");	
		WinInfo.document.write("<input type=hidden name='InfoOutput' value='" + listaLayer [livAttivo].infoOutput + "'>");	
		WinInfo.document.write("<input type=hidden name='TipoGeom' value='" + listaLayer [livAttivo].tipoGeom + "'>");
		rExp = /'/g;
		colLabel=listaLayer [livAttivo].col_label;
//		alert(colLabel);
		if (null == colLabel)
			colLabel='';
		WinInfo.document.write("<input type=hidden name='col_label' value='" + colLabel.replace(rExp,'**APICE**') + "'>");	
		WinInfo.document.write("<input type=hidden name='uid' value='" + listaLayer [livAttivo].uid + "'>");	
		rExp = /\'/g;
		WinInfo.document.write("<input type=hidden name='filtro' value=\"" + listaLayer [livAttivo].filtro.replace(rExp,'@') + "\">");	
		WinInfo.document.write("<input type=hidden name='srs' value=\"" + listaLayer [livAttivo].srs + "\">");	
//alert(listaLayer [livAttivo].filtro);
		WinInfo.document.write("<br>");
	}
	else
	{
		for (i = 0; i < listaLayer.length; i++){
			if ((listaLayer[i].scMin<=parseInt(strScala))&&(listaLayer[i].scMax>=parseInt(strScala))&&(listaLayer[i].queryable=='1')) {
				rExp = /,/g;
				WinInfo.document.write("<input type=hidden name='titolo' value='" + listaLayer[i].titolo.replace(rExp,'**VIRGOLA**') + "'>");	
				nomeLiv = listaLayer[i].name;
				if (nomeLiv.indexOf('__TEMA_') != -1)
					nomeLiv = nomeLiv.substring(0,nomeLiv.indexOf('__TEMA_'));			
				if (nomeLiv.indexOf('__QUERY') != -1)
					nomeLiv = nomeLiv.substring(0,nomeLiv.indexOf('__QUERY'));			
				WinInfo.document.write("<input type=hidden name='Layers' value='" + nomeLiv + "'>");	
				if (null != listaLayer[i].getFeatureInfoUrl)
				{
					var sInfoUrl = listaLayer[i].getFeatureInfoUrl + "&layers=" + nomeLiv + "&query_layers=" + nomeLiv ;
				}
				else
				{
					var sInfoUrl = preparaUrlGetFeatureInfo(listaLayer[i].url);
				}
//alert(sInfoUrl);
				WinInfo.document.write("<input type=hidden name='InfoUrl' value='" + sInfoUrl + "'>");	
				WinInfo.document.write("<input type=hidden name='XslUrl' value='" + listaLayer [i].infoUrl + "'>");	
				WinInfo.document.write("<input type=hidden name='InfoOutput' value='" + listaLayer [i].infoOutput + "'>");	
				WinInfo.document.write("<input type=hidden name='TipoGeom' value='" + listaLayer [i].tipoGeom + "'>");	
				rExp = /'/g;


				colLabel=listaLayer[i].col_label;
				if (null == colLabel)
					colLabel='';
				WinInfo.document.write("<input type=hidden name='col_label' value='" + colLabel.replace(rExp,'**APICE**') + "'>");	
				WinInfo.document.write("<input type=hidden name='uid' value='" + listaLayer [i].uid + "'>");	
				rExp = /\'/g;
				WinInfo.document.write("<input type=hidden name='filtro' value='" + listaLayer [i].filtro.replace(rExp,'@') + "'>");	
				WinInfo.document.write("<input type=hidden name='srs' value=\"" + listaLayer [i].srs + "\">");	
				WinInfo.document.write("<br>");
			}
		}
	}

	WinInfo.document.write("</form>");
	WinInfo.document.write("</body></html>");
	WinInfo.document.frm.submit();	

	WinInfo.focus();


}

function preparaUrlGetFeatureInfo(url)
{
	indStart=url.indexOf('LAYERS=')+7;
	indStop=url.indexOf('&',indStart);
	if (indStop==-1)
		indStop=url.length;
	nomeLayer=url.substring(indStart,indStop);
	url = url.replace('REQUEST=GetMap','REQUEST=GetFeatureInfo') + "&QUERY_LAYERS="+nomeLayer;
	return url;
}

function normalizzaBbox(minx,miny,maxx,maxy,rapportoDimensioniMappa)
		{

//	alert (minx+' '+miny+' '+maxx+' '+maxy+' '+rapportoDimensioniMappa);

			rapportoFind = parseInt((maxx - minx)/(maxy - miny));

			if (rapportoDimensioniMappa > rapportoFind) 
			{
				DeltaX = parseInt(rapportoDimensioniMappa*(maxy - miny) - (maxx - minx));
				minx = parseInt(minx - DeltaX/2);
				maxx = parseInt(maxx + DeltaX/2);
			}
			else 
			{
				DeltaY = parseInt((maxx - minx)/rapportoDimensioniMappa - (maxy - miny));
				miny = parseInt(miny - DeltaY/2);
				maxy = parseInt(maxy + DeltaY/2);
			}
			Bbox = minx + "," + miny + "," + maxx + "," + maxy;
			return Bbox;

		}

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event, id) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

function onMouseWheelCB() {

	// calcolo le coordinate del centro della mappa
	if (modo!='STAMPA') 
	{
		tlwcx = document.ECWView1.GetTopLeftWorldCoordinateX(); 
		tlwcy = document.ECWView1.GetTopLeftWorldCoordinateY(); 
		brwcx = document.ECWView1.GetBottomRightWorldCoordinateX(); 
		brwcy = document.ECWView1.GetBottomRightWorldCoordinateY(); 
		worldX = tlwcx + (brwcx - tlwcx)/2;
		worldY = brwcy + (tlwcy - brwcy)/2;
		
		if(event.wheelDelta>0)
			Zoomin(worldX, worldY);
		else	
			Zoomout(worldX, worldY);
	}	
}

//--------------------------------------------------------------------------------------------
//-- Funzione caricaCarta - funzione di caricamento carte in modalità AJAX
//-- utilizza il modulo CwCaricaCarta.asp a cui passa il cod_catalogo della carta da caricare
//--------------------------------------------------------------------------------------------

function caricaCarta(codCatalogo)
{
		    var sUrl = 'CwCaricaCarta.asp';
		    sUrl += '?cod_catalogo='+ valoreParametro('cod_catalogo'); 
	        xmlhttp=getXMLHttp();
	        if (xmlhttp!=null)
	        {
		        xmlhttp.onreadystatechange=onHTTPResponse;
		        xmlhttp.open('GET',sUrl,false);
		        xmlhttp.send(null);
	        }
	        stringaXML = xmlhttp.responseText;	
            //alert(stringaXML);
            aggiungiLayer(stringaXML);
}            

//--------------------------------------------------------------------------------------------
//-- Funzione aggiungiLayer - richiamata dal modulo CwAggiungiCarte.asp CwAggiungiCarteCanali.asp
//-- e dal modulo di aggiunta carte di Agrinet ..... e da una serie di altri moduli
//-- Aggiunge i livelli corrispondenti ad una carta
//--------------------------------------------------------------------------------------------
function aggiungiLayer(stringaXML) {

	if (debug) {
		Opzioni = 'status=yes, toolbar=yes, menubar=no, width=1000, height=486, resizable=yes, scrollbars=yes';
		WinAlert = window.open('', 'stringaXml', Opzioni)
		WinAlert.document.write('<br>-- aggiungiLayer - stringaXML in sorgente pagina '+stringaXML+'------------------------------<br><br>');
	}

//console.log(stringaXML);

// sostituisco il carattere & con il carattere @ perchè altrimenti il parser xml non funziona	
	stringaXML=stringaXML.replace(/&/gi,'@')
// Parsing della stringa XML e costruzione dell'array di oggetti layer
	if (window.ActiveXObject) 
	{
		var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(stringaXML);
	}
	else
	{
		var parser=new DOMParser();
		var xmlDoc=parser.parseFromString(stringaXML,"text/xml");
	}
	layers=xmlDoc.getElementsByTagName("Layer");
	listaLayerAggiungere = new Array();
	indLiv=0;
	
	for(var i=0;i<layers.length;i++){
		LivTitolo=layers[i].getAttribute('titolo').replace(/@/gi,'&');
// Controllo che il livello non sia già presente nel qual caso non lo carico
		LivelloPresente=false;
		for(var j=0;j<listaLayer.length;j++){
			if (listaLayer[j].titolo==LivTitolo){
				LivelloPresente=true;
			}
		}
		if (!LivelloPresente){
			LivName=layers[i].getAttribute('name').replace(/@/gi,'&');
			LivUrl=layers[i].getAttribute('url').replace(/@/gi,'&');
			LivTipo=layers[i].getAttribute('tipo').replace(/@/gi,'&');
			LivLegImg=layers[i].getAttribute('legImg').replace(/@/gi,'&');
			LivLegTipo=layers[i].getAttribute('legTipo').replace(/@/gi,'&');
			LivQueryable=layers[i].getAttribute('queryable').replace(/@/gi,'&');
			LivInfoOutput=layers[i].getAttribute('infoOutput').replace(/@/gi,'&');
			LivInfoUrl=layers[i].getAttribute('infoUrl').replace(/@/gi,'&');
			LivSldUrl=layers[i].getAttribute('sldUrl').replace(/@/gi,'&');
			LivScMin=layers[i].getAttribute('scMin');
			LivScMax=layers[i].getAttribute('scMax');
			LivTrasp=layers[i].getAttribute('trasp');
			if (LivTrasp == null)
				LivTrasp='100';
			LivTipoGeom=layers[i].getAttribute('tipoGeom');
			LivStyleCurrent=layers[i].getAttribute('styleCurrent');
			LivGroup=layers[i].getAttribute('grouped');
			LivUID=layers[i].getAttribute('uid');
			LivColLabel=layers[i].getAttribute('colLabel');
			LivDesLabel=layers[i].getAttribute('desLabel');
			LivLogoImg=layers[i].getAttribute('logoImg');
			LivUrlWmsEcw=layers[i].getAttribute('urlWmsEcw');
			LivGetFeatureInfoURL=layers[i].getAttribute('getFeatureInfoUrl');
			if (null != LivUrlWmsEcw)
				LivUrlWmsEcw=LivUrlWmsEcw.replace(/@/gi,'&');
			else
				LivUrlWmsEcw='';
			LivNameWmsEcw=layers[i].getAttribute('nameWmsEcw');
			if (null != LivNameWmsEcw)
				LivNameWmsEcw=LivNameWmsEcw.replace(/@/gi,'&');
			else
				LivNameWmsEcw='';
//alert('aggiungiLayer: ' + LivNameWmsEcw + ' - ' + LivUrlWmsEcw);
			srs=layers[i].getAttribute('srs');
			if (null == srs)
				srs='';
			if (null != LivGetFeatureInfoURL)
				getFeatureInfoUrl=LivGetFeatureInfoURL.replace(/@/gi,'&');
			else
				getFeatureInfoUrl='';
			LivStato='0';
			LivOrdine=i;
			LivHidden='0';
			Filtro=layers[i].getAttribute('filtro');
			if (null == Filtro)
				Filtro='';
			xmlRules=layers[i].getElementsByTagName("Rule");
			listaRule = new Array();
			for(var j=0;j<xmlRules.length;j++){
				ruleName =  xmlRules[j].getAttribute('name').replace(/@/gi,'&');
				ruleUrl =  xmlRules[j].getAttribute('url').replace(/@/gi,'&');
				listaRule[j] = new rule(ruleName,ruleUrl);
			}
			LivNumClassi=xmlRules.length
			listaLayerAggiungere[indLiv] = new layer(LivTitolo,LivName,LivUrl,LivTipo,LivLegImg,LivLegTipo,LivQueryable,LivInfoOutput,LivInfoUrl,LivSldUrl,LivScMin,LivScMax,LivOrdine,LivStato,LivTrasp,LivNumClassi,listaRule,LivHidden,LivTipoGeom,LivStyleCurrent,LivGroup,LivUID,LivColLabel,LivDesLabel,Filtro,LivLogoImg,LivUrlWmsEcw,LivNameWmsEcw,srs,getFeatureInfoUrl);
			if ((listaLayerAggiungere[indLiv].scMin<parseInt(strScala))&&(listaLayerAggiungere[indLiv].scMax>=parseInt(strScala))) 
			{
				listaLayerAggiungere[indLiv].stato=1;
			}
			else {
				listaLayerAggiungere[indLiv].stato=3;
			}
			if ((listaLayerAggiungere[indLiv].tipo!='ECW')&&(tipoMappa!='OL')) {
				inizializzaVettoriale(listaLayerAggiungere[indLiv].titolo);
			}
			indLiv++;

		}
	}	
// aggiungo i nuovi livelli nell'array dei livelli
	

	for(var i=0;i<listaLayerAggiungere.length;i++){
		listaLayer.push(listaLayerAggiungere[i]);
	}

// aggiorno l'ordine dei livelli
	aggiornaOrdine();
// aggiorno la mappa con i nuovi livelli
	if(tipoMappa!='OL') {
		aggiornaLivelliECW(listaLayerAggiungere);
	}
	else {
		aggiornaLivelliOL(listaLayerAggiungere);
	}
	
//riscrivo la legenda con il nuovo array
	scriviLegenda();
	inizializzaLogo();	
//  imposto trasparenza
	for(var i=0;i<listaLayerAggiungere.length;i++){
		LivTitolo=listaLayerAggiungere[i].titolo;
		valore=listaLayerAggiungere[i].trasp;
		SetLayerTransparency(LivTitolo, "#" , valore/100);
	}

}

//--------------------------------------------------------------------------------------------
//-- Funzione resizeMappaOnResizeWin - chiamata all'avvio della applicazione e quando viene 
//-- lanciato l'evento di onResize
//-- effettua un resize della mappa in base alla dimensione della finestra
//--------------------------------------------------------------------------------------------

function resizeMappaOnResizeWin() {

	// metto il return per disabilitare la funzione
	//return;
	
	//calcolo le dimensioni della finestra
	if (browser.isIE) 
	{
		winW = document.body.offsetWidth;
		winH = document.body.offsetHeight;
	}
	if (browser.isNS) 
	{
		winW = window.innerWidth;
		winH = window.innerHeight;
	}
	//calcolo le dimensioni della mappa

	rapportoFinestra = winW/winH;
	rapportoMappa = width/height;

//alert(rapportoFinestra + ' ' + rapportoMappa);
	if (rapportoFinestra<rapportoMappa)
	{
		width = parseInt(winW - 300);
		height = parseInt(width/rapportoMappa);
		widthDiv = winW - 270;
		heightDiv = widthDiv/rapportoMappa;
	}
	else
	{
		heightDiv = winH - headerHeight - 120;
		widthDiv = heightDiv*rapportoMappa;
		height = parseInt(heightDiv - 30);
		width = parseInt(height*rapportoMappa);
	}		
		
//alert(winW + ' ' + winH);
//alert(widthDiv + ' ' + heightDiv);
//alert(width + ' ' + height);
	
	mappaDiv = document.getElementById('MAPPA');
	mappaDiv.style.width=widthDiv;
	mappaDiv.style.height=heightDiv;
	

	if(tipoMappa!='OL')	{
		ecwDiv = document.getElementById('ECWPLUG');
		attendereDiv = document.getElementById('ATTENDERE');
		attendereDiv.style.left=width/2;
		pan_nDiv = document.getElementById('PAN_N');
		pan_nDiv.style.left=width/2;
		pan_neDiv = document.getElementById('PAN_NE');
		pan_neDiv.style.left=parseInt(width) + parseInt(15);
		pan_eDiv = document.getElementById('PAN_E');
		pan_eDiv.style.left=parseInt(width) + parseInt(15);
		pan_eDiv.style.top=(parseInt(height) + parseInt(15))/2-5;
		pan_seDiv = document.getElementById('PAN_SE');
		pan_seDiv.style.left=parseInt(width) + parseInt(15);
		pan_seDiv.style.top=parseInt(height) + parseInt(2);
		pan_sDiv = document.getElementById('PAN_S');
		pan_sDiv.style.left=width/2;
		pan_sDiv.style.top=parseInt(height) + parseInt(2);
		pan_swDiv = document.getElementById('PAN_SW');
		pan_swDiv.style.top=parseInt(height) + parseInt(2);
		pan_wDiv = document.getElementById('PAN_W');
		pan_wDiv.style.top=(parseInt(height) + parseInt(15))/2-5;
	}
	else {
		ecwDiv = document.getElementById('map');
	}

	ecwDiv.style.width=width;
	ecwDiv.style.height=height;

	
	
	if (modo!='STAMPA') {
		legendaDiv = document.getElementById('LEGENDADIV');
		legendaDiv.style.left=parseInt(widthDiv) + parseInt(20);
		legendaDiv.style.height=parseInt(height) - parseInt(30);

		scalaDiv = document.getElementById('SCALA');
		scalaDiv.style.left=parseInt(widthDiv) + parseInt(20);
		scalaDiv.style.top=parseInt(heightDiv) + parseInt(65);
	}

//legendaDiv.style.background='red';
//alert(scalaDiv.style.height);	
	

} 

//--------------------------------------------------------------------------------------------
//-- Funzione resizeMappa - chiamata all'avvio della applicazione
//-- effettua un resize della finestra
//--------------------------------------------------------------------------------------------

function resizeMappa() {

	winWidth = parseInt(width) + parseInt(270);

	winHeight = parseInt(height) + parseInt(130);

	window.resizeTo(winWidth,winHeight);
	if (browser.isIE) 
	{
		winWidth = 2*winWidth - document.body.clientWidth;
		winHeight = 2*winHeight - document.body.clientHeight;
	}
	if (browser.isNS) 
	{
		winWidth = 2*winWidth - window.innerWidth;
		winHeight = 2*winHeight - window.innerHeight;
	}
	window.resizeTo(winWidth, winHeight);
}

function serviziWMS() {

	Pagina="CwServiziWMS.asp?stile="+stile;
	Opzioni = 'status=yes, toolbar=no, menubar=no, width=500, height=500, resizable=no, scrollbars=no';
	WinWMS = window.open(Pagina, 'WMS', Opzioni)
	WinWMS.focus();

}



