/* *************************************
 * Funzione per la registrazione dell'evento info foto in mappa
 ************************************ */
function setInfoFotoEvent() {
	 		
	 // Registro l'evento per l'info foto
	 map.events.register('click', map, function (e) {
		//Control added to capture click event in insert point
		if (!map.getLayerByName(testoLayerFoto).visibility)
		{
			return;
		}
      	//Se � attivo la selezione grafica della tappa
      	if (navToolBar.controls[3].active)
      	{
      	  	return;
      	}
		//Se � attiva l'info puntuale
      	if (navToolBar.controls[2].active)
      	{
      	  	return;
      	}
      	
      	//Visualizziamo il messaggio di "elaborazione in corso"
      	loadingMsg.startLoad();
      	
    	var px = new OpenLayers.Pixel(e.xy.x,e.xy.y);
    	var currentPosition = map.getLonLatFromPixel(px);
		  
	  	var par = "?locale=" +language+"&command=Info&pointGeom="+currentPosition.lon+","+currentPosition.lat+"&nomeProperties=InfoFoto";
		  
	    new OpenLayers.Ajax.Request(urlSentieriWebBackend + par,
	                     {   method: 'get',
	                         parameters: null,
	                         onComplete: setHTMLBalloonFoto,
	                         onFailure: setHTMLBalloonFoto
	                      }
	                     );
	    Event.stop(e);
	 });
}     

var xmlResponseFoto = null;
/* *************************************
 * Funzione per la creazione del balloon delle foto
 ************************************ */
function setHTMLBalloonFoto(response) {
	
		//Nascondiamo il messaggio di "elaborazione in corso"
        loadingMsg.stopLoad();
        
	    var xmlResponse = response.responseXML;
	    if (!xmlResponse || response.fileType!="XML") {
	            xmlResponse = OpenLayers.parseXMLString(response.responseText);
	        }


		//verifichiamo se almeno la prima foto � presente
		if(xmlResponse.getElementsByTagName('URL_1').length == 0 || xmlResponse.getElementsByTagName('URL_1')[0].firstChild == null)
		{
			return;
		}
		
		//a questo punto siamo sicuri che almeno una foto � presente		
		//quindi possiamo costruire il popup
		xmlResponseFoto = xmlResponse;
		
		//Creazione dell'html per il popup
		var onclicktext ="window.open('" + setFotoUrl(xmlResponse.getElementsByTagName('URL_1')[0].firstChild.nodeValue)+ "','','');"; 
        var contentHTML =	'<div class="width100 alignCenter">'+ 
        						'<a id="thumbLinkId" onclick="' + onclicktext + '" href="#"><img id="thumbImageId" src="'+ setFotoUrl(xmlResponse.getElementsByTagName('URL_1')[0].firstChild.nodeValue) +'" class="thumbnail "/></a>';
        						
        //Costuriamo il div dei link agli altri thumbnails
        contentHTML +='<div class="width100 ">';
        var i = 1;
        for(i = 1; i <= numMaxFoto; i++)
        {
        	if (xmlResponse.getElementsByTagName('URL_' + i).length > 0 && xmlResponse.getElementsByTagName('URL_' + i)[0].firstChild != null)
        	{
        		if (trim(xmlResponse.getElementsByTagName('URL_' + i)[0].firstChild.nodeValue,' ') != "")
        		{
        			contentHTML +='<a class="hr-space" onclick="setThumbnail(' + i + ');" href="#">' + i + '</a>';
        		}
        	}
        	else
        	{
        		//contentHTML += i;
        	}
        }
        contentHTML += '</div>'; // chiusura div dei link agli altri thumbnails
        contentHTML += '</div>'; //chiusura div del thumbnail
        contentHTML += '<div class="width100 ">'; //div delle informazioni
        
        contentHTML += '<div class=" width100"><b>' + autoreFoto + ': </b></div>';
        
        if (xmlResponse.getElementsByTagName('AUTORE_1').length > 0 && xmlResponse.getElementsByTagName('AUTORE_1')[0].firstChild != null)
        {
        	contentHTML +='<div id="thumbAutoreId" class=" width100">' + xmlResponse.getElementsByTagName('AUTORE_1')[0].firstChild.nodeValue + '</div>';
        }					
        else
        {
        	contentHTML +='<div id="thumbAutoreId" class=" width100">&nbsp;</div>';
        }
        
        contentHTML += '<div class=" width100"><b>' + descrizioneFoto +': </b></div>';
        
        if (xmlResponse.getElementsByTagName('DESCRIZ_1').length > 0 && xmlResponse.getElementsByTagName('DESCRIZ_1')[0].firstChild != null)
		{
			contentHTML +='<div id="thumbDescrId" class=" width100">' + xmlResponse.getElementsByTagName('DESCRIZ_1')[0].firstChild.nodeValue + '</div>';
		}
		else
		{
			contentHTML +='<div id="thumbDescrId" class=" width100">&nbsp;</div>';
		}
                
		
		contentHTML +=  '</div>'; //chiusura div delle informazioni
							
        	
		//Estraggo la geometria
		var punto = xmlResponse.getElementsByTagName('row')[0];
		if (punto == null)
		{
			return;
		}
		var geometria = punto.attributes.getNamedItem('geometria').value;
		
		//Estraggo le coordinate del punto
		var idx1 = geometria.indexOf('<gml:coordinates');
		var idx2 = geometria.indexOf('</gml:coordinates>');
		var coordinates = geometria.substring(idx1, idx2 + 18);
		
		//Estraggo i valori x e y
		var searchComma = ",";
		var	position = coordinates.indexOf(searchComma);
		var x = coordinates.substring(coordinates.indexOf('>')+1,position);
		var y = coordinates.substring(position+1,coordinates.indexOf('</gml:coordinates>'));

        var lonlat = new OpenLayers.LonLat(x,y);

		//Se esiste il layer dei marker lo ripulisco
		if (markersLayer!=null)
		{
			markersLayer.clearMarkers();
		}
		//altrimenti lo creo
		else
		{
			var options = {
			   displayInLayerSwitcher:false
			}	
			 markersLayer = new MW.Layer.Markers( "Markers",options);
	         map.addLayer(markersLayer);
		}
      	
        AutoSizeFramedCloudMinSize = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
            'autoSize': true, 
            'minSize': new OpenLayers.Size(250,250),
            'maxSize': new OpenLayers.Size(400,500)
        });
      	
		popupClass = AutoSizeFramedCloudMinSize;
		popupContentHTML = contentHTML;
		
		var data={
			icon: new OpenLayers.Icon(OpenLayers.ImgPath + "dot.gif", new OpenLayers.Size(0, 0), null, null),
			popupSize: new OpenLayers.Size(300, 200)
		}
		
        var feature = new OpenLayers.Feature(markersLayer, lonlat, data); 
        feature.closeBox = true;
        feature.popupClass = popupClass;
        feature.data.popupContentHTML = popupContentHTML;
        feature.data.overflow = "hidden";
                
        var marker = feature.createMarker();

        markersLayer.addMarker(marker);
              
        if (marker.popup == null) {
            marker.popup = feature.createPopup(feature.closeBox);
            map.addPopup(marker.popup);
        }                
        
        marker.popup.show();
};

