$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

var prevent_cerca = false;

function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.setMapType(G_HYBRID_MAP);
		map.setUIToDefault();
		map.setCenter(new GLatLng(42.5,12.041016), 6);
		GEvent.addListener(map, "moveend", function() {
			if(map.getZoom() > 10 && !prevent_cerca) {
				cerca_autoscuole();
			}
		});
	} else alert('Browser non compatibile');
}

function cerca_autoscuole() {
	caricamento('start');
	$("#avvisi").html(' ');
	var bounds = map.getBounds();
	sw = bounds.getSouthWest().toUrlValue();
	ne = bounds.getNorthEast().toUrlValue();
	$.postJSON("ajax/cerca_geo.php", { sw: sw, ne: ne }, function(data) {
		if(data.result == 'ok') {
			html = '<span class="leg"><b>Autoscuole:</b></span><ul class="autoul">';
			for(i in data.autoscuole) {
				addmarker(data.autoscuole[i]);
				html += '<li class="autoscuola">';
				html += '<a class="autonome" href="/autoscuole/dettaglio.php?id='+data.autoscuole[i].id+'">'+data.autoscuole[i].nome+'</a><br>In '+data.autoscuole[i].indirizzo+'<br>'+data.autoscuole[i].comune+'<br>Tel: '+data.autoscuole[i].telefono;
			}
			html += '</ul>';
			$("#lista_autoscuole").empty();
			$("#lista_autoscuole").append(html);
			caricamento('stop');
		} else {
			alert('Errore nella ricerca, si prega di riprovare');
		}
	});
}

function addmarker(data) {
	var marker = new GMarker(new GLatLng(data.lat,data.lon));
	var html = "<div style='width:200px; padding: 0px 10px 10px 0px;'>";
	html = html + "<h2 style='font-size: 16px;'>" + data.nome + "<\/h2>";
	html = html + "<p>" + data.indirizzo + "<br/>" + data.cap + " - " + data.comune + "<\/span><\/p>";
	html = html + "<p style='margin: 10px 0px 0px 0px;'><a href='/autoscuole/dettaglio.php?id=" + data.id + "' title='vai alla Scheda'>Dettagli<\/a><\/p>";
	html = html + "<\/div>";
	GEvent.addListener(marker, "click", function() {
		prevent_cerca = true;
		marker.openInfoWindowHtml(html);
		prevent_cerca = false;
	});
	map.addOverlay(marker);
}

function caricamento(cosa) {
	if(cosa == 'start')	$("#strumenti").html('<p style="color:red;">Sto caricando le autoscuole...</p>');
	if(cosa == 'stop') $("#strumenti").html(' ');
}

window.onload = initialize;
