// ------------------------------------------------------------ Global Variables and Constants ------------------------------
//
//

// Debug
	var
		idDisplay = false;

//	Constants
	var
		mapImage='./mapImages/',					// Path to the icon and other images

		displayPolyIconsStart = true,				// Set True (False) to start with Polygon Icons on / off  
		displayPolyIcons,
		iconOnText = 'Icons On',
		iconOffText = 'Icons Off',
		searchText='... search text',
		copyrightNotice='&#169; 2007, 2008, 2009 Murray Lynn',		
//
// Global variables
//
		searchType,
		showMarkerWindow,									//used to ensure only the first popup Window is displayed when using "show all".
		map,													//the actual map
		geo,
		reasons=[],
		polyIcon,
		qsParm = new Array(),							// Commandline parameters
		tableLoaded,	

// Settings from database
		version,
		groupTable,											// this points to the table with the group information (accessed by groupname+'.php')
		placeTable,											// this points to the table with the place data
		placeinTable,										// this points to the table with the place in data
		groupSelectedStart,								// Initial groupSelected - from settings table
		subgroupSelectedStart,							// Initial subgroupSelected - from settings table
		extendedDataUrl,
		polygonLineOpacity,
		polygonFillOpacity,
		encodedLineNumber,
		encodedLineZoom,
		latStart,
		lngStart,
		zoomStart,

	// Settings related variables 
		groupSelected,										// Current groupSelected
		groupListSelected,								// ID of Current groupListSelected
		groupListSelectedName,							// Name of Current groupListSelected
		subgroupSelected,									// Current subgroupSelected
		subgroupSelectedID,								// ID of current subgroupSelected 
		subgroupListSelected,							// ID of Current subgroupListSelected
		subgroupListSelectedName,						// Name of Current subgroupListSelected
		contributorName = new Array(),				// Name of contributor to database
		contributorInitials= new Array(),			// Initials of contributor to database
		contributorPrivacy = new Array(),			// Privacy of contributor to database (1 - don't show, 2 - initials only, 3 - full details)

// ... and some more Settings 

// Group info from database
		groupName = new Array(),						// Group names
		groupNamePlural = new Array(),				// Group plural names
		groupTable = new Array(),						// Group sqlTable name
		grouplineColourNormalMap = new Array(),	// Group outline colour - normal map
		grouplineColourSatellite = new Array(),	// Group outline colour - satellite or hybrid map
		grouplineWidth = new Array(),					// Group outline width
		groupminZoom = new Array(),					// Group minZoom - the zoom level the Icons appear at
		groupmaxZoom = new Array(),					// Group maxZoom - the zoom level the Icons disappear at
		groupShow = new Array(),						// Group included in the Group pulldown selection list?
		subgroupShow = new Array(),					// Group included in the subGroup pulldown selection list?
		groupIconID = new Array(),						// Group Icon

//	Odds & Ends
		polygonDownloaded = new Array(),				// keeps track of which polygons have been downloaded	- the polygon
		polygonIDDownloaded = new Array(),			// keeps track of which polygons have been downloaded - the ID		
		iconDownloaded = new Array(),					// keeps track of which icons have been downloaded - in theory same as polygons, but keep independant for now		
		iconMarker = new Array (),						// array of icon markers	
		sideMarker = new Array (),						// array of icin markers for geo search
		entry,												// used for data entry

// Create marker icon for Polygons
		polyIcon = new GIcon();
		polyIcon.shadow = mapImage+"shadow.png";
		polyIcon.iconSize = new GSize(20, 34);
		polyIcon.shadowSize = new GSize(37, 34);
		polyIcon.iconAnchor = new GPoint(9, 34);
		polyIcon.infoWindowAnchor = new GPoint(9, 2);
		polyIcon.infoShadowAnchor = new GPoint(18, 25);
		polyIcon.transparent = mapImage+"markerTransparent.png";

// ------------------------------------------------------------ Setup the Map -----------------------------------------------
//
//	Started from the Map webpage with: <body onload="loadMap('ireSettings')" onunload="GUnload()" > 
//			ireSettings..		- table containing the Settings and +'.php' the php file to access it
//
//	Another Webpage can call the Map Program and pass parameters which overide the local calls
//
// To center the map differently: 
//		<a class="mapLink" href="Ulster_Map.html?Lat=54.82808&Lng=-6.40778&Zoom=13" target="_blank"> ...
//
//			Lat, Lng			- startup map center
//			Zoom					- startup map zoom
//
//	and / or ...
// 
//	To display a specific polygon or group of polygons (identical to clicking on an item in the pulldown)
//			GroupLevel	- the level of the group 	= groupSelected 
//			GroupName		- the name of the group 	= groupListSelectedName
//			Level				- the level of the item		= subgroupSelected
//			Name				- the name of the item	 	= subgroupListSelectedName
//
// and / or ...
//
//	To enable diagnostics:
//			Diagnostics = 1
//

   function loadMap(settingsTable)
	{
		//
		// Warning to me only!
		//
      if (settingsTable== '') 
      {
	      alert("You haven't specified a datafile");
      }
		
      if (GBrowserIsCompatible()) 
		{

      //
      // reset forms - they can retain the last startup values
      //			
			resetForms();
      // 
      //	Read any command line parameters
      //
         qs();
			
// Process parameters for initial position:
//		- Lat
//		- Lng
//		- Zoom

   		if (qsParm['Lat']!=null && qsParm['Lng']!=null && qsParm['Zoom']!=null)
   		{
   			zoomStart=qsParm['Zoom'];
   			latStart=qsParm['Lat'];
				lngStart=qsParm['Lng'];
   		};
			
			if (qsParm['Diagnostics']==1)
			{
				idDisplay=true;
			}

//
//	Read in the Settings from the database
//
//		version								-	currently just the date
//		groupTable						-	this points to the table with the group information (accessed by groupname+'.php')
//		placeTable						-	this points to the table with the place data
//		placeinTable					-	this points to the table with the place in data
//		extendedDataUrl				-	the URL for a program to display additional data  - linked in the popup menus
//		listLevelInitial			-	the initial group number for Pulldown list items 
//		groupbyLevelInitial		-	the inital group number for Pulldown list group  
//		polygonLineOpacity		-	the opacity of all polygon lines
//		polygonFillOpacity		-	the opacity of all polygon fills
//		encodedLineNumber			-	setting for line compression - see google documentation
//		encodedLineZoom				-	setting for line compression - see google documentation	
//		latStart							-	startup position
//		lngStart							-			"
//		zoomStart							-			"
//

			settingsFile = settingsTable +'.php?q0='+settingsTable+'&rld='+Math.random();  // rld variable to force reload

   		GDownloadUrl(settingsFile , function(datafile)
   		{
         	var xmlLines = GXml.parse(datafile);
	  	// Get overall settings
   			var settings =  xmlLines.documentElement.getElementsByTagName("settings");
   
   			for (var a = 0; a < settings.length; a++) 
            {
      			version = settings[a].getAttribute("version");
      			groupTable = settings[a].getAttribute("groupTable");
						placeTable = settings[a].getAttribute("placeTable");
						placeinTable = settings[a].getAttribute("placeinTable");
      			subgroupSelectedStart = settings[a].getAttribute("subgroupSelectedStart");
      			groupSelectedStart = settings[a].getAttribute("groupSelectedStart");
      			extendedDataUrl = settings[a].getAttribute("extendedDataUrl");
          	polygonLineOpacity = settings[a].getAttribute("polygonLineOpacity");
         		polygonFillOpacity = settings[a].getAttribute("polygonFillOpacity");
         		encodedLineNumber = settings[a].getAttribute("encodedLineNumber");
         		encodedLineZoom = settings[a].getAttribute("encodedLineZoom");

				// only fetch these if the commandline parameters are omitted
      			if (latStart==null) {latStart = parseFloat(settings[a].getAttribute("latStart"));}
      			if (lngStart==null) {lngStart = parseFloat(settings[a].getAttribute("lngStart"));}
      			if (zoomStart==null) {zoomStart = parseFloat(settings[a].getAttribute("zoomStart"));}
   			}
		//
		//	Remember this is Asynch - the data is ready now ...
		//
      //
      //		And now set up the map
      //

  				setupmap();
			});
	   }
		else
		{
			alert("Sorry, your Browser does not support Google Maps");
		}
   }
		
