/*
 * Il file definisce gli oggetti principali utilizzati
 * nel Portale www.sistemauni.it per l'interfacciamento
 * con Google Maps e la costruzione delle mappe sulla
 * base dei dati caricati nella pagina HTML contenitore;
 * contiene inoltre alcune funzioni utilizzate in altri
 * ambiti.
 * La libreria potrebbe essere fortemente dipendente,
 * in alcune sue parti, con Typo3 (v.4.2).
 * 
 * @author Sivieri Alessandro
*/

/**
 * Questa funzione mostra due form differenti, costruite con
 * DB Integration (o con metodologia alternativa), che vengono
 * visualizzate alternativamente, a seconda del momento in cui
 * la funzione stessa viene invocata.
 */
function advSearch()
{
	var briefNode=document.getElementById("dbintegration");
	var longNode=document.getElementById("dbintegration2");
	if(longNode.style.display=="none")
	{
		longNode.style.display="block";
		briefNode.style.display="none";
	}
	else
	{
		longNode.style.display="none";
		briefNode.style.display="block";
	}
}

function setCoords(place)
{
	var lat=document.getElementById("lat");
	var lng=document.getElementById("lng");
	if(GBrowserIsCompatible())
	{
		var geocoder = new GClientGeocoder();
		if(geocoder)
		{
			geocoder.getLatLng(place+", Milano, Italy", function(point)
			{
				if(point)
				{
					lat.value=point.x;
					lng.value=point.y;
				}
			});
		}
	}
}

/**
 * Funzione necessaria per visualizzare alcuni popup della mappa
 * del Centrorientamento della Provincia di Milano, ospitata sul
 * nostro Portale: a seconda di quale elemento viene invocato,
 * varia leggermente la dimensione del popup.
 * Ereditato dai files passatici dall'ufficio Sistemi Informativi
 * della Provincia.
 * 
 * @param str la stringa contenente il nome del file HTML da
 * mostrare nel popup
 */
function DisplayAmbito(str)
{
	var prefix="http://www.sistemauni.it/fileadmin/megliomilano/provincia/";
	if (str=='Ambito1.htm')
		window.open(prefix + str,"","HEIGHT=500,WIDTH=500,status=no");
	else
		 window.open(prefix + str,"","HEIGHT=400,WIDTH=500,status=no");
}

/**
 * Variabile usata per memorizzare il marcatore corrente.
 */
var cur=null;

/**
 * Classe di definizione del marker; i parametri specificati nel costruttore
 * sono obbligatori, mentre è opzionale la definizione di una funzione 
 * specifica per la distinzione dell'icona sulla base di un campo specifico
 * di ciascun record, così come la creazione di un link o di un testo specifico.
 * 
 * @param {Object} lat latitudine del punto
 * @param {Object} lng longitudine del punto
 * @param {Object} type tipo di icona da associare; viene usato come nome del file png
 */
