var map;
var infoplz;
var polys = [];
var labels = [];
var anzahlen = [];
var einwohners = [];
var schnitte = [];
var typ = 'plz';
var requrl = [];

var gmarkers = [];
var html = [];
var geoeffnet;


var nelat;
var nelng;
var swlat;
var swlng;



var requrl = [];
requrl['bundesland'] = 'request_bl.php';
requrl['plz'] = 'request_pl.php';
requrl['user'] = 'request_user.php';
requrl['anbieter'] = 'request_anbieter.php';

var HTMLWait ='<img src="/img/icons/wait_breit.gif" width="780" height="10" alt="Daten werden geladen" />';
var HTMLNix ='<img src="/img/icons/wait_breit-leer.gif" width="780" height="10" alt="Platzhalter"/>';







if(document.images) {
	var img = [];
	img[0] = new Image();
     img[0].src = '/img/icons/wait_breit.gif';
	img[1] = new Image();
     img[1].src = '/img/icons/wait_breit-leer.gif';
}


function ZoomNeu(zoom){
	map.setZoom(zoom);
}

function zoomendHandler() {
	var zoom = map.getZoom();
	var zoomStr = zoom.toString();

	HTMLinDIV('DivZoomAnzeige', zoomStr);



	for (var a = 6; a < 13; a++) {
		document.getElementById('zoom' + a).className = 'nixx';
	}

	if (document.getElementById('zoom' + zoomStr)) {
		document.getElementById('zoom' + zoomStr).className = 'aktiv';
	}


	lesen();
}


function moveendHandler() {

	if (map.getZoom() > 7) {
		var bounds = map.getBounds();
		// nur neu laden wenn die neuen Grenzen ausserhalb der schon berechneten Lage sind
		if ( 
			bounds.getSouthWest().lat().toFixed(6).toString() < swlat
			||
			bounds.getSouthWest().lng().toFixed(6).toString() < swlng
			||
			bounds.getNorthEast().lat().toFixed(6).toString() > nelat
			||
			bounds.getNorthEast().lng().toFixed(6).toString() > nelng
			) {

			lesen();
			geoeffnet = "";
		}
	}
}


function loeschen() {
	polys = [];
	labels = [];
     anzahlen = [];
     einwohners = [];
     schnitte = [];
     colours = [];
     geoeffnet = "";
	map.clearOverlays();
}


var ue1;
var ue1_z;
var ue2;
var inf;

function addUserToMap(
				id, 
				point, 
				icon,
				anzahl,
				speed,
				tech,
				zufrieden,
				info1, 
				info2
				) {

	var picon = new GIcon();
	picon.image = '/img/icon.php?ico=' + icon + '&i1=Intere.' + '&i2=' + info2 + '&a='+anzahl + '&s='+speed;
	picon.shadow = "/img/schatten.png";
	picon.iconSize = new GSize(36, 45);
	picon.shadowSize = new GSize(55, 55);
	picon.iconAnchor = new GPoint(0, 40);
	picon.infoWindowAnchor = new GPoint(15, 5); 

	var marker = new GMarker(point, picon);
	
	map.addOverlay(marker);
	var mehrzahl = "";
	var mehrzahl2 = "";
	if (anzahl > 1) {
		mehrzahl = "Durchschnittliche ";
		mehrzahl2 = " (u.a.)";
	}
	html[id] = "<strong>Interessenten: " + anzahl + "</strong><br />";
	if (info2 != "") {
		html[id] += ue2 + info2 + "<br />";
	}
	html[id] += mehrzahl + "Geschwindigkeit: " + speed + " kBit/s<br />";
	html[id] += "Technik: " + tech + mehrzahl2 + "<br />";
	html[id] += mehrzahl + "Zufriedenheit: " + zufrieden + "%<br />";

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html[id]);
		geoeffnet = id;
	});
	gmarkers[id] = marker;
	if (geoeffnet == id) {
		gmarkers[id].openInfoWindowHtml(html[id]);
	}
	return marker;
}





