/*
	VARIABILI GLOBALI
*/

//Variabilie per XML Ajax
var xmlHttp;

//Configurazione per zoom delle API di google
var latItalia = 41.896655; //Centrata su ROMA
var longItalia = 12.495918;
var zoomBase = 5;
var zoomProvMin = 0;
var zoomProvMax = 10;
var zoomCaseMin = 11;
var zoomCaseMax = 17;
var descrizione = '';
var caricamento = "<b>Caricamento descrizione in corso...</b><br/><br/>Se l'attesa diventa troppo lunga <br/>si prega di riprovare a cliccare nuovamente."; 
var dominio = 'affittistudentiuniversitari';
//var webapps = 'affittogiovani';
var urlImage = 'layout/images/img_';
var urlImageGlobal = '/layout/images/';
var urlView = 'http://www.'+dominio+'.it/View';


var elementiPagina=5;
var arrayJSON;

//Variabile per icone 
var baseIcon = new GIcon();
    baseIcon.iconSize=new GSize(32,32);
    baseIcon.shadowSize=new GSize(56,32);
    baseIcon.iconAnchor=new GPoint(16,32);
    baseIcon.infoWindowAnchor=new GPoint(16,0);
    
//Variabile per icone dei Beb 
var baseIconBeb = new GIcon();
    baseIconBeb.iconSize=new GSize(24,24);
    baseIconBeb.shadowSize=new GSize(56,27);
    baseIconBeb.iconAnchor=new GPoint(16,27);
    baseIconBeb.infoWindowAnchor=new GPoint(16,0);
    
//Variabile per icone delle provincie 
var baseIconProv = new GIcon();
    baseIconProv.iconSize=new GSize(30,30);
    baseIconProv.shadowSize=new GSize(30,20);
    baseIconProv.iconAnchor=new GPoint(16,32);
    baseIconProv.infoWindowAnchor=new GPoint(16,0);
    
//Variabile per icone delle uni 
var baseIconUni = new GIcon();
    baseIconUni.iconSize=new GSize(25,17);
    baseIconUni.shadowSize=new GSize(56,32);
    baseIconUni.iconAnchor=new GPoint(16,32);
    baseIconUni.infoWindowAnchor=new GPoint(16,0);

//Icona case
var casa = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon10.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon10s.png");
//Icona BeB
var beb = new GIcon(baseIconBeb, "http://www.affittistudentiuniversitari.it/layout/images/icon_beb.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon10s.png");
//Icona citta
var citta = new GIcon(baseIconProv, "http://www.affittistudentiuniversitari.it/layout/images/icon_prov.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon10s.png");
//Icona agenzia
var agenzia = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon14.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon14s.png");
//Icona Universita
var universita = new GIcon(baseIconUni, "http://www.affittistudentiuniversitari.it/layout/images/icon_uni.gif", null, null);

//Variabile Mappa 
var map;
var mapAgenzia;
var mm;
var mmAgenzia;

//HashMap elementi caricati sulla mappa
var hashMap = {
	Set : function(key,value) {this[key] = value;},
	Get : function(key) {return this[key];}
};

var hashMapProv = {
	Set : function(key,value) {this[key] = value;},
	Get : function(key) {return this[key];}
};



/*
	FUNZIONI JAVASCRIPT
*/
//Metodo per creare nuove case, parametri -> Punto, Descrizione, Icona
function createMarkerCase(point,id) {
	      var marker = new GMarker(point, {clickable: true, icon: casa, title: id});
	      GEvent.addListener(marker, "click", function() {
	      		marker.openInfoWindowHtml(caricamento);
		        ajaxSearchDescrizione(marker,id);
	      });
	      return marker;
}

//Metodo per creare nuove case, parametri -> Punto, Descrizione, Icona
function createMarkerBeb(point,id) {
	      var marker = new GMarker(point, {clickable: true, icon: beb, title: id});
	      GEvent.addListener(marker, "click", function() {
	      		marker.openInfoWindowHtml(caricamento);
		        ajaxSearchDescrizione(marker,id);
	      });
	      return marker;
}

		      
//Metodo per creare nuove citta, parametri -> Punto, Icona			      
function createMarkerCitta(point) {
	       var marker = new GMarker(point,citta);
	       GEvent.addListener(marker, "click", function(){
		  	   					 map.setCenter(point,zoomCaseMin);						 
	      					 });
	      return marker;
}