function Marker(lat, lng, type, size)
{
	this.lat=lat;
	this.lng=lng;
	this.type=type;
	this.size=size;
	this.text=null;
	this.addr=null;
	this.type_fun=null;
	this.size_fun=null;
	this.setSizeFunction=function(size_fun)
	{
		this.size_fun=size_fun;
	}
	this.setTypeFunction=function(type_fun)
	{
		this.type_fun=type_fun;
	}
	this.setText=function(text)
	{
		this.text=text;
	}
	this.setLink=function(link)
	{
		this.link=link;
	}
	this.getIcon=function()
	{
		var icon = new GIcon();
		if (this.size_fun != null)
		{
			dim=this.size_fun(this.size).split(":");
			if (dim.length == 2)
			{
				icon.iconSize = new GSize(parseInt(dim[0]), parseInt(dim[1]));
			}
		}
		else
		{
			icon.iconSize = new GSize(30, 30);
		}
		icon.iconAnchor = new GPoint(9, 34);
		icon.infoWindowAnchor = new GPoint(9, 2);
		icon.infoShadowAnchor = new GPoint(18, 25);
		if (this.type_fun != null)
		{
			icon.image = "http://www.sistemauni.it/fileadmin/megliomilano/markers/" + this.type_fun(this.type) + ".png";
		}
		else
		{
			icon.image = "http://www.sistemauni.it/fileadmin/megliomilano/markers/" + this.type + ".png";
		}
		return icon;
	}
	this.getMarker=function()
	{
		var temp=this.text; // necessario perchè dalle funzioni anonime non possiamo leggere this!
		var temp2=this.link; // necessario perchè dalle funzioni anonime non possiamo leggere this!
		var iconObj = this.getIcon();
		var markerOptions={ icon:iconObj };
		var point = new GLatLng(parseFloat(this.lat), parseFloat(this.lng));
		var marker = new GMarker(point, markerOptions);
		if (this.text != null)
		{
			GEvent.addListener(marker, "click", function()
			{
				if(cur!=null)
			    {
					cur.closeInfoWindow();
			    }
				marker.openInfoWindowHtml(temp);
				cur=marker;
			});
		}
		return marker;
	}
}

/**
 * Classe di definizione delle mappe; vengono personalizzati l'id del div
 * in cui creare la mappa, la presenza o meno dei controlli e lo zoom della
 * mappa. Altri parametri sono opzionali.
 * La mappa è sempre centrata su Milano, Italy, salvo indicazione contraria.
 * 
 * @param {Object} id l'id dell'elemento in cui creare la mappa
 * @param {Object} controls se settato a true, i controlli appaiono
 * @param {Object} zoom il livello di zoom cui mettere la mappa
 */
function SMap(id, controls, zoom)
{
	this.id=id;
	this.controls=controls;
	this.zoom=zoom;
	this.map=null;
	this.markers=new Array();
	this.visibleMarkers=new Array();
	this.link_fun=null;
	this.text_fun=null;
	this.type_fun=null;
	this.size_fun=null;
	this.separator=":";
	this.center=null;
	this.setCenter=function(x, y)
	{
		this.center=new GLatLng(x, y);
	}
	this.setSeparator=function(separator)
	{
		this.separator=separator;
	}
	this.setSizeFunction=function(size_fun)
	{
		this.size_fun=size_fun;
	}
	this.setLinkFunction=function(link_fun)
	{
		this.link_fun=link_fun;
	}
	this.setTextFunction=function(text_fun)
	{
		this.text_fun=text_fun;
	}
	this.setTypeFunction=function(type_fun)
	{
		this.type_fun=type_fun;
	}
	this.prepareMap=function()
	{
		this.map = new GMap2(document.getElementById(this.id));
		if (this.map)
		{
			if(this.center==null)
			{
				// Milano, Italy: 45.463671, 9.188126
				this.map.setCenter(new GLatLng(45.463671, 9.188126), this.zoom);
			}
			else
			{
				this.map.setCenter(this.center, this.zoom);
			}
			if (this.controls==true)
			{
				this.map.addControl(new GLargeMapControl());
				this.map.enableScrollWheelZoom();
			}
			else
			{
				// se avessimo lo zoom ma non avessimo il dragging, sarebbe perfettamente inutile dato che potremmo solo zoomare in verticale stretto
				this.map.disableDragging();
			}
			return true;
		}
		else
		{
			return false;
		}
	}
	this.loadMarkers=function(fields, list_id, entry_id, lat_index, lng_index, type_index, size_index)
	{
		var e=document.getElementById(list_id);
		for(var i=0; i<e.childNodes.length; ++i)
		{
			if(e.childNodes[i].nodeName=="P" && e.childNodes[i].id.substr(0, entry_id.length)==entry_id)
			{
				result=e.childNodes[i].childNodes[0].nodeValue.split(this.separator);
				if(result.length==fields)
				{
					var m=new Marker(result[lat_index], result[lng_index], result[type_index], result[size_index]);
					if(this.size_fun!=null)
					{
						m.setSizeFunction(this.size_fun);
					}
					if(this.link_fun!=null)
					{
						m.setLink(this.link_fun(result));
					}
					if(this.text_fun!=null)
					{
						m.setText(this.text_fun(result));
					}
					if(this.type_fun!=null)
					{
						m.setTypeFunction(this.type_fun);
					}
					this.markers.push(m.getMarker());
				}
			}
		}
	}
	this.run=function(fields, list_id, entry_id, lat_index, lng_index, type_index, size_index)
	{
		if (GBrowserIsCompatible() && this.prepareMap())
		{
			this.loadMarkers(fields, list_id, entry_id, lat_index, lng_index, type_index, size_index);
			for(var i=0; i<this.markers.length; ++i)
			{
				this.map.addOverlay(this.markers[i]);
			}
		}
		else
		{
			alert("Your browser is not supported by Google Maps.");
		}
	}
}

