//	declare global variables (activeMarker is a new global which holds a reference to the marker whose infowindow is open)
var map, displayedMarkers=[], customIcons=[], categoryLoaded=[], activeMarker;

function onPageLoad(){
	if (GBrowserIsCompatible()) {
		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);
		
		customIcons['SH']=new GIcon(baseIcon,'../images/mm_20_blue.gif');
		customIcons['SF']=new GIcon(baseIcon,'../images/mm_20_red.gif');
		customIcons['SB']=new GIcon(baseIcon,'../images/mm_20_yellow.gif');
	
		customIcons['FH']=new GIcon(baseIcon,'../images/mm_20_blue.gif');
    	customIcons['FF']=new GIcon(baseIcon,'../images/mm_20_red.gif');
		customIcons['FB']=new GIcon(baseIcon,'../images/mm_20_yellow.gif');
	
		customIcons['JH']=new GIcon(baseIcon,'../images/mm_20_blue.gif');
		customIcons['JF']=new GIcon(baseIcon,'../images/mm_20_red.gif');
		customIcons['JB']=new GIcon(baseIcon,'../images/mm_20_yellow.gif');
	
		customIcons['OH']=new GIcon(baseIcon,'../images/mm_20_blue.gif');
		customIcons['OF']=new GIcon(baseIcon,'../images/mm_20_red.gif');
		customIcons['OB']=new GIcon(baseIcon,'../images/mm_20_yellow.gif');
		
		//	array categoryLoaded(category) is true or false to indicate if a category is already loaded
		//	here we initialise the array and set all categories to false
		var categories=['SH', 'SF', 'SB', 'FH', 'FF', 'FB', 'JH', 'JF', 'JB', 'OH', 'OF', 'OB'];
		for (var i=0; i<categories.length; i++){
			categoryLoaded[categories[i]]=false;
		}
		
		map=new GMap2(document.getElementById('map'));
		map.setCenter(new GLatLng(0, 0), 0, G_NORMAL_MAP);
		map.addControl(new GMapTypeControl());
		map.addControl(new GSmallMapControl());
		//map.enableGoogleBar();
		//	create an HtmlControl to use as a 'map loading message'
		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);
		//	ensure all checkboxes are unchecked on page load
		setAllCheckboxes(false);
		//	set categories to be loaded when map first loads
		//var startCategories=['SH', 'SF', 'SB'];
		var startCategories=['SH'];
		for (var i=0; i<startCategories.length; i++){
			var checkBox=document.getElementById(startCategories[i]+'box');
			checkBox.checked=true;
			checkBoxChange(checkBox, startCategories[i]);
		}
	}
}

function onPageUnload(){
	//	set all global variables to null to enable any memory used by them to be freed when map is unloaded
	map=null;
	displayedMarkers=null;
	customIcons=null;
	categoryLoaded=null;
	GUnload();
}

//	if any markers are displayed then pan and zoom the map to show them all
//	otherwise simply pan to zoom level 6 and GLatLng(56.192574500000006, 11.6593725)
function fitMapToMarkers(){
	if (displayedMarkers.length){
		var bounds=new GLatLngBounds();
		for (var i=0; i<displayedMarkers.length; i++){
			bounds.extend(displayedMarkers[i].getLatLng());
		}
		var z=map.getBoundsZoomLevel(bounds);
		var minZoom=8; 
		if (z>minZoom) {
			z=minZoom;
		}
		map.setCenter(bounds.getCenter(), z);
	} else {
		map.setCenter(new GLatLng(56.192574500000006, 11.6593725), 6);
	}
	map.savePosition();
}

function checkBoxChange(checkBox, category){
	if (checkBox.checked && !categoryLoaded[category]){
		//	category selected but not already loaded
		queryDatabase(category);
	}
	if (!checkBox.checked && categoryLoaded[category]){
		//	category loaded and unselected 
		var marker, newDisplayedMarkers=[];
		for (var i=0; i<displayedMarkers.length; i++){
			marker=displayedMarkers[i];
			if (marker.category==category){
				GEvent.removeListener(marker.eventListener);
				map.removeOverlay(marker);
			} else {
				newDisplayedMarkers.push(marker);
			}
		}
		categoryLoaded[category]=false;
		displayedMarkers=newDisplayedMarkers;
		if(document.getElementById('autoFitMapToMarkers').checked){
			fitMapToMarkers();
		}
	}
	updateSidebar();
}

function newMarker(point, name, branch_id, branchname, adresse, postnummer, tlf, telefax, city, email, hjemmeside, category) {
	var marker=new GMarker(point, {icon:customIcons[category], title:name});
	marker.category=category;
	marker.name=name;
	marker.branchname=branchname;
	marker.branch_id=branch_id;	//	new code to store branch_id as a property of each marker

var html='<div class="infowindow"><b>Branch id: </b> '+branch_id+'&nbsp; &#8212; &nbsp; <b>Bibliotekstype: </b>' + category + '<br /><b>Biblioteksnavn:</b> '+name+'<br /><b>Biblioteksafdeling:</b> '+branchname+'<br /><b>Adresse: </b>'+adresse+', '+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+'">'+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 />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() + '"/>';

		html+='<br /><a href="javascript:zoomIn()"><img src="../images/transparent.gif" width="140" height="1"><img src="../images/zoomin.gif" alt="Zoom In" title="Zoom In" height="24" width="26"></a><a href="javascript:zoomOut()"><img src="../images/resetzoom.gif" alt="Reset Zoom" title="Reset Zoom" height="24" width="26"></a><a href="javascript:map.closeInfoWindow()"><img src="../images/close.gif" alt="Close" title="Close" height="24" width="21"></a>';
	   html+='</div>';
				
	marker.eventListener=GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
		//	store marker whose infowindow is open as activeMarker (new global)
		activeMarker=marker;
	});
	return marker;
}


