/* VARIABILI */

var myMap = null;
var myDirections;
var startPoint = null;
var myGeocoder = null;
var addressMarker;
var zoom = 14;

// camping icon
var myIconC = new GIcon();
myIconC.image = '../img/icon_c.png';
myIconC.shadow = '../img/icon_shadow.png';
myIconC.iconSize = new GSize(22, 26);
myIconC.shadowSize = new GSize(36, 26);
myIconC.iconAnchor = new GPoint(1, 24);
myIconC.infoWindowAnchor = new GPoint(22, 1);
// area attrezzata icon
var myIconA = new GIcon();
myIconA.image = '../img/icon_a.png';
myIconA.shadow = '../img/icon_shadow.png';
myIconA.iconSize = new GSize(22, 26);
myIconA.shadowSize = new GSize(36, 26);
myIconA.iconAnchor = new GPoint(1, 24);
myIconA.infoWindowAnchor = new GPoint(22, 1);
// parcheggio pagamento icon
var myIconP = new GIcon();
myIconP.image = '../img/icon_p.png';
myIconP.shadow = '../img/icon_shadow.png';
myIconP.iconSize = new GSize(22, 26);
myIconP.shadowSize = new GSize(36, 26);
myIconP.iconAnchor = new GPoint(1, 24);
myIconP.infoWindowAnchor = new GPoint(22, 1);
// parcheggio gratuito icon
var myIconG = new GIcon();
myIconG.image = '../img/icon_g.png';
myIconG.shadow = '../img/icon_shadow.png';
myIconG.iconSize = new GSize(22, 26);
myIconG.shadowSize = new GSize(36, 26);
myIconG.iconAnchor = new GPoint(1, 24);
myIconG.infoWindowAnchor = new GPoint(22, 1);
// altro icon
var myIcon = new GIcon();
myIcon.image = '../img/icon_map.png';
myIcon.shadow = '../img/icon_shadow.png';
myIcon.iconSize = new GSize(22, 26);
myIcon.shadowSize = new GSize(36, 26);
myIcon.iconAnchor = new GPoint(1, 24);
myIcon.infoWindowAnchor = new GPoint(22, 1);


// -- INIZIALIZZA
// --
function initialize() {
	if (GBrowserIsCompatible()) {
		myMap = new GMap2(document.getElementById("map_canvas"));
		myMap.addControl(new GSmallMapControl());
		myMap.addControl(new GMapTypeControl());
		myMap.setCenter(new GLatLng(46.227638, 2.213749), 6);
		myDirections = new GDirections(myMap, document.getElementById("directions"));
		myGeocoder = new GClientGeocoder();
		//var myBounds = new GLatLngBounds();	// POTREBBE NON SERVIRE...
	}
}

function createMarker(point, name, where, notes, tipo, last) {
	var tipologia = "";
	if (tipo=="1") { var marker = new GMarker(point,myIconC); tipologia = ""; }
	if (tipo=="2") { var marker = new GMarker(point,myIconA); tipologia = "Area camper attrezzata"; }
	if (tipo=="3") { var marker = new GMarker(point,myIconP); tipologia = "Parcheggio a pagamento"; }
	if (tipo=="4") { var marker = new GMarker(point,myIconG); tipologia = "Parcheggio gratuito"; }
	if (tipo=="5") { var marker = new GMarker(point,myIcon); }
	var html = '<b>' + name + '</b>';
	if (where!="") { html += '<br/>' + where + ''; }
	if (tipologia!="") { html += '<br/><span class="note">' + tipologia + '</span>'; }
	html += '<br/>';
	if (notes!="") { html += '<br/><span class="note">Note: <i>' + notes + '</i></span>'; }
	if (last!="") { html += '<br/><span class="note">Ultima visita: <i>' + last + '</i></span>'; }
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}   

// -- AJAX
/*function MyDownloadUrl(method, url, func) {
	var httpObj;
	var browser = navigator.appName;
	if(browser.indexOf("Microsoft") > -1)
		httpObj = new ActiveXObject("Microsoft.XMLHTTP");
	else
		httpObj = new XMLHttpRequest();

	httpObj.open(method, url, true);
	httpObj.onreadystatechange = function() {
		if(httpObj.readyState == 4){
			if (httpObj.status == 200) {
				var contenttype = httpObj.getResponseHeader('Content-Type');
				if (contenttype.indexOf('xml')>-1) {
					func(httpObj.responseXML);
				} else {
					func(httpObj.responseText);
				}
			} else {
				func('Error: '+httpObj.status);
			}
		}
	};
	httpObj.send(null);
}*/


// -- CERCA LOCATION
// --
function searchLocations(qs) {
	var address = document.getElementById('location').value;
	myGeocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			alert(address + ' not found');
		} else {
			startPoint = latlng;
			searchLocationsNear(latlng,qs,address);
		}
	});
}