function getUniversity(i)
{
	var result;
	
	switch(i)
		{
			case 1:
				result="brera";
				break;
			case 2:
				result="bicocca";
				break;
			case 3:
				result="cons";
				break;
			case 4:
				result="polimi";
				break;
			case 5:
				result="statale";
				break;
			case 6:
				result="bocconi";
				break;
			case 7:
				result="catt";
				break;
			case 8:
				result="liuc";
				break;
			case 9:
				result="hsr";
				break;
			case 10:
				result="iulm";
				break;
			case 11:
				result="naba";
				break;
			default:
				alert(type+"!");
				break;
		}
		return result;
}

/**
 * Creazione della mappa delle sedi universitarie cittadine (centrali e distaccate)
 * id:nome:indirizzo:web:tipo:lat:lng
 */
function centralPlacesMap()
{
	var smap=new SMap("map", true, 12);
	smap.setSeparator("$");
	smap.setTypeFunction(function(type)
	{
		return getUniversity(parseInt(type))+".sede";
		
	});
	smap.setSizeFunction(function(type)
	{
		if (type == "centrale")
		{
			return "30:30";
		}
		else
		{
			return "20:20";
		}
	});
	smap.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[1]+"</strong><br />"+fields[2]+"</p><p><a href=\""+fields[3]+"\" title=\"\">Vai al sito</a></p>";
		return text;
	});
	smap.run(7, "list", "map", 5, 6, 0, 4);
	var smap2=new SMap("map2", true, 13);
	smap2.setSeparator("$");
	smap2.setTypeFunction(function(type)
	{
		return getUniversity(parseInt(type))+".sede";
		
	});
	smap2.setSizeFunction(function(type)
	{
		if (type == "centrale")
		{
			return "30:30";
		}
		else
		{
			return "20:20";
		}
	});
	smap2.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[1]+"</strong><br />"+fields[2]+"</p><p><a href=\""+fields[3]+"\" title=\"\">Vai al sito</a></p>";
		return text;
	});
	// Castellanza, Varese, Italy: 45.633217, 8.888477
	smap2.setCenter(45.633217, 8.888477);
	smap2.run(7, "list", "map", 5, 6, 0, 4);
}

/**
 * Creazione della mappa dei poli universitari al di fuori di Milano ed hinterland:
 * id:nome:indirizzo:tipo:lat:lng
 */
function otherPlacesMap()
{
	var smap=new SMap("map", true, 7);
	smap.setSeparator("$");
	smap.setTypeFunction(function(type)
	{
		return getUniversity(parseInt(type))+".polo";
		
	});
	smap.setSizeFunction(function(type)
	{
		return "30:30";
	});
	smap.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[1]+"</strong><br />"+fields[2]+"</p><p><a href=\""+fields[3]+"\" title=\"\">Vai al sito</a></p>";
		return text;
	});
	smap.run(7, "list", "map", 5, 6, 0, 4);
}

/**
 * Creazione della mappa delle biblioteche comunali
 * id:nome:indirizzo:lat:lng
 */
