// map.js
// handling of google maps in www.litteraturpriser.dk
// $Id: map.js,v 1.4 2008-10-26 15:20:53+01 nje Exp nje $
//
// version 20080920
// 20080921 IE6 sidebar gif-icons 
// 20081026 load af xml-filer
// 20090207 tabs
// 20090214 Error in IE solved, empty tag or tag with only space equals null
// 20090215 final version, SimpleData-tags identified by name attribute
// 20090318 draws polygon with municipality boundaries
// 20090320 municipality lines final version!

var divsidebar2 = 'side_bar2';
var container;
var oldcontainer;
var hcontainer;
var map;
var oldmapdiv = "";
var onespace = " "; // must be one space
var googlemapkey = "ABQIAAAAFWFaIcie729VzkuX0b1MDxTo8xUxUpyYu9S5I9WZh8LPZp6iVRS6OJ6TVPfnKOqLMNlYi4XhyxWcsQ";
var gicons = [];
var giconsIE6 = [];
var gmarkers = [];
var ghtmls = [];
var glabels = ["Født","Gravsted","Minde mv."];
var zoomlevel = 7;
var placezoomlevel = 12;
var mymaxwidth = 300;
var i = 0;
// Nord for Kalundborg
// bedre sted naar Bornholm er med og zoomlevel 7
var defaultlat = 56.05;
var defaultlng = 11.5;
var sorrytxt = "Beklager, Google Maps kan ikke vises i denne browser";
var dirtytrickpoly = 'poly';
var kommuneshow = false;
var polygonar = [];
var polyi = 0;
var divkommuneshow = "divkommuneshow";
var kommuneshowcopyright = '<br/>Kommunegr&aelig;nser udarbejdet af <a href="http://www.microformats.dk/om/" target="_blank">S&oslash;ren Johannessen</a>';
var callshowkommune = '<a href="javascript:overlay_kommune(0)">Vis kommunegr&aelig;nser</a><br/>';
var callhidekommune = '<a href="javascript:overlay_kommune(1)">Vis ikke kommunegr&aelig;nser</a><br/>';
var marktxt = '[Markeringen p&aring; kortet er omtrentlig]';
var aboutmaps = '../maps/ommaps.htm';
var functionmytabclick = 'mytabclick';
var functionmyclick = 'myclick';
var functionrezoom = 'rezoom';
var rezoomtxt = 'Tilbage til oversigtskort';
var showdenmark = 'Vis hele Danmark';
var iconback = '../back.gif';
var iconrotation = '/pics/bigrotation2.gif';

function init_gicons() {
	// default values
	// Icon.iconAnchor=new GPoint(16,32); 
	// Icon.infoWindowAnchor=new GPoint(16,0); 
	// default shadow icon: shadow: msmarker_shadow.png
	gicons["yellow"] = new GIcon(G_DEFAULT_ICON, "/pics/yellow-dot.png");
	gicons["yellow"].iconSize = new GSize(32,32); 
	gicons["orange"] = new GIcon(G_DEFAULT_ICON, "/pics/orange-dot.png");
	gicons["orange"].iconSize = new GSize(32,32); 
	gicons["green"]  = new GIcon(G_DEFAULT_ICON, "/pics/green-dot.png");
	gicons["green"].iconSize =  new GSize(32,32); 
	gicons["info"]   = new GIcon(G_DEFAULT_ICON, "/pics/info.png");
	gicons["info"].shadow = "/pics/info_shadow.png";
	gicons["info"].iconSize =  new GSize(32,32); 
	gicons["info"].shadowSize = new GSize(56,32); 
	gicons["house"]  = new GIcon(G_DEFAULT_ICON, "/pics/icon56.png");
	gicons["house"].shadow = "/pics/icon56s.png";
	gicons["house"].iconSize = new GSize(32,32); 
	gicons["house"].shadowSize = new GSize(56,32);
	gicons["red"]  = new GIcon(G_DEFAULT_ICON, "/pics/red-dot.png");
	gicons["red"].iconSize = new GSize(32,32); 
	gicons["red"].shadowSize = new GSize(56,32);
	giconsIE6["yellow"] = "/pics/yellow-dott.gif";
	giconsIE6["orange"] = "/pics/orange-dott.gif";
	giconsIE6["green"]  = "/pics/green-dott.gif";
	giconsIE6["info"]   = "/pics/infot.gif";
	giconsIE6["house"]  = "/pics/icon56t.gif";
	giconsIE6["red"]    = "/pics/red-dott.gif";  // default

}

