//	moved var declarations - no need to declare them each time changeText is called
var theText=[];
//Sj&aelig;lland
theText[1]="Sj&aelig;lland - Hovedbiblioteker";
theText[2]="Sj&aelig;lland - Folkebiblioteker";
theText[3]="Sj&aelig;lland - Bogbusser";
theText[4] = "Sj&aelig;lland - ALLE";
 
//Fyn
theText[5]="Fyn - Hovedbiblioteker";
theText[6]="Fyn - Folkebiblioteker";
theText[7]="Fyn - Bogbusser";
theText[8] = "Fyn - ALLE";
 
//Jylland
theText[9]="Jylland - Hovedbiblioteker";
theText[10]="Jylland - Folkebiblioteker";
theText[11]="Jylland - Bogbusser";
theText[12] = "Jylland - ALLE";
 
//&Oslash;erne
theText[13]="&Oslash;erne - Hovedbiblioteker";
theText[14]="&Oslash;erne - Folkebiblioteker";
theText[15]="&Oslash;erne - Bogbusser";
theText[16] = "&Oslash;erne - ALLE";

//	define global variables
var map;
var side_bar_html="";
var gmarkers=[];
var htmls=[];
var i=0;	//	choose better name for this global?
var customIcons=[];
var xmlfile=[];

	  
//	a new variable to store references to currently created event listeners
//	when we map.removeOverlays() we will then GEvent.removeListener each reference too
//	when dealing with lots of markers this should minimalise any memory leaks
var eventListeners=[];
//	NEW: two new global variables to hold url parameter requests
var urlCategory=getUrlParameter('category');
if(!urlCategory){
	//	no category requested in url so set a default category
	urlCategory='sh';
}
var urlBranchId=getUrlParameter('branch_id');

function changeText(strText){
	document.getElementById('hiddenText').innerHTML=theText[strText];
}

// This function picks up the click and opens the corresponding info window
function myclick(i){
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}

function createMarker(point,name,html,category) {
	var marker=new GMarker(point,customIcons[category]);
	
		html=html +'<a href="javascript:ZoomIn('+i+')"><img src="images/transparent.gif" width="20" height="1"><img src="images/zoomin.gif" alt="Zoom In" title="Zoom In" height="24" width="26"></a><a href="javascript:ZoomOut('+i+')"><img src="images/transparent.gif" width="10" height="1"><img src="images/resetzoom.gif" alt="Reset Zoom" title="Reset Zoom" height="24" width="26"></a><a href="javascript:map.closeInfoWindow()"><img src="images/transparent.gif" width="10" height="1"><img src="images/close.gif" alt="Close" title="Close" height="24" width="21"></a>';
	eventListeners.push(GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	}));
	gmarkers[i]=marker;
	htmls[i]=html;
	side_bar_html += '<li><a href="javascript:myclick(' + i + ')">' + name + '</a></li>';
	i++;

	return marker;
}

function handleSelected(opt) {
	var url='map_data_xml.php?category='+xmlfile[opt];
	readMap(url);
}

	function ZoomIn(i){
		map.setCenter(gmarkers[i].getLatLng(), 17, G_HYBRID_MAP);
}
	  
function ZoomOut(i){
	map.closeInfoWindow();
	map.setCenter(gmarkers[i].getLatLng(), 7, G_NORMAL_MAP); 
	GEvent.trigger(gmarkers[i], "click");
}

function ResetMap(){
	map.closeInfoWindow();
	map.setMapType(G_NORMAL_MAP);
	map.returnToSavedPosition();
}