function addHVTToMap(id, point, inf) {

		var picon = new GIcon();
		picon.image = '/img/hvt.png';
		picon.shadow = "/img/hvt_schatten.png";
		picon.iconSize = new GSize(28, 30);
		picon.shadowSize = new GSize(37, 36);
		picon.iconAnchor = new GPoint(0, 40);
		picon.infoWindowAnchor = new GPoint(15, 5); 


	var marker = new GMarker(point, picon);
	
	map.addOverlay(marker);
	html[id] = "<strong>DSL-Hauptverteiler</strong><br />" + inf;

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html[id]);
		geoeffnet = id;
	});
	gmarkers[id] = marker;
	/****
	if (geoeffnet == id) {
		gmarkers[id].openInfoWindowHtml(html[id]);
	}
	***////
	return marker;
}




function addAnbieterToMap(id, point, ico, ue, inf, plz, anzahl, olat, ulat, llng, rlng) {


	if (typ == 'bundesland') {
		var picon = new GIcon();
		picon.image = "/img/icon_bundeslaender/" + id + '.gif';
		picon.shadow = "/img/schatten_bundesland.png";
		picon.iconSize = new GSize(50, 50);
		picon.shadowSize = new GSize(60, 60);
		picon.iconAnchor = new GPoint(0, 50);
		picon.infoWindowAnchor = new GPoint(15, 5); 
	
	} else {
		var picon = new GIcon();
		picon.image = '/img/icon_anbieter.php?ico=' + ico + '&text1=' + plz + '&text2=' + anzahl;
		picon.shadow = "/img/schatten.png";
		picon.iconSize = new GSize(36, 45);
		picon.shadowSize = new GSize(55, 55);
		picon.iconAnchor = new GPoint(0, 40);
		picon.infoWindowAnchor = new GPoint(15, 5); 
	}

	var marker = new GMarker(point, picon);
	
	map.addOverlay(marker);
	html[id] = "<strong>" + ue + "</strong><br />" 
		+ inf + "";
	if (anzahl > 1) {
		html[id] += '<br /><small>Mehere Anbieter, bitte die Karte weiter vergroessern für Details</small>';
	}
/*
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html[id]);
		geoeffnet = id;
	});
*/


	GEvent.addListener(marker,"click",function() {

		var x = marker.getPoint().lat();
		var y = marker.getPoint().lng();


		var z = map.getZoom();

		var ohneKabel = 0;
		if(document.FormInfoAuswahl.ohneKabel.checked){
			ohneKabel = 1;
		}


		var link =  'request_region_anbieter.php?z=' + z + '&olat=' + olat + '&ulat=' + ulat + '&llng=' + llng + '&rlng=' + rlng + '&ohneKabel=' + ohneKabel;
		GDownloadUrl(link, function(html) {
			marker.openInfoWindowHtml('<div class="divinfoanbieter">' + html + '</div>');
		});
	});



	gmarkers[id] = marker;
	/****
	if (geoeffnet == id) {
		gmarkers[id].openInfoWindowHtml(html[id]);
	}
	***////
	return marker;
}