//
// 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," ");
         }
      }
   }

//
//	Now the housekeeping is complete, set up the actual Map and read in the data
//
	function setupmap()
	{
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
//		map.addControl(new GHierarchicalMapTypeControl());
		map.addControl(new GMapTypeControl());
//		map.addControl(new GMenuMapTypeControl());  // Pull down Map Type menu

		map.addControl(new GScaleControl(500));
		map.addControl(new GOverviewMapControl());
		map.addMapType(G_PHYSICAL_MAP);


		map.enableDoubleClickZoom();		  
		new GKeyboardHandler(map);

		map.enableScrollWheelZoom();
		
		latStart=parseFloat(latStart);
		lngStart=parseFloat(lngStart);
		zoomStart=parseFloat(zoomStart);

		map.setMapType(G_SATELLITE_MAP ); // Set initial map

//
//	Map types:
//
//		G_NORMAL_MAP
//		G_SATELLITE_MAP
//		G_HYBRID_MAP
//		G_PHYSICAL_MAP
//

		map.setCenter(new GLatLng(latStart, lngStart), zoomStart);		
		
	// Add Div over map to show assorted data
		var place = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5,40));
		place.apply(document.getElementById("mapInfoBox"));
		map.getContainer().appendChild(document.getElementById("mapInfoBox"));
		
	// Add listener to Track & Display Coords of Mouse in the infoBox

		GEvent.addListener(map, "mousemove", function(point)
		{
			document.getElementById("latpos").firstChild.nodeValue = point.y.toFixed(5);
			document.getElementById("lngpos").firstChild.nodeValue = point.x.toFixed(5);
			showNumZoom();		//show the Number of points and the Zoom level (picks up Zoom changes)
		});

	// ====== 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.";


//	Now get the Group Information
		groupFile = groupTable +'.php?q0='+groupTable+'&rld='+Math.random();  // rld variable to force reload

		GDownloadUrl(groupFile , function(datafile)
		{
      	var dataRows = GXml.parse(datafile);

	// Get the group info
	//
	//	Group Names - the index into the array is the same as Level
	//		name 							name of the group
	//		namePlural					plural of name
	//		lineColourNormal			colour of the outline in Normal mode
	//		lineColourSatellite		colour of the outline in Satellite mode
	//		lineWidth					width of outline
	//		maxZoom						the max zoom level at which icons for this group appear
	//		minZoom						the min zoom level at which icons for this group appear
	//		groupShow					show this item in the groupSelection list?
	//		s0 ...						is Group 0 ... included in this item's subgroup selection list?
	//		groupIconID					the Icon for this group
	//

			var groups =  dataRows.documentElement.getElementsByTagName("group");

	//	Create 2d array for the Group Selection data 
			for (a=0; a < groups.length; a++) 
			{
				subgroupShow[a]=new Array()
			}

			for (var a = 0; a < groups.length; a++) 
			{
				groupName[a]= groups[a].getAttribute("name");
				groupNamePlural[a]= groups[a].getAttribute("namePlural");
				grouplineColourNormalMap[a]= groups[a].getAttribute("lineColourNormal");
				grouplineColourSatellite[a]= groups[a].getAttribute("lineColourSatellite");
				grouplineWidth[a]= parseFloat(groups[a].getAttribute("lineWidth"));
				groupminZoom[a]= parseFloat(groups[a].getAttribute("minZoom"));
				groupmaxZoom[a]= parseFloat(groups[a].getAttribute("maxZoom"));
				groupShow[a]= groups[a].getAttribute("groupShow");
				groupIconID[a] = groups[a].getAttribute("groupIconID");
			// One per list item
				for (var b = 0; b < groups.length; b++)
				{
					subgroupShow[b][a]= groups[a].getAttribute("s"+b);
				}
			}

		//
		//	Remember this is Asynch - the data is ready now ...
		//


		//	Initialise stuff	
			initialiseMisc();
		// Display any command line selections
			displayCommandLinePolygons();
		});


//	And get the contributor information
		contributorFile = 'ireContributors.php?rld='+Math.random();  // rld variable to force reload

		GDownloadUrl(contributorFile , function(datafile)
		{
			var dataRows = GXml.parse(datafile);

			var contributors =  dataRows.documentElement.getElementsByTagName("group");

			for (var a = 0; a < contributors.length; a++) 
      {
				contributorInitials[a]= contributors[a].getAttribute("initial");
				contributorName[a]= contributors[a].getAttribute("name");
				contributorPrivacy[a]= contributors[a].getAttribute("privacy");
			}
		});

	};