//Metodo per creare il marker della casa, non cliccabilie -> Pagina di dettaglio di un annuncio
function createMarkerCaseNoClick(point,tipo){
	      var marker;
	      if (tipo == 'P') marker = new GMarker(point,casa);
	      else marker = new GMarker(point,beb);
	      return marker;
}


	

function createMarkerAgenzia(point){
	       var marker = new GMarker(point,agenzia);
	       return marker;
}	

function createMarkerUniversita(point,id){
	       var marker = new GMarker(point,universita);
	       GEvent.addListener(marker, "click", function() {
	      		marker.openInfoWindowHtml(caricamento);
		        ajaxSearchDescrizioneUniversita(marker,id);
	       });	       
	       return marker;
}

			
//Funzione in risposta quando si fa il submit dei campi di ricerca
//La funzione Ajax che accetta l'xml č stateChangedSearch      			      
function ajaxSearch(){ 
			xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null){
			 alert ("Spiacente, il tuo browser non supporta l'oggetto XmlRequest")
			 return
		}
		//Passo dei parametri alla mia jsp, sarannpo i filtri di ricerca
		var query="";
		if (document.getElementById('tipologia').value!=''){
			query=query+"tipologia="+document.getElementById('tipologia').value
		}
		if (document.getElementById('regione') !=null && document.getElementById('regione').value!=''){
			if (query!="") query=query+"&"
			query=query+"regione="+document.getElementById('regione').value
		}
		if (document.getElementById('provincia') !=null && document.getElementById('provincia').value!=''){
			if (query!="") query=query+"&"
			query=query+"provincia="+document.getElementById('provincia').value
		}	
		if (document.getElementById('citta').value!=''){
			if (query!="") query=query+"&"
			query=query+"citta="+document.getElementById('citta').value
		}
		if (document.getElementById('provincia').value == 'MI'){
			if (query!="") query=query+"&"
			query=query+"zona="+document.getElementById('zonaMi').value
		}else{
			if (document.getElementById('provincia').value == 'RO'){
				if (query!="") query=query+"&"
				query=query+"zona="+document.getElementById('zonaRo').value
			}
		}						
		if (document.getElementById('prezzo').value!=''){
			if (query!="") query=query+"&"
			query=query+"prezzo="+document.getElementById('prezzo').value
		}				
		if (query != ""){
				query = query +"&search=true";
				//Se ci sono valori di ricerca impostati li aggiungo all'url come parametri
				var url="ajaxServlet.jsp"
			 	url=url+"?"+query
				//imposto la funzione di riposta
				xmlHttp.onreadystatechange=stateChangedSearch 
				xmlHttp.open("GET",url,true)
				xmlHttp.send(null)
		}
}

function ajaxSearchLast10(){
		xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null){
			 alert ("Spiacente, il tuo browser non supporta l'oggetto XmlRequest")
			 return
		}		
		var query = "lastTen=true";
		var url="ajaxServlet.jsp"
	 	url=url+"?"+query
		//imposto la funzione di riposta
		xmlHttp.onreadystatechange=stateChangedSearch 
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)		
}

//Funzione in risposta quando si carica il sito
//La funzione Ajax che accetta l'xml č stateChanged  
function ajaxIndex(stato){
			var m = document.getElementById("map");	
			m.style.height = "400px";
		    m.style.width = "500px";
			map = new GMap2(m);
			GEvent.addListener(map,'dblclick',function(){
		  	   					 map.zoomIn();
			});					
		 	map.addControl(new GLargeMapControl());
		 	map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(latItalia,longItalia),zoomBase);
			mm = new GMarkerManager(map, {borderPadding:1});
			GEvent.addListener(map,'moveend',function(){
		  	   					 mapMove('move');
			});		
			mapMove(stato);
}
 
 
//Funzione invocata quando clicco su una casetta
function ajaxSearchDescrizione(marker,id){
			var url="ajaxServlet.jsp?desc=true&id="+id;
			xmlHttp=GetXmlHttpObject()	
			xmlHttp.onreadystatechange= function() {
									stateChangedDescrizione(marker,id);
							};
			xmlHttp.open("GET",url,true)
			xmlHttp.send(null)		  		       			
}

