var map;
var lastclick = "" ;
var point; 
var geocoder = null;
	
//Valore minimo dello zoom perchè siano visibili i marker
var ZoomIconVisibile = 9;
	
//--- variabili x Lista markers ---
	// contiene codice HTML della sidebar
	var side_bar_html = '';
	
	// arrays to hold copies of the markers and html used by the side_bar
	// because the function closure trick doesnt work there
	var gmarkers = [];
	var j = 0;
//--- variabili x Lista markers ---


// ----------------------------------------------------------------------------------------------------------------------				
//SUL PORTALE/SITO
function loadmapSito(mapdiv) {
	
	mapdiv = mapdiv=='undefined'?'map':mapdiv;
	
	map = new GMap2(document.getElementById(mapdiv));
	
	if (mapdiv=='map') {
		var latitudine = document.getElementById('latitudine').value
		var longitudine = document.getElementById('longitudine').value	
		var zoom = document.getElementById('zoom').value * 1 //converte zoom in numero
	} else {		
		var latitudine = document.getElementById('LatitudineCentro').value
		var longitudine = document.getElementById('LongitudineCentro').value	
		var zoom = document.getElementById('zoomPTIMAP').value * 1 //converte zoom in numero		
	}
	
	// Creo GeoCoder Max 1.6 query/sec
	geocoder = new GClientGeocoder();
		
	//G_NORMAL_MAP , G_SATELLITE_MAP , G_HYBRID_MAP 
	map.setCenter(new GLatLng(latitudine, longitudine), zoom, G_HYBRID_MAP);
	
	// Visualizza controlli - TIPO MAPPA
	map.addControl(new GMapTypeControl());
	
	// Visualizza controlli - ZOOM GRANDE
	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl ());
	
	//Zoom senza bisogno di aspettare
	map.enableContinuousZoom();		
	
	//Controllo zoom tramite rotella del mouse (funzione definita in questa pagina)
	map.enableScrollWheelZoom();	
	
	//Crea marker singolo
	if (mapdiv=='map') {
		var point = new GLatLng(latitudine, longitudine) ;
		fc( point, "5" );
	}
	
	//solo per PTIMAP
	if (mapdiv=='PTIMAP') {
		//Salva Informazioni correnti della mappa (coordinate centro, nord est, sud ovest, zoom level)
		CurrentMapInfo();
		GeneraMarker('all','moveend');										
			
		// SPOSTAMENTO o MODIFICA ZOOM MAPPA -> Salva Informazioni e Aggiorna Marker visibili
		GEvent.addListener(map, "moveend", function() {
			
			//Salva Informazioni correnti della mappa (coordinate centro, nord est, sud ovest, zoom level)
			CurrentMapInfo();
			//Aggiorna Marker da visualizzare
			GeneraMarker('all','moveend')				
													
		}); 
	}
	
}

// ----------------------------------------------------------------------------------------------------------------------				
//SU ADMIN
function loadmap(mapdiv) {

	map = new GMap2(document.getElementById("map"));
	
	var latitudine = document.getElementById('latitudine').value
	var longitudine = document.getElementById('longitudine').value	
	var zoom = document.getElementById('zoom').value * 1 //converte zoom in numero
	var coordinatepresenti = document.getElementById('coordinatepresenti').value
	
	map.setCenter(new GLatLng(latitudine, longitudine), zoom, G_NORMAL_MAP);
	
	// Visualizza controlli - TIPO MAPPA
	map.addControl(new GMapTypeControl());
	
	// Visualizza controlli - ZOOM GRANDE
	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl ());
	
	//Zoom senza bisogno di aspettare
	map.enableContinuousZoom();		
	
	//Controllo zoom tramite rotella del mouse (funzione definita in questa pagina)
	map.enableScrollWheelZoom();
	
	//Posizione marker iniziale
	if (coordinatepresenti=='1') {		
		var point = new GLatLng(latitudine, longitudine) ;
		fc( point, "5" );		
	}
	
	var lastclick = "" ;
	
	//Crea marker al click del mouse
	GEvent.addListener(map, "click", function(overlay, point) {  		
		 if (overlay) {
		 } else if (point)  {
		 	clearmap();
			checkclick( point ) ;
		 }				
		}
	);
}