// A function to read the data
function readMap(url){
	//GLog.write(url);
	
	//	NEW: add loading message
	map.addControl(map.loadingMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(180, 182)));
	
	var request=GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange=function(){
		if (request.readyState==4){
 			//var xmlDoc=request.responseXML;
			var xmlDoc=GXml.parse(request.responseText);
			// obtain the array of markers and loop through it
 			var markers=xmlDoc.documentElement.getElementsByTagName("marker");
			// re-set
			map.closeInfoWindow();
			map.clearOverlays();
			//	now remove event listeners to avoid memory leaks and reset the eventListener array to empty ready for next lot of event listeners to be added
			for (var i=eventListeners.length-1; i>=0; i--){
				GEvent.removeListener(eventListeners[i]);
			}
			eventListeners=[];
			gmarkers=[];
			//side_bar_html="";
			side_bar_html="<ul>";
			// declare all variables first - don't declare them each time they're used in the loop
			var bounds=new GLatLngBounds(), lat, lng, point, name, branchname, category, adresse, adresse1, postnummer, city, email, hjemmeside, telefax, tlf, googles_lat, googles_lng, html, marker, branchId;
			for (i=0; i < markers.length; i++) {
				// obtain the attribues of each marker
				lat=parseFloat(markers[i].getAttribute("lat"));
				lng=parseFloat(markers[i].getAttribute("lng"));
				point=new GLatLng(lat,lng);
				name=markers[i].getAttribute("name");
				branchname=markers[i].getAttribute("branchname");
				category=markers[i].getAttribute("category");
				adresse=markers[i].getAttribute("adresse");
				adresse1=markers[i].getAttribute("adresse1");
				postnummer=markers[i].getAttribute("postnummer");
				city=markers[i].getAttribute("city");
				email=markers[i].getAttribute("email");
				hjemmeside=markers[i].getAttribute("hjemmeside");
				telefax=markers[i].getAttribute("telefax");
				tlf=markers[i].getAttribute("tlf");
				googles_lat=markers[i].getAttribute("googles_lat");
				googles_lng=markers[i].getAttribute("googles_lng");
				//	id=markers[i].getAttribute("id"); there is no id field in the xml so this will return null
				branchId=markers[i].getAttribute("branch_id");	//	NEW
				
html="<a href='kontakt/index.php?id=" + branchId + "'target='_blank'><b>Opdater informationerne</b></a><br /><b>Branch id:</b> "+ branchId + " &nbsp; &#8212; &nbsp; <b>Bibliotekstype: </b>" + category + "<br /><b>Biblioteksnavn: </b>" + name + "<br /><b>Biblioteksafdeling: </b>" + branchname +  "<br /><b>Adresse: </b>" + adresse + " &nbsp; &#8212; &nbsp; <b>Adresse1: </b>" + adresse1 + "<br /><b>Postnr. og by: </b>" + postnummer + " " + city + "<br /><b>Tlf.nr.: </b>" + tlf + " &nbsp; &#8212; &nbsp; <b>Telefax: </b>" + telefax + "<br /><b>E-mail: </b><a href=\"mailto:" + email + "\">" + email + "</a><br /><b>Hjemmeside: </b><a href=" + hjemmeside + "\ target=\"_blank\">" + hjemmeside + '</a><br /><img src="images/icon_dgs.gif" width="20" height="19">&nbsp;<a href="http://www.degulesider.dk/vbw/kort/rute-resultat.do?&to.b=' + city + '&to.z=' + postnummer + '&to.g=' + adresse + '&partnerid=kortlink' + '">I bil - Til fods - P&aring; cykel - Ruteplan</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/icon_rejseplan.gif" width="17" height="17">&nbsp;<a href="http://www.rejseplanen.dk/bin/query.exe/mn?ZADR=1&Z=' + adresse + ', ' + postnummer + '">Rejseplanen</a><br /><br />S&oslash;g i n&aelig;rheden: f.eks. pizza, caf&eacute;, tog osv.<form action="http://maps.google.dk/maps" method="get"" target="_blank">'+ '<input type="text" SIZE=35 MAXLENGTH=80 name="q" id="q" value="" />'+ '<INPUT value="S&Oslash;G" TYPE="SUBMIT">'+ '<input type="hidden" name="near" value="' + name+ ' @' + point.lat() + ',' + point.lng() + '"/>';


				
	
				//	NEW: built a link to open the map with this marker's infowindow open
				var myLink=document.location.protocol+'//'+document.location.host+document.location.pathname+'?branch_id='+branchId;
				myLink='<a href="'+myLink+'"><img src="images/transparent.gif" width="100" height="1"><img src="images/mapit.gif" width="30" height="34"></a>';
				html+='<br />'+myLink;
				// create the marker
marker=createMarker(point,'<img src="'+ customIcons[category].image + '" width="9" height="15"> <b>' + name + '</b><br />' + branchname + '<br />', html, category);
				map.addOverlay(marker);
				//	NEW: check if branchId requested and if so is it this marker?
				if(urlBranchId==parseFloat(markers[i].getAttribute("branch_id"))){
					GEvent.trigger(marker, 'click');
				}
				//	extend the GLatLngBounds to include the marker's location
				bounds.extend(point);
			}
			// put the assembled side_bar_html contents into the side_bar div
			side_bar_html+='</ul>';
			document.getElementById("side_bar").innerHTML=side_bar_html;
			//	fit map center and zoom level to markers
			var z=map.getBoundsZoomLevel(bounds);
			var minZoom=8;	
			if (z>minZoom) {
				z=minZoom;
			}
			map.setCenter(bounds.getCenter(), z, G_NORMAL_MAP);
			map.savePosition();
			//	NEW: remove loading message
			map.removeControl(map.loadingMessage);
		}
	}
	request.send(null);
}