// -- CERCA LOCATION VICINE
// --
function searchLocationsNear(center,qs,address) {
//	var radius = 45; // selezione del raggio di ricerca
	var radius = document.getElementById('raggio').value;

	//SCRIVE I DIV DI MAPPA E SIDEBAR
	var searchUrl = 'getResultsMarkers.asp?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&qs=' + qs + '&address=' + address;
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		markers = xml.documentElement.getElementsByTagName('marker');
		myMap.clearOverlays();
		var sidebar = document.getElementById('sidebar');
		sidebar.innerHTML = '';
		if (markers.length == 0) {
			sidebar.innerHTML = 'Nessun risultato.';
			myMap.setCenter(new GLatLng(46.227638, 2.213749), 5); // Francia
			return;
		} else {																		// ELIMINATO RAMO ELSE: niente paginazione
			sidebar.innerHTML = markers.length+' risultati:<br/><br/>';
/*			//var new_pages = document.getElementById('new_pages');		QUESTA FORSE NON SERVE!!!!
			
			//SCRIVE IL DIV DI PAGINAZIONE
			var paginazioneUrl = 'paginazioneG_new.asp?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&qs=' + qs + '&address=' + address;
			MyDownloadUrl('get', paginazioneUrl, function(purehtml) {
				document.getElementById('new_pages').innerHTML = purehtml;
			});
		
*/		}
		var myBounds = new GLatLngBounds();
		var findGeo = 0;
		for (var i = 0; i < markers.length; i++) {
			var sId  = markers[i].getAttribute('sId');
			var nome = markers[i].getAttribute('nome');
			var dove = markers[i].getAttribute('dove');
			var note = markers[i].getAttribute('note');
			var tipo = markers[i].getAttribute('tipo');
			var last = markers[i].getAttribute('last');
//			if (markers[i].getAttribute('lat')!="") {
			findGeo = 1;
			var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
			var distance = parseFloat(markers[i].getAttribute('distance'));
			var marker = createMarker(point, nome, dove, note, tipo, last);
			myMap.addOverlay(marker);
			var sidebarEntry = createSidebarEntry(marker, nome, dove, note, tipo, distance, i, sId);
			sidebar.appendChild(sidebarEntry);
			myBounds.extend(point);
/*			} else {																		// ELIMINATO RAMO ELSE: tutti sono geolocalizzati
				var sidebarEntry = createSidebarEntryNoMap(nome, recapito, email, i, sId);
				sidebar.appendChild(sidebarEntry);
			}
*/		}
		if (findGeo) {
			myMap.setCenter(myBounds.getCenter(), myMap.getBoundsZoomLevel(myBounds));
		} else {
			var point = new GLatLng(46.227638, 2.213749); // Francia
			myBounds.extend(point);
			myMap.setCenter(myBounds.getCenter(), 6);
		}
	});
		
}


function createSidebarEntry(marker, name, where, notes, tipo, distance, i, sId) {
	var div = document.createElement('div');
	var html = '<a><b>' + name + '</b></a> (' + distance.toFixed(1) + ' km)<br />';
	var tipologia = "";
	if (tipo=="1") tipologia = "Campeggio";
	if (tipo=="2") tipologia = "Area camper attrezzata";
	if (tipo=="3") tipologia = "Parcheggio a pagamento";
	if (tipo=="4") tipologia = "Parcheggio gratuito";
	if (tipologia!="") { html += '<span class="note">' + tipologia + '</span><br/>'; }
	html +='<span class="note"><a href="javascript:toHere('+i+')">Mostra percorso</a></span><br />'
	div.innerHTML = html;
	div.style.cursor = 'pointer';
	div.style.marginBottom = '5px'; 
	GEvent.addDomListener(div, 'click', function() {
		GEvent.trigger(marker, 'click');
	});
	GEvent.addDomListener(div, 'mouseover', function() {
		div.style.backgroundColor = '#33475B';
	});
	GEvent.addDomListener(div, 'mouseout', function() {
		div.style.backgroundColor = '#1C3248';
	});
	return div;
}

function setDirections(fromAddress, toAddress) {
	myDirections.load("from: " + fromAddress + " to: " + toAddress, { "locale": "it" });
}

function handleErrors(){
	if (myDirections.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("Indirizzo non trovato.\n Error code: " + myDirections.getStatus().code);
	else if (myDirections.getStatus().code == G_GEO_SERVER_ERROR)
		alert("Indirizzo errato.\n Error code: " + myDirections.getStatus().code);
	else if (myDirections.getStatus().code == G_GEO_MISSING_QUERY)
		alert("Non avete inserito l\'indirizzo di partenza.\n Error code: " + myDirections.getStatus().code);
	else if (myDirections.getStatus().code == G_GEO_BAD_KEY)
		alert("Errore di comunicazione con il server di mapping. \n Error code: " + myDirections.getStatus().code);
	else if (myDirections.getStatus().code == G_GEO_BAD_REQUEST)
		alert("L\'indirizzo non e\' nel formato corretto'.\n Error code: " + myDirections.getStatus().code);
	else alert("Errore di ricerca.");
}

function toHere(indice) {
	var newpoint = markers[indice].getAttribute('lat') + ',' + markers[indice].getAttribute('lng');
	setDirections(startPoint.toUrlValue(),newpoint);
}