function queryDatabase(category){
	map.addControl(map.loadingMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(180, 182)));
	var url='map_data_xml.php?category='+category;
	var request=GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange=function(){
		if (request.readyState==4){
			var  xmlElement, point, branch_id, branchname, name, email, adresse, postnummer, city, hjemmeside, html, marker;
			var xmlDoc=GXml.parse(request.responseText);
 			var markers=xmlDoc.documentElement.getElementsByTagName("marker");
			for (var i=0; i<markers.length; i++){
				xmlElement=markers[i];
				point=new GLatLng(parseFloat(xmlElement.getAttribute('lat')), parseFloat(xmlElement.getAttribute('lng')));
				branch_id=xmlElement.getAttribute('branch_id');
				branchname=xmlElement.getAttribute('branchname');
				name=xmlElement.getAttribute('name');
				email=xmlElement.getAttribute('email');
				adresse=xmlElement.getAttribute('adresse');
				postnummer=xmlElement.getAttribute('postnummer');
				city=xmlElement.getAttribute('city');
				tlf=xmlElement.getAttribute('tlf');
				telefax=xmlElement.getAttribute('telefax');
				hjemmeside=xmlElement.getAttribute('hjemmeside');
				
				//	infowindow html to be created in newMarker() function so we pass all parsed xml attributes to newMarker()
				
				marker=newMarker(point, name, branch_id, branchname, adresse, postnummer, tlf, telefax, city, email, hjemmeside, category);
				map.addOverlay(marker);
				displayedMarkers.push(marker);
			}
			categoryLoaded[category]=true;
			updateSidebar();
			if(document.getElementById('autoFitMapToMarkers').checked){
				fitMapToMarkers();
			}
			setTimeout("map.removeControl(map.loadingMessage)", 500);
		}
	};
	request.send(null);
}

//	clearAllCheckBoxes function can be deleted as we can use setAllCheckboxes(false) instead
function clearAllCheckBoxes(){
	var categories=['SH', 'SF', 'SB', 'FH', 'FF', 'FB', 'JH', 'JF', 'JB', 'OH', 'OF', 'OB'];
	for (var i=0; i<categories.length; i++){
			var checkBox=document.getElementById(categories[i]+'box');
			checkBox.checked=false;
			checkBoxChange(checkBox, categories[i]);
		}
}

//	bool is boolean TRUE or FALSE and all category checkboxes are set to value of bool
function setAllCheckboxes(bool){
	var categories=['SH', 'SF', 'SB', 'FH', 'FF', 'FB', 'JH', 'JF', 'JB', 'OH', 'OF', 'OB'];
	for (var i=0; i<categories.length; i++){
		var checkBox=document.getElementById(categories[i]+'box');
		checkBox.checked=bool;
		checkBoxChange(checkBox, categories[i]);
	}
}
function updateSidebar(){
	function sortByName(a, b){
		return a.name.localeCompare(b.name);
	}
 
	var html='<ul>', sorted=[];
	//	copy all marker names and indexes to array 'sorted'
	for (var i=0; i<displayedMarkers.length; i++){
		//sorted.push({branchname:displayedMarkers[i].branchname, name:displayedMarkers[i].name, index:i});
	sorted.push({branchname:displayedMarkers[i].branchname, name:displayedMarkers[i].name, branch_id:displayedMarkers[i].branch_id, index:i});
	}
	//	sort array 'sorted' by name alphabetically
	sorted=sorted.sort(sortByName);
	//	built sidebar HTML
	for (i=0; i<sorted.length; i++){
		/*html+='<li><a href="javascript:void(0)" onclick="triggerMarker('+sorted[i].index+')"><b>'+sorted[i].name+'<br /></b>'+sorted[i].branchname+'</a></li>';*/
		html+='<li><a href="javascript:void(0)" onclick="triggerMarker('+sorted[i].index+')"><b>'+sorted[i].name+'</b><br />'+sorted[i].branchname+'<br />'+sorted[i].branch_id+'</a></li>';
	}
	html+='</ul>';
	//document.getElementById('sidebar').innerHTML=html;
	document.getElementById('side_bar').innerHTML=html;
}

function triggerMarker(index){
	GEvent.trigger(displayedMarkers[index], 'click');
}


/*function zoomIn(){
	map.closeInfoWindow();
	map.setCenter(activeMarker.getLatLng(), 17, G_HYBRID_MAP);
	GEvent.trigger(activeMarker, "click");
}*/

	function zoomIn(lat, lng) {
		map.setCenter(activeMarker.getLatLng(), 17, G_HYBRID_MAP);
    }
	
	function zoomOut(){
	map.closeInfoWindow();
	//map.setCenter(activeMarker.getLatLng(), 7, G_NORMAL_MAP);
	map.setCenter(activeMarker.getLatLng(), 10, G_NORMAL_MAP);
	GEvent.trigger(activeMarker, "click");
}