//Funzione invocata quando clicco su un Universita
function ajaxSearchDescrizioneUniversita(marker,id){
			var url="ajaxServlet.jsp?uni=true&id="+id;
			xmlHttp=GetXmlHttpObject()	
			xmlHttp.onreadystatechange= function() {
									stateChangedDescrizioneUniversita(marker,id);
							};
			xmlHttp.open("GET",url,true)
			xmlHttp.send(null)		  		       			
}

//Funzione invocata quando clicco su un Bed and breakfast
function ajaxLoadArticoliBeB(id,color){
		xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null){
			 alert ("Spiacente, il tuo browser non supporta l'oggetto XmlRequest")
			 return
		}		
		var query = "articleBeB=true&id="+id;
		var url="ajaxServlet.jsp"
	 	url=url+"?"+query
		//imposto la funzione di riposta
		xmlHttp.onreadystatechange= function() {
									stateChangedLoadArticoliBeb(id,color);
							};
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)  		       			
}



//Funzione per visualizzare le universita nella stessa provincia dell'annuncio che sto visualizzando.
function mapLoadUniversita(prov){
			xmlHttp=GetXmlHttpObject()
			if (xmlHttp==null){
				 alert ("Spiacente, il tuo browser non supporta l'oggetto XmlRequest")
				 return
			}	
			var url="ajaxServlet.jsp?loaduni=true&prov="+prov;
			xmlHttp.onreadystatechange=stateChangedLoadUniversita
			xmlHttp.open("GET",url,true)
			xmlHttp.send(null)	
}

function stateChangedDescrizione(marker,id) { 
//Se la risposta va a buon fine
if (xmlHttp.readyState==4){ 	
	//Qua si puņ mettere un loader
	if (xmlHttp.status == 200){
			var rispostaJson = xmlHttp.responseText
			var arrayFromJSON = rispostaJson.parseJSON();
			marker.closeInfoWindow();
			if (arrayFromJSON.length==1){
				 var foto = arrayFromJSON[0].foto;
				 var html =  "<table width='230'>";
				 html = html + "<tr><td bgcolor='#F0F0F0'>" + arrayFromJSON[0].infowindow + "</td></tr>";
				 if ( arrayFromJSON[0].pr != null && arrayFromJSON[0].pr != undefined){
 				 	html = html + "<tr><td>Prezzo : " + arrayFromJSON[0].pr + " &euro;</td></tr>";
 				 }			 
				 if ( foto != null && foto != 'null' && foto != ''){
					 html = html + "<tr><td><img width='150px' height='112' src="+urlImage+id+"/"+ foto + "></td></tr>";				 
				 }
				 html = html + "<tr><td><a href='"+urlView+"?p="+id+"'><b>Apri Annuncio</b></a></td></tr>";				 
				 html = html + "</table>"
				 marker.openInfoWindowHtml(html);
			}else marker.openInfoWindowHtml("Spiacente, non č stato possibile caricare la descrizione");
	}
 } 
}

function stateChangedDescrizioneUniversita(marker,id) { 
//Se la risposta va a buon fine
if (xmlHttp.readyState==4){ 	
	//Qua si puņ mettere un loader
	if (xmlHttp.status == 200){
			var rispostaJson = xmlHttp.responseText
			var arrayFromJSON = rispostaJson.parseJSON();
			marker.closeInfoWindow();
			if (arrayFromJSON.length==1){
				 var html =  "<table width='230'>";
				 html = html + "<tr><td><b>" + arrayFromJSON[0].infowindow + "</b></td></tr>";				 
				 html = html + "<tr><td><a target='_blank' href='http://"+arrayFromJSON[0].link+"'>Vai al sito dell'Universita</a></td></tr>";				 
				 html = html + "</table>"
				 marker.openInfoWindowHtml(html);
			}else marker.openInfoWindowHtml("Spiacente, non č stato possibile caricare l'universita");
	}
 } 
}