//
//  Initialise stuff
//
	function initialiseMisc()
	{

	//  Write the version number in the infoBox
		entry = version;
		if (idDisplay){entry += " diagnostics on"};
		
		document.getElementById("Version").firstChild.nodeValue = entry;		

	//	Setup Icon button
		displayPolyIcons=displayPolyIconsStart;  // as iconButton will toggle it
		button=document.getElementById('iconbutton');
		if (displayPolyIcons)
		{
			button.value=iconOffText;
		}
		else
		{
			button.value=iconOnText;
		};
		
	// Reset arrays storing the downloaded data		
		polygonDownloaded.length = 0;		
		polygonIDDownloaded.length = 0;		
		iconDownloaded.length = 0;	

		
	//	Initialise pulldown lists
		groupSelected = groupSelectedStart;
		groupListSelected = -1;
		groupListSelectedName = -1;
		subgroupSelected = subgroupSelectedStart;
		subgroupListSelected = -1;

		buildGroupSelection();								// Build the groupSelect menu
		buildSubgroupSelection(); 							// Build the subGroupSelect menu
		buildGroupSelectionList();							// Build the groupSelectList menu
		buildSubgroupSelection(); 							// Build the subGroupSelect menu
		initialiseSubgroupSelectionList();				// Clear the subgroupSelectionList now as nothing selected at this time				 			

	// Initialise Search stuff
		initialiseSearch();
		initialiseSidebar();
		createInitialSidebarEntry();
		
	};
	
	function displayCommandLinePolygons()
	{
//			GroupLevel	- the level of the group 	= groupSelected 
//			GroupName	- the name of the group 	= groupListSelectedName
//			Level			- the level of the item		= subgroupSelected
//			Name			- the name of the item	 	= subgroupListSelectedName
/*		
		if(qsParm['group']!=null && qsParm['groupName']!= null && qsParm['subgroup'] != null && qsParm['subgroupName'] != null)
		{
   		groupSelected =qsParm['group'];
   		groupListSelectedName =qsParm['groupName'];
   		subgroupSelected =qsParm['subgroup'];
   		subgroupListSelectedName = qsParm['subgroupName'];
			displaySelectedItem();
		}
*/
	}


//
// ------------------------------------------------------------ Build the pull down lists -----------------------------------
//
//

	function addItemToPulldownList(group,item,title,selected)
	{
		opt=document.createElement("option");
		opt.setAttribute("value",item);
		opt.appendChild(document.createTextNode(item));
		opt.setAttribute("title",title);
		if (selected=='y')
		{
			opt.setAttribute("selected","selected");
		}
		group.appendChild(opt);	
	};

	function clearList(group)
	{
		itemList=document.getElementById(group);

		for (i=itemList.options.length-1; i>-1 ;i--)
		{
			itemList.options[i] = null;
		}
	};

//
//		Build the groupSelection pulldown menu
//		Built once on startup
//
	function buildGroupSelection()
	{
		clearList("groupSelection");

		var selected;
		group=document.getElementById("groupSelection");
		for (var a = groupName.length-1; a>-1 ;a--)
		{
			if (groupShow[a]=="y")
			{
				if(a==groupSelected){selected="y"}else{selected="n"}
   	      addItemToPulldownList(group,groupName[a],a,selected)
			}
		}
	};

//
//		Build the groupSelectionList pulldown menu (2nd list)
//		Built each time groupSelect is changed
//
//
	function buildGroupSelectionList()
	{
		var 
			name = new Array(),
			id = new Array(),
			county = new Array(),
			q0=groupSelected;

		var groupFile='ireCensus1851q2.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload

		GDownloadUrl(groupFile , function(datafile)
		{
			var dataRows = GXml.parse(datafile);
   
			// Get overall settings
			var data =  dataRows.documentElement.getElementsByTagName("line");

			for (var a = 0; a < data.length; a++) 
			{
				name[a] = data[a].getAttribute('name');
				id[a] = data[a].getAttribute('id');
				county[a] = data[a].getAttribute('county');
			}
		//
		//	Remember this is Asynch - the data is ready now ...
		//

			clearList("groupSelectionList");

			group=document.getElementById("groupSelectionList");
			addItemToPulldownList(group," select a "+groupName[groupSelected],-1,'y')
			addItemToPulldownList(group,"("+name.length+" in database)",-1,'n')
			addItemToPulldownList(group,"",-1,'n')

			if(name.length!=0)
			{
			//go get the list pointed to by selection
				for (var a = 0; a<name.length; a++)
				{
					if (groupSelected<=3)
					{
						entry=name[a]+" ["+county[a]+"]";
					}
					else{
						entry=name[a];
					}
					addItemToPulldownList(group,entry,id[a],'n')
				}
				}
				else
				{
					addItemToPulldownList(group,'No entries for '+groupListSelectedName,-1, 'n')
			}
   	});
	};
	
//
//		Build the subgroupSelection pulldown menu (3rd list)
//		Built each time groupSelect is changed
//
	function buildSubgroupSelection()
	{
	// default to subgroupSelected unless it is 1 - then default to level 0
		if (groupSelected==1||groupSelected==2)
		{
			subgroupSelected = 0;
		}
		else
		{
			subgroupSelected = subgroupSelectedStart;
		}

		clearList("subgroupSelection");
		group=document.getElementById("subgroupSelection");
		for (var b = groupName.length-1; b>-1 ;b--)
		{
			if(subgroupShow[b][groupSelected]=='y')
			{
				if(b==subgroupSelected){selected="y"}else{selected="n"}
				addItemToPulldownList(group,groupName[b],b,selected)
			}
		}
	};

