var gralMapEvents = function () {
	Mapa.init();
	Mapa.showEstacions();
}

var detailMapEvents = function()  {
	Mapa.init();
	map.setMapType(G_HYBRID_MAP);
	if (form.id_municipi.value != 0) {
		var index = form.id_municipi.selectedIndex;
		var index_prov = form.id_provincia.selectedIndex;

		nom_municipi = form.id_municipi.options[index].text;
		nom_provincia = form.id_provincia.options[index_prov].text
		Mapa.showMunicipi(nom_municipi, nom_provincia);
	}
}

var map = null;
var geocoder = new GClientGeocoder();


var Infow={
	cont:null,
	infow:null,
	container:null,
	mnu_options:["Presentació","Totals","Espčcies","La Zona","Ajuda"],
	mnu_id:["presenta","totals","spp","zona","ajuda"],
	reInfo:/^i_(.*)/,
	estacio:null,
	totals_url:"http://www.sioc.cat/imatges/map_est/",
	logos_url:"http://www.sioc.cat/imatges/logos/",
	fotos_url:"http://www.sioc.cat/imatges/map_fotos/",
	imgsp_url:"http://www.sioc.cat/imatges/map_esp",
	close:function() {
		if (infow != null && cont != null) {
			cont.removeChild(infow);
		}
	},
	init:function(titulo, id) {
		cont = document.getElementById("mapContainer");
		infow = document.getElementById("infow");
		if (infow != null) {
			cont.removeChild(infow);
		}
		infow = document.createElement("DIV");
		var tanca = document.createElement("DIV");
		tanca.id = "tancar";
		var tancalnk = document.createElement("A");
		tancalnk.href = "javascript:Infow.close()";
		var tancatxt = document.createTextNode("Tancar");
		tancalnk.appendChild(tancatxt);
		tanca.appendChild(tancalnk);
		
		infow.id = "infow";
		//infow.innerHTML = "<h1>"+estacio.nom_estacio+"</h1>";
		var tit = document.createElement("H1");
		tit.onclick = Infow.close;
		var tittxt = document.createTextNode(titulo);
		tit.appendChild(tittxt);
		infow.appendChild(tanca);
		infow.appendChild(tit);
		infow.appendChild(Infow.getMenu());
		
		Infow.container = document.createElement("DIV");
		
		infow.appendChild(Infow.container);
		cont.appendChild(infow);
		Infow.load(id);
	},
	getMenu:function() {
		var menu = document.createElement("UL");
		for (var i=0; i<Infow.mnu_options.length; i++) {
			var li = document.createElement("LI");
			var litxt = document.createTextNode(Infow.mnu_options[i]);
			var lnk = document.createElement("A");
			lnk.id = "i_"+Infow.mnu_id[i];
			lnk.onclick = function () {
				switch(this.id) {
					case 'i_presenta':
						Infow.showIntro();
						break;
					case 'i_totals':
						Infow.showTotals();
						break;
					case 'i_spp':
						Infow.getEspecies();
						break;
					case 'i_zona':
						Infow.showZona();
						break;
					case 'i_ajuda':
						Infow.showAjuda();
						break;
				}				
			};
			lnk.appendChild(litxt);
			li.appendChild(lnk);
			menu.appendChild(li);
		}
		return menu;
	},
	showIntro:function(transport, json) {
		var html = "";
		if (Infow.estacio.logo != "") {
			var src = Infow.logos_url+Infow.estacio.logo;
			html += "<div id='logoestacio'><img src='"+src+"'></div>";
		}
		html += "<strong>Participants</strong><div id='ifparticipants'>"+Infow.estacio.participants+"</div>";
		Infow.container.innerHTML = html;
		var zoom = document.createElement("A");
		zoom.id = "zoom";
		zoom.onclick = function () {
			var lat = Infow.estacio.lat;
			var lng = Infow.estacio.lng;
			var point = new GLatLng(lat, lng);
			//alert(point);
			// Infow.close();
			// map.showMapBlowup(point);
			Infow.showZoom(lat, lng);
		} 
		var zoomtxt = document.createTextNode("Zoom");
		zoom.appendChild(zoomtxt);
		Infow.container.appendChild(zoom);
	},
	showZoom:function(lat, lng) {
		var html = "<div id='zoommap'></div>";
		Infow.container.innerHTML = html;
		
		if (GBrowserIsCompatible()) {
			// crea un  mapa
			var map = new GMap2(document.getElementById("zoommap"));
			// map.setMapType(G_HYBRID_MAP);
			//map.disableDragging();
			map.addControl(new GSmallMapControl());
			map.disableScrollWheelZoom();
			//map.addControl(new CatControl());
			/*
			map.addControl(new GSmallMapControl());
			// map.addControl(new GMapTypeControl());
			map.addControl(new CatControl());
			map.enableScrollWheelZoom();
			*/
			var center = new GLatLng(lat, lng);
			var zoom = 14;
			map.setCenter(center, zoom);
  			
			if ((Infow.estacio.kml != null) && (Infow.estacio.kml != '')) {
				var kml = new GGeoXml("http://www.sioc.cat/imatges/kml_atles/"+Infow.estacio.kml);
				map.addOverlay(kml);
			} else {
				map.addOverlay(new GMarker(center));
			}
			map.setMapType(G_HYBRID_MAP);
			// var mgrOptions = { borderPadding: 50, maxZoom: 18, trackMarkers: true };
			// Mapa.mgr = new GMarkerManager(map, mgrOptions);
			
		} else {
			alert("El seu navegador no és compatible amb l'aplicació de mapes");
		}
	},
	showTotals:function(){
		var src = Infow.totals_url+Infow.estacio.totals;
		// var html = "<img src='"+src+"' />";
		// var html = "<iframe src='"+src+"' id='iftotals' width='100%' height='375'></iframe>";
		var html = "<div id='iftotals'><img src='"+src+"' /></div>";
		Infow.container.innerHTML = html;
	},
	getEspecies:function() {
		var pars = 'codi_estacio=' + Infow.estacio.codi_estacio;
		var url = '/ajax/get_sp_estacio.php';
		var ajax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: Infow.showEspecies } );
	},
	showEspecies:function(transport, json){
		// Infow.container.innerHTML = "No disponible";
		// lee la cookie alert(document.cookie);
		var cook = readCookie("show_nom_cientific");
		Infow.container.innerHTML = "";
		var combo = document.createElement("SELECT");
		var option = document.createElement("OPTION");
		option.value = 0;
		var optxt = document.createTextNode("Selecciona una espčcie");
		option.appendChild(optxt);
		combo.appendChild(option);
		var lst_sp = eval(transport.responseText);
		for (var i=0; i<lst_sp.length; i++) {
			var option = document.createElement("OPTION");
			option.value = lst_sp[i].imatge;
			if (cook == 1) {
				var optxt = document.createTextNode(lst_sp[i].nom_cientific);
			} else {
				var optxt = document.createTextNode(lst_sp[i].nom_ca);
			}
			option.appendChild(optxt);
			if (cook == 1) {
				option.style.fontStyle = "italic";
			}
			combo.appendChild(option);
		}
		combo.onchange = Infow.showImgSp;
		Infow.container.appendChild(combo);
	},
	showImgSp:function(){
		if (this.value != 0) {
			var img = document.getElementById("spimg");
			if (img == null) {
				var img = document.createElement("IMG");
				img.id = "spimg";
				Infow.container.appendChild(img);
			}
			var src = Infow.imgsp_url+this.value;
			img.src = src;
		}
	},
	showZona:function() {
		if (Infow.estacio.foto != '') {
			var src = Infow.fotos_url+Infow.estacio.foto;
			var html = "<img src='"+src+"' />";
		} else {
			var html = "Imatge no disponible";
		}
		Infow.container.innerHTML = html;
	},
	showAjuda:function() {
	    switch (Infow.estacio.projecte) {
	    	case 'sylvia':
		    	url = '/ajuda_sylvia.html';
		    	break;
		    case 'migracio_primavera':
		    	url = '/ajuda_primavera.html';
		    	break;
		    case 'migracio_tardor':
		    	url = '/ajuda_tardor.html';
		    	break;
		    case 'socc':
		    	url = '/ajuda_socc.html';
		    	break;
		    case 'pernis':
		    	url = '/ajuda_pernis.html';
		    	break;
	    }
	    var w = window.open(url,"w",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=400,height=350');
	},
	load:function(id) {
		// carrega les dades de la estacio
		var pars = 'id=' + id;
		var ajax = new Ajax.Request( '/ajax/get_estacio.php', { method: 'get', parameters: pars, onComplete: Infow.create } );
	},
	create:function(transport, json) {
		Infow.estacio = eval(transport.responseText);
		Infow.showIntro();
	}
}

