/**
 * @author averlicchi
 */

// Funzione JS che restituisce il punto GLatLng in base al parametro passato
function myGetPoint(aElement) {
	//alert(aElement);
	return new GLatLng(aElement.lat, aElement.lng);
}

// Funzione per comporre l'html del fumetto
function myHtmlBaloon (e) {
	return '<div class="myBaloon"><h3>'+e.titolo+' '+e.nome+' '+e.cognome+'<br />' + e.ragsoc + '</h3><br/>' +
		'<p>'+e.indirizzo+'<br/>'+e.cap+' - '+e.citta+' ('+e.provincia+')</p><br />' +
		'<p>Tel: '+e.tel+'</p></div>';
}

// Funzione che ritorna le options del marker, cioè l'icona
function myGetMarkerOptions(e) {
	if (e.utenti_cat_id == 5) 
		return {icon:myGetDoctorIcon()};
	else if (e.utenti_cat_id == 4) 
		return {icon:myGetPharmacyIcon()};
}

// Funzione JS che aggiunge un overlay marker alla mappa gMap in base al parametro passato e lo restituisce
function myAddMarker(aElement) {
	var point = myGetPoint(aElement);
	markerOptions = myGetMarkerOptions(aElement);
	var marker = new GMarker(point, markerOptions);
	marker.myHtml = myHtmlBaloon(aElement);
	marker.bindInfoWindowHtml(marker.myHtml, myInfoWindowOptions);
	gMap.addOverlay(marker);
	return marker;
}

// Funzione JS che aggiunge TUTTI gli overlay marker alla mappa in base al RS passato e centra/zoomma la mappa
function myAddAllMarkers(aArgElements) {
	gMarkers = new Array();
	var iLen = aArgElements.length;
	var aIthElement;
	for (iInd=0; iInd<iLen; iInd++) {
		aIthElement = aArgElements[iInd];
		gMarkers[aIthElement.id] = myAddMarker(aArgElements[iInd]);
	}
	if (gMarkers.length > 0) 
		myAutoZoom(aArgElements);
	else {
		myZoomHome();
	}
}

function myAutoZoom(aArgElements) {
	var bounds = new GLatLngBounds();
	var iLen = aArgElements.length;
	var aIthElement;
	for (iInd=0; iInd<iLen; iInd++) {
		aIthElement = aArgElements[iInd];
		bounds.extend (myGetPoint(aIthElement));
	}
	gMap.setCenter(bounds.getCenter(), gMap.getBoundsZoomLevel(bounds));
}

// Funzione JS che inizializza la mappa e la centra in Italia
function initialize() {
  if (GBrowserIsCompatible()) {
    gMap = new GMap2(document.getElementById("map_canvas"));
    gMap.addControl(new GSmallMapControl());
	gMap.addControl(new GMapTypeControl());
	myZoomHome();
  } else {
  	alert('Attenzione: il vostro browser non &egrave; compatibile con il sistema di mappe di Google utilizzato in questo sito. Aggiornare il browser ad una versione compatibile se si desidera visualizzare Guna.');
  }
}

function aGetElementByDbId(iArgId, aArgElements) {
	iLen = aArgElements.length;
	for (iInd=0; iInd<iLen; iInd++) {
		//alert('iind='+iInd+' ilen='+iLen+' aArgElements[iInd][0]=' + aArgElements[iInd][0] + ' iArgId='+iArgId);
		if (aArgElements[iInd][0] == iArgId) return aArgElements[iInd];
	}
	return null;
}

// Funzione JS che apre la infowindow del marker corrispondente all'ID (DB) passato
function myOpenInfo (iId) {
	var myMarker = gMarkers[iId];
	var myElement = aGetElementByDbId(iId, aSegnalazioni);
	gMap.openInfoWindowHtml(myGetPoint(myElement), myMarker.myHtml, myInfoWindowOptions);
	return false;
}

function getDirections(iId) {
	var argAddressFrom = prompt('Indirizzo di partenza', '[Citta\', Indirizzo, CAP]');
	if (argAddressFrom != null) {
		var aSegnalazione = aGetElementByDbId(iId, aSegnalazioni);
		var argAddressTo = aSegnalazione[4] + ' @' + aSegnalazione[1] + ', ' + aSegnalazione[2];
		window.open('http://maps.google.it/maps?f=d&hl=it&saddr=' + argAddressFrom + '&daddr=' + argAddressTo);
	}
}

function myZoomTo(iId) {
	var aSegnalazione = aGetElementByDbId(iId, aSegnalazioni);
	gMap.setCenter(new GLatLng(aSegnalazione[1], aSegnalazione[2]), 17);
}