function localBiblio()
{
	var smap=new SMap("map", true, 12);
	smap.setTypeFunction(function(type)
	{
		return "liuc.biblio";
	});
	/* map.setLinkFunction(function(fields)
	{
		return "studiare/biblioteche/ricerca-biblioteche-comunali/dettagli-risultato/?tx_wfqbe_pi1[id]="+fields[0];
	}); */
	smap.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[1]+"</strong><br />"+fields[2]+"</p><p><a class=\"scheda\" href=\"/studiare/biblioteche/dettagli-risultato/?tx_wfqbe_pi1[id]="+fields[0]+"\" title=\"\">Vai alla scheda</a></p>";
		return text;
	});
	smap.setSizeFunction(function(type)
	{
		return "30:30";
	});
	smap.run(5, "list", "map", 3, 4, 0, 0);
}

/**
 * Creazione della mappa delle biblioteche di facoltà
 * id:universita:nome:indirizzo:lat:lng
 */
function loadUniBiblio()
{
	var smap=new SMap("map", true, 12);
	smap.setTypeFunction(function(type)
	{
		return getUniversity(parseInt(type))+".biblio";
	});
	smap.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[2]+"</strong><br />"+fields[3]+"</p><p><a class=\"scheda\" href=\"/studiare/biblioteche/dettagli-risultato/?tx_wfqbe_pi1[id]="+fields[0]+"\" title=\"\">Vai alla scheda</a></p>";
		return text;
	});
	smap.setSizeFunction(function(type)
	{
		return "30:30";
	});
	smap.run(6, "list", "map", 4, 5, 1, 0);
}

/**
 * Creazione della mappa delle residenze
 * id:nome:indirizzo:lat:lng
 */
function loadHouses()
{
	var smap=new SMap("map", true, 12);
	smap.setTypeFunction(function(type)
	{
		return "liuc.residenza";
	});
	smap.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[1]+"</strong><br />"+fields[2]+"</p><p><a class=\"scheda\" href=\"/vivere/abitare/residenze-studentesche/dettagli-risultato-residenze-non-convenzionate/?tx_wfqbe_pi1[id]="+fields[0]+"\" title=\"\">Vai alla scheda</a></p>";
		return text;
	});
	smap.setSizeFunction(function(type)
	{
		return "30:30";
	});
	smap.run(5, "list", "map", 3, 4, 0, 0);
}

/**
 * Creazione della mappa delle mense
 * id:universita:nome:indirizzo:lat:lng
 */
function loadCanteensFull()
{
	var smap=new SMap("map", true, 12);
	smap.setTypeFunction(function(type)
	{
		return getUniversity(parseInt(type))+".mensa";
	});
	smap.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[2]+"</strong><br />"+fields[3]+"</p><p><a class=\"scheda\" href=\"/vivere/mangiare/dettagli-mensa/?tx_wfqbe_pi1[id]="+fields[0]+"\" title=\"\">Vai alla scheda</a></p>";
		return text;
	});
	smap.setSizeFunction(function(type)
	{
		return "30:30";
	});
	smap.run(6, "list", "map", 4, 5, 1, 0);
}

/**
 * Creazione della mappa delle residenze di uno specifico Ateneo
 * id:universita:nome:indirizzo:lat:lng
 */
function loadUniversityHouses()
{
	var smap=new SMap("map", true, 12);
	smap.setTypeFunction(function(type)
	{
		return getUniversity(parseInt(type))+".residenza";
	});
	smap.setTextFunction(function(fields)
	{
		var text="<p><strong>"+fields[2]+"</strong><br />"+fields[3]+"</p><p><a class=\"scheda\" href=\"/vivere/abitare/residenze-studentesche/dettagli-risultato-residenze-convenzionate/?tx_wfqbe_pi1[id]="+fields[0]+"\" title=\"\">Vai alla scheda</a></p>";
		return text;
	});
	smap.setSizeFunction(function(type)
	{
		return "30:30";
	});
	smap.run(6, "list", "map", 4, 5, 1, 0);
}
