$(function(){
	$('.maplink').click(function(){
		$(this).hide();
		$('#map').show();
		$('<p><a href="karte.html">Hinweise zur Karte</a>').insertAfter($('#map'));


		$.getScript('js/leaflet.js', function() {

			// get geo from classes
			var classes = $('#map').attr('class').split(' ');
			var lat = 0, lon = 0, iconClass = null;
			for(var i=0; i<classes.length; i++) {
				var res = classes[i].match(/^lat([0-9]+\.[0-9]+)$/);
				if (res) {
					lat = parseFloat(res[1]);
					continue;
				}
				res = classes[i].match(/^lon([0-9]+\.[0-9]+)$/);
				if (res) {
					lon = parseFloat(res[1]);
					continue;
				}
				res = classes[i].match(/^icon([a-zA-Z]+)$/);
				if (res) {
					iconClass = res[1];
					continue;
				}
			}

			var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
			var osmAttrib='Map data © <a href="http://openstreetmap.org?lat='+lat+'&lon='+lon+'&zoom=12">openstreetmap</a>';
			var osm = new L.TileLayer(osmUrl,{attribution: osmAttrib});


			var fireUrl='http://openfiremap.org/hytiles/{z}/{x}/{y}.png';
			var fireAttrib='<a href="http://openfiremap.org/?zoom=12&lat='+lat+'&lon='+lon+'">openfiremap</a>';
			var fire = new L.TileLayer(fireUrl,{attribution: fireAttrib});

			var map = new L.Map('map', {
				center: new L.LatLng(lat, lon),
				zoom: 15,
				layers: [osm, fire]
			});

			var marker = getMarker(lat, lon, iconClass, $('h1').text());

			map.addLayer(marker);
			marker.openPopup();

		});
	});
});

function getMarker(lat, lon, i, text) {
	var Icon;
	var m;

		// [ name, size, size, icon, icon, popup, popup ]
	if(i=='Feuer'){
		m=['feuer_neu.png',28,40,6,35,2,-26];
	}else if(i=='Baum'){
		m=['baum.png',60,27,5,13,2,-13];
	}else if(i=='Oelspur'){
		m=['oelspur.png',40,36,20,18,0,-19];
	}else if(i=='Trage'){
		m=['trage.png',45,27,20,18,0,-19];
	}else if(i=='Auto'){
		m=['auto.png',45,33,20,18,0,-19];
	}else if(i=='Tueroeffnen'){
		m=['tueroeffnen.png',23,40,11,20,0,-24];
	}else if(i=='Ausbildung'){
		m=['ausbildung.png',45,36,11,20,0,-24];
	}else if(i=='Wettkampf'){
		m=['wettkampf.png',39,34,11,20,0,-24];
	}else if(i=='Feier'){
		m=['feier.png',38,38,19,19,0,-20];
	}else if(i=='Einsatz'){
		m=['blaulicht.png',40,31,20,20,2,-26];
	}else{
		m=null;
	}

	if (m == null) {
		Icon = L.Icon.extend({
			iconUrl: 'js/images/marker.png',
			shadowUrl: 'js/images/marker-shadow.png',
			iconSize: new L.Point(25, 41),
			shadowSize: new L.Point(41, 41),
			iconAnchor: new L.Point(12, 41),
			popupAnchor: new L.Point(0, -45)
		});
	} else {
		Icon = L.Icon.extend({
			iconUrl: 'js/images/' + m[0],
			shadowUrl: 'js/images/' + m[0],
			iconSize: new L.Point(m[1], m[2]),
			shadowSize: new L.Point(0, 0),
			iconAnchor: new L.Point(m[3], m[4]),
			popupAnchor: new L.Point(m[5], m[6])
		});

	}

	var marker = new L.Marker(new L.LatLng(lat, lon), {icon: new Icon()});
	marker.bindPopup(text);
	return marker;
}