//
//		Build the subgroupSelectionList pulldown menu
//		Built each time groupSelectList or subGroup is changed
//			also on initialisation
//
	function buildSubgroupSelectionList()
	{
		var 
			name = new Array(),
			id  = new Array();
		
		if (groupListSelected == -1) 
		{
	     	clearList("subgroupSelectionList");
   	  	group=document.getElementById("subgroupSelectionList");
	     	addItemToPulldownList(group,'Select a '+ groupName[groupSelected] +' first',-1,'y');
		}
		else
		{
		// Display busy message
			clearList("subgroupSelectionList");
			group=document.getElementById("subgroupSelectionList");
			addItemToPulldownList(group,'Downloading data, please wait...',-1,'y');

		var
			q0=subgroupSelected,
			q1=groupListSelected;
			
			var groupFile='ireCensus1851q3.php?q0='+q0+'&q1='+q1+'&rld='+Math.random();  // rld variable to force reload

     		GDownloadUrl(groupFile , function(datafile)
   		{
           	var dataRows = GXml.parse(datafile);
      
        	// Get overall settings
        		var data =  dataRows.documentElement.getElementsByTagName("line");

        		for (var a = 0; a < data.length; a++) 
            {
        			name[a] = data[a].getAttribute('name');
        			id[a] = data[a].getAttribute('id');
        		}

   		//
   		//	Remember this is Asynch - the data is ready now ...
   		//
				if(name.length!=0)
				{
	         //go get the list pointed to by selection

					clearList("subgroupSelectionList");
					group=document.getElementById("subgroupSelectionList");
					addItemToPulldownList(group," select "+groupName[subgroupSelected]+" ... ("+name.length+")",-1,'y');
					addItemToPulldownList(group,"",-1,'n');
					addItemToPulldownList(group,"... show all "+groupNamePlural[subgroupSelected]+" ...","all",'n');

					for (var a = 0; a<name.length; a++)
					{
						addItemToPulldownList(group,name[a],id[a], 'n');
					};
				}
				else
				{
					clearList("subgroupSelectionList");
					group=document.getElementById("subgroupSelectionList");
					addItemToPulldownList(group,'No entries for '+groupListSelectedName,-1, 'y');
				}
      	});
		}
	};

	
	// Initialise the subGroupSelectList menu - blank at this stage - so clear it and put message line in
	function initialiseSubgroupSelectionList()
	{
		clearList("subgroupSelectionList");
		group=document.getElementById("subgroupSelectionList");
		addItemToPulldownList(group,'Select a '+ groupName[groupSelected] +' first',-1,'y')
	}
	

//
// -------------------------------------- Build polygon and marker icon ------------------------------------------ 
//				can be selected from subgroupList - either 'all' or a particular item
//				or as the result of a search
//
//		type=all
//			var0= subgroupSelected (the item type)
//			var1= groupListSelected (the group ID)
//
//		type=item OR map OR detail
//			var0= itemID
//			var1= {blank}
//
// if item is 'detail' closeInfoWindow

	function displaySelectedItem(type, var0, var1)
	{
	// data from Database
		var 
		ireID = new Array(), 
		ireName = new Array(),
		ireAck = new Array(),
		ireArea = new Array(),
		ireLatOffset = new Array(), 
		ireLngOffset = new Array(), 
		ireNotes = new Array(),
		ireLevel = new Array(),
		ireType = new Array(),
		irePolyEnc = new Array(),
		irePolyVer = new Array(),

		ireContributor,					// the person who drew the district's map
		averageLat=0,						// average latitude
		averageLng=0,						// average longitude
		averageNo=0;						// average count

		if (type == 'detail')
		{
			map.closeInfoWindow();
		}

   	if(type == 'all')
		{
			var groupFile='ireCensus1851q4.php?q0='+var0+'&q1='+var1+'&rld='+Math.random();  // rld variable to force reload
		}
		else if (type == 'map' || type == 'item' || type == 'detail')
		{
			var groupFile='ireCensus1851q11.php?q0='+var0+'&rld='+Math.random();  // rld variable to force reload
		}

		GDownloadUrl(groupFile , function(datafile)
		{
			var dataRows = GXml.parse(datafile);

			// Get overall settings
			var data =  dataRows.documentElement.getElementsByTagName("line");

			for (var a = 0; a < data.length; a++)
			{
				ireID[a] = data[a].getAttribute('ireID');
				ireName[a] = data[a].getAttribute('ireName');
				ireAck[a] = data[a].getAttribute('ireAck');
				ireLatOffset[a] = parseFloat(data[a].getAttribute('ireLatOffset'));
				ireLngOffset[a] = parseFloat(data[a].getAttribute('ireLngOffset'));
				ireArea[a] = data[a].getAttribute('ireArea');
				ireNotes[a] = data[a].getAttribute('ireNotes');
				ireLevel[a] = parseFloat(data[a].getAttribute('ireLevel'));
				ireType[a] = parseFloat(data[a].getAttribute('ireType'));
				irePolyEnc[a] = data[a].getAttribute('irePolyEnc');
				irePolyVer[a] = data[a].getAttribute('irePolyVer');
			}

		//
		//	Remember this is Asynch - the data is ready now ...
		//

	// This code could do with a tidy up at some stage 

			for (var a = 0; a < data.length; a++)
			{
			// Basic check that the database is ok:- if there is a contributor, irePolyEnc[a] and irePolyVer[a] should be non-blank
				if (ireAck[a]!="" && (irePolyEnc[a]=="" || irePolyVer[a] ==""))
				{
				// Error in database, don't process
				// If diagnostics on display alert
					if(idDisplay==1)
					{
						alert("The Polygon data is missing from "+ireID[a]+", "+ireName[a]);
					}
				}
				else
				{
				// Is there a polygon associated with the data?
					if (ireAck[a]!="")
					{
					//
					// Find the contributor in the database (-1 if not found)
					//

						ireContributor=-1;
						for (var c = 0; c < contributorInitials.length; c++)
						{
							if (ireAck[a]==contributorInitials[c]) {ireContributor=c}
						}

					// create the polygon - we need the center later regardless - added later if it doesn't exist
						var polygon = createPolygon(ireLevel[a], irePolyEnc[a], irePolyVer[a]);

					// Yes, is it already downloaded - is it's ID in the list?
						var downloaded = -1;
						for (i=0; i< polygonIDDownloaded.length; i++)
						{
							if(polygonIDDownloaded[i]==ireID[a])
							{
									downloaded = i;
							}
						}

						if (downloaded==-1)
						{
						// No, so create it
							polygonIDDownloaded.push(ireID[a]);
	//						polygonDownloaded.push(polygon);
							map.addOverlay(polygon);
						}
						else
						{
	//						polygon=polygonDownloaded[downloaded];
						}

					//	and find the polygon's center
						var polyLat = polygon.getBounds().getCenter().lat()+ireLatOffset[a]; 			//latitude of centre of rectangle containing polygon 
						var polyLng = polygon.getBounds().getCenter().lng()+ireLngOffset[a]; 			//longitude of centre of rectangle containing polygon 

					}
					else
					{
					// No, and so the marker is positioned solely by the coordinates in the 'Offset'
						var polyLat = ireLatOffset[a]; 
						var polyLng = ireLngOffset[a];
					}
					averageLat+=polyLat;
					averageLng+=polyLng;
					var markerExists = Math.abs(polyLat)+Math.abs(polyLng);
					if (markerExists > 1){averageNo++;}; // to omit places with no data (a place at 0,0 is unlikely!)

				//	Now create the Marker
				//	Already downloaded?
					var downloaded = false;

				// Clear showMarker. This ensures only one Marker is displayed. showMarker is set by createPolygonMarker when using "show all". 
					showMarkerWindow = false; 

					for (i=0; i< iconDownloaded.length; i++){	if(iconDownloaded[i]==ireID[a]){downloaded=true;}}

				// Is the position 0,0 - if so don't create
					if (!downloaded && (polyLat+polyLng!=0))
					{
					// No, so create it
						iconDownloaded.push(ireID[a]);
						marker = createPolygonMarker(polyLat, polyLng, ireLevel[a], ireType[a], ireID[a], ireName[a], ireNotes[a], ireContributor, ireArea[a]);  
					}
				}
			}

			// Have now created all of the polygons
			
			//If zoom < 10, zoom = 10 (otherwise it is too far out to see some items)
			var mapZoom=map.getZoom();
			if (mapZoom<10 && subgroupListSelected != 'all'){mapZoom=10;}

			// recenter the map, if there is data to display
			if(data.length!=0 && (averageLat+averageLng!=0))
			{
				averageLat=averageLat/averageNo;
				averageLng=averageLng/averageNo;
				map.setCenter(new GLatLng(averageLat,averageLng),mapZoom);
			}
			else
			{
				alert('Sorry - there is no map showing your selection(s) in the database as yet.');
			
			// if there is only one selection and no marker or border, display the sub-district details now			
			
				if (type!="all")
				{
					subDistrictDisplay(ireID, ireName, groupName[ireLevel], ireNotes, ireArea);
				}
			}
   	});
	};