// ----------------------------------------------------------------------------------------------------------------------				
//GENERA MARKER SU PUNTO CLICCATO (ADMIN)
function fc( point, zoomlvl ) {
	
	var html = "";
	
	//map.setCenter(point,zoomlvl);
	
	//map.centerAndZoom( point, zoomlvl) ;
	
	html += html + "<font size=1>Latitudine e Longitudine <br>" + map.getCenter(point)+"</font>";
			
	//GENERA MARKER SUL PUNTO CLICCATO 
	//parametri: coordinate (point) e codice HTML del fumetto (html)	
	var marker = new createMarker(point, html);
	
	map.addOverlay(marker);
	
	//MEMORIZZA LE COORDINATE NEI CAMPI NASCOSTI
	coordinate=String(point);
	coordinate=coordinate.replace("(","")
	coordinate=coordinate.replace(")","")
	
	var coordinate_array=coordinate.split(", ");
		
	document.getElementById('latitudine').value=coordinate_array[0]
	document.getElementById('longitudine').value=coordinate_array[1]
	if (document.getElementById('coordinatepresenti')) {
		document.getElementById('coordinatepresenti').value = '1';
	}
}

// ----------------------------------------------------------------------------------------------------------------------				
//ELIMANA MARKER PRESENTI
function clearmap() {
	map.clearOverlays() ;
	lastclick = "" ;
}


// ----------------------------------------------------------------------------------------------------------------------				
// Al click verifica se punto diverso
function checkclick ( point ) {
	if ( lastclick != point ) {
		lastclick = point ;
		
		var zoomlvl = map.getZoom();
		
		fc( point, zoomlvl);		
	}
}

// ----------------------------------------------------------------------------------------------------------------------				
//CREA MARKER SINGOLO (es. su sito personale e nelle schede)
function createMarker(point, html) {
		
	//Coordinate iniziali presenti	
	var latitudine = document.getElementById('latitudine').value
	var longitudine = document.getElementById('longitudine').value	
	var zoom = document.getElementById('zoom').value	
	
	if (zoom==5) {
		if (html=='') {
			html='lat: '+latitudine+'<br>lon: '+longitudine
		}
	}	
	
	var marker = new GMarker(point);
	
	//Apre info window
	GEvent.addListener(marker, "click", function() {
			//marker.openInfoWindowHtml(html);
		}
	);		
	
	return marker;
}	 	

// ----------------------------------------------------------------------------------------------------------------------				
//---------------- SALVA COORDINATE E ZOOM NEI CAMPI HIDDEN -----------------------
function CurrentMapInfo() {
	
	//Zoom
	var ZoomLevel = map.getZoom()
	document.getElementById('zoomPTIMAP').value=ZoomLevel
		
	//Centro
	var CoordinateCentro = map.getCenter()
	document.getElementById('LatitudineCentro').value = CoordinateCentro.lat()
	document.getElementById('LongitudineCentro').value = CoordinateCentro.lng()
	
	//Area Visibile
	var AreaVisibile = map.getBounds()
	
	var NordEst = AreaVisibile.getNorthEast()
	var SudOvest = AreaVisibile.getSouthWest()
	
	document.getElementById('LatitudineNordEst').value = NordEst.lat()
	document.getElementById('LongitudineNordEst').value = NordEst.lng()					
	
	document.getElementById('LatitudineSudOvest').value = SudOvest.lat()
	document.getElementById('LongitudineSudOvest').value = SudOvest.lng()
}  

