
//////////////////////
//////////////////////
// FUNZIONI DI MAPPA 
//////////////////////
//////////////////////


////////////////////////////////////////////
// Funzione dei creazione mappa
////////////////////////////////////////////
function cgtInit(){
	//opzioni di mappa (Google, Bing e Yahoo usano EPSG:900913, mentre il resto del mondo usa EPSG:4326 equivalente a WGS84)
	// se non metti questi valori, quando disegni i punti ti vengono sfasati
	var options = {
			projection: sourceproj, //EPSG:900913 (metri) otteniamo le mappe cosi
			displayProjection: displayproj, //EPSG:4326 (gradi) le mostriamo e interscambiamo dati con questo
			units: "m",
			numZoomLevels: 20,
			maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508)
		};
		
		if(geoserver=="Google"&&geo_layer=="Stradale") { engine = new OpenLayers.Layer.Google("Google",{"type": G_NORMAL_MAP, "sphericalMercator": true});}
		else if(geoserver=="Google"&&geo_layer=="Ibrido") { engine = new OpenLayers.Layer.Google("Google",{"type": G_HYBRID_MAP, "sphericalMercator": true});}
		else if(geoserver=="Google"&&geo_layer=="Satellite") { engine = new OpenLayers.Layer.Google("Google",{"type": G_SATELLITE_MAP, "sphericalMercator": true});}
		else if(geoserver=="Yahoo") { engine = new OpenLayers.Layer.Yahoo("Yahoo",{"sphericalMercator": true});}
		else if(geoserver=="Bing") { engine = new OpenLayers.Layer.VirtualEarth("Bing",{"type": VEMapStyle.Hybrid, "sphericalMercator": true});}
												
		//crea la mappa per il div id="map"
		map = new OpenLayers.Map("map", options);
					
		//aggiungi i layers alla mappa
		map.addLayers([engine, vector]);
						
		//aggiungi i controlli alla mappa
		map.addControl(new OpenLayers.Control.LayerSwitcher());
		map.addControl(new OpenLayers.Control.MousePosition());
		//crea il nuovo controllo, definito sopra
		var click = new OpenLayers.Control.Click();
		map.addControl(click);
		//attiva il click solo se siamo nei commenti, altrimenti il reverse geocode cerca i campi dove scrivere ed impazzisce
		if ((action == "COMMENTI")||(action == "TINY")) click.activate();
							
		//centra la mappa sulle coordinate di default
		//map.setCenter(new OpenLayers.LonLat(dlon, dlat), dzoom);
		ccpoint = new OpenLayers.Geometry.Point(dlon,dlat); //alert(dlon + " " +dlat);
		
		//trasforma il punto from  EPSG4326 (deg) to EPSG900913 (m)
		ccpoint.transform(displayproj,sourceproj); //alert(ccpoint.x + " " +ccpoint.y);
		//centra la mappa
		map.setCenter(new OpenLayers.LonLat(ccpoint.x,ccpoint.y),dzoom);
		
		//Disegna i feed GEORSS sulla mappa (oppure il punto di interesse)
		if (geocom!=null) { map.addLayer(geocom); }
		if (geocat!=null)  { map.addLayers(geocat);} 
		if (geopoi!=null) { 
			map.addLayer(geopoi); 
			geopoi.addMarker(
				new OpenLayers.Marker(
					new OpenLayers.LonLat(ccpoint.x,ccpoint.y)
				)
			); 
			
		}

}
					
////////////////////////////////////////////
//funzione di geocoding, cioč ricerca per indirizzo
////////////////////////////////////////////
function cgtGeocode() {
//comincia a prendere il valore dal campo location
//non usare la variabile location che openalyers se la usa di suo ed impazzisce
var address = document.getElementById("cgt-location").value;
						
switch (geoserver) {				
	case "Google":
		var geocoder = new GClientGeocoder();
		if (geocoder) {
			geocoder.getLatLng(	address, function(result) {
				if (!result) {
					alert(address + " non trovato, prova a fare click sulla mappa");
				} else {
					point = new OpenLayers.LonLat(result.x,result.y); //EPSG4326 (deg) 
					//disegna il punto a partire dai valori
					drawPoint(new OpenLayers.Geometry.Point(point.lon,point.lat)); 
					//Posizionati in alto dalla mappa
					document.getElementById("cgt-top").focus(); document.getElementById("cgt-top").blur();
				}
			});
		}
	break;
	case "Bing":
	//NON OK
	//http://www.bing.com/toolbox/blogs/maps/archive/2008/04/08/geocoding-with-virtual-earth.aspx
	//VEMap.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
	break;
	case "Yahoo":
	//http://trac.openlayers.org/attachment/ticket/1784/yahoogeocoder.html
	//yurl = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=".GEO_API_KEY."&location="+address;
	var yurl = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=euzuro-openlayers&location="+address;
	OpenLayers.loadURL(yurl, null, null, 
			function(yreq) {
					if(!yreq.responseXML.documentElement) { //alert("NON XML");
						var yans = yformat.read(yreq.responseText); 
					} else { //alert("XML");
						var yans = yreq.responseXML;  
					}
					yres=yans.documentElement.getElementsByTagName("Result");
					//for (i=0;i<yres.length;i++) {
						lon = yres[0].getElementsByTagName("Longitude"); 
						xx = lon[0].firstChild.nodeValue;
						lat = yres[0].getElementsByTagName("Latitude"); 
						yy = lat[0].firstChild.nodeValue;
					//	}
					//valori in gradi
					point = new OpenLayers.LonLat(xx,yy);
					//esattamente come sopra in google geocode
					//disegna il punto a partire dai valori
					drawPoint(new OpenLayers.Geometry.Point(point.lon,point.lat)); 
					//Posizionati in alto dalla mappa
					document.getElementById("cgt-top").focus();	document.getElementById("cgt-top").blur();
			}, 
			function() { alert("Indirizzo non trovato.");}
	);
	break;
	}
}