//-------------------------------------------------------- Polygon Construction ---------------------------------------------
//
//		
//
	function createPolygon(polyLevel, polyEncoded, polyVertices)
	{
	//		var polyFill=(polyFillColour=="")?false:true;
		polyFill=false;
	//
   	// Draw outline according to map type to increase contrast
  	// This doesn't work perfectly as the lines are built once and even if Cleared or Reset the colour etc is retained
   	// 
		var polyLineColour=(map.getCurrentMapType()==G_NORMAL_MAP)?grouplineColourNormalMap[polyLevel]:grouplineColourSatellite[polyLevel];;
		var polyFillColour="";
	
		polygon=new GPolygon.fromEncoded(
		{
			polylines:
			[{
				points:		polyEncoded,
				levels:		polyVertices,
				color:		polyLineColour,
				opacity:		polygonLineOpacity,
				weight:		grouplineWidth[polyLevel],
				numLevels:	encodedLineNumber,
				zoomFactor:	encodedLineZoom
			}],
			fill: 		polyFill, 
			color:		polyFillColour, 
			opacity:		polygonFillOpacity,
			outline:		true
		});
		return polygon;
	};



//-------------------------------------------------------- Polygon Marker Construction --------------------------------------
//
//		
//
	function createPolygonMarker(polyLat, polyLng, polyLevel, polyType, polyID, polyName, polyNotes, polyContributor, polyArea)
	{   	
		var
			inGroupLevel = new Array(),
			inGroupName = new Array(),
			q0=polyID;
			
	// Fetch the groups it belongs to

		var groupFile='ireCensus1851q6.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload

		GDownloadUrl(groupFile , function(datafile)
		{
			var dataRows = GXml.parse(datafile);

		// Get overall settings
			var data =  dataRows.documentElement.getElementsByTagName("line");

			for (var a = 0; a < data.length; a++)
			{
				inGroupLevel[a] = data[a].getAttribute('level');
				inGroupName[a] = data[a].getAttribute('name');
			}

		//	The Data is now here

			var	pIcon = new GIcon(polyIcon);

		// Icon filename from groupIconID
			pIcon.image = mapImage+groupIconID[polyLevel];

		// Top of popup shows Item Name and Group Name

	// Get name of level, unless level is 0, in which case use type
		if (polyLevel==0)
			{
				if(polyType==1)
				{
					entry='Townland';
				}
				else if(polyType==2)
				{
					entry='Town';
				}
				else if(polyType==3)
				{
					entry='Island';
				}
			}
			else
			{
				entry = groupName[polyLevel]
			}

			var tableData=
				'<table class= "mapPopup" width= "350px">'+
					'<tr>'+
						'<td colspan="2" class="mapPopupTop">'+polyName+' ('+entry+')';

				if (idDisplay)
				{
					tableData+=' (ID: '+polyID+')';
				}

				for (var i = 0; i < inGroupLevel.length; i++)
				{
					tableData+=
						'<tr>'+
							'<td class="mapPopupCol1">'+groupName[inGroupLevel[i]]+
							'<td class="mapPopupCol2">'+inGroupName[i];
				}
				
				if(polyArea!=""&&polyArea!=0)
				{
					tableData=tableData+
						'<tr>'+
							'<td class="mapPopupCol1">Area'+
							'<td class="mapPopupCol2">'+polyArea+" acres";
				}

				if(polyNotes!=null && polyNotes!="")
				{
					tableData=tableData+
						'<tr>'+
							'<td class="mapPopupCol1">Notes'+
							'<td class="mapPopupCol2">'+polyNotes;
				}


				if(contributorPrivacy[polyContributor]==2)
				{
					tableData+=
						'<tr>'+
							'<td colspan="2" class="mapPopupCol2">My thanks to '+contributorInitials[polyContributor]+' who drew this map'
				}

				if(contributorPrivacy[polyContributor]==3)
				{
					tableData+=
						'<tr>'+
							'<td colspan="2" class="mapPopupCol2">My thanks to '+contributorName[polyContributor]+' who drew this map'
				}

		//
		//	Build a link for expanded data - pass the id, level and names as parameters  
		//
		
			tableData=tableData+
				'<tr>'+
     	  	'<td class="mapPopupLink" colspan="2"><a onclick="subDistrictDisplay('+polyID+', \''+polyName+'\', \''+groupName[polyLevel]+'\', \''+polyNotes+'\', \''+polyArea+'\')">Click here to show a list of the  sub-districts</a>';

			tableData+=
      	'<tr>'+
					'<td colspan="2" class="mapPopupBottom">'+copyrightNotice

			tableData+=
				'</tr>'+
					'</table>';

		//  Create marker
			var point = new GLatLng(polyLat,polyLng);

		// Date to display on mouseover
			infoName1=groupName[polyLevel]+':  '+polyName+' (ID: '+polyID+')';
			infoName2=groupName[groupSelected]+':  '+groupListSelectedName; 
	
		// Create the maker
			var marker=buildMarker(point, pIcon, tableData, infoName1, infoName2);

			map.addOverlay(marker);

   	// Open info widow unless Icons are off, in which case hide the marker.
   		if (!displayPolyIcons)
   		{
   			marker.hide();
   		}
			else
			{
			// if Icons are on show the popup window for the first marker
				if (!showMarkerWindow)
				{
					marker.openInfoWindowHtml(tableData);
					showMarkerWindow = true;
				}
			// note that the map is centred on the centre of all of the polygons opened.
			}
		});   
	};
	