function lesen(typ_neu) {


	var zoom = map.getZoom();
	var zoomStr = zoom.toString();
	var InfoAuswahl = checkradio(document.FormInfoAuswahl.InfoAuswahl);

	HTMLinDIV('Hinweis', '');

	if (zoomStr <= 6) {
		typ = 'bundesland';
		/* In dieser Ansicht nur Interessenten*/
		if(InfoAuswahl != 0){
			HTMLinDIV('Hinweis', '<p>In dieser Ansicht sind nur Interessenten sichtbar, bitte vergr&ouml;&szlig;ern Sie die Ansicht</p>');
			return;
		}
	}
	if (zoomStr == 7 ) {
		typ = 'plz';
	}
	if (zoomStr > 7) {
		var typ_neu = 'user';
		if(InfoAuswahl == 0){
			typ = "user";
		}
		if(InfoAuswahl == 1){
			typ = "anbieter";
		}

	}



	loeschen();

	document.getElementById('ImgWaiting').src = img[0].src;

	var bounds = map.getBounds();


	

	//// Interessenten / Anbieter
	var InfoAuswahl = 0;
	if(document.FormInfoAuswahl.InfoAuswahl[1].checked){
		InfoAuswahl = 1;
		showdiv('DivohneKabel');
	} else {
		hidediv('DivohneKabel');
	}	
	var ohneKabel = 0;
	if(document.FormInfoAuswahl.ohneKabel.checked){
		ohneKabel = 1;
	}

	gets = 	   'swlat=' + bounds.getSouthWest().lat().toFixed(6).toString() 
			+ '&swlng=' + bounds.getSouthWest().lng().toFixed(6).toString() 
			+ '&nelat=' + bounds.getNorthEast().lat().toFixed(6).toString() 
			+ '&nelng=' + bounds.getNorthEast().lng().toFixed(6).toString()
			+ '&zoom='  + zoomStr 
			+ '&InfoAuswahl=' + InfoAuswahl
			+ '&ohneKabel=' + ohneKabel
			;

			
	
	var request = GXmlHttp.create();
	request.open("GET", requrl[typ] + '?' + gets, true);

	request.onreadystatechange = function() {
		if (request.readyState == 4) {
          var xmlDoc = GXml.parse(request.responseText);
          



          // ========= User Point ===========

		if (typ == "user") {

	          var info = xmlDoc.documentElement.getElementsByTagName("i");
				nelat  	= info[0].getAttribute("nelat");
				nelng  	= info[0].getAttribute("nelng");
				swlat  	= info[0].getAttribute("swlat");
				swlng  	= info[0].getAttribute("swlng");


				ue1  	= info[0].getAttribute("ue1"); // global
				ue2  	= info[0].getAttribute("ue2"); // global
				ue1_z  	= info[0].getAttribute("ue1_z"); // global Zusatz nach der Ueberschrift 1
				icon  	= info[0].getAttribute("ico");
				was  	= info[0].getAttribute("was");

	          var daten = xmlDoc.documentElement.getElementsByTagName("b");

	          // read each line
			for (var a = 0; a < daten.length; a++) {
				
				// get any state attributes
				var lat  	= daten[a].getAttribute("lat");
				var lng 	= daten[a].getAttribute("lng");
				var id 	= daten[a].getAttribute("id");
				var info1	= daten[a].getAttribute("i1");
				var info2	= daten[a].getAttribute("i2");

				var anzahl= daten[a].getAttribute("a");
				var speed = daten[a].getAttribute("s");
				var tech  = daten[a].getAttribute("t");
				var zufrieden = daten[a].getAttribute("z");
				var point = new GLatLng(parseFloat(lat),parseFloat(lng));

				addUserToMap(
						id, 
						point, 
						icon,
						anzahl,
						speed,
						tech,
						zufrieden,
						info1, 
						info2
						);

			}

	          var daten = xmlDoc.documentElement.getElementsByTagName("h");

	          // hvt falls vorhandn
			for (var a = 0; a < daten.length; a++) {
				
				// get any state attributes
				var lat  	= daten[a].getAttribute("lat");
				var lng 	= daten[a].getAttribute("lng");
				var id 	= daten[a].getAttribute("id");
				var inf	= daten[a].getAttribute("i");

				var point = new GLatLng(parseFloat(lat),parseFloat(lng));

				addHVTToMap(
						id, 
						point, 
						inf
						);

			}







			document.getElementById('ImgWaiting').src = img[1].src;
		}


          // ========= Anbieter Point ===========

		if (typ == "anbieter") {

	          var info = xmlDoc.documentElement.getElementsByTagName("i");
				nelat  	= info[0].getAttribute("nelat");
				nelng  	= info[0].getAttribute("nelng");
				swlat  	= info[0].getAttribute("swlat");
				swlng  	= info[0].getAttribute("swlng");

				ue1  	= info[0].getAttribute("ue1");
				ue2  	= info[0].getAttribute("ue2");
				inf  	= info[0].getAttribute("inf");
				ico  	= info[0].getAttribute("ico");

	          var daten = xmlDoc.documentElement.getElementsByTagName("b");

	          // read each line
			for (var a = 0; a < daten.length; a++) {
				
				var icon = ico;
				// get any state attributes
				var lat  	= daten[a].getAttribute("lat");
				var lng 	= daten[a].getAttribute("lng");
				var id 	= daten[a].getAttribute("id");
				var plz 	= daten[a].getAttribute("plz");
				var ue 	= daten[a].getAttribute("n");
				var anzahl= daten[a].getAttribute("a");
				var point = new GLatLng(parseFloat(lat),parseFloat(lng));

				var olat 	= daten[a].getAttribute("olat");
				var ulat 	= daten[a].getAttribute("ulat");
				var llng 	= daten[a].getAttribute("llng");
				var rlng	= daten[a].getAttribute("rlng");

				var idiico= daten[a].getAttribute("ic"); // individuelle Icon
				if (idiico != null && idiico != "") {
					icon = idiico;
				}

				addAnbieterToMap(id, point, icon, ue1 + ue + ue2, inf + anzahl, ue + ue2, anzahl, olat, ulat, llng, rlng);
			}
//			HTMLinDIV('DivWaitInfo', HTMLNix);
			document.getElementById('ImgWaiting').src = img[1].src;
		}
          
          // ========= PLZ Bereiche polylines ===========

		if (typ == "plz") {
	          var daten = xmlDoc.documentElement.getElementsByTagName("b");
	          // read each line
			for (var a = 0; a < daten.length; a++) {
				// get any state attributes
				var label  = daten[a].getAttribute("n");
				infoplz  = daten[a].getAttribute("info");
				var colour = daten[a].getAttribute("f");
				var anzahl = daten[a].getAttribute("a");
				var einwohner = daten[a].getAttribute("e");
				var schnitt = daten[a].getAttribute("s");
				// read each point on that line
				var points = daten[a].getElementsByTagName("p");
				var pts = [];
				for (var i = 0; i < points.length; i++) {
				   pts[i] = new GLatLng(parseFloat(points[i].getAttribute("la")),
				                       parseFloat(points[i].getAttribute("ln")));
				}
				//  GPolygon(latlngs,  strokeColor?,  strokeWeight?,  strokeOpacity?,  fillColor?,  fillOpacity?,  opts?)
				var poly = new GPolygon(pts,"#FF0000",2,0.3,colour,0.7,{clickable:false});
				polys.push(poly);
				labels.push(label);
				anzahlen.push(anzahl);
				einwohners.push(einwohner);
				schnitte.push(schnitt);
				map.addOverlay(poly);
			}
		//	HTMLinDIV('DivWaitInfo', HTMLNix);
			document.getElementById('ImgWaiting').src = img[1].src;
		}
		if (typ == "bundesland") {

			var daten = xmlDoc.documentElement.getElementsByTagName("bundesland");
			// read each line
			var label = [];
			var colour = [];
			var anzahl = [];
			var einwohner = [];
			var schnitt = [];
			var lat = [];
			var lng = [];
			var alle_ids = [];
			for (var a = 0; a < daten.length; a++) {
				// get any state attributes
				var bid  = daten[a].getAttribute("bid");
				alle_ids[a]  = daten[a].getAttribute("bid");
				label[bid]  = daten[a].getAttribute("name");
				colour[bid] = daten[a].getAttribute("farbe");
				anzahl[bid] = daten[a].getAttribute("anzahl");
				einwohner[bid] = daten[a].getAttribute("einwohner");
				schnitt[bid] = daten[a].getAttribute("schnitt");
				lat[bid] = parseFloat(daten[a].getAttribute("lat"));
				lng[bid] = parseFloat(daten[a].getAttribute("lng"));
				// read each point on that line

				var bl_punkt = new GLatLng(lat[bid],lng[bid]);

				var infos = 'Eingetragene Interessenten: ' + anzahl[bid]
							+ '<br />Einwohner: ' + einwohner[bid] + ' Mio.'
			            		+ '<br />Durchschnitt: ' + schnitt[bid] + ' Betr. / 1 Mio.'
			            		;
			     var ico = 'bl';
				addIconBL( 
					bid, 
					bl_punkt, 
					ico, 
					
					label[bid], 
					infos
					
					);


				var points = daten[a].getElementsByTagName("point");
				var pts = [];
				for (var i = 0; i < points.length; i++) {
				   pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
				                       parseFloat(points[i].getAttribute("lng")));


				}
				var poly = new GPolygon(pts,"#000000",1,0.5,colour[bid],0.5,{clickable:false});
				polys.push(poly);
				colours.push(colour[bid]);
				labels.push(label[bid]);
				anzahlen.push(anzahl[bid]);
				einwohners.push(einwohner[bid]);
				schnitte.push(schnitt[bid]);
				map.addOverlay(poly);
			}
			var infoTeaser = '';
			for (var i=0; i<alle_ids.length; i++) {
					var tempid = alle_ids[i];
					var marker = gmarkers[tempid];
					var punkt = new GLatLng(lat[tempid],lng[tempid]);
					var punkt = new GLatLng(parseFloat(lat[tempid]),parseFloat(lng[tempid]));
				         
					var infoTeaser = '<a href="#" onclick="map.setZoom(7); return false;" '
								+ 'onmouseover="gmarkers['+tempid+'].openInfoWindowHtml(html['+tempid+']);" '
								+ 'onmouseout="gmarkers['+tempid+'].closeInfoWindow(html['+tempid+']);" '
								+ '>'
								+ '<span class="breit" style="background-color:' + colour[tempid] + ' " ><strong>' +label[tempid] + '</strong>'
			            			+ '<br /> &#216; ' + schnitt[tempid] + ' Betr. / 1 Mio. Einw.</span></a>'
			            			+ infoTeaser
			            			;
			}
			var zusatzinfo = "";
			if(document.FormInfoAuswahl.InfoAuswahl[1].checked){
				zusatzinfo = "<p>Info: in dieser Ansicht k&ouml;nnen nur Interessenten angezeigt werden</p>";
			}

			infoTeaser = '<h3>Bundesl&auml;nder</h3>' + zusatzinfo + infoTeaser + '</p>';
			HTMLinDIV('DivBundeslaender', infoTeaser);
			showdiv('DivBundeslaender');
//			hidediv('DivBBTechniken');
			hidediv('DivUserLegende');

			document.getElementById('ImgWaiting').src = img[1].src;
			
		} else {
			hidediv('DivBundeslaender');
		}	
          // ================================================           
        }
      }