//FUNZIONE PER GESTIONE DI PROVINCE, UNIVERSITA E CASE DA VISUALIZZARE SULLA MAPPA
function stateChanged() { 
//Se la risposta va a buon fine
if (xmlHttp.readyState==4){ 	
	if (xmlHttp.status == 200){
			var gmarkerscittaTemp = [];
			var gmarkerscaseTemp = [];
			var gmarkersuniTemp = [];					
			var rispostaJson = xmlHttp.responseText
			var arrayFromJSON = rispostaJson.parseJSON();
			var i = 0;							
			if (arrayFromJSON.length > 1){
					//Se devo aggiungere le province e le universita
					if (arrayFromJSON[0].t=='p'){
						//Estraggo il numero di annunci inseriti, popolo la combo-box delle province.
						if (arrayFromJSON[1].count != 'KO') {
							document.getElementById("txtRicerca").innerHTML = "Ricerca tra "+(arrayFromJSON[1].count)+" annunci presenti <a href='http://feed43.com/affittistudenti.xml' target='_blank'><img border='0' src='http://www.affittistudentiuniversitari.it/layout/images/feed_add.gif' alt='Feed RSS'></a>";				
							var txtProv = "<select name='provincia' id='provincia' class='form-comboPiccola' onchange='changeFormSearchProvincia()'>";
							if (arrayFromJSON.length > 2){
									for (i=2;i<arrayFromJSON.length && arrayFromJSON[i].id == undefined ;i++){
										txtProv = txtProv + "<option value='"+arrayFromJSON[i].prov+"'>"+arrayFromJSON[i].prov+"</option>";
									}
									//controllo se roma o milano per attivare le zone
									if (arrayFromJSON[2].prov=='MI'){
												document.getElementById("zonaTxtDiv").style.display = 'inline';	
												document.getElementById("zonaDivMi").style.display = 'inline';
									}else if (arrayFromJSON[2].prov=='RO'){
												document.getElementById("zonaTxtDiv").style.display = 'inline';	
												document.getElementById("zonaDivRo").style.display = 'inline';								
									}
									txtProv = txtProv + "</select>";
									document.getElementById("provinciaDiv").innerHTML = txtProv;
							}
						}
						//Visualizzo i marker PER LE PROVINCE in cui sono presenti annunci
						for (i=2;i<arrayFromJSON.length && arrayFromJSON[i].id == undefined ;i++){
							if (hashMapProv.Get("'"+arrayFromJSON[i].prov+"'") == undefined){
								hashMapProv.Set("'"+arrayFromJSON[i].prov+"'","");
								var point = new GLatLng(arrayFromJSON[i].lat,arrayFromJSON[i].lon);
					            var marker = createMarkerCitta(point);
					            gmarkerscittaTemp.push(marker);					            
		            		}
						}	
						mm.addMarkers(gmarkerscittaTemp,zoomProvMin,zoomProvMax);
						
						//Carico le universita sulla Mappa
						for (i=i;i<arrayFromJSON.length;i++){
							if (hashMap.Get("'"+arrayFromJSON[i].id+"'") == undefined){
									hashMap.Set("'"+arrayFromJSON[i].id+"'","");
									var point = new GLatLng(arrayFromJSON[i].lat,arrayFromJSON[i].lon);
									var markerUni = createMarkerUniversita(point,arrayFromJSON[i].i);
									gmarkersuniTemp.push(markerUni);		
							}
						}
						mm.addMarkers(gmarkersuniTemp,zoomCaseMin,zoomCaseMax);
						
					//Se devo aggiungere delle case, estratte mentre muovevo la mappa!
					}else{
						for (i=1;i<arrayFromJSON.length;i++){
							if (hashMap.Get("'"+arrayFromJSON[i].id+"'") == undefined){
								hashMap.Set("'"+arrayFromJSON[i].id+"'","");
								var point = new GLatLng(arrayFromJSON[i].lat,arrayFromJSON[i].lon);
								var markerCase;	
								if (arrayFromJSON[i].t == "P")							
							    	markerCase = createMarkerCase(point,arrayFromJSON[i].id);
							    else markerCase = createMarkerBeb(point,arrayFromJSON[i].id);
							    gmarkerscaseTemp.push(markerCase);	
							}
						}
						mm.addMarkers(gmarkerscaseTemp,zoomCaseMin,zoomCaseMax);
					}	
					if (gmarkerscaseTemp.length > 0 || 	gmarkerscittaTemp.length > 0){
						mm.refresh();
					}	
			}
	   		document.getElementById("loaderFinish").style.display = 'inline';
    		document.getElementById("loaderBegin").style.display = 'none';   
	}
 } 
}