////////////////////////////////////////////
//funzione di geocoding inverso, cioč ricerca per per coordinate e trova indirizzo
////////////////////////////////////////////
function cgtReverseGeocode() {
						
	switch (geoserver) {
						
		case "Google":
			var reversegeocoder = new GClientGeocoder();
			//prendi i valori segnati nei campi nascosti
			if (document.getElementById("cgt-lon")) { //se siamo su una pagina pubblica
				point = new OpenLayers.LonLat(document.getElementById("cgt-lon").value,document.getElementById("cgt-lat").value);
			}
			if (ilon=document.getElementById("CGT_DLON")) { //se invece siamo nella pagina di amministrazione
				point = new OpenLayers.LonLat(document.getElementById("CGT_DLON").value,document.getElementById("CGT_DLAT").value);
			}
			if (reversegeocoder) {
				reversegeocoder.getLocations(new GLatLng(point.lat,point.lon), function(response) {
					if (!response || response.Status.code != 200) {
						alert("Status Code:" + response.Status.code);
					} else {
						//scrivi indirizzo dentro input
						ilocation = document.getElementById("cgt-location"); 
						ilocation.value = response.Placemark[0].address;
						ilocation.focus();
					}
				});
			}
			break;
			case "Yahoo":
				//Funzione supportata solo in Flash e non in Javascript
			break;
			case "Bing":
				//http://www.bing.com/toolbox/blogs/maps/archive/2008/04/08/geocoding-with-virtual-earth.aspx
			break;
	}
}
					
////////////////////////////////////////////
// FUnzione di disegno punto su mappa, ovvero
//Se gli passi un punto in sphericalmercator
//lui te lo disegna in mappa sul layer vector
////////////////////////////////////////////
function drawPoint(point) {
	//prendiamo il punto in EPSG4326 e lo duplichiamo
	//scrivi le coordinate trasformate dentro gli input
	if (document.getElementById("cgt-lon")) { //se siamo su una pagina pubblica
	//alert(point.x + " " + point.y);
		ilon=document.getElementById("cgt-lon"); ilon.value=point.x;
		ilat=document.getElementById("cgt-lat"); ilat.value=point.y;
		if(document.getElementById("cgt-zoom")) { 
			izoom=document.getElementById("cgt-zoom"); izoom.value=map.getZoom();
		}
	}
	if (ilon=document.getElementById("CGT_DLON")) { //se invece siamo nella pagina di amministrazione
		ilon=document.getElementById("CGT_DLON"); ilon.value=point.x;
		ilat=document.getElementById("CGT_DLAT"); ilat.value=point.y;
		izoom=document.getElementById("CGT_DZOOM"); izoom.value=map.getZoom();
	}
	//trasforma il punto from  EPSG4326 (deg) to EPSG900913 (m)
	point.transform(displayproj,sourceproj); 
	//centra la mappa
	map.setCenter(new OpenLayers.LonLat(point.x,point.y),map.getZoom());
	//se abbiamo un punto sulla mappa distruggilo prima di rifarlo
	if (pointFeature) { vector.removeFeatures([pointFeature]);}
	pointFeature = new OpenLayers.Feature.Vector(point); 
	vector.addFeatures([pointFeature]);
	//trasforma il punto indietro da EPSG900913(m) a EPSG4326 (deg)
	point.transform(sourceproj,displayproj);
}
					
////////////////////////////////////////////
//Aggiunge il controllo del click singolo
//quando fai click sulla mappa scrive lonlat dentro box di testo e disegna in mappa	
////////////////////////////////////////////					
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
	defaultHandlerOptions: {
		"single": true,
		"double": false,
		"pixelTolerance": 0,
		"stopSingle": false,
		"stopDouble": false
	},
		initialize: function(options) {
		this.handlerOptions = OpenLayers.Util.extend(
		{}, this.defaultHandlerOptions
	);
	OpenLayers.Control.prototype.initialize.apply(
		this, arguments
	); 
		this.handler = new OpenLayers.Handler.Click(
			this, { "click": this.trigger}, this.handlerOptions
		);
	}, 

	trigger: function(e) {
		//con un click prende il punto in mappa formato EPSG900913 (m)
		var lonlat = map.getLonLatFromViewPortPx(e.xy);	
		// trasforma il catturato in un punto
		point = new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat);
		//trasforma il punto from EPSG900913 (m) in EPSG4326 (deg)
		point.transform(sourceproj,displayproj); //alert (p.x+" " +p.y);		
		//disegna il punto a partire dai valori
		drawPoint(point);
		//fai il reverse geocode
		cgtReverseGeocode();
	}
});
					