//	if(document.FormInfoAuswahl.InfoAuswahl[1].checked){
//		showdiv('DivBBTechniken');
//	} else {
//		hidediv('DivBBTechniken');
//	}
	if(document.FormInfoAuswahl.InfoAuswahl[0].checked){
		showdiv('DivUserLegende');
	} else {
		hidediv('DivUserLegende');
	}


      request.send(null);

}



function myclick(i) {
	GEvent.trigger(gmarkers[i], "click");
}



/** addadress **/




function addIconBL(id, point, ico, ue, inf, plz, anzahl) {

	var picon = new GIcon();
	picon.image = "/img/icon_bundeslaender/" + id + '.gif';
	picon.shadow = "/img/schatten_bundesland.png";
	picon.iconSize = new GSize(50, 50);
	picon.shadowSize = new GSize(60, 60);
	picon.iconAnchor = new GPoint(0, 50);
	picon.infoWindowAnchor = new GPoint(15, 5); 
	

	var marker = new GMarker(point, picon);
	
	map.addOverlay(marker);
	html[id] = "<strong>" + ue + "</strong><br />" 
		+ inf + "";
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html[id]);
		geoeffnet = id;
	});
	gmarkers[id] = marker;
	if (geoeffnet == id) {
		gmarkers[id].openInfoWindowHtml(html[id]);
	}
	return marker;
}


function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					alert(address + " nicht gefunden");
				} else {
					map.setCenter(point, 12);
					var marker = new GMarker(point);
					map.addOverlay(marker);
//					marker.openInfoWindowHtml(address);
				}
			}
		);
	}
}


function myunload() {
	GUnload();
}

