<!--
	
//******************************************* Browser Version? ******************************************************

      function browserVersion()
      {
         if(window.XMLHttpRequest)
         {
         if(window.ActiveXObject)
         {
				// IE 7
				//document.write("IE7");
				Version="IE7"
         }
         else
         {
   	      // Opera, Safari, Firefox
				//document.write("The Others");
				Version="FF"
         }
         }
         else
         {
	         //IE 6 and below
				//document.write("IE6 or below");
				Version="IE"
         }   
			return Version	
		}

//******************************************* Contact ******************************************************

	function Contact(Subject)
	{
      var lhs = "&#109;"+"&#112;"+"&#108;"+"&#121;"+"&#110;"+"&#110;";
      var rhs = "gmail"+"&#46;"+"com";
      document.write('<A HREF="mailto:'+lhs+'@'+rhs+'?subject='+Subject+'">Contact Me</a>');
	}

//******************************************* Find Position & Width of element ******************************************************

   function getElementPosition(elemID) 
	{
       var offsetTrail = document.getElementById(elemID);
       var offsetLeft = 0;
       var offsetTop = 0;
       while (offsetTrail) {
           offsetLeft += offsetTrail.offsetLeft;
           offsetTop += offsetTrail.offsetTop;
           offsetTrail = offsetTrail.offsetParent;
       }
       if (navigator.userAgent.indexOf("Mac") != -1 && 
           typeof document.body.leftMargin != "undefined") {
           offsetLeft += document.body.leftMargin;
           offsetTop += document.body.topMargin;
       }
		 elWidth=document.getElementById(elemID).offsetWidth;

    return {left:offsetLeft, top:offsetTop, width:elWidth};
   }
	
//******************************************* Document Create Date ******************************************************
	
/* Fetch the Doc Create Date

 */	
 	function fileModDate()
	{
   if (Date.parse(document.lastModified) != 0) 
		{
     		var modiDate = new Date(document.lastModified);
     		var monthName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	     	var dateString = 'last modified: ' + monthName[modiDate.getMonth()] + ' ' + modiDate.getDate() + ', ' + modiDate.getFullYear();
			return dateString;
     	}	
	}

//******************************************* Header on all pages ******************************************************


	function buildHeader(docTitle)
	{
		document.write ('<div class="pageTitle"> <a name="Top"></a>'+docTitle+'</div>');

	//
	//	Google advert code
	//		
		document.write ('&#160;'+'&#160;'+'&#160;<script type="text/javascript">'+
            'google_ad_client = "pub-6053522278480849";'+
            'google_ad_width = 728;'+
            'google_ad_height = 15;'+
            'google_ad_format = "728x15_0ads_al_s";'+
            'google_ad_channel = "";'+
            'google_color_border = "203e50";'+
            'google_color_bg = "203e50";'+
            'google_color_link = "0000FF";'+
            'google_color_text = "AECCEB";'+
            'google_color_url = "00800";'+
         '</script>'+
         '<script type="text/javascript"'+
   			'src="http://pagead2.googlesyndication.com/pagead/show_ads.js">'+
         '</script>'
		);
	};


//******************************************* Footer on all pages ******************************************************

	function buildFooter(docTitle)
	{
      var lhs = "&#109;"+"&#112;"+"&#108;"+"&#121;"+"&#110;"+"&#110;";
      var rhs = "gmail"+"&#46;"+"com";

	
		document.write
		(
			'<form method="get" action="http://www.google.co.uk/custom" target="_top" style="margin: 0 0 0 0">'+
				'<table border="0">'+
					'<tr>'+
						'<td rowspan="2">'+
							'<a href="http://www.google.com/"><img src="http://www.google.com/logos/Logo_25blk.gif" border="0" alt="Google"></img></a>'+

						'<td rowspan="2">'+
							'<input type="hidden" name="domains" value="fhr.kiwicelts.com"></input>'+
							'<label for="sbi" style="display: none">Enter your search terms</label>'+
         	     	      '<input type="text" name="q" size="31" maxlength="255" value="" id="sbi"  style="vertical-align: middle;"></input>'+
            	         '<label for="sbb" style="display: none;">Submit search form</label>'+
               	      '<input type="submit" name="sa" value="Google Search" id="sbb" '+
								'style="color: #ffffff; background: #8098b0; border: 2.5px outset lightblue; vertical-align: middle;" ></input>'+
                  	   '<input type="hidden" name="client" value="pub-6053522278480849"></input>'+
                     	'<input type="hidden" name="forid" value="1"></input>'+
                        '<input type="hidden" name="ie" value="ISO-8859-1"></input>'+
                        '<input type="hidden" name="oe" value="ISO-8859-1"></input>'+
                			'<input type="hidden" name="cof"'+
								'value="GALT:#ffff99;GL:1;DIV:#666666;VLC:bbbbbb;AH:left;BGC:203e50;LBGC:44677b;ALC:ffff00;LC:ff00ff;T:ffffff;GFNT:ff00FF;GIMP:ffff00;'+
								'LH:50;LW:179;L:http://kiwicelts.com/javascripts_styles/Images/kiwicelts.gif;S:http://kiwicelts.com;FORID:1">'+
							'</input>'+
                        '<input type="hidden" name="hl" value="en"></input>'+

						'<td>'+
							'<input  style="background: #44677B; border-color: #44677B;" type="radio" name="sitesearch" value=""  id="ss0"></input>'+
							'<label for="ss0" title="Search the Web">Search The Web</font></label>'+

						'<td rowspan="2" style="font-size: 1.6em;">'+
							'<b>'+'<a href=mailto:'+lhs+'@'+rhs+'?subject=Cemetery&#32;Database&#32;Enquiry>Contact Me</a>'+'</b>'+

						'<td>'+
							docTitle+' © 2004-2008 Murray Lynn'+

					'<tr>'+
						'<td>'+
							'<input style="background: #44677B; border-color: #44677B;" type="radio" name="sitesearch" value="fhr.kiwicelts.com" checked id="ss1"></input>'+
							'<label for="ss1" title="Search fhr.kiwicelts.com">Search Here</font></label>'+

						'<td>'+
							fileModDate()+
									
				'</table>'+
			'</form>'
		);
	}


	
	