/* *************************************
 * Funzione per l'impostazione dell'url corretta. Se non � un url assoluta, viene usata
 * l'url relativa
 ************************************ */
function setFotoUrl(url) {
	if (url.indexOf('http:')<0)
	{
		return fotoUrl + "/" + url;
	}
	
	return url;
}

/* *************************************
 * Funzione per l'aggiornamento dei dati delle foto
 ************************************ */
function setThumbnail(i) {
	//per il campo URL non c'� bisogno di verificare se eiste il valore perch�
	//il controllo viene fatto gi� nel metodo chiamante e se non esiste non viene creato il link 
	$("thumbLinkId").onclick= function () {window.open(setFotoUrl(xmlResponseFoto.getElementsByTagName('URL_'+i)[0].firstChild.nodeValue),'','');} ;	
	$("thumbImageId").src = setFotoUrl(xmlResponseFoto.getElementsByTagName('URL_'+i)[0].firstChild.nodeValue);
	
	
	if (xmlResponseFoto.getElementsByTagName('DESCRIZ_'+i).length > 0 && xmlResponseFoto.getElementsByTagName('DESCRIZ_'+i)[0].firstChild != null)
	{
		$("thumbDescrId").innerHTML = xmlResponseFoto.getElementsByTagName('DESCRIZ_'+i)[0].firstChild.nodeValue;
	}
	else
	{
		$("thumbDescrId").innerHTML = '';
	}
	
	if (xmlResponseFoto.getElementsByTagName('AUTORE_'+i).length > 0 && xmlResponseFoto.getElementsByTagName('AUTORE_'+i)[0].firstChild != null)
	{
		$("thumbAutoreId").innerHTML = xmlResponseFoto.getElementsByTagName('AUTORE_'+i)[0].firstChild.nodeValue;
	}
	else
	{
		$("thumbAutoreId").innerHTML = '';
	}
}


function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