function myShowZoomLink(iId, sDirection) {
	var eHide;
	var eShow;
	if (sDirection == 'out') {
		eHide = document.getElementById('in'+iId);
		eShow = document.getElementById('out'+iId);
	} else {
		eHide = document.getElementById('out'+iId);
		eShow = document.getElementById('in'+iId);
	}
	eShow.style.display = 'inline';
	eHide.style.display = 'none';
}

/* Funzione che appare */
function myNoSelectedCat() {
	var myWindow = gMap.openInfoWindowHtml(gMap.getCenter(), "<h3>Benvenuto nella pagina della mappa!</h3>"+
		"<p><b>Stai visualizzando le ultime segnalazioni inserite nella mappa</b> indipendentemente dalla categoria.</p>" +
		"<p>- Per inserire una segnalazione, fai click sul pulsante 'Invia segnalazione' nel riquadro a lato.</p>" +
		"<p>- Per visualizzare le segnalazioni esistenti per categoria, seleziona una categoria dal men&ugrave; a lato.</p>" +
		"<p>Buona navigazione.</p>", myInfoWindowOptions);
}

function myZoomHome() {
	gMap.setCenter(new GLatLng(41.277806, 13.64502), 6);
}

function myGetDoctorIcon() {
	var myIcon = new GIcon();
	myIcon.image = "http://www.guna.it/img/markers/mrkDoc.png";
	myIcon.shadow = "http://www.guna.it/img/markers/mrkShadow.png";
	myIcon.iconSize = new GSize(20, 34);
	myIcon.shadowSize = new GSize(34, 34);
	myIcon.iconAnchor = new GPoint(10, 33);
	myIcon.infoWindowAnchor = new GPoint(5, 1);
	return myIcon;
}

function myGetGenericIcon() {
	var myIcon = new GIcon();
	myIcon.image = "http://www.guna.it/img/markers/mrkGen.png";
	myIcon.shadow = "http://www.guna.it/img/markers/mrkShadow.png";
	myIcon.iconSize = new GSize(20, 34);
	myIcon.shadowSize = new GSize(34, 34);
	myIcon.iconAnchor = new GPoint(10, 33);
	myIcon.infoWindowAnchor = new GPoint(5, 1);
	return myIcon;
}

function myGetPharmacyIcon() {
	var myIcon = new GIcon();
	myIcon.image = "http://www.guna.it/img/markers/mrkPha.png";
	myIcon.shadow = "http://www.guna.it/img/markers/mrkShadow.png";
	myIcon.iconSize = new GSize(20, 34);
	myIcon.shadowSize = new GSize(34, 34);
	myIcon.iconAnchor = new GPoint(10, 33);
	myIcon.infoWindowAnchor = new GPoint(5, 1);
	return myIcon;
}

function aggiungiCellaARiga(riga, tag, testo) {
	var cell = document.createElement(tag);
	var cellText = document.createTextNode(testo);
	cell.appendChild(cellText);
    riga.appendChild(cell);
}

function createJsonTable(elenco) {
	
	var t = $('jsonTable');
	
	// Vuota la tabella
	$each(t.getChildren(), function(el) {
		el.dispose();
	});		
	
    // creates a <table> element and a <tbody> element
    var tbl     = document.createElement("table");
	var tblHead = document.createElement("thead");
    var tblBody = document.createElement("tbody");				
	
	// creates a table row
    var row = document.createElement("tr");
	
	// crea la cella nome
	aggiungiCellaARiga(row, 'th', 'Tipo');
	aggiungiCellaARiga(row, 'th', 'Città');
	aggiungiCellaARiga(row, 'th', 'Nome e cognome');
	aggiungiCellaARiga(row, 'th', 'Indirizzo');
	aggiungiCellaARiga(row, 'th', 'Dist. (km)');
	
	// add the row to the end of the table body
    tblHead.appendChild(row);
	
    // creating all cells
    for (var j = 0; j < elenco.length; j++) {
        
		// creates a table row
        var row = document.createElement("tr");

		// crea la cella nome
		aggiungiCellaARiga(row, 'td', elenco[j].profilo);
		aggiungiCellaARiga(row, 'td', elenco[j].citta);
		aggiungiCellaARiga(row, 'td', elenco[j].titolo+' '+elenco[j].nome+' '+elenco[j].cognome);
		aggiungiCellaARiga(row, 'td', elenco[j].indirizzo);
		aggiungiCellaARiga(row, 'td', elenco[j].distance.replace('.',','));
							
        // add the row to the end of the table body
        tblBody.appendChild(row);
    }

    // put the <tbody> in the <table>
    tbl.appendChild(tblHead);
	tbl.appendChild(tblBody);
    // appends <table> into <body>
    t.appendChild(tbl);

}