// ****************************************** Code for Map ***************************************************************

// Global variables

// Diagnostic stuff:
	var
		infoDisplayEnabled = true; 

// Constants
	var
		iconZoomVisibility = 7,					//zoom visibility for Marker Manager
		zoomTo = 9, 								//zoom to level on search
		tableLoaded = false,
		displayPolyIconsStart = true,	 		// Set True (False) to start with Polygon Icons on / off  
		displayPolyIcons,
		iconOnText =  'Icons On',
		iconOffText = 'Icons Off';

// Other globals:	
	var 
		mgr,
		markers,
		map,
		reasons=[],
		geo,
		cemListRows,								// number of rows in cemList
		cemLinksRows,								// number of rows in cemLinks
		searchFor = "data",
		searchSortby ="name",
		searchArea="all",
		sideMarkers=[],
		iMarker = 0,
		iconMarker = new Array ();				// array of icon markers	


   function load() 
	{
		if (GBrowserIsCompatible()) 
		{
			setupmap()
		}
		else
		{
			alert("Sorry, your Browser does not support Google Maps");
		}   
	}
		

	function setupmap()
	{
		map = new GMap2(document.getElementById("cemeteryMap"));
		
		map.addControl(new GLargeMapControl());
//		map.addControl(new GHierarchicalMapTypeControl());
//		map.addControl(new GMapTypeControl());
		map.addControl(new GMenuMapTypeControl());
		map.addControl(new GScaleControl(500));
		map.addControl(new GOverviewMapControl());

		map.addMapType(G_PHYSICAL_MAP);
		
	  	map.setCenter(new GLatLng(-41.2,175.4),5);		
      	geocoder = new GClientGeocoder();
      
		map.enableDoubleClickZoom();		  
		new GKeyboardHandler(map);
		
		map.enableScrollWheelZoom();

// Monitor the window resize event and let the map know when it occurs - leave code here but it seems to be unnecessary in v2
//		if (window.attachEvent) 
	  	{ 
// 			window.attachEvent("onresize", function() {map.checkResize()} );
//			window.attachEvent("onload", function() {map.checkResize()} );
		} 
//		else
//		{
//			window.addEventListener("resize", function() {map.checkResize()} , false);
//			window.addEventListener("load", function() {map.checkResize()} , false);
//		}

		mgr = new MarkerManager(map, {borderPadding: 10});

	// ====== Create a Client Geocoder ======
		geo = new GClientGeocoder();

	// ====== Array for decoding the failure codes ======
		reasons[G_GEO_SUCCESS]            = "Success";
		reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
		reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
		reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
	
	// Add Div over map to show Lat & Lng of cursor, Cemname etc
		if (infoDisplayEnabled)
		{
			var place = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(6,40));
			place.apply(document.getElementById("infoBox"));
			map.getContainer().appendChild(document.getElementById("infoBox"));
		
	// Add listener to Track & Display Coords of Mouse and update other information

			GEvent.addListener(map, "mousemove", function(point)
			{
				document.getElementById("latpos").firstChild.nodeValue = point.y.toFixed(5);
				document.getElementById("lngpos").firstChild.nodeValue = point.x.toFixed(5);
				updateInfoDisplay();		//show the Number of points and the Zoom level (picks up Zoom changes)
			});
		}
		initialiseStuff();

		getDatabaseInfo(); // and initialise display once data received

	//
	// Check for Command Line options:
	//	- ID = ID of cemetery to display
	// 
		processCommandLine();
	}
	

// Get basic info from database
	function getDatabaseInfo()
	{
		var searchQuery='cemDatabaseq0.php';

		GDownloadUrl(searchQuery , function(nzCemetery)
		{
			var xml = GXml.parse(nzCemetery);
			markers = xml.documentElement.getElementsByTagName("Fields");

			if (markers.length != 0)
			{
				cemListRows=markers[0].getAttribute("Rows");			
				updateInfoDisplay()		//show the Number of points and the Zoom level - called here as initialise called before number is known.
			}
		});
	};
	
