/******************************************************************************
******* FUNZIONI DI RICERCA e GEOCODING     ***********************************
*******************************************************************************
Simone Gadenz
*******************************************************************************
Questo file raccoglie le funzioni di ricerca e di geocoding, 
ritornanod sempre oggetti georeferenziati
Si integra con le pagine dinamiche server-side
******************************************************************************/
/*
* RICERCA SPAZIALE: funzione filtro, interpreta le impostazioni selezionate 
* nel form di ricerca e reindirizza alle varie funzioni
*/
function spatialSearch(){
	var operation = OpenLayers.Util.getElement('selSpatialSearch').value;
	var searchvalue = OpenLayers.Util.getElement('txtSpatialSearch').value;
	if (operation == '-1')
	{
		alert("Selezionare una voce dalla lista a tendina prima di ricercare.");
	}
	else if (operation == '0')//azienda
	{
		if(searchvalue != null && searchvalue != '')
		{
			searchFeature('contenuto',searchvalue);
		}
		else
		{
			alert("E' necessario inserire un valore nel campo per effettuare la ricerca");
		}
	}
	else if (operation == '1')// indirizzo
	{
		searchAddress(searchvalue,function(point){/*metter qui codice se necessario*/});
	}
	else if (operation == '2')// vino
	{
		//searchFeature('vino',searchvalue);
	}
	else if (operation == '3')// latlon
	{
		var coords = searchvalue.split(",");
		if(parseInt(coords[0]) > 90 && parseInt(coords[0]) < -90){
			alert("Valore di latitudine errato. Prego inserire un valore compreso tra -90 and 90");
		}else{
			if(parseFloat(coords[1]) > 180 && parseFloat(coords[1]) < -180){
				alert("Valore di latitudine errato. Prego inserire un valore compreso tra -180 and 180");
			}else{
				var style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
				style_mark.graphicWidth = 28;
				style_mark.graphicHeight = 31;
				//style_mark.graphicXOffset = -style_mark.graphicWidth;  // this is the default value
				style_mark.graphicYOffset = -style_mark.graphicHeight;
				style_mark.externalGraphic = "/images/pin_red.png";
				var geopoint = new OpenLayers.Geometry.Point(parseFloat(coords[1]),parseFloat(coords[0]));
				var geopointtrans = geopoint.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")); 
	
				var data = {"address": "<b>Lat,Lon: <b><br>"+searchvalue+""};
	
				var pointFeature = new OpenLayers.Feature.Vector(geopointtrans,data,style_mark);
				map.setCenter(new OpenLayers.LonLat(geopointtrans.x, geopointtrans.y), 11);
				geocodedLayer.addFeatures([pointFeature]);
				geocodedLayer.setVisibility(true);
			}
		}
	}
	
	
}

/**********************************************************
********* RICERCA DI ELEMENTI GEOGRAFICI ******************
***********************************************************/
/*
**  Ricerca l'elemento geografico in base al tipo
*/
function searchFeature(tipo,searchvalue){
	var getcoordinatepage = "tutte_segnalazioni.php";
	switch(tipo)
	{
	case "contenuto":
		loadContent(getcoordinatepage+'?desc='+searchvalue,'risultati ricerca::');
		closeEditingToolBar();
		//ajaxObj = OpenLayers.loadURL(getcoordinatepage+"?desc="+searchvalue, null, this, this.requestCoordinatesSuccess, this.requestFailure);
		break;    
	case "vino":
		//ajaxObj = OpenLayers.loadURL(getcoordinatepage+"?vino="+searchvalue, null, this, this.requestCoordinatesSuccess, this.requestFailure);
		break;
	default:
		alert("Errore in fase di ricerca!");
		break;
	}
}

/* 
** Gestisce l'oggetto contenente i risultati della ricerca 
*/
function requestCoordinatesSuccess(){
		var iHTML = "";
		var title = "<h1>Risultati ricerca ::</h1>";// titolo di default che si aggiunge alla intestazione
		var titleDiv = OpenLayers.Util.getElement('title');
		var resultDiv = OpenLayers.Util.getElement('left');
		var jsondata = eval('(' + ajaxObj.responseText + ')');
		if (jsondata.results == null || jsondata.results.length == 0){
			iHTML="<div class=\"text\"><b>0</b> risultati. Verifica il parametro utilizzato per la ricerca o contriuisci con una nuova segnalazione <a href=\"javascript:loadContent('/gestione/registrazione.php', 'registrati::');\">cliccando qui</a></div>";
		}else{
			iHTML = "<div class=\"text\">";
			iHTML += "<p>"+jsondata.results.length+" risultato/i per la ricerca effettuata:</p>";
			for (x in jsondata.results){
				iHTML += "<h2>"+jsondata.results[x].properties.title+"</h2>"
				iHTML += "<br><a href=\"javascript:setContentOriginalStatus();zoom2Point("+jsondata.results[x].geometry.coordinates[1]+","+jsondata.results[x].geometry.coordinates[0]+",18)\">Visualizza su mappa</a>";
				iHTML += "<br><a href=\"javascript:getPoiList('/ppgis/getInfoPois.php?id="+ jsondata.results[x].properties.guid +"','"+ jsondata.results[x].properties.guid +"')\">Visualizza info azienda </a>";
				
				
			}
			iHTML += "</div>";
		}
		
		titleDiv.innerHTML = title;
		resultDiv.innerHTML = iHTML;
	}

/**********************************************************
********* GEOCODING USING GOOGLE GEOCODER******************
***********************************************************/
function searchAddress(address, callbacksa){
	//var address = OpenLayers.Util.getElement('txtAddressSearch').value;
	
	
	pointFeature = null;
	if (geocoder) {
		geocoder.getLatLng(
		  address,
		  function(point) {
			if (!point) {
				alert(address + " non trovato!");
			} else {
				var style_mark = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
				style_mark.graphicWidth = 28;
				style_mark.graphicHeight = 31;
				//style_mark.graphicXOffset = -style_mark.graphicWidth;  // this is the default value
				style_mark.graphicYOffset = -style_mark.graphicHeight;
				style_mark.externalGraphic = "/images/pin_red.png";
				var geopoint = new OpenLayers.Geometry.Point(point.x,point.y);
				var geopointtrans = geopoint.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")); 
	
				var data = {"address": "<b>Geocoded address: <b><br>"+address+"<br /><i>Geocoded by Google</i>"};
				
				pointFeature = new OpenLayers.Feature.Vector(geopointtrans,data,style_mark);
				
				map.setCenter(new OpenLayers.LonLat(geopointtrans.x, geopointtrans.y), 16);
				geocodedLayer.addFeatures([pointFeature]);
				geocodedLayer.setVisibility(true);
				callbacksa(pointFeature);
				
			}
		  }
		);
		
		
	  }
	
}