//Fuziona di risposta per caricare sulla mappa tutte le universita della provincia
function stateChangedLoadUniversita(){
//Se la risposta va a buon fine
if (xmlHttp.readyState==4){ 	
	//Qua si puņ mettere un loader
	if (xmlHttp.status == 200){
			var gmarkersuniTemp = [];					
			var rispostaJson = xmlHttp.responseText
			var arrayFromJSON = rispostaJson.parseJSON();
			for (i=0;i<arrayFromJSON.length;i++){
					var point = new GLatLng(arrayFromJSON[i].lat,arrayFromJSON[i].lon);								
				    var markerUni = createMarkerUniversita(point,arrayFromJSON[i].id);
				    gmarkersuniTemp.push(markerUni);	
			}
			mm.addMarkers(gmarkersuniTemp,0,17);
			if (gmarkersuniTemp.length > 0){
					mm.refresh();
			}	
	}
 }
}

function mapMove(type){
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast(); 
    document.getElementById("loaderFinish").style.display = 'none';
    document.getElementById("loaderBegin").style.display = 'inline';    
		var url="ajaxServlet.jsp?zoom="+map.getZoom()+"&swLat="+southWest.lat()+"&swLong="+southWest.lng()+"&neLat="+northEast.lat()+"&neLong="+northEast.lng();
    	xmlHttp=GetXmlHttpObject()
    	if (type=='start')	{ 
    		url = url + "&start=true";
    		xmlHttp.onreadystatechange=stateChanged
    	}
    	if (type=='ricerche') { 
    		url = "ajaxServlet.jsp?ricerche=true"; 
    		xmlHttp.onreadystatechange=stateChangedSearchInSession
    	}
    	if (type=='move'){
    		xmlHttp.onreadystatechange=stateChanged
    	}
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)
}	


function stateChangedLoadArticoliBeb(id,color) { 
//Se la risposta va a buon fine
if (xmlHttp.readyState==4){ 	
	if (xmlHttp.status == 200){
			var rispostaJson = xmlHttp.responseText
			var arrayFromJSON = rispostaJson.parseJSON();
			var htmlArticoli = "<table cellpadding='0' cellspacing='0' width='100%'><tr bgcolor='"+color+"'><td colspan='2' bgcolor='"+color+"'><u>Annunci inseriti : </u></td></tr>";
			htmlArticoli = htmlArticoli+ "<tr bgcolor='"+color+"'>";
				if (arrayFromJSON.length == 0){
				
					htmlArticoli = htmlArticoli+"<td bgcolor='"+color+"'> Nessun annuncio inserito <br/></td>";
				}else{
						for (i=0;i<arrayFromJSON.length;i++){
							
							if (arrayFromJSON[i].f != "")
								htmlArticoli = htmlArticoli+ "<td width='180px' bgcolor='"+color+"'><img width='150px' height='112' src="+urlImage+arrayFromJSON[i].id+"/"+ arrayFromJSON[i].f + "></td>";
							htmlArticoli = htmlArticoli+ "<td valign='top' width='220px' bgcolor='"+color+"'>" + arrayFromJSON[i].tit + "<br/>";
							htmlArticoli = htmlArticoli+ "Prezzo : " + arrayFromJSON[i].pr + " &euro;<br/>";
							htmlArticoli = htmlArticoli+ "<a href='http://www.affittistudentiuniversitari.it/View?p="+arrayFromJSON[i].id + "'>Vedi</a></td>";
						}
				}
			htmlArticoli = htmlArticoli+ "</tr>";			
				

		
			htmlArticoli = htmlArticoli+ "</table>";
			var divId = "bebArticoli_" + id;
			document.getElementById(divId).innerHTML = htmlArticoli;
	}
 } 
}