function wrapdiv(html, h, sted) {
    if (html != onespace) {	
		if (BrowserDetect.browser == "Firefox" && h <200) {
			html = "<div style='background-color:#F0F0F0; border:2px #D0D0D0 solid; font-family:arial; font-size:11px; height:90%; width:95%; padding: 2px; overflow:auto;'>" + sted + html + "</div>";
		}
		else {							
			html = "<div style='background-color:#F0F0F0; border:2px #D0D0D0 solid; font-family:arial; font-size:11px; padding: 2px; height:" + h + "px; width:350px; overflow:auto'>" + sted+html + "</div>";
		}	
	}	
	return html;
}

function closemap(mapdiv) {
   	hcontainer = document.getElementById(mapdiv+'h');
	hcontainer.style.display = 'none';		
	container = document.getElementById(mapdiv);
	container.style.display = 'none';
	oldcontainer = '';
	oldmapdiv = '';
	i = 0;	
}

function myclick(i) {
	map.setZoom(placezoomlevel);		
	gmarkers[i].openInfoWindowHtml(ghtmls[i], {maxWidth: mymaxwidth});
	map.panTo(gmarkers[i].getLatLng());  // center mark
}

function mytabclick(i) {
	map.setZoom(placezoomlevel);		
	gmarkers[i].openInfoWindowTabsHtml(ghtmls[i], {maxWidth: mymaxwidth});
	map.panTo(gmarkers[i].getLatLng());  // center mark
}

function rezoom(zoom) {  
    var centerPoint = new GLatLng(defaultlat,defaultlng);   
	map.setCenter(centerPoint, zoom);    
}

function doLoadMap(mapdiv, myJSONtext) {
    //var myobject = JSON.parse(myJSONtext);
    var myobject = myJSONtext.evalJSON(true);	// prototype version
	var side_bar_html = '<img src="' + iconback +'"> <a href="javascript:' + functionrezoom + '(' + zoomlevel + ');"> ' + rezoomtxt + '</a><br/>';	
	side_bar_html += '<img src="' + iconback + '" > <a href="javascript:closemap(';
	side_bar_html += "'" + mapdiv + "'" + ');"> Luk kort</a><br/>';
	side_bar_html += '<img src="../sptegn.gif"> <a href="' + aboutmaps + '">Om kortvisning</a><br/><br/>';
	
	if (GBrowserIsCompatible()) {
			
	    if (oldmapdiv != '') {	
			oldcontainer = document.getElementById(oldmapdiv+'h');
			oldcontainer.style.display = 'none';	
			oldcontainer = document.getElementById(oldmapdiv);
			oldcontainer.innerHTML = oldmapdiv;
			i = 0;
		}
		else {
		        init_gicons();			
		}
			
		var centerPoint = new GLatLng(defaultlat,defaultlng);
		hcontainer = document.getElementById(mapdiv+'h');
		hcontainer.style.display = '';
		container = document.getElementById(mapdiv);
		container.style.display = '';
		
		map = new GMap2(container);
		map.setCenter(centerPoint, zoomlevel);
		map.addControl(new GScaleControl());
		map.addControl(new GSmallMapControl());
		//map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
        map.addControl(new GOverviewMapControl());
	
		// A function to create the marker and set up the event window
		// mouseover shows title
		function createMarker(point,addr,html,icontype, type) {
			var marker = new GMarker(point,{icon: gicons[icontype],title: addr});
			GEvent.addListener(marker, "click", function() {
				map.panTo(point);
				marker.openInfoWindowHtml(html, {maxWidth: mymaxwidth});				
			});			
			gmarkers[i] = marker;
			ghtmls[i] = html;
			if (icontype != "default") {
			    if (BrowserDetect.browser == "Explorer" && BrowserDetect.version <= 6) {
					side_bar_html += ' <img src="' + giconsIE6[icontype] + '">';
				}
				else {
					side_bar_html += ' <img src="' + gicons[icontype].image + '">';
				}	
			}
			if (point.x != 0 && point.y != 0) {
				side_bar_html += '<a href="javascript:' + functionmyclick + '(' + i + ')">';				
			}
			side_bar_html += '<b>' + type + ':</b> ';
			side_bar_html += addr + '</a><br>';
			i++;
			return marker;
		}
		// create the marker
		side_bar_html += "<h3>" + myobject[0].name + "</h3>";
		for (var count = 0; count < myobject.length; count++) {
			var point = new GLatLng(myobject[count].lat, myobject[count].lng);
			html = '<b>'+myobject[count].name+'</b><br/>'+ '<b>' + myobject[count].type + ':</b> ' + myobject[count].addr;
			if (myobject[count].precision == 'u') {
				html += '<br/><br/>' + marktxt + '<div id="' + 'ajax_andrepersoner' + '"></div>';
			}	
			html = "<div class='mapshowhtmlpopup'>"+html+"</div>";
			var marker = createMarker(point,myobject[count].addr,html,myobject[count].icon, myobject[count].type);
			if (point.x != 0 && point.y != 0) {
				map.addOverlay(marker);
			}				
		}	
		oldmapdiv = mapdiv;
		document.getElementById("side_bar" + mapdiv).innerHTML = side_bar_html;
	}
	else {
		alert(sorrytxt);
	}
}