//
// build marker
//
	function buildMarker(point, pIcon, tableData, lab1, lab2)
	{
		var marker = new GMarker(point,{icon:pIcon});

	// Save it
		iconMarker.push(marker);

		GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(tableData);});
		GEvent.addListener(marker, "dblclick", function() {marker.openInfoWindowHtml(tableData);});
		GEvent.addListener(marker, "mouseover", function() {showName(lab1,lab2); });
		GEvent.addListener(marker, "mouseout", function() {showName("","");});

		return marker;
	};


// ------------------------------------- Operator Functions ------------------------------

//	When groupSelection selected
	function groupSelect(selItem)	
	{
		groupSelected = selItem.options[selItem.selectedIndex].title;
		groupListSelected = -1; 				// reset 
		
		buildGroupSelectionList()				// Build the Group Selection list. 
		buildSubgroupSelection()				// Build the subGroup list.
		initialiseSubgroupSelectionList()	// Clear list now as nothing selected				 			
	}

//	When groupSelectionList selected
	function groupSelectList(selItem)	
	{
		groupListSelected = selItem.options[selItem.selectedIndex].title;
		groupListSelectedName = selItem.options[selItem.selectedIndex].value;
		if (groupListSelected != -1) 
		{
			buildSubgroupSelectionList()			// Build the subGroupList list.
		}
		else
		{
			initialiseSubgroupSelectionList()	// Clear list now as nothing selected				 			
		}
	}

//	When subgroupSelection selected
	function subgroupSelect(selItem)	
	{
		subgroupSelected = selItem.options[selItem.selectedIndex].title;
		buildSubgroupSelectionList()			// Build the subGroupList list.
	}

//	When subgroupSelectionList selected
//		type=all
//			var0= subgroupSelected
//			var1= groupListSelected
//
//
//		type=item
//			var0= subgroupListSelected (the item's ID)
//			var1= ''

	function subgroupSelectList(selItem)	
	{
		subgroupListSelected = selItem.options[selItem.selectedIndex].title;
		subgroupListSelectedName = selItem.options[selItem.selectedIndex].value;
		
		if  (subgroupListSelected=='all')
		{
			displaySelectedItem('all',subgroupSelected,groupListSelected);
		}
		else if (subgroupListSelected!=-1)
		{
			displaySelectedItem('item',subgroupListSelected,'');
		}
	}

	
// 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();
			}
		}
	}

// When Clear All button selected
	function clearMapButton()
	{
	// Reset arrays storing the downloaded data		
		polygonDownloaded.length = 0;		
		polygonIDDownloaded.length = 0;		
		iconDownloaded.length = 0;	
		buildSubgroupSelectionList();			// otherwise it is not possible to select the last item before it was cleared

		map.clearOverlays();

	// Initialise Search stuff
		initialiseSearch();
		initialiseSidebar();
		createInitialSidebarEntry();
	}


//
//	Reset the map
//
	
	function resetMapButton() //reset map zoom level retaining current filters
	{

	// Reset Forms otherwise the last entry is retained
		resetForms();	

	//clear all polygons, markers and any search results
		map.clearOverlays();

	//recenter & rezoom
		map.setCenter(new GLatLng(latStart, lngStart), zoomStart);		

	//update infoBox
		showNumZoom();

	//clear any open info windows
		map.closeInfoWindow();

 	//restore map type
//		map.setMapType(G_NORMAL_MAP );
		map.setMapType(G_SATELLITE_MAP );

	// initialise
		initialiseMisc();

	};
	

//
//	Reset the entry forms - otherwise it can keep the information there on next restart
//
	function resetForms()
	{
		for (i=0; i < document.forms.length; i++) 
   		{
			document.forms[i].reset();
		}
	};

// ------------------------------------------------------------ Database Search ---------------------------------------------
	
//
//	Select Search Type
//
// types:
//	exactSearch
//	soundexSearch
//	partialSearch
//	mapSearch
//
	function saveSearchType(type)
	{
		searchType = type;
	};
	

//	Initialise Search
//		searchType
//		searchBox
//
	function initialiseSearch()
	{
		searchType="partialSearch";
		document.iSearchForm.searchBox.value=searchText;
	};


// do something when the search box is clicked		
	function prepareSearchBox()
	{
		document.iSearchForm.searchBox.value="";
	}


	function searchFor(address) 
	{
		if (address==searchText||address=="") // don't search if nothing to look for
		{
		}
		else
		{
			setupSidebar();
			newSidebarRow("","");
			entry='Downloading data, please wait...<img src="Images/updating.gif" align="top" height="15px">';
			newSidebarCell(entry,2);

			if (searchType=="mapSearch")
			{
				searchPlace(address);
			}
			else
			{
				var
					searchIDFound=new Array(),
					searchName = new Array(),
					searchLevel = new Array(),
					searchID = new Array(),
					searchInID = new Array(),
					searchInName = new Array(),
					searchInLevel = new Array(),

					q0=address;
   	
			// Exact search
				if (searchType=="exactSearch")
				{
					var groupFile='ireCensus1851q8.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload
				}

			// Soundex search
				if (searchType=="soundexSearch")
				{
					var groupFile='ireCensus1851q9.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload
				}

			// Partial search
				if (searchType=="partialSearch")
				{
					var groupFile='ireCensus1851q10.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload
				}

				GDownloadUrl(groupFile , function(datafile)
				{
					var dataRows = GXml.parse(datafile);

				// Get overall settings
					var data =  dataRows.documentElement.getElementsByTagName("line");
					for (var a = 0; a < data.length; a++)
					{
						searchName[a] = data[a].getAttribute('searchName');
						searchLevel[a] = data[a].getAttribute('searchLevel');
						searchID[a] = data[a].getAttribute('searchID');
						searchInID[a] = data[a].getAttribute('searchInID');
						searchInName[a] = data[a].getAttribute('searchInName');
						searchInLevel[a] = data[a].getAttribute('searchInLevel');
					}

			//
			//	Remember this is Asynch - the data is ready now ...
			//	
					var name, inName, level, id
					setupSidebar();
					if(searchName.length!=0)
					{
				//go get the list pointed to by selection - returned sorted by ID and inLevel
						
						for (var a = 0; a<searchName.length; a++)
						{
							name=searchName[a];
							level=searchLevel[a];
							id=searchID[a];
							inName="";
							// pick up the Civil Parish and County the place is in.
							while (id == searchID[a])
							{	
								if (searchInLevel[a]==1)
								{
									inName+=searchInName[a]+', ';
								}
								if (searchInLevel[a]==7)
								{
									inName+=searchInName[a];
								}
								a=a+1
							}
							a=a-1; //to get the correct index number for the for loop
							newSidebarRow("","");
							entry = '<a href="javascript:displaySelectedItem(\'item\','+id+',\'\')">'+name+'</a>';
							newSidebarCell(entry,1);
							entry = groupName[level];
							newSidebarCell(entry,1);
							entry = inName;
							newSidebarCell(entry,1);
						};
					}	
					else
					{
						entry='No entries for '+address;
						newSidebarRow("","");
						newSidebarCell(entry,1);
					}
	      	completeSidebar();
  	    });
			};
		};
	};