//
// Process any Command Line options:
//	- ID = ID of cemetery to display
// 
	qsParm = new Array();							// Commandline parameters		

	function processCommandLine()
	{
		qs()
	// Request to display ID?
		if(qsParm['ID']!=null)
		{
		// Display selected item
			createCemeteryMarkers("byID",qsParm['ID'])
		};
	};	
		
	//
	// read any parameters passed to the map:
	//
   function qs() 
	{
		qsParm.length=0;
		var query = window.location.search.substring(1);
		var parms = query.split('&');
		for (var i=0; i<parms.length; i++) 
		{
			var pos = parms[i].indexOf('=');
			if (pos > 0) 
			{
				var key = parms[i].substring(0,pos);
				var val = parms[i].substring(pos+1);
		// As this is passed in the url spaces appear as %20. Firefox does not convert %20 to a space (IE does) so fix it now
				qsParm[key] = val.replace(/%20/g," ");
			}
		}
	};

// Shows the number of icons displayed and the zoom level in the info box.
	function updateInfoDisplay()
	{
		if(infoDisplayEnabled)
		{
			document.getElementById("mZoom").firstChild.nodeValue = map.getZoom();
			document.getElementById("cCount").firstChild.nodeValue = iMarker+' of '+cemListRows;
		}
	}
	
// Shows the cemetery data in the info box.
	function showCemName(cemlab1,cemlab2)
	{
		if(infoDisplayEnabled)
		{
			document.getElementById("CemName1").firstChild.nodeValue = cemlab1;
			document.getElementById("CemName2").firstChild.nodeValue = cemlab2;
		}
	}