function stateChangedSearch() { 
//Se la risposta va a buon fine
if (xmlHttp.readyState==4){ 	
	stateChangedCommonFunction(); 
 } 
}

function stateChangedSearchInSession() { 
//Se la risposta va a buon fine
if (xmlHttp.readyState==4){ 	
	stateChangedCommonFunction();
    mapMove('start');  
 } 
}

function stateChangedCommonFunction(){
	//Qua si puņ mettere un loader
	if (xmlHttp.status == 200){
			var rispostaJson = xmlHttp.responseText
			arrayJSON = rispostaJson.parseJSON();
			if (arrayJSON.length>0){
					//METODO PER STAMPARE A VIDEO I RISULTATI PAGINATI, PARAMETRO 0 IDENTIFICA LA PRIMA PAGINA
					if (arrayJSON.length>1)
						document.getElementById("txtTitle").innerHTML="<h3>"+ arrayJSON.length +" Risultati corrispondono ai criteri :-)</h3>";
					else document.getElementById("txtTitle").innerHTML="<h3>1 Risultato corrisponde ai criteri</h3>";
					viewResult(1);						
			}else{
				document.getElementById("txtTitle").innerHTML="<h3>Nessun Risultato :-( </h3>";
				document.getElementById("txtResult").innerHTML="Spiacente, nessuna inserzione corrisponde ai tuoi criteri di ricerca... speriamo che presto qualche annuncio possa essere di tuo gradimento.";
				document.getElementById("txtBottoni").innerHTML = "";	
			}
	}
	document.getElementById("loaderFinish").style.display = 'inline';
    document.getElementById("loaderBegin").style.display = 'none';
}



//Funzione per visualizzare l'annuncio sulla mappa nella pagina di dettaglio
function mapViewDetail(lat,long,tipo){
			var m = document.getElementById("map");	
			m.style.height = "400px";
		    m.style.width = "500px";
			map = new GMap2(m);
			GEvent.addListener(map,'dblclick',function(){
		  	   					 map.zoomIn();
			});			
		 	map.addControl(new GLargeMapControl());
		 	map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(lat,long),13);
			mm = new GMarkerManager(map, {borderPadding:1});
				var point = new GLatLng(lat,long);
	            var markerDetail = createMarkerCaseNoClick(point,tipo);
	             var gmarkesDetail = [];
	            gmarkesDetail.push(markerDetail);
			mm.addMarkers(gmarkesDetail,0,17);	       		 	
			mm.refresh();	
}



			
//Funzione per visualizzare l'ubicazione dell'agenzia
function mapViewAgenzia(lat,long){
			var m = document.getElementById("mapAgenzia");	
			m.style.height = "260px";
		    m.style.width = "260px";
			mapAgenzia = new GMap2(m);
			GEvent.addListener(mapAgenzia,'dblclick',function(){
		  	   					 mapAgenzia.zoomIn();
			});			
		 	mapAgenzia.addControl(new GSmallZoomControl());
		 	mapAgenzia.addControl(new GMapTypeControl());
			mapAgenzia.setCenter(new GLatLng(lat,long),13);
			mmAgenzia = new GMarkerManager(mapAgenzia, {borderPadding:1});
				var point = new GLatLng(lat,long);
	            var markerAgenzia = createMarkerAgenzia(point);
	            var gmarkesAgenzia = [];
	            gmarkesAgenzia.push(markerAgenzia);
			mmAgenzia.addMarkers(gmarkesAgenzia,0,17);	       		 	
			mmAgenzia.refresh();	
}