function readCookie(cookieName) {
	var theCookie = document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind == -1 || cookieName == '') {
		return false;
	}
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length; 
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

var Mapa={
	mgr:null,
	init:function() {
		if (GBrowserIsCompatible()) {
			// crea un  mapa
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			// map.addControl(new GMapTypeControl());
			map.addControl(new CatControl());
			map.enableScrollWheelZoom();
			var center = new GLatLng(41.70162734378918, 1.4776611328125);
			var zoom = 8;
			map.setCenter(center, zoom);
			var mgrOptions = { borderPadding: 50, maxZoom: 18, trackMarkers: true };
			Mapa.mgr = new GMarkerManager(map, mgrOptions);
			/*
	        GEvent.addListener(map, "moveend", function() {
	          var center = map.getCenter();
	          document.getElementById("message").innerHTML = center.toString();
	        });
	        */
		} else {
			alert("El seu navegador no és compatible amb l'aplicació de mapes");
		}
	},
	showEstacions:function(req) {
		// carrega la llista d'estacions
		var ajax = new Ajax.Request( '/ajax/llista_estacions.php?projecte=sylvia', { method: 'get', onComplete: Mapa.checkResponse } );
	},
	checkResponse:function(transport, json) {
		map.clearOverlays();
		// json = tranport.responseText.evalJSON(true);
		estacions = eval(transport.responseText);
		var estacio = null;
		var point = null;
		var markerlist = Array();
		var marker = null;
		for (i=0; i<estacions.length; i++) {
			estacio = estacions[i];
			marker = Mapa.createEstacioMarker(estacio);
			map.addOverlay(marker);
			// markerlist.push(marker);
		}
		/*
		Mapa.mgr.addMarkers(markerlist, 0);
		Mapa.mgr.refresh();
		*/
	},
	createEstacioMarker:function(estacio) {
		// discrimina iconos
		var icon = new GIcon();
		switch(estacio.projecte) {
			case 'sylvia':
				icon.image = "/img/mm_20_green.png";
				break;
			case 'migracio_tardor':
				icon.image = "/img/mm_20_red.png";
				break;
			case 'migracio_primavera':
				icon.image = "/img/mm_20_blue.png";
				break;
			case 'pernis':
				icon.image = "/img/mm_20_gray.png";
				break;
			default:
				icon.image = "/img/mm_20_yellow.png";
				break;
		}

		icon.shadow = "/img/mm_20_shadow.png";
		icon.iconSize = new GSize(12, 20);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);
		
		var point = new GLatLng(estacio.lat, estacio.lng);
		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, "click", function() {
			// var html = "<div>"+estacio.id_estacio+"</div>";
			// marker.openInfoWindowHtml(html);
			Infow.init(estacio.nom_estacio, estacio.id_estacio);

		});
		return marker;
	}
}