function emptymap(lng,lat, zoom) {
	if (GBrowserIsCompatible()) {
		// create the map
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());		
		map.setCenter(new GLatLng(lat,lng), zoom);	
	}
	else {
		alert(sorrytxt);
	}
}

//
// show or remove municipality overlay
function overlay_kommune (action) {
	if (!kommuneshow) {
		if (action == 0) {
			for (var i = 0; i < polyi; i++) {
				map.addOverlay(polygonar[i]);
			}
			kommuneshow = true;
			document.getElementById(divkommuneshow).innerHTML = callhidekommune;
		}
	}	
	else {
		if (action == 1) {		
			for (var i = 0; i < polyi; i++) {
				map.removeOverlay(polygonar[i]);
			}
			kommuneshow = false;
			document.getElementById(divkommuneshow).innerHTML = callshowkommune;							
		}
	}	
}

function renderpoly(pcoordinates) {
	var pts= [];
	for (var y2=0; y2 < pcoordinates.length; y2++) {
	
		// coordinates is child of LinearRing, whitch is child of outherBoundaryIS or innerBoundaryIS
		var coordtype = pcoordinates[y2].parentNode.parentNode.nodeName;
		// Firefox only allows 4096 bytes in child-nodes
		//	http://bytes.com/groups/xml/482760-problem-reading-large-amount-data-xml-tag
		if (BrowserDetect.browser == "Firefox") {
			var t = pcoordinates[y2].textContent;
		}
		else {
			var t = pcoordinates[y2].firstChild.nodeValue;
		}
		
		var polycords = t.split(" ");
		//side_bar_html += '<br/>polycords=' + polycords.length;	
		//side_bar_html += '<br/>start: ' + polycords[0] + ' slut:' + polycords[polycords.length-2] ;
		for (var y=0; y < polycords.length; y++) {
			
			var coords = polycords[y].split(",");									
			var lng = parseFloat(coords[0]);  // kml coordinates are: longitude, latitude, altitude	
			var lat = parseFloat(coords[1]);	
			if (coords[0] != "" && coords[1] != "") {
				pts[y] = new GLatLng(lat,lng);
			}			
		}	  
		//GPolygon(latlngs:GLatLng[], 
		//strokeColor?:String, 
		//strokeWeight?:Number, 
		//strokeOpacity?:Number, 
		//fillColor?:Number, 
		//fillOpacity?:Number, 							
		//opts?:GPolygonOptions)
		
		// blue: aaaaff, orange: ffa500
		// while: ffffff, black: 000000	
		
		if (coordtype == "outerBoundaryIs") {
			var polygon = new GPolygon(pts, "#000000", 2, 0.5, "#ffa500", 0.4); 									
		}
		else {								
			var polygon = new GPolygon(pts, "#ffffff", 2, 0.5, "#00a5ff", 0.2); 
		}	
		//map.addOverlay(polygon);
		// don't show boundaries as default
		kommuneshow = false;
		polygonar[polyi] = polygon;								
		polyi++;
		pts = [];
	}
}