// ------------------------------------------------------------ Search for Placename 

//Geocoder
// ====== Geocoding ======
	// This function picks up the click and opens the corresponding info window
	function sideClick(i)
	{
		map.setCenter(new GLatLng(sideMarker[i].getPoint().lat(),sideMarker[i].getPoint().lng()),"");
		setTimeout( function() {GEvent.trigger(sideMarker[i], "click")}, 10); 
	}
	  


	function searchPlace(search)
	{
		
	// ====== Perform the Geocoding ======        
		geo.getLocations(search, function (result) {
		// If search was successful
			if (result.Status.code == G_GEO_SUCCESS)
			{
				setupSidebar();
				sideMarker.length=0; 
		// Display the number of results found
				newSidebarRow("","");
				if (result.Placemark.length==1)
				{
					entry="Found " +result.Placemark.length +" result:";
				}
				else
				{
					entry="Found " +result.Placemark.length +" results:";
				}
				newSidebarCell(entry,1);
				
			// 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="mapPopup">'+
							'<tr>'+
								'<td colspan="2" class="mapPopupTop">Search Results';

					for (var r=0; r<q.length ; r++)
					{
						addressData+= '<tr>';
							if (r==0)
							{
								addressData+='<td class="mapPopupCol1">Place:';
							}
							else
							{
								addressData+='<td class="mapPopupCol1">';
							}
						addressData+='<td class="mapPopupCol2">'+q[r];
					};

					addressData+=			
         					'<tr>'+
         			   	   '<td class="mapPopupCol1">'+
         			      	'<td class="mapPopupCol2">&#160;'+
         					'<tr>'+
         			   	   '<td class="mapPopupCol1">Location:'+
         			      	'<td class="mapPopupCol2">'+p[1]+', '+p[0]+
                     	'<tr>'+
         		            '<td colspan="2" class="mapPopupBottom">'+copyrightNotice+
                     	'</tr>'+
               		'</table>';
						
		//  Create marker
					var point = new GLatLng(lat,lng);
					var	pIcon = new GIcon(polyIcon);
					pIcon.image = mapImage+"iconAst.png";

		// Create the maker
					var marker=buildMarker(point, pIcon, addressData, q[0], q[1]);

					map.addOverlay(marker);
					sideMarker[i] = marker;
					
				// Put address into sidebar
					entry=i+1+': <a href="javascript:sideClick(' + i + ')">' + result.Placemark[i].address + '</a><br />&#160;&#160;&#160;&#160;'+p[1]+', '+p[0];
					newSidebarRow("","");
					newSidebarCell(entry,1);
				}

				entry="<hr>";
				newSidebarRow("","");
				newSidebarCell(entry,1);

			}
			// ====== Decode the error status ======
			else
			{
			// Display error
				setupSidebar();
				var reason="Code "+result.Status.code;
				if (reasons[result.Status.code])
				{
					reason = reasons[result.Status.code]
				}
				entry='<b>Could not find "'+search+ '" .</b><br />' + reason;
				newSidebarRow("","");
				newSidebarCell(entry,1);
			}
		});
   	completeSidebar();
	};


// ------------------------------------------------------------ Information Box ---------------------------------------------

	function showNumZoom()
	{
		var zoom=map.getZoom();
		document.getElementById("infoBoxZoom").firstChild.nodeValue = zoom;
	}

	function showName(lab1,lab2)
	{
		document.getElementById("infoBoxDesc").firstChild.nodeValue = lab1;		
		document.getElementById("infoBoxLocn").firstChild.nodeValue = lab2;		
	}


// ------------------------------------------------------------ sideBar functions ---------------------------------------------
//     ref http://www.w3schools.com/HTMLDOM/
// 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()
	{
		initialiseSidebar();
	// 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;
  
	};

	
	function completeSidebar()
	{
	// create a blank at the bottom as it gets cut off sometimes
		entry="<br /><hr>";
		newSidebarRow("","");
		newSidebarCell(entry,2);
	// Insert the table into the document.
	
		var sideBarId=document.getElementById("searchResults");
		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);
			}
		}
	};
	

	function newSidebarRow(weight, height)
	{
		sideRow=document.createElement("tr");
		if (height!="") 
		{
			sideRow.style.fontSize=height;
		}
		if (weight=="bold") 
		{
			sideRow.style.fontWeight="bold";
		}
		sideRow.vAlign="top";
		sideTBody.appendChild(sideRow);
	};

	
	function newSidebarHead(text, width)
	{
		sideCell=document.createElement("td");
		sideRow.appendChild(sideCell);
		sideRow.style.fontWeight="bold";
		sideCell.width=width;
		sideCell.innerHTML=text;
	};


	function newSidebarCell(text, span)
	{
		sideCell=document.createElement("td");
		sideRow.appendChild(sideCell);
		sideCell.colSpan=span;
		sideCell.innerHTML=text;
	};

	
	function createInitialSidebarEntry()
	{
		entry=
			"<h3>The Interactive Irish District Database</h3>"+
			
			"Listing & mapping Townlands, Parishes, Baronies, Poor Law Unions, Councils and Counties of Ireland. <p>"+ 
			
			"It is a 'work in progress' currently covering: <ul>"+
			"<li>all divisions in Northern Ireland (many mapped)"+
			"<li>all Counties, PLUs, Baronies and Councils elsewhere (some mapped)"+
			"<li>see <a href='ireMapHelp.html#status' target='_blank'>Current Status</a>.</ul><p->"+
			
			"<b>To Use</b> either:<ul>"+
			"<li><b>Search Directly</b> for a name (above)"+
			"<li><b>Search by Administrative Divisions</b> (above map).</ul><p>"+
			
			"For <b>Help</b>:<ul>"+
			"<li>Mouse-over the query icons or Buttons"+
			"<li>Click the <b>Help Button</b></ul><p>"+
			
			"With over 60,000 townlands in Ireland I will never be able to map them all. If you have a specific interest in a townland or parish let me know and I will try to add it. If you are keen to create some townlands maps youself, I can show you how to add them.<p>"+
			
			"For an excellent description of the types of districts, go to <a href='http://www.igp-web.com/down/admin_dist.htm' target='_blank'>Fiona Jones' website</a> ";

		setupSidebar();
		newSidebarRow("","");
		newSidebarCell(entry, 1);
		completeSidebar();
	};
	

	