//////////////////////
//////////////////////
// FUNZIONI DI FORM 
//////////////////////
//////////////////////
					
////////////////////////////////
//Funzione per aggiungere campi alla sezione commenti
////////////////////////////////
function cgtAddFileds(cgtmaximages,comment) { 

	for (i=0; i<document.forms.length; i++) {
    var f = document.forms[i];
    if (f.comment_post_ID) {
        f.encoding = "multipart/form-data";

        var l = f.getElementsByTagName("textarea");
        l = l[0].parentNode;

        var p = document.createElement("p");
		p.setAttribute("style", "margin:0px;width:100%");
		//se le categorie sono definite e non sono un insieme vuoto
	if (comment == true) {
		/*if ((comcat && maxcat)&&(comcat!="" && maxcat!="")) {
			var categoria = document.createElement("select");
			categoria.setAttribute("name", "cgt-cat");
			categoria.setAttribute("id", "cgt-cat");
			categoria.setAttribute("style", "height:22px;width:40%;");
			for(k=0; k<maxcat; k++) {
				var opzione = document.createElement("option");
				//nomecat = "categoria-" +k; 
				opzione.value = comcat[k];
				//opzione.setAttribute("name", nomecat);
				if (k==1) opzione.setAttribute("select", "true");
				opzione.appendChild(document.createTextNode(comcat[k]));
				categoria.appendChild(opzione);
			}
			p.appendChild(categoria);
			p.appendChild(document.createElement("br"));
		}*/
		
        var indirizzo = document.createElement("input");
        indirizzo.setAttribute("name", "cgt-location");
		indirizzo.setAttribute("id", "cgt-location");
        indirizzo.setAttribute("type", "text");
        indirizzo.setAttribute("style", "height:18px;width:70%;");
        p.appendChild(indirizzo);

        var cerca = document.createElement("input");
        cerca.setAttribute("name", "cerca");
		cerca.setAttribute("id", "cerca");
		cerca.setAttribute("value", "Cerca Indirizzo");
        cerca.setAttribute("type", "button");
		cerca.setAttribute("onclick", "cgtGeocode();");
        cerca.setAttribute("style", "width:25%;");
        p.appendChild(cerca);

        var lon = document.createElement("input");
        lon.setAttribute("name", "cgt-lon");
		lon.setAttribute("id", "cgt-lon");
        lon.setAttribute("type", "hidden");
        lon.setAttribute("style", "height:18px;width:40%;");
		//lon.setAttribute("value", "Longitudine");
        p.appendChild(lon);		

		var lat = document.createElement("input");
        lat.setAttribute("name", "cgt-lat");
        lat.setAttribute("id", "cgt-lat");
		lat.setAttribute("type", "hidden");
        lat.setAttribute("style", "height:18px;width:40%;");
		//lat.setAttribute("value", "Latitudine");
        p.appendChild(lat);		
	}
	
		var pp = document.createElement("p");
		pp.setAttribute("style", "width:100%;");
        pp.innerHTML = "<b>Carica immagini a commento</b><br /><small><i>Nel fare questo dichiaro che le foto sono di mia esclusiva proprieta ed autorizzo alla loro pubblicazione a titolo gratuito su questo sito.</i></small>";
		p.appendChild(pp);
		p.appendChild(document.createElement("br"));
		
		
		for (j=0; j<cgtmaximages; j++) {
		var nameid = "cgt-image"; if (j>0) {nameid = nameid+j;}
		var t = document.createElement("input");
        t.setAttribute("name", nameid);
		t.setAttribute("id", nameid);
        t.setAttribute("type", "file");
        t.setAttribute("style", "width:auto;");
        p.appendChild(t);
		p.appendChild(document.createElement("br"));
		}
        //p.appendChild(document.createTextNode("Carica immagini a commento"));
        l.parentNode.insertBefore(p, l.nextSibling);
		
		
        //break;

    }
	}

}


////////////////////////////////////////
//Funzione di controllo di compilazione di tutti i campi
////////////////////////////////////////
function checkvalue() {
	
	comment  =   document.getElementById("comment");
	lon  =   document.getElementById("cgt-lon");
	lat  =   document.getElementById("cgt-lat");
	indirizzo  =   document.getElementById("cgt-location");
	
	if ( comment.value == "") {alert("Per cortesia inserisci un commento"); return false;}
	if ( lon.value == "" || lat.value =="") {alert("Per cortesia posiziona il commento in mappa(fai click su \"Cerca indirizzo\" oppure direttamente in mappa)"); return false;}
	if ( indirizzo.value == "") {alert("Per cortesia inserisci un indirizzo"); return false;}
	
	return true;
}