// no tabs
function loadxmlmap (xmlFile, zoom, gifdiv, sidebardiv){
    polyi = 0;
	kommuneshow = false;
	var side_bar_html = '<img src="' + iconback + '"> <a href="javascript:'+ functionrezoom + '(' + zoomlevel + ');"> ' + showdenmark + '</a><br/>';		
	document.getElementById(divsidebar2).innerHTML = side_bar_html;
	if (!xmlFile) {
		return;
	}
	
	if (GBrowserIsCompatible()) {
		var newlat = defaultlat;
		var newlng = defaultlng;
		init_gicons();
	  
		// create the map
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		// CUSTOMISE - Change the coordinates and zoom level as appropriate
		map.setCenter(new GLatLng(defaultlat,defaultlng), zoom);  

		// A function to create the marker and set up the event window
		function createMarker(point, name, html, icontype) {
			var marker = new GMarker(point,{icon: gicons[icontype],title: name});	// display place name on mouse over		
			GEvent.addListener(marker, "click", function() {
				map.panTo(point);
				marker.openInfoWindowHtml(html, {maxWidth:350,maxHeight:350});
				//map.setCenter(marker.getPointer());
			});
			return marker;
		}
		
		if (xmlFile) {
		// Read the data from xml-file
			var request = GXmlHttp.create();				
			request.open("GET", xmlFile, true);
			request.onreadystatechange = function() {
				if (request.readyState == 1) {
					document.getElementById(gifdiv).innerHTML = '<img src="' + iconrotation + '">';	
				}
				if (request.readyState == 4) {
					var xmlDoc = request.responseXML;
					// obtain the array of markers and loop through it
					var markers = xmlDoc.documentElement.getElementsByTagName("Placemark");
					for (var i = 0; i < markers.length; i++) {
						// obtain the attribues of each marker
						var addr = markers[i].getElementsByTagName("description")[0].firstChild.nodeValue;
						var name = markers[i].getElementsByTagName("name")[0].firstChild.nodeValue;
						var itype =  markers[i].getElementsByTagName("styleUrl")[0].firstChild.nodeValue;
						itype = itype.replace(/^#/,"");
						
						if (itype != dirtytrickpoly) {
							var coords = markers[i].getElementsByTagName("coordinates")[0].firstChild.nodeValue.split(",");
							var lng = parseFloat(coords[0]);  // kml coordinates are: longitude, latitude, altitude
							var lat = parseFloat(coords[1]);
							var point = new GLatLng(lat,lng);
							
							var html = "";
							var h = 350;
							newlat = lat;
							newlng = lng;							
						
							// create the marker
							html = "<b>"+name+"</b><br/>"+addr;
							
							// IE can't handle overflow:auto if height and width relative
							if (addr.length <100) {
								h = 40;
							}
							else if (addr.length <200) {
								h = 70;
							}
							else if (addr.length <300) {
								h = 100;
							}
							else if (addr.length <400) {
								h = 150;
							}
							else if (addr.length <500) {
								h = 200;
							}
							html=wrapdiv(html, h, "");

							var marker = createMarker(point,name,html,itype);
							map.addOverlay(marker);	
							if (i == 0) {
								map.setCenter(new GLatLng(newlat,newlng), zoom);
							}
							if (point.x != 0 && point.y != 0) {
								side_bar_html += '<a href="javascript:' + functionmyclick + '(' + i + ')">';
							}
							gmarkers[i] = marker;
							ghtmls[i] = html;
							side_bar_html += '<b>' + name + '</b></a><br>';
						}
						else {								
							var pcoordinates =	markers[i].getElementsByTagName("coordinates");								
							renderpoly(pcoordinates);
						}
					}	
					document.getElementById(gifdiv).innerHTML = "";	// remove progress gif	
					if (polyi > 0) {
						if (sidebardiv) {
							side_bar_html = '<div id="' + divkommuneshow +'">' + callshowkommune + '</div>'+ side_bar_html + kommuneshowcopyright;
						}	
						else {
							document.getElementById(divsidebar2).innerHTML = '<div id="' + divkommuneshow +'">' + callshowkommune + '</div>'
									+ document.getElementById(divsidebar2).innerHTML
									+ kommuneshowcopyright;
						}
					}						
					if (sidebardiv) {
						document.getElementById(sidebardiv).innerHTML = side_bar_html;					
					}					
				}
			}
			request.send(null);				
		}			
	}

	else {
		alert(sorrytxt);
	}
}

// popup with tabs, test for Explorer at the moment not used
function loadtabxmlmap (xmlFile, zoom, gifdiv, sidebardiv){
   if (BrowserDetect.browser == "Explorer") {
		loadtabxmlmapfire (xmlFile, zoom, gifdiv, sidebardiv);
   }
   else {
		loadtabxmlmapfire (xmlFile, zoom, gifdiv, sidebardiv);
   }
}

function loadtabxmlmapfire(xmlFile, zoom, gifdiv, sidebardiv){
	polyi = 0;
	kommuneshow = false;
	var side_bar_html = '<img src="' + iconback + '"> <a href="javascript:' + functionrezoom + '(' + zoomlevel + ');"> ' + showdenmark + '</a><br/>';		
	document.getElementById(divsidebar2).innerHTML = side_bar_html;
	if (!xmlFile) {
		return;
	}
	
	if (GBrowserIsCompatible()) {
		var newlat = defaultlat;
		var newlng = defaultlng;
		init_gicons();
	  
		// create the map
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		// CUSTOMISE - Change the coordinates and zoom level as appropriate
		map.setCenter(new GLatLng(defaultlat,defaultlng), zoom);  		

		// A function to create the marker and set up the event window
		function createMarker(point, name, htmls, labels, icontype) {
			var marker = new GMarker(point,{icon: gicons[icontype],title: name});	// display place name on mouse over		
			var tabs = [];
			for (var i=0; i< htmls.length; i++) {
				if (htmls[i] != onespace) {
					tabs.push(new GInfoWindowTab(labels[i], htmls[i]));
				}	
			}
			GEvent.addListener(marker, "click", function() {
				map.panTo(point);
				marker.openInfoWindowTabsHtml(tabs, {maxWidth:350,maxHeight:350});								
			});
			return marker;
		}
		
		if (xmlFile) {
		// Read the data from xml-file
			var request = GXmlHttp.create();				
			request.open("GET", xmlFile, true);
			request.onreadystatechange = function() {
				if (request.readyState == 1) {
					document.getElementById(gifdiv).innerHTML = '<img src="' + iconrotation + '">';	
				}
				if (request.readyState == 4) {
					var xmlDoc = request.responseXML;
					// obtain the array of markers and loop through it
					var markers = xmlDoc.documentElement.getElementsByTagName("Placemark");
					for (var i = 0; i < markers.length; i++) {
						// obtain the attribues of each marker
						var born = onespace; // empty tab if equal space
						var dead = onespace;
						var other = onespace;	
						var addr = 99;  // used to size the ballon, resized if data in a SimpleData tag is longer
						// description not used, SimpleData is used
						//var addr = markers[i].getElementsByTagName("description")[0].firstChild.nodeValue;
						var itype =  markers[i].getElementsByTagName("styleUrl")[0].firstChild.nodeValue;
						var name = markers[i].getElementsByTagName("name")[0].firstChild.nodeValue;
				
						// dirty trick!! to recognise overlay coordinates for municipality bounderies
						itype = itype.replace(/^#/,"");
						if (itype != dirtytrickpoly) {
						
							var coords = markers[i].getElementsByTagName("coordinates")[0].firstChild.nodeValue.split(",");									
							var lng = parseFloat(coords[0]);  // kml coordinates are: longitude, latitude, altitude
							var lat = parseFloat(coords[1]);
							var point = new GLatLng(lat,lng);
							
							// tag description not used any more but included
							// test if tag is empty (space equals empty in IE) - error in IE if so
							// at most 3 tags in xml-file, attribute name with value: born, dead or other
							//
							var extradata = markers[i].getElementsByTagName("SimpleData");
							for (var y=0; y < extradata.length; y++) {
								// test for empty tag (in ie also tags with one space)	
								if (extradata[y].firstChild != null) {
									if (extradata[y].getAttribute("name") == "born") {
										born = extradata[y].firstChild.nodeValue;
										if (born.length > addr) {
											addr = born.length;
										}
									}
									if (extradata[y].getAttribute("name") == "dead") {
										dead = extradata[y].firstChild.nodeValue;
										if (dead.length > addr) {
											addr = dead.length;
										}									
									}
									if (extradata[y].getAttribute("name") == "other") {
										other = extradata[y].firstChild.nodeValue;
										if (other.length > addr) {
											addr = other.length;
										}									
									}
								}
							}
							var html = "";
							var h = 350;
							
							newlat = lat;
							newlng = lng;							

							// create the marker
							html = "<b>"+name+"</b><br/>";
							
							// IE can't handle overflow:auto if height and width relative
							if (addr <100) {
								h = 40;
							}
							else if (addr <200) {
								h = 70;
							}
							else if (addr <300) {
								h = 100;
							}
							else if (addr <400) {
								h = 150;
							}
							else if (addr <500) {
								h = 200;
							}						
							born = wrapdiv(born, h, html);
							dead = wrapdiv(dead, h, html);
							other = wrapdiv(other, h, html);
							
							// put tabbed marker on map
							var marker = createMarker(point,name,[born,dead,other],glabels,itype);						
							map.addOverlay(marker);						
							
							// position map on first coordinate
							if (i == 0) {
								map.setCenter(new GLatLng(newlat,newlng), zoom);					
							}
							
							// create data for sidebar
							if (point.x != 0 && point.y != 0) {
								side_bar_html += '<a href="javascript:' + functionmytabclick + '(' + i + ')">';
							}
							gmarkers[i] = marker;
							var tabs = [];
							if (born != onespace) {
								tabs.push(new GInfoWindowTab(glabels[0], born));
							}
							if (dead != onespace) {						    
								tabs.push(new GInfoWindowTab(glabels[1], dead));
							}
							if (other != onespace) {
								tabs.push(new GInfoWindowTab(glabels[2], other));
							}	
							ghtmls[i] = tabs;
							side_bar_html += '<b>' + name + '</b></a><br>';
						}
						else {								
							var pcoordinates =	markers[i].getElementsByTagName("coordinates");									
							renderpoly(pcoordinates);	
						}						
					}
					document.getElementById(gifdiv).innerHTML = "";	// remove progress gif	
					if (polyi > 0) {
						if (sidebardiv) {
							side_bar_html = '<div id="' + divkommuneshow +'">' + callshowkommune + '</div>'+ side_bar_html + kommuneshowcopyright;
						}					
						else {
							document.getElementById(divsidebar2).innerHTML = '<div id="' + divkommuneshow +'">' + callshowkommune + '</div>'
										+ document.getElementById(divsidebar2).innerHTML
										+ kommuneshowcopyright;
						}	
					}
					if (sidebardiv) {
						document.getElementById(sidebardiv).innerHTML = side_bar_html;
					}					
				}
			}
			request.send(null);				
		}			
	}

	else {
		alert(sorrytxt);
	}
}

// end of map.js