//Funzione per visualizzare i risultati della ricerca, paginati!!
function viewResult(pageRichiesta){
	var page = (pageRichiesta - 1);
	var elemento = page * elementiPagina;
	var ultimaPagina = Math.floor(arrayJSON.length/elementiPagina);
	if (arrayJSON.length/elementiPagina > ultimaPagina) ultimaPagina = ultimaPagina + 1;
	var testo = "", bopen = ""; bclose = "";
	testo = testo + "<img src='"+urlImageGlobal+"result_zoom.jpg' border='0'> : Visualizza l'immobile sulla mappa<br/>";
	testo = testo + "<img src='"+urlImageGlobal+"result_annuncio.jpg' border='0'> : Vai alla pagina dedicata all'annuncio<br/>";
	testo = testo + "<img src='"+urlImageGlobal+"result_photo.jpg' border='0'> : Annuncio con fotografie<br/>";
	testo = testo + "<hr heigth='1' width='290'/><br/>"	
	testo = testo + "<table height='150px' width='290' cellspacing='0'>";
	for (i=elemento;i<(elemento+elementiPagina)&&i<arrayJSON.length;i++){
		if (i % 2 == 0) bgcolor='#FFFFFF';
		else bgcolor = '#F0F0F0';
		if (arrayJSON[i].t == 'P'){
			 bopen = "";
			 bclose = "";
		}else{
			 bopen = "<b>"; 
			 bclose = "</b>";
		}
		testo = testo + "<tr>";
		testo = testo + "<td bgcolor="+bgcolor+" width='28px'><a href='javascript:viewHouse("+arrayJSON[i].lat+","+arrayJSON[i].lon+","+arrayJSON[i].id+")'><img src='"+urlImageGlobal+"result_zoom.jpg' border='0'></a></td>";
		testo = testo + "<td bgcolor="+bgcolor+" width='28px'><a href='javascript:view("+arrayJSON[i].id+")'><img src="+urlImageGlobal+"result_annuncio.jpg border='0'></a></td>";		
		testo = testo + "<td bgcolor="+bgcolor+" valign='middle'>"+bopen+"[" + arrayJSON[i].p + "] "+ arrayJSON[i].tit;		
		if ( arrayJSON[i].pr != null && arrayJSON[i].pr != undefined){
			testo = testo + "<br/>Prezzo : " + arrayJSON[i].pr + " &euro;"
		}	
		testo = testo + bclose + "</td><td bgcolor="+bgcolor+" width='28px'>";
		if ( arrayJSON[i].f == "Y"){
			testo = testo + "<img src='"+urlImageGlobal+"result_photo.jpg' border='0'>";
		}			
		testo = testo + "</td>";
		testo = testo + "</tr>";
	}
	testo = testo + "</table>";
	document.getElementById("txtResult").innerHTML=testo;
	
	var bottoni="";
	if (arrayJSON.length>elementiPagina){
		bottoni = bottoni + "<table width='270'><tr>";
		if (pageRichiesta>1){
			bottoni = bottoni + " <td width='30'><a href='javascript:viewResult(1)'><img src='"+urlImageGlobal+"result_inizio.jpg' border='0'></a></td> ";
			bottoni = bottoni + " <td width='30'><a href='javascript:viewResult("+ (pageRichiesta-1) +")'><img src='"+urlImageGlobal+"result_prima.jpg' border='0'></a></td> ";
			bottoni = bottoni + " <td width='150' align='center'>Pagina "+ pageRichiesta +" di "+ ultimaPagina +"</td> ";		
			if (pageRichiesta < ultimaPagina){
				bottoni = bottoni + " <td width='30'><a href='javascript:viewResult("+ (pageRichiesta+1) +")'><img src='"+urlImageGlobal+"result_successiva.jpg' border='0'></a></td> ";		
				bottoni = bottoni + " <td width='30'><a href='javascript:viewResult("+ ultimaPagina+ ")'><img src='"+urlImageGlobal+"result_ultima.jpg' border='0'></a></td> ";		
			}else{
				bottoni = bottoni + " <td width='30'></td> ";		
				bottoni = bottoni + " <td width='30'></td> ";				
			}		
		}else{
			bottoni = bottoni + " <td width='30'></td> ";
			bottoni = bottoni + " <td width='30'></td> ";
			bottoni = bottoni + " <td width='150' align='center'>Pagina 1 di "+ ultimaPagina +"</td> ";			
			bottoni = bottoni + " <td width='30'><a href='javascript:viewResult("+ (pageRichiesta+1) +")'><img src='"+urlImageGlobal+"result_successiva.jpg' border='0'></a></td> ";
			bottoni = bottoni + " <td width='30'><a href='javascript:viewResult("+ ultimaPagina +")'><img src='"+urlImageGlobal+"result_ultima.jpg' border='0'></a></td> ";				
		}
		bottoni = bottoni + "</tr></table>";
	}
		document.getElementById("txtBottoni").innerHTML = bottoni;	
}