// Download and display cemetery markers
	function createCemeteryMarkers(searchType,searchItem)
	{
	// Define field names
		var cemID, cemNZSG, cemName, cemAdmin, cemMaori, cemChurch, cemCWGC, cemCWGCCode, cemNZWars, cemStatus, cemAddr1, cemAddr2, cemDist, cemProv, cemCountry, cemNote, cemWeb, lat, lng, cemZoom, cemAcc, C_icon, cemText;
	// Misc stuff
		var q0, q1, q2, q3; 

	// Create marker icon
		var
			baseIcon = new GIcon();
			baseIcon.shadow = "Images/shadow.png";
			baseIcon.iconSize = new GSize(20, 34);
			baseIcon.shadowSize = new GSize(37, 34);
			baseIcon.iconAnchor = new GPoint(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			baseIcon.infoShadowAnchor = new GPoint(18, 25);
			baseIcon.transparent = "Images/markerTransparent.png";

//	
// Set up search
//		q0 - the type (by ID or searchTerm)
//		q1 - the searchTerm
//		q2 - the area (true everywhere, false NZ)
//		q3 - the sort order (name, location)
//
 
		q0=searchType;
		
		if (searchType=="byID")
		{
		// Search by ID - will return one place (hopefully) as ID is unique
		//  only used by external command line call
			q1=searchItem;
			document.searchArea.searchAreaResult.checked=true; //force the tickbox true to ensure it searches all data 
		}
		else if (searchType=="byName")
		{	
		// Search by name - will return all places with the name anywhere in their data
		// If q1=
		//	- '*'  			All cemeteries
		//	-	'G Code'	All with accuracy = G
		//	-	'M Code'	All with accuracy = M
		//	-	'P Code'	All with accuracy = P
		//	-	'V Code'	All with accuracy = V
		//	- otherwise All with searchText in data
		// 
			q1=searchItem.replace(/\+/g,"|");  //The Php $_Get function changes + to space and so change + to | here and reverse it in the php code
		}

		// Restrict Search Area?
		//	if searchArea checkbox ticked (true) search everywhere
		//	if searchArea checkbox not ticked (false) search NZ only
		//
			q2=document.searchArea.searchAreaResult.checked;

		// Search by
		//	name			- ORDER BY  cemName, country, province, district, address2
		//	location	- ORDER BY  country, province, district, address2, cemName
			q3=searchSortby;

		var searchQuery='cemDatabaseq1.php?q0='+q0+'&q1='+q1+'&q2='+q2+'&q3='+q3+'&rld='+Math.random();

		GDownloadUrl(searchQuery , function(NZ_Cemeteries)
		{
			var xml = GXml.parse(NZ_Cemeteries);
			markers = xml.documentElement.getElementsByTagName("Fields");

			if (markers.length == 0)
			{
				sideRow=document.createElement("tr");
				sideRow.style.fontSize="10pt";
				sideTBody.appendChild(sideRow);
				sideCell=document.createElement("td");
				sideRow.appendChild(sideCell);
				sideCell.innerHTML="<b>No results found for '"+searchItem+"'.</b><br />Try the first few letters followed by * eg: '"+searchItem.slice(0,4)+"*'<hr>";
			}
			else
			{
				for (var i = 0; i < markers.length; i++) 
				{
					lati=markers[i].getAttribute("Lat");
					lngi=markers[i].getAttribute("Lng");

					if (lati!=null) //Ignore points which aren't positioned
					{
						lat = parseFloat(lati);
						lng = parseFloat(lngi);
					}
					else
					{
						lat = 999;
						lng = 999;
					}
					

					cemNZSG = markers[i].getAttribute("NZSG");
					if (cemNZSG==null) {cemNZSG=""}

					cemName = markers[i].getAttribute("Cem");
					if (cemName==null) {cemName=""};

					cemAdmin = markers[i].getAttribute("Admin");
					if (cemAdmin==null) {cemAdmin=""};
					
					var 
						adminText="",
						adminTextFlag=false;
					
					if (cemAdmin!="")
					{
						adminText=cemAdmin; 
						adminTextFlag=true;
					}

					cemMaori = markers[i].getAttribute("Maori");
					if (cemMaori=='Maori') 
					{
						if (adminTextFlag)
						{
							adminText+=", Maori"
						}
						else
						{
							adminText="Maori"
							adminTextFlag=true;
						}
					} 

					cemChurch = markers[i].getAttribute("Church");
					if (cemChurch==null) {cemChurch=""}
					if (cemChurch!="") 
					{
						if (adminTextFlag)
						{
							adminText+=", "+cemChurch;
						}
						else
						{
							adminText=cemChurch;
							adminTextFlag=true;
						}
					} 

					cemID = markers[i].getAttribute("ID");

					cemCWGC = markers[i].getAttribute("CWGC");

					cemCWGCCode = markers[i].getAttribute("CWGCcode");

					cemNZWars = markers[i].getAttribute("NZWars");
					
					
					cemStatus = markers[i].getAttribute("Status");
					if (cemStatus==null) {cemStatus=""}	

					cemAddr1 = markers[i].getAttribute("Add1");
					if (cemAddr1==null) {cemAddr1=""}

					cemAddr2 = markers[i].getAttribute("Add2");
					if (cemAddr2==null) {cemAddr2=""}
						
					var cemAddr="";
					if (cemAddr1!="")
					{
						cemAddr=cemAddr1
						if (cemAddr2!="")
						{
							cemAddr+=", "+cemAddr2;
						}
					}
					else
					{
						cemAddr=cemAddr2;
					}
					
					cemDist = markers[i].getAttribute("Dist");
					if (cemDist==null) {cemDist=""}

					cemProv = markers[i].getAttribute("Prov");
					if (cemProv==null) {cemProv=""}

					cemCountry = markers[i].getAttribute("Country");
					if (cemCountry==null) {cemCountry=""}

					cemNote = markers[i].getAttribute("Note");
					if (cemNote==null) {cemNote=""}

					cemWeb = markers[i].getAttribute("Web");
					
					cemZoom = parseFloat(markers[i].getAttribute("Zoom"));
					if (cemZoom==null) {cemZoom=9;};

					cemAcc = markers[i].getAttribute("Acc");
					C_icon= new GIcon(baseIcon);
					if (cemAcc!=null) 
					{
						if (cemAcc=="V") 
						{
							cemAcc="Visible"
							C_icon.image = "Images/iconV.png";
						}
						else if (cemAcc=="P") 
						{
							cemAcc="Position correct but not visible"
							C_icon.image = "Images/iconC.png";
						}
						else if (cemAcc=="G") 
						{
							cemAcc="Nearby but exact position is unknown"
							C_icon.image = "Images/iconG.png";
						}
						else if (cemAcc=="M") 
						{
							cemAcc="The position is unknown"
							C_icon.image = "Images/iconQuestion.png";
						}
						}
					else
					{
						cemAcc="";
					}	      

					tableData=
					'<table class="cemMapPopup">'+
						'<tr>'+
							'<td colspan="2" class="cemMapHead">'+cemName+" ("+cemID+")";
						
					if (cemNZSG!="")
					{
						tableData+=
							'<tr>'+
								'<td class="cemMapCol1">NZSG code:'+
								'<td class="cemMapCol2">'+cemNZSG;
					}
					else
					{
						tableData+=
							'<tr>'+
								'<td class="cemMapCol1" colspan="2">There is no NZSG code for this cemetery.';
					}
							
					tableData+=
						'<tr>'+
							'<td class="cemMapCol1">Location:'+
							'<td class="cemMapCol2">'+cemAddr+
						'<tr>'+
							'<td class="cemMapCol1">Council:'+
							'<td class="cemMapCol2">'+cemDist;
								
					if (cemCountry=='New Zealand')
					{
						var provTxt="Province:";
					}
					else
					{
						var provTxt="County:";
					}
							
					tableData+=
						'<tr>'+
							'<td class="cemMapCol1">'+provTxt+
							'<td class="cemMapCol2">'+cemProv;

					if (cemCountry!='New Zealand')
					{
						tableData+=
							'<tr>'+
								'<td class="cemMapCol1">Country:'+
								'<td class="cemMapCol2">'+cemCountry;
					}
						
					tableData+=
						'<tr>'+
							'<td class="cemMapCol1">Administration:'+
							'<td class="cemMapCol2">'+adminText;

					if (cemCWGC!='')
					{
						if (cemCWGCCode=="")
						{
							tableData+=
							'<tr>'+
								'<td class="cemMapCol1">War Graves:'+
								'<td class="cemMapCol2">Cemetery contains service war burials.';
						}
						else
						{
							tableData+=
							'<tr>'+
								'<td class="cemMapCol1">War Graves:'+
								'<td class="cemMapCol2"><a href="http://www.cwgc.org/search/cemetery_details.aspx?cemetery='+cemCWGCCode+'&mode=1" target=_blank>CWGC burial database</a>';							
						}
					}
					
					if (cemNZWars!="")
					{
						tableData+=
						'<tr>'+
							'<td class="cemMapCol1">NZ Wars:'+
								'<td class="cemMapCol2">Contains graves from the 19th C. NZ Land Wars';							
						
					}
							
					tableData+=
						'<tr>'+
							'<td class="cemMapCol1">Status:'+
							'<td class="cemMapCol2">'+cemStatus+
						'<tr>'+
							'<td class="cemMapCol1">Notes:'+
							'<td class="cemMapCol2">'+cemNote+
						'<tr>'+
							'<td class="cemMapCol1">Accuracy:'+
							'<td class="cemMapCol2">'+cemAcc;
								
							
					if(cemWeb=='y')
					{					
						var modifiedName=cemName.replace(/'/,"xx");  //get rid of troublesome quotes (restored later)
						tableData+=
							'<tr>'+
								'<td class="cemMapHead">Web Links:'+
								'<td class="cemMapCol2Link" >'+ 
								'<a onclick="showWebLinks(\''+modifiedName+'\', \''+cemID+'\')">Click to see Web Links</a>';
					}

					tableData+=
						'<tr>'+
							'<td colspan="2" class="cemMapFoot">'+"&#169; 2007-2008 MPL"+

						'</tr>'+
						'</table>';
					

					createSidebarEntry(lat, lng, cemName, cemNZSG, cemAddr1, cemAddr2, cemDist, cemProv, cemCountry, iMarker);

				// Is there a position?
					if(lat!=999)
					{
					// Create the marker
						createCemMarker(C_icon, lat, lng, cemNZSG, cemZoom, tableData, cemName, cemAddr2, iMarker);
						iMarker++;
					}
				}
			}
			updateInfoDisplay();		//show the Number of points and the Zoom level

		// centre the map on the first result
		
		if (iMarker!=0)
		{
			if( map.getZoom()<= iconZoomVisibility)
			{
				var zoomToLevel=zoomTo;
			}
			else
			{
				var zoomToLevel=map.getZoom();
			}
			map.setCenter(new GLatLng(sideMarkers[0].getPoint().lat(),sideMarkers[0].getPoint().lng()),zoomToLevel);
			setTimeout( function() {GEvent.trigger(sideMarkers[0], "click")}, 10);
		}
	//finish sidebar table
		completeSidebar();
			
		});
	}
	
// Creates a marker at the given point with the given label
	// mouseover shows info
	// dblclick zooms in to the zoomlevel
	// click shows a map at the zoomlevel

	function createCemMarker(myicon, lat, lng, cemNZSG, cemzom, infoData, cemlab1, cemlab2, i) 
	{
		var point = new GLatLng(lat,lng);
		var marker = new GMarker(point,{icon:myicon});

		iconMarker.push(marker); //used to manipulate markers ------ Could use sideMarkers instead

		GEvent.addListener(marker, "click", function() {if(!displayPolyIcons){marker.show()}; marker.openInfoWindowHtml(infoData)});  
		GEvent.addListener(marker, "mouseover", function() {showCemName(cemlab1,cemlab2);});
		GEvent.addListener(marker, "dblclick", function() {map.setCenter(point,cemzom); showNumZoom();});
		GEvent.addListener(marker, "mouseout", function() {showCemName("","");});

	//Add Marker visible at level iconZoomVisibility & greater - at which point the province markers vanish
		mgr.addMarker(marker,iconZoomVisibility);
		
	// Save the maker so the side_bar can find it.
		sideMarkers[i] = marker;
	}

//
//	Display Weblinks
//

	function clearWebLinks()
	{
		document.getElementById("webLinks").innerHTML="";
	}
	
	function showWebLinks(cemName, cemCode)
	{
	// Fetch the links from the database
		var 
			linkName, 
			linkURL, 
			linkDatabase,
			linkDesc, 
			linkHeadstone, 
			linkPlan;

		var cemName=cemName.replace(/xx/,"'");  //Restore the quote

		var q0 = cemCode;
	
		var searchQuery='cemDatabaseq2.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload

		GDownloadUrl(searchQuery , function(NZ_Cemeteries)
		{
			var xml = GXml.parse(NZ_Cemeteries);
			markers = xml.documentElement.getElementsByTagName("Fields");

			if (markers.length != 0)
			{

				initialiseSidebar()

				sideRow=document.createElement("tr");
				sideRow.style.fontWeight="bold";
				sideTBody.appendChild(sideRow);
				sideCell=document.createElement("td");
				sideRow.appendChild(sideCell);
				sideCell.innerHTML='Websites containing information for:';

				sideRow=document.createElement("tr");
				sideRow.style.fontWeight="bold";
				sideTBody.appendChild(sideRow);
				sideCell=document.createElement("td");
				sideRow.appendChild(sideCell);
				sideCell.innerHTML=cemName + ' ('+cemCode+')<p>';
				
				for (var i = 0; i < markers.length; i++) 
				{
					linkName=markers[i].getAttribute("linkName");
					linkURL=markers[i].getAttribute("linkWeb");
					linkType=markers[i].getAttribute("linkType");
					linkDesc=markers[i].getAttribute("linkDesc");

					sideRow=document.createElement("tr");
					sideTBody.appendChild(sideRow);
					sideCell=document.createElement("td");
					sideRow.appendChild(sideCell);
					
					var urlText="";

					if (linkDesc=="")
					{
						if(linkType=="db")
						{
							urlText ='<a href="http://'+linkURL+'" target=_blank>Burial Database</a>';
						}
						else if (linkType=="di")
						{
							urlText ='<a href="http://'+linkURL+'" target=_blank>Burial Database (including gravestone photos)</a>';
						}
						else if (linkType=="id")
						{
							urlText ='<a href="http://'+linkURL+'" target=_blank>Partial Burial Database</a>';
						}
						else if(linkType=="pl")
						{
							urlText = '<a href="http://'+linkURL+'" target=_blank>Site Plan</a>';
						}
						else if(linkType=="im")
						{
							urlText = '<a href="http://'+linkURL+'" target=_blank>Photo of Site</a>';
						}
						else if(linkType=="ar")
						{
							urlText = '<a href="http://'+linkURL+'" target=_blank>Article</a>';
						}
						else if(linkType=="kw")
						{
							urlText = '<a href="http://www.kiwicelts.com/mediawiki/index.php/'+linkURL+'" target=_blank>KiwiWiki Article</a>';
						}
						else if(linkType=="fg")
						{
							urlText = '<a href="http://www.findagrave.com/cgi-bin/fg.cgi?page=cr&CRid='+linkURL+'" target=_blank>Find a Grave Database</a>';
						}						
					}
					else
					{
						urlText = '<a href="http://'+linkURL+'" target=_blank>'+linkDesc+'</a>';
					}


					if (linkURL.indexOf('pdf')>-1)
					{
						urlText += " (pdf file)";
					}
					urlText += "<br />"
					sideCell.innerHTML=urlText;

				}
				sideRow=document.createElement("tr");
				sideTBody.appendChild(sideRow);
				sideCell=document.createElement("td");
				sideRow.appendChild(sideCell);
				sideCell.innerHTML='<br /><hr>Click <b>Search</b> again to restore the last result.<p>Please let me know of any broken links.';
			}
			completeSidebar();
		});
	};
	

	
	
//
// This set of functions creates the sideBar
//
	// Declare variables and create the header, footer, and caption.
	var 
		sideTable = document.createElement("TABLE"),
		sideTHead = document.createElement("THEAD"),
		sideTBody = document.createElement("TBODY"),
		sideTFoot = document.createElement("TFOOT"),
		sideCaption = document.createElement("CAPTION"),
		sideRow, 
		sideCell;

	function setupSidebar()
	{
	// Insert the created elements into Table.
		sideTable.appendChild(sideTHead);
		sideTable.appendChild(sideTBody);
		sideTable.appendChild(sideTFoot);
		sideTable.appendChild(sideCaption);

	// Set the table's style
		sideTable.border=0;
  
	};

	// This function picks up the click and opens the corresponding info window
	function sideClick(i)
	{
		if( map.getZoom()<= iconZoomVisibility)
		{
			var zoomToLevel=zoomTo;
		}
		else
		{
			var zoomToLevel=map.getZoom();
		}
		map.setCenter(new GLatLng(sideMarkers[i].getPoint().lat(),sideMarkers[i].getPoint().lng()),zoomToLevel);
		setTimeout( function() {GEvent.trigger(sideMarkers[i], "click")}, 10); 
	}
	  
	function createInitialSidebarEntry()
	{
		setupSidebar();

		sideRow=document.createElement("tr");
		sideRow.style.fontSize="100%";
		sideTBody.appendChild(sideRow);
		sideCell=document.createElement("td");
		sideRow.appendChild(sideCell);
		sideCell.innerHTML=
			"The New Zealand Cemetery database contains all known cemeteries in New Zealand as well as all of the CWGC administered cemeteries worldwide with New Zealand Service graves.<p>"+
			"<b>Searching</b> will list all of the cemeteries in the database with the search text in their name or address.<p>"+
			"You can show the Cemetery's location on the map by clicking the link in the search results.<p>"+
			"For many Cemeteries, links to web sites with burial records, plot maps, photos, historic articles etc are included.<p>"+
			"Click the <b>Help Button</b> above for more detailed assistance in using the map."+
			"<br /><hr>";

		completeSidebar();
	};
	
	function createSidebarEntry(lat, lng, cemName, cemNZSG, cemAddr1, cemAddr2, cemDist, cemProv, cemCountry, i)
	{
	// Clear busy message
		if (i==0)
		{
			initialiseSidebar();
		}
		
		sideRow=document.createElement("tr");
		sideRow.style.fontSize="100%";
		sideRow.style.fontWeight="bold";
		sideTBody.appendChild(sideRow);
		sideCell=document.createElement("td");
		sideRow.appendChild(sideCell);
	// Does the site have a position?	
		if (lat!=999)
		{
		// Yes
			sideCell.innerHTML='<a href="javascript:sideClick(' + i + ')">' + cemName + '</a>';
		}
		else
		{
		// No
			sideCell.innerHTML=cemName;
		}

		if (cemNZSG != "")
		{
			sideCell=document.createElement("td");
			sideRow.appendChild(sideCell);
			sideCell.innerHTML=cemNZSG;
		}

		if (cemAddr1 != "")
		{
			sideRow=document.createElement("tr");
			sideTBody.appendChild(sideRow);
			sideCell=document.createElement("td");
			sideRow.appendChild(sideCell);
			sideCell.innerHTML=cemAddr1;
		}
		
		if (cemAddr2 != "")
		{
			sideRow=document.createElement("tr");
			sideTBody.appendChild(sideRow);
			sideCell=document.createElement("td");
			sideRow.appendChild(sideCell);
			sideCell.innerHTML=cemAddr2;
		}
		
		if (cemDist != "")
		{
			sideRow=document.createElement("tr");
			sideTBody.appendChild(sideRow);
			sideCell=document.createElement("td");
			sideRow.appendChild(sideCell);
			sideCell.innerHTML=cemDist;
		}

		sideRow=document.createElement("tr");
		sideTBody.appendChild(sideRow);
		sideCell=document.createElement("td");
		if (cemProv != "")
		{
			sideRow.appendChild(sideCell);
			sideCell.innerHTML=cemProv;		
		}
		else
		{
			sideRow.appendChild(sideCell);
			sideCell.innerHTML='&#160';
		}
				
		sideCell=document.createElement("td");
		if (cemCountry != "New Zealand")
		{
			sideRow.appendChild(sideCell);
			sideCell.innerHTML=cemCountry;
		}
		else
		{
			sideRow.appendChild(sideCell);
			sideCell.innerHTML='&#160';
		}
				
		sideRow=document.createElement("tr");
		sideTBody.appendChild(sideRow);
		sideCell=document.createElement("td");
		sideRow.appendChild(sideCell);
		sideCell.innerHTML="&#160";		
	};

	function completeSidebar()
	{
	// Insert the table into the document.
		var sideBarId=document.getElementById("mapSideBarResults");
		sideBarId.appendChild(sideTable);
		tableLoaded=true;
	};
	
	function initialiseSidebar()
	{
	// Clear table if it exists
		if (tableLoaded)
		{
			for (var i = sideTable.tBodies[0].rows.length-1; i >= 0 ; i--) 
			{
				sideTable.tBodies[0].deleteRow(i);
			}
		}
	}
	
//
//	User Functions
//

//
//	Search box
//

		
	function mapSearch(filterData)
	{
	// Setup the sidebar
		document.searchForm.iFindText.focus();
		document.searchForm.iFindText.select();
		initialiseSidebar();

	// Initial message
		sideRow=document.createElement("tr");
		sideRow.style.fontSize="100%";
		sideRow.style.fontWeight="bold";
		sideTBody.appendChild(sideRow);
		sideCell=document.createElement("td");
		sideRow.appendChild(sideCell);
		sideCell.innerHTML="Fetching data ...";

		iMarker = 0;			// initialise counter for sidebar array
		mgr.clearMarkers();	// get rid of existing markers
		map.clearOverlays();
		setupSidebar();		//set up sidebar table
		
		if (searchFor=="data")
		{
			createCemeteryMarkers("byName",filterData);
		}
		else
		{
			showAddress(filterData)
		};
	};
	
	function clickSearch()
	{
		document.searchForm.iFindText.focus();
		document.searchForm.iFindText.select();
	};
		
//
//	Saves search type when radio button is changed
//
	function saveSearchType(type)
	{
		searchFor=type;
	};

//
//	Saves search sort order when radio button is changed
//
	function saveSearchSort(type)
	{
		searchSortby=type;
	};
	
	

//
//	Reset button
//
	function mapReset()
	{
	// Initialise map by clearing markers and icons and resetting view
		map.setCenter(new GLatLng(-41.2,175.4),5);		
		mgr.clearMarkers();
		map.clearOverlays();
		map.setMapType(G_NORMAL_MAP );
		
		initialiseStuff();
	};

//
//	Initialise Stuff (no map stuff as this is also called from startup)
//
	function initialiseStuff()
	{
	// Setup the sidebar
		initialiseSidebar();
		createInitialSidebarEntry()
		
	// Reset the Info display
		iMarker=0;
		updateInfoDisplay()		//show the Number of points and the Zoom level
		
	// Reset the data entry forms
		resetForms();
		document.searchForm.iFindText.value="Enter Search Text"
		
	// Initialise the search type
		searchFor="data";

	// and the radio buttons
		document.searchType.searchTypeResult.value="data";	

		document.searchSort.searchSortResult.value="name";
		
		document.searchArea.searchAreaResult.checked=false;	
	

	// Setup Icon button
		displayPolyIcons=displayPolyIconsStart;  // as iconButton will toggle it
		button=document.getElementById('iconbutton');
		if (displayPolyIcons)
		{
			button.value=iconOffText;
		}
		else
		{
			button.value=iconOnText;
		};		
	}

// When Icon On/Off button selected
	function iconButton(buttonobj)
	{
		displayPolyIcons = !displayPolyIcons; 
		button=document.getElementById('iconbutton');
		if (displayPolyIcons)
		{
			button.value=iconOffText;
		}
		else
		{
			button.value=iconOnText;
		};

		for (i=0 ; i<iconMarker.length ; i++)
		{
			if (displayPolyIcons)
			{
				iconMarker[i].show();
			}
			else
			{
				iconMarker[i].hide();
				map.closeInfoWindow();				
			}
		}
	}


//
//	Reset the entry forms
//
	function resetForms()
	{
		for (i=0; i < document.forms.length; i++) 
   		{
			document.forms[i].reset();
		}
	};

	
 
// ====== Geocoding ======
	function showAddress(search)
	{
		
	// ====== Perform the Geocoding ======        
		geo.getLocations(search, function (result) {
		// If search was successful
			if (result.Status.code == G_GEO_SUCCESS)
			{
			// Display the number of results found
				sideRow=document.createElement("tr");
				sideRow.style.fontSize="100%";
				sideRow.style.fontWeight="bold";
				sideTBody.appendChild(sideRow);
				sideCell=document.createElement("td");
				sideRow.appendChild(sideCell);
				if (result.Placemark.length==1)
				{
					sideCell.innerHTML="Found " +result.Placemark.length +" result:";
				}
				else
				{
					sideCell.innerHTML="Found " +result.Placemark.length +" results:";
				}
				
			// Loop through the results, placing markers
				for (var i=0; i<result.Placemark.length; i++)
				{
					var p = result.Placemark[i].Point.coordinates;
					var lat = p[1];
					var lng = p[0];
					var q = result.Placemark[i].address.split(", ");


					var addressData=
         				'<table class="cemMapPopup">'+
         					'<tr class="cemMapHead">'+
          		            '<td colspan="2" class="cemMapTB">Search Results';

					for (var r=0; r<q.length ; r++)
					{
						addressData+= '<tr>';
							if (r==0)
							{
								addressData+='<td class="cemMapCol1">Place:';
							}
							else
							{
								addressData+='<td class="cemMapCol1">';
							}
						addressData+='<td class="cemMapCol2">'+q[r];
					};

						addressData+=			
         					'<tr>'+
         			   	   '<td class="cemMapCol1">'+
         			      	'<td class="cemMapCol2">&#160;'+
         					'<tr>'+
         			   	   '<td class="cemMapCol1">Location:'+
         			      	'<td class="cemMapCol2">'+p[1]+', '+p[0]+
                     	'<tr>'+
         		            '<td colspan="2" class="cemMapFoot">&#169; 2007-2008 MPL'+
                     	'</tr>'+
               		'</table>';
						
					createSearchMarker(lat, lng, addressData, i);

				
				// Put address into sidebar
					sideRow=document.createElement("tr");
					sideTBody.appendChild(sideRow);
					sideCell=document.createElement("td");
					sideRow.appendChild(sideCell);
					sideCell.innerHTML=i+1+': <a href="javascript:sideClick(' + i + ')">' + result.Placemark[i].address + '</a><br />&#160;&#160;&#160;&#160;'+p[1]+', '+p[0];

					iMarker++;
				}

				sideRow=document.createElement("tr");
				sideTBody.appendChild(sideRow);
				sideCell=document.createElement("td");
				sideRow.appendChild(sideCell);
				sideCell.innerHTML="<hr>";

			// centre the map on the first result and open info window
				var p = result.Placemark[0].Point.coordinates;
				if( map.getZoom()<= iconZoomVisibility)
				{
					var zoomToLevel=zoomTo;
				}
				else
				{
					var zoomToLevel=map.getZoom();
				}
	
				map.setCenter(new GLatLng(p[1],p[0]),zoomToLevel);
				setTimeout( function() {GEvent.trigger(sideMarkers[0], "click")}, 10);
			}
			// ====== Decode the error status ======
			else
			{
			// Display error
				var reason="Code "+result.Status.code;
				if (reasons[result.Status.code])
				{
					reason = reasons[result.Status.code]
				}
				sideRow=document.createElement("tr");
				sideTBody.appendChild(sideRow);
				sideCell=document.createElement("td");
				sideRow.appendChild(sideCell);
				sideCell.innerHTML='<b>Could not find "'+search+ '" .</b><br />' + reason;
			}
		});
	};

	function createSearchMarker(lat, lng, infoData, i) 
	{
		var point = new GLatLng(lat,lng);
		var marker = new GMarker(point);
		iconMarker.push(marker); //used to manipulate markers
		GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(infoData);});

	//Add Marker visible at level iconZoomVisibility & greater - at which point the province markers vanish
		map.addOverlay(marker);
		
	// Save the maker so the side_bar can find it.
		sideMarkers[i] = marker;
	}