// ----------------------------------------------------------------------------------------------------------------------				
	// -----------------------------------
	// ----------- CREA MARKER------------	
	//parametri: coordinate, icona marker, testo info window
	function createMarker2(point, icona, label, tiplabel) {
		
		// ---------- PROPRIETA' MARKER ------------
		// Create our "tiny" marker icon
		var tinyIcon = new GIcon();
		// Controlla la dimensione dell'icona in funzione dello zoom
		var zoomIcon = 11;
		
		//Icone particolari
		/*
		if (icona=='photo.png') {
			
			img=icona.replace('.png','')
			
			//Dimensione delle icone
			if (document.getElementById('zoomPTIMAP').value>zoomIcon) {
				tinyIcon.image = "images/marker/"+icona;
				tinyIcon.iconSize = new GSize(24, 24);
				tinyIcon.iconAnchor = new GPoint(12, 24);
			} else {
				tinyIcon.image = "images/marker/"+img+"_small.png";
				tinyIcon.iconSize = new GSize(12, 12);
				tinyIcon.iconAnchor = new GPoint(6, 12);					
			}			

			tinyIcon.infoWindowAnchor = new GPoint(5, 1);
		
		//Altri marker classici di google map	
		} else {
		*/		
			tinyIcon.image = "images/marker/"+icona;
			tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
			tinyIcon.iconSize = new GSize(12, 20);
			tinyIcon.shadowSize = new GSize(22, 20);
			tinyIcon.iconAnchor = new GPoint(6, 20);
			tinyIcon.infoWindowAnchor = new GPoint(5, 1);		
		/*
		}
		*/
		
		//------------- CREAZIONE MARKER -----------------
		//PdMarker genera un Tooltip che appare onmouseover
		var marker = new PdMarker(point, tinyIcon);
		marker.setTooltip(tiplabel);
		
		//SIDEBAR
        // salva marker in array (serve per apertura info window da sidebar)
        gmarkers[j] = marker;
		//identificativo del marker
		var idMarker = j;		
        // aggiunge codice html alla sidebar
        side_bar_html += '<DIV id="link"><img src="images/marker/'+icona+'" align="absmiddle"><a href="javascript:myclick(' + j + ')">' + tiplabel + '</a></DIV>';
        j++;		
			
		var eliminamarker = true;
			
		// Crea Info Window al click sull'oggetto
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(label);
			eliminamarker=false;
		});	
				
		// Crea Info Window al click sull'oggetto e disabibilita la rimozione del marker
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(label);
			document.getElementById('idMarker').value=idMarker;
			eliminamarker=false;			
		});	
		
		//Abilita la rimozione del marker
		GEvent.addListener(marker, "infowindowclose", function() { 
      		eliminamarker=true; 
			document.getElementById('idMarker').value='';
    	}); 
		
		GEvent.addListener(map, "moveend", function() {
			//Se fuori dalla mappa, elimina marker
			if (eliminamarker==true) {
				map.removeOverlay(marker)				
			}						
		}); 						
				
					
		//------- EFFETTO COLORI MARKER ON MOUSE OVER ------- 
		
		var icona2 = icona;
		
		if (icona=='blu.png')  {
			icona2 = 'azzurro.png';
		} else if (icona=='rosso.png')  {
			icona2 = 'rosso_light.png';
		} else if (icona=='giallo.png')  {
			icona2 = 'giallo_strong.png';						
		}

		// Cambia colore del marker on mouse over (pdmarker)
		GEvent.addListener(marker, "mouseover", function() {
			marker.setImage("images/marker/"+icona2);
		}); 
		
		// Ripristina colore del marker on mouse out (pdmarker)
		GEvent.addListener(marker, "mouseout", function() {
			marker.setImage("images/marker/"+icona);
		});			
		
		//------- FINE COLORI MARKER ON MOUSE OVER ------- 					
				
		return marker;
	}		
	// ------- FINE CREA MARKER ----------			
	// -----------------------------------
			
// ----------------------------------------------------------------------------------------------------------------------		
	
	// -----------------------------------
	// --------- APPLICA FILTRI  ---------
	//Genera i marker in funzione della selezione (chekcbox,...)		
	function GeneraMarker(campo, azione) {						
				
		//Se azione è spuntatura di un checkbox elimina tutti i marker e li rigenera
		if (azione=='checkbox') {
			map.clearOverlays() ;				
		}
		
		//Azzera il n° di risultati	
		ResetCounters();
		
		//Svuota Sidebar
		side_bar_html = '';
		
		//disattivato id località (regione o PV)
		var id=''		
		
		//crea-ricrea marker se zoom > valore prefissato
		//IF DISABILITATO PERCHE' USATA LA FUNZIONE TOP NELLA QUERY SQL PER LIMITARE N° RISULTATI
		//if (document.getElementById('zoomPTIMAP').value>ZoomIconVisibile) {
						
			//Query dinamiche per popolamento dei marker in base ai filtri spuntati			
			//if (document.getElementById('checkMAP_SR').checked) {
				side_bar_html += '<DIV>------- Strutture ricettive -------</DIV>'				
				
				where = ''				
				var idCategoriaVacanza = document.getElementById('idCategoriaVacanza').value; //solo per TipoRisultati=='SR'
				var idStrutturaRicettivaTipologia = document.getElementById('idStrutturaRicettivaTipologia').value; //solo per TipoRisultati=='SR'
				
				where += idCategoriaVacanza!=''?'idCategoriaVacanza='+idCategoriaVacanza+'|':''
				where += idStrutturaRicettivaTipologia!=''?'idTipologia='+idStrutturaRicettivaTipologia+'|':''
					
				LoadMarkersFromQuery('Q_StruttureRicettive',campo,id,'rosso.png',where)								
			//}				
				
			//if (document.getElementById('checkMAP_IT').checked) {
				side_bar_html += '<DIV>------- Informazioni turistiche -------</DIV>'
				
				var idTipologiaInfo = document.getElementById('idTipologiaInfo').value; //solo per TipoRisultati=='IT'
				where = idTipologiaInfo!=''?'idTipologiaInfo='+idTipologiaInfo+'|':''
				
				LoadMarkersFromQuery('Q_InfoTuristiche',campo,id,'blu.png',where)
			//}
			
			//if (document.getElementById('checkMAP_AS').checked) {
				
				side_bar_html += '<DIV>------- Altre strutture -------</DIV>'
								
				var idCategoriaVacanza = document.getElementById('idCategoriaVacanza').value; //solo per TipoRisultati=='AS'
				var idStrutturaTipologia = document.getElementById('idStrutturaTipologia').value; //solo per TipoRisultati=='AS'
				
				where = ''
				where += idCategoriaVacanza!=''?'idCategoriaVacanza='+idCategoriaVacanza+'|':''
				where += idStrutturaTipologia!=''?'idStrutturaTipologia='+idStrutturaTipologia+'|':''
				
				LoadMarkersFromQuery('Q_Strutture',campo,id,'giallo.png',where)
				
			//}			
																										
								
		//}
		/*			
		// GENERA SIDEBAR (inserisce codice HTML nel tag DIV)
		document.getElementById("side_bar_contenuto").innerHTML = side_bar_html;
		
		// Nasconde DIV risultati
		if (document.getElementById('MarkerCounter').value=='0')  {
			document.getElementById("side_bar").style.display = 'none';
		// mostra DIV risultati nasconde DIV Help
		} else {
			document.getElementById("side_bar").style.display = 'block';
		}
		*/
		
	}
		