function viewHouse(lat,longi,id){
	map.setCenter(new GLatLng(lat, longi),(zoomCaseMax-1));
	//var point = new GLatLng(lat,longi);
	//var markerCasa = createMarkerCase(point,id);
	//ajaxSearchDescrizione(markerCasa,id);
}

function view(id){
	location.href = urlView+"?p="+id;
}




//Funzione per ottenere l'oggetto XMLHTTP di Ajax in base ai diversi browser
// funzione che ricava l'oggetto in base al browser dell'utente
function GetXmlHttpObject(){
	var objXmlHttp = null;
	if(window.XMLHttpRequest){
		objXmlHttp = new XMLHttpRequest(); // code for Mozilla, etc.
	}
	else if(window.ActiveXObject){
		objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE7
	}
	return objXmlHttp;
}



/*
    json.js
    2007-10-05

    Public Domain

    This file adds these methods to JavaScript:

        array.toJSONString(whitelist)
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString(whitelist)
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

            The object and array methods can take an optional whitelist
            argument. A whitelist is an array of strings. If it is provided,
            keys in objects not found in the whitelist are excluded.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.

    This file will break programs with improper for..in loops. See
    http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load untrusted third party
    code into your pages.
*/

/*jslint evil: true */

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'object':

// Serialize a JavaScript object value. Treat objects thats lack the
// toJSONString method as null. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                if (v && typeof v.toJSONString === 'function') {
                    a.push(v.toJSONString(w));
                } else {
                    a.push('null');
                }
                break;

            case 'string':
            case 'number':
            case 'boolean':
                a.push(v.toJSONString());
                break;
            default:
                a.push('null');
            }
        }

// Join all of the member texts together and wrap them in brackets.

        return '[' + a.join(',') + ']';
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {

// Eventually, this method will be based on the date.toISOString method.

        function f(n) {

// Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getUTCFullYear()   + '-' +
                   f(this.getUTCMonth() + 1) + '-' +
                   f(this.getUTCDate())      + 'T' +
                   f(this.getUTCHours())     + ':' +
                   f(this.getUTCMinutes())   + ':' +
                   f(this.getUTCSeconds())   + 'Z"';
    };


    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : 'null';
    };


    Object.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            k,          // The current key.
            i,          // The loop counter.
            v;          // The current value.

// If a whitelist (array of keys) is provided, use it assemble the components
// of the object.

        if (w) {
            for (i = 0; i < w.length; i += 1) {
                k = w[i];
                if (typeof k === 'string') {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString(w));
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        } else {

// Iterate through all of the keys in the object, ignoring the proto chain
// and keys that are not strings.

            for (k in this) {
                if (typeof k === 'string' &&
                        Object.prototype.hasOwnProperty.apply(this, [k])) {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString());
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        }

// Join all of the member texts together and wrap them in braces.

        return '{' + a.join(',') + '}';
    };


    (function (s) {

// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.

// m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


        s.parseJSON = function (filter) {
            var j;

            function walk(k, v) {
                var i, n;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                            n = walk(i, v[i]);
                            if (n !== undefined) {
                                v[i] = n;
                            }
                        }
                    }
                }
                return filter(k, v);
            }


// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

// We split the first stage into 3 regexp operations in order to work around
// crippling deficiencies in Safari's regexp engine. First we replace all
// backslash pairs with '@' (a non-JSON character). Second we delete all of
// the string literals. Third, we look to see if only JSON characters
// remain. If so, then the text is safe for eval.

            if (/^[,:{}\[\]0-9.\-+eE \n\r\t]*$/.test(this.
                    replace(/\\./g, '@').
                    replace(/"[^"\\\n\r]*"|true|false|null/g, ''))) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + this + ')');

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

                return typeof filter === 'function' ? walk('', j) : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('parseJSON');
        };


        s.toJSONString = function () {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) +
                                               (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}