// ------------------------------------------------------------ Show Sub District Data in sidebar	 ---------------------------------------------

// Display the selected data
//

	function subDistrictDisplay(selectedIconID, selectedIconName, selectedIconLevelName, selectedIconNotes, selectedIconArea)
	{

	//
	// Fetch and display all sub-districts of this division
	//
		var
			inGroupID = new Array(),
			inGroupLevel = new Array(),
			inGroupType = new Array(),
			inGroupArea = new Array(),
			inGroupName = new Array(),
			inOutline = new Array(),
			inNotes = new Array(),
			inLat = new Array(),
			inLng = new Array(),
			q0 = selectedIconID;

	// Fetch the groups it belongs to
		var groupFile='ireCensus1851q7.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload

		// Clear sideBar

		setupSidebar();
		entry='Downloading data, please wait...<img src="Images/updating.gif" align="top" height="15px">';
		newSidebarRow('','');
		newSidebarCell(entry, 2);

		GDownloadUrl(groupFile , function(datafile)
		{
			var dataRows = GXml.parse(datafile);
		// Get overall settings
			var data =  dataRows.documentElement.getElementsByTagName("line");
			for (var a = 0; a < data.length; a++)
			{
				inGroupID[a] = parseFloat(data[a].getAttribute('id'));
				inGroupLevel[a] = parseFloat(data[a].getAttribute('level'));
				inGroupType[a] = parseFloat(data[a].getAttribute('type'));
				inGroupArea[a] = data[a].getAttribute('area');
				inGroupName[a] = data[a].getAttribute('name');
				inOutline[a] = data[a].getAttribute('acknowledge');
				inNotes[a] = data[a].getAttribute('notes');
				inLat[a] = data[a].getAttribute('lat');
				inLng[a] = data[a].getAttribute('lng');
			}

		//	The Data is now here, note that it can be empty so test...


			if (inGroupName.length > 0)
			{
				setupSidebar();
				entry='Districts in '+selectedIconName+' '+selectedIconLevelName;
				newSidebarRow('bold','130%');
				newSidebarCell(entry, 2);

				newSidebarRow('bold','');
				newSidebarHead('Place Name','70%');
				newSidebarHead('District','30%');

				
			// Extract the data for each group
				for (var i=0; i<inGroupName.length; i++)
				{
					newSidebarRow("","");

				// 
				//	Is there a marker?
				//	If the (absolute) latitude or longitude are > 1 we can assume there is a marker and no polygon
				//
					var onlyMarker = Math.abs(inLat[i])+Math.abs(inLng[i]);

					if (inOutline[i]!="" || onlyMarker > 1.0)
					{
						entry = '<a href="javascript:displaySelectedItem(\'detail\','+inGroupID[i]+',\'\')">'+inGroupName[i]+'</a>';
					}
					else 
					{
						entry = inGroupName[i];
					}
				// Show IDs?
					if (idDisplay)
					{
						entry += ' ('+inGroupID[i]+')';
					}
					newSidebarCell(entry, 1);

			// Show name of level, unless level is 0, in which case use type
				if (inGroupLevel[i]==0)
					{
						if(inGroupType[i]==1)
						{
							entry='Townland';
						}
						else if(inGroupType[i]==2)
						{
							entry='Town';
						}
						else if(inGroupType[i]==3)
						{
							entry='Island';
						}
					}
					else
					{
						entry = groupName[inGroupLevel[i]]
					}
					
					newSidebarCell(entry,1);
					
				// Show notes on next line
					if (inNotes[i]!="")
					{
						entry="("+inNotes[i]+")";
						newSidebarRow("","");
						newSidebarCell(entry,2);
					}
				};

			// and complete the div	
				completeSidebar();
			}
			else
			{
			// no sub division data and so show the districts that it is in instead
				districtDisplay(selectedIconID, selectedIconName, selectedIconLevelName, selectedIconNotes, selectedIconArea)
			};
		});
	};
	

	function districtDisplay(selectedIconID, selectedIconName, selectedIconLevelName, selectedIconNotes, selectedIconArea)
	{
		setupSidebar();
		entry='There are no sub-districts in the database for '+selectedIconName+' ';
		if (idDisplay)
		{
			entry+='('+selectedIconID+') ';
		}
		entry +=selectedIconLevelName+' which is in:';
		newSidebarRow('bold','');
		newSidebarCell(entry, 2);

   	var
			groupInLevel = new Array(),
			groupInName = new Array(),
			q0 = selectedIconID;
   			
	// Fetch the groups it belongs to
		var groupFile='ireCensus1851q6.php?q0='+q0+'&rld='+Math.random();  // rld variable to force reload

 		GDownloadUrl(groupFile , function(datafile)
		{
			var dataRows = GXml.parse(datafile);
      
   	// Get overall settings
   		var data =  dataRows.documentElement.getElementsByTagName("line");

 	 		for (var a = 0; a < data.length; a++) 
   	  {
				groupInLevel[a] = data[a].getAttribute('level');
				groupInName[a] = data[a].getAttribute('name');
			}

	//	The Data is now here

	 		for (var i = 0; i < groupInLevel.length; i++)
			{
				newSidebarRow('','');
 		   	entry=groupName[groupInLevel[i]];
				newSidebarCell(entry, 1);
				entry=groupInName[i];
				newSidebarCell(entry, 1);
			};

			if (selectedIconArea!=""&&selectedIconArea!=0)
			{
				newSidebarRow('','');
				entry="Area";
				newSidebarCell(entry, 1);
				entry=selectedIconArea+" acres";
				newSidebarCell(entry, 1);
			}
			
			if(selectedIconNotes==null || selectedIconNotes=="")
			{
			}
			else
			{
				newSidebarRow('','');
				entry="("+selectedIconNotes+")";
				newSidebarCell(entry, 2);
			};
 	  	completeSidebar();
		});

	};