// ----------------------------------------------------------------------------------------------------------------------		
	// APRE INFO WINDOW AL CLICK SUI MARKER DELLA SIDEBAR
	function myclick(i) {
		GEvent.trigger(gmarkers[i], "click");		
	}

// ----------------------------------------------------------------------------------------------------------------------		
	// ELIMINA MARKER
	function EliminaMarker(i) {
		//id marker passato come parametro
		var NewMarkerId=i

		//id marker recuperato da hidden (se esiste campo)
		if (document.getElementById("NewMarkerId")) {
			if (document.getElementById("NewMarkerId").value!='') {
				NewMarkerId=document.getElementById("NewMarkerId").value
			}
		}
		
		if (NewMarkerId) {
			gmarkers[NewMarkerId].hide();
		}
		NascondeGuida()	
	}	  

// ----------------------------------------------------------------------------------------------------------------------		
		
	//RESTITUISCE IL N° DI RISULTATI PER LE DIVERSE CATEGORIE
	function NumeroRisultati(tbl,numerorisultati) {
		
		if (isNaN(numerorisultati)==false) {
			document.getElementById('MAPConta'+tbl).value = parseInt(numerorisultati)
			//aggiorna contatore totale marker
			document.getElementById('MarkerCounter').value = parseInt(document.getElementById('MarkerCounter').value) + parseInt(numerorisultati)
		}
	}
	
// ----------------------------------------------------------------------------------------------------------------------			
	//AZZERA I CONTATORI
	function ResetCounters() {
		
		document.getElementById('MAPContaQ_StruttureRicettive').value=0;
		document.getElementById('MAPContaQ_Strutture').value=0;
		document.getElementById('MAPContaQ_InfoTuristiche').value=0;
		
		//contatore totale marker
		document.getElementById('MarkerCounter').value=0
		
	}
	
// ----------------------------------------------------------------------------------------------------------------------			
	//REDIRECT DA INFO WINDOWS	
	function RedirectSR(idSR) {
		makeRequest(rootfolder+'ajax/schede/struttura_ricettiva.asp?idStrutturaRicettiva='+idSR,'ContentDIV',true,'struttura_ricettiva')
	}
	function RedirectIT(idIT) {
		makeRequest(rootfolder+'ajax/schede/informazione_turistica.asp?idInfoTuristica='+idIT,'ContentDIV',true,'portale_informazione_turistica')
	}
	function RedirectAS(idAS) {
		makeRequest(rootfolder+'ajax/schede/struttura_AS.asp?idStruttura='+idAS,'ContentDIV',true,'struttura_AS')
	}
// ----------------------------------------------------------------------------------------------------------------------		
	  
	// ------------ GEOCODER  ------------
	// Traduce indirizzo inserito in coordinate tramite GeoCoder
	function showAddress(address) {	
		
		if (Left(address,5)!='Cerca' && address!='') {
			geocoder.getLatLng(address,
				function(point) 
				{
					if (!point) {
						// Indirizzo non trovato, cerca nel database.
						alert(address + " non trovato!");
					} else {
						// Indirizzo trovato, centra la mappa ;)
						map.setCenter(point, 12);
					}
				}
			);
		} 		
	}	