function myOnLoad(){
	if (GBrowserIsCompatible()) {
		
		//Sj&aelig;lland
		xmlfile[1]="sh";
		xmlfile[2]="sf";
		xmlfile[3]="sb";
		xmlfile[4] = "s%25";
		
		//Fyn
		xmlfile[5]="fh";
		xmlfile[6]="ff";
		xmlfile[7]="fb";
		xmlfile[8] = "f%25";
		
		//Jylland
		xmlfile[9]="jh";
		xmlfile[10]="jf";
		xmlfile[11]="jb";
		xmlfile[12] = "j%25";
		
		
		//&Oslash;erne
		xmlfile[13]="oh";
		xmlfile[14]="of";
		xmlfile[15]="ob";
		xmlfile[16] = "o%25";
		
		var baseIcon=new GIcon();
		baseIcon.shadow='images/mm_20_shadow.png';
		baseIcon.iconSize=new GSize(12, 20);
    	baseIcon.shadowSize=new GSize(22, 20);
    	baseIcon.iconAnchor=new GPoint(6, 20);
    	baseIcon.infoWindowAnchor=new GPoint(5, 1);
		
		var iconBlue=new GIcon(baseIcon, 'images/mm_20_blue.gif'); 
		var iconRed=new GIcon(baseIcon, 'images/mm_20_red.gif'); 
		var iconYellow=new GIcon(baseIcon, 'images/mm_20_yellow.gif');
	
		customIcons["SH"]=iconBlue;
		customIcons["SF"]=iconRed;
		customIcons["SB"]=iconYellow;
	
		customIcons["FH"]=iconBlue;
    	customIcons["FF"]=iconRed;
		customIcons["FB"]=iconYellow;
	
		customIcons["JH"]=iconBlue;
		customIcons["JF"]=iconRed;
		customIcons["JB"]=iconYellow;
	
		customIcons["OH"]=iconBlue;
		customIcons["OF"]=iconRed;
		customIcons["OB"]=iconYellow;

		
			
			// create the map
		map=new GMap2(document.getElementById("map"));
		map.addMapType(G_SATELLITE_3D_MAP);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		//map.enableGoogleBar();
		//	map now centered to (0, 0) at zoom level 0
		//	map will be centered and zoomed using bounds GLatLngBounds routine
		map.setCenter(new GLatLng(0,0), 0);
		
		//	NEW: create a HtmlControl 'Loading map' message
		//	we'll add and remove the loading message in the readMap() function.
		var html='<div style="background-color:transparent; border:solid 1px black; width:300px"><div style="background-color:white; border:solid 1px grey; padding:2ex; margin:1px; font-weight:bold; font-size:24px; text-align:center">Map Loading...</div></div>';
		map.loadingMessage=new HtmlControl(html);
		
		// When initially loaded, use the data from here
		// readMap("branch_id_map_data_xml.php?category=fh"); NEW: commented out as not used, this line now incorporated into the check for url parameters
		
		//	NEW:
		if(!urlBranchId){
			//	no branch id requested in url so open map with default category selected
			readMap("map_data_xml.php?category="+urlCategory);
		}	else {
			//	a branch id requested in url so process it
			//	query database for requested branch_id
			//	xml to return complate category that contains requested branch_id
			//	then we'll trigger click event on requested marker after it's been created
			readMap("map_data_xml.php?branch_id="+urlBranchId);
		}
	}
	}
//	new function to get parameter from url
function getUrlParameter(name) {
	var query=window.location.search.substring(1);
	var vars=query.split('&');
	var pair;
	for (var i=0; i<vars.length; i++) {
		pair=vars[i].split('=');
		if (pair[0]==name) {
			return pair[1];
		}
	}
}