/** Initialise variables **/


/* Global array to maintain the current parameters for use in searches */
var searchVariables = new Array();
searchVariables['businessCategory']		= '';
searchVariables['businessSubCategory']	= '';
searchVariables['businessSubSubCategory']	= '';
searchVariables['businessName']			= '';
//searchVariables['areaServed']			= '';
searchVariables['nearTown']				= '';
searchVariables['prodServ']				= '';
searchVariables['postcode']				= '';

/* Global array to contain the results returned by a search */
var businessResults = new Array();

/* define the start point and number of results per page to display */
var limit = 5;
var start = 0;


/** Event Handling Functions - Start **/

/** Reset form and set resultsDiv back to default **/
function resetForm()
{
	searchVariables = new Array();
	resetResults();
	createForm();
	setupForm();
}

/** Called on key up event on the buiness Name field
*	sets the searchVariable for buiness name and then
*	calls the function loadBizNameSuggestions to load
*	the business Name suggestions **/
function nameKeyupHandler()
{
	// Get business name field
	nameInput = document.getElementById('businessName');
	// Set the searchVariable
	searchVariables['businessName'] = nameInput.value;
	// load suggestions
	loadBizNameSuggestions();
}

/** Called when the focus is moved away from the buiness
*	Name field.	Sets the searchVariable for buiness name and then
*	calls the function loadResults to get and draw the results, then
*	sets a timeout to hide the suggestions. **/
function nameBlurHandler()
{
	// Get business name field
	nameInput = document.getElementById('businessName');
	// Set the searchVariable
	searchVariables['businessName'] = nameInput.value;
	// Load results
	// loadResults();
	// Hide suggestions after delay to allow the suggestions to be clicked upon
	setTimeout("hideSuggestions('businessSuggestions')",200);
}

/** Called when a new option is selected in the Business Category select.
*	Sets the search variable for Business Category, then uses loadSubCategories
*	to update the sub category select. Finally updates the results. **/
function categoryChangeHandler()
{
	// Get business category field
	categoryDD = document.getElementById('businessCategory');
	// set search variable
	searchVariables['businessCategory'] = categoryDD.options[categoryDD.selectedIndex].value;
	searchVariables['businessSubCategory'] = '';
	searchVariables['businessSubSubCategory'] = '';
	// Load the subcategories select with subcategories of the current category
	loadSubCategories();
	// Load Results
	// loadResults();
}

/** Called when a new option is selected in the Business Sub Category select.
*	Sets the search variable for Business Sub Category, then uses loadResults
*	to update the results. **/
function subcategoryChangeHandler()
{
	// Get business sub category field
	categoryDD = document.getElementById('businessSubCategory');
	// set search variable
	searchVariables['businessSubCategory'] = categoryDD.options[categoryDD.selectedIndex].value;
	searchVariables['businessSubSubCategory'] = '';
	// Load the subcategories select with subcategories of the current category
	loadSubSubCategories();
	// Load Results
	// loadResults();
}

/** Called when a new option is selected in the Business Sub Category select.
*	Sets the search variable for Business Sub Category, then uses loadResults
*	to update the results. **/
function subsubcategoryChangeHandler()
{
	// Get business sub category field
	categoryDD = document.getElementById('businessSubSubCategory');
	// set search variable
	searchVariables['businessSubSubCategory'] = categoryDD.options[categoryDD.selectedIndex].value;

	// Load Results
	// loadResults();
}

/** Called when a new option is selected in the Area Served select.
*	Sets the search variable for Area Served, then uses loadResults
*	to update the results. **/
function areaChangeHandler()
{
	// Get area served field
	areaServedDD = document.getElementById('areaServed');
	// set search variable
	searchVariables['areaServed'] = areaServedDD.options[areaServedDD.selectedIndex].value;
	// loadResults();
}

/** Called when a new option is selected in the Nearest Town select.
*	Sets the search variable for Nearest Town, then uses loadResults
*	to update the results. **/
function townChangeHandler()
{
	// Get nearest town field
	townDD = document.getElementById('nearTown');
	// set search variable
	searchVariables['nearTown'] = townDD.options[townDD.selectedIndex].value;
	// Load Results
	// loadResults();
}

/**
################ Currently unused ####################
*	Called on key up event on the Product or Service
*	field sets the searchVariable for Product or Service
*	and then calls the function loadProdServNameSuggestions
*	to load the Product or service suggestions.
################ Currently unused ####################
**/
function prodServKeyupHandler()
{
	// Get Product or Service field
	prodServInput = document.getElementById('prodServ');
	// set search variable
	searchVariables['prodServ'] = prodServInput.value;
	// Load Suggestions
	loadProdServNameSuggestions();
}

/**
*	Called when the focus is moved away from the Product
*	or Service field. Sets the searchVariable for Product
*	or Service and then calls the function loadResults
*	to get and draw the results, then sets a timeout to
*	hide the suggestions.
**/
function prodServBlurHandler()
{
	// Get Product or Service field
	nameInput = document.getElementById('prodServ');
	// set search variable
	searchVariables['prodServ'] = nameInput.value;
	// Load Results
	// loadResults();
	// Hide suggestions after delay to allow the suggestions to be clicked upon
	// Commented out after feedback from KT
	// setTimeout("hideSuggestions('prodServSuggestions')",200);
}

/**	Called on key up event on the Postcode field sets
*	the searchVariable for Postcode and then calls
*	the function loadPostcodeNameSuggestions to load
*	the Postcode suggestions. **/
function postcodeKeyupHandler()
{
	// Get Postcode field
	prodServInput = document.getElementById('postcode');
	// Set search variable
	searchVariables['postcode'] = prodServInput.value;
	// Load Suggestions
	loadPostcodeNameSuggestions();
}


/**	Called when the focus is moved away from the Postcode
*	field. Sets the searchVariable for Postcode and then
*	calls the function loadResults to get and draw the
*	results, then sets a timeout to hide the suggestions. **/
function postcodeBlurHandler()
{
	// Get Postcode field
	nameInput = document.getElementById('postcode');
	// set search variable
	searchVariables['postcode'] = nameInput.value;
	// Load Results
	// loadResults();
	// Hide suggestions after delay to allow the suggestions to be clicked upon
	setTimeout("hideSuggestions('postcodeSuggestions')",200);
}

/** Function used to set the text value of fields once a suggestion
*	is clicked upon. Needs to be in the same document as the form
*	is as suggestions in the iframe cannot access elements in the
*	parent document under security rules in IE. **/
function setText(name,fieldID,suggestionsID)
{
	// Get field
	nameInput = document.getElementById(fieldID);
	// Set search variable and field value
	nameInput.value = name;
	searchVariables[fieldID] = name;
	// Load Results
	// loadResults();
	// Hide suggestions iframe
	hideSuggestions(suggestionsID);
}

/** Event Handling Functions - End **/

/** Data loading functions - End **/

/** Makes the AJAX request and sets the function to deal with the feedback **/
function loadResults()
{
	// check we have something to search with, otherwise the results show a bit slow
	if (document.getElementById('businessName').value == "" &&
		document.getElementById('businessCategory').options[document.getElementById('businessCategory').selectedIndex].value == "" &&
		document.getElementById('nearTown').options[document.getElementById('nearTown').selectedIndex].value == "" &&
		document.getElementById('prodServ').value == "" &&
		document.getElementById('postcode').value == "") {

		document.getElementById('results-message').innerHTML = "Please enter a search term above before searching";
		return;
	}

	// change the search button to searching...
	document.getElementById('searchButton').value = "Searching...";

	document.getElementById('results-message').innerHTML = "";

	// Create query string to pass search variables to xml request
	var qryStr = generateQueryString();

	nameXmlHttp = createXMLObj();
	nameXmlHttp.onreadystatechange=resultsStateChangeHandler;
	nameXmlHttp.open("GET", 'getresultsxml.php?'+qryStr, true);
	nameXmlHttp.send(null);
}

/** Deals with the AJAX response as the state changes **/
function resultsStateChangeHandler()
{
	switch(nameXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			// Check that the document loaded is aok
			if(nameXmlHttp.status == 200){
				document.getElementById('searchButton').value = "Search";
				var resultsDoc=getXMLDom(nameXmlHttp);

				// Set global results array to contain the just fetched set.
				businessResults = resultsDoc.getElementsByTagName('business');

				// Output the results
				drawResults(start,limit);
			}
		break;
	}

}

/**	Produces the actual output of the results to the
*	resultsDiv and pagination controls. Passed two
*	integers which define the starting record and
*	number of records to disaply per page. **/
function drawResults(drawStart,drawLimit)
{
	// Fetch and blank the results and pagination divs
	paginationDivTopRef = document.getElementById('paginationDivTop');
	paginationDivTopRef.innerHTML = '';
	resultsDivRef = document.getElementById('resultsDiv');
	resultsDivRef.innerHTML = '';
	paginationDivBotRef = document.getElementById('paginationDivBottom');
	paginationDivBotRef.innerHTML = '';

	// Create the results table and set up parameters
	tableChild = document.createElement('table');
	tableChild.cellSpacing = 0;
	tableChild.cellPadding = 0;
	tableChild.border = 0;
	tableChild.width = '100%';
	tableChild.style.className = "dataTbl";
	tableChild.summary = "List of businesses"

	// Create tbody as this is required for correct display in IE
	tableBody = document.createElement('tbody');

	// Create initial header row
	headerRow = document.createElement('tr');

	// Check to see if results have been returned
	if(businessResults.length > 0){
		// If results have been found set the header row content and append it
		headerTh = document.createElement('th');
		headerTh.innerHTML = "Results";
		headerRow.appendChild(headerTh);


		var resultsMessage = document.getElementById('results-message');
		// resultsMessage.innerHTML = 'Results are displayed to the right';


		// append the header row to the table
		tableBody.appendChild(headerRow);

		/**	set blank array to contain elements and loop through the results
		*	from the passed parameter drawStart for the number of repetions
		*	defined by the passed paramter drawLimit **/
		currOption = new Array();
		for(var i=drawStart,lastRecord=drawLimit+(drawStart*1);i<lastRecord;i++){
			try{
				/** Create the title for the result and append it into
				*	the table row. Alos add a br tag after the title so
				*	that any description will occur on the line below. **/
				titleLink = document.createElement('a');
				titleLink.title = businessResults[i].getElementsByTagName('name')[0].firstChild.nodeValue;
				titleLink.href = "javascript:showBusiness('"+i+"');";
				titleLink.innerHTML = businessResults[i].getElementsByTagName('name')[0].firstChild.nodeValue;
				brTag = document.createElement('br');
				tdTag = document.createElement('td');
				tdTag.appendChild(titleLink);
				tdTag.appendChild(brTag);

				// Check to see if there is a description to display
				if(businessResults[i].getElementsByTagName('prodserv')[0].firstChild.nodeValue){
					// if there is a description create a span tag and populate it.
					servSpan = document.createElement('span');
					servSpan.className = "business-description";
					prodservName = businessResults[i].getElementsByTagName('prodserv')[0].firstChild.nodeValue;

					// Impose a maximum character length for the description
					prodservName = prodservName.substring(0,200);

					/** If the maximum charcter length has
					*	changed the description tidy it up. **/
					if(prodservName != businessResults[i].getElementsByTagName('prodserv')[0].firstChild.nodeValue){
						// Find the last instance of a space in the modified string
						lastspace = prodservName.lastIndexOf(' ');
						/**	if a space if found, re chop the string to that last
						*	space to prevent breaking in the middle of a word.
						**/
						if(lastspace){
							prodservName = prodservName.substring(0,lastspace);
						}
						// Add a suspension point (...) to the finished string.
						prodservName = prodservName+'&hellip;';
					}
					// Add the description to the result cell
					servSpan.innerHTML = '&ndash; ' + prodservName;
					tdTag.appendChild(servSpan);
				}

				// create a new table row and add it to the results array
				currOption[i] = document.createElement('tr');

				// if this is an odd row apply the 'odd' class
				if(!(i%2 != 0)){
					currOption[i].className = "odd";
				}

				// add the cell to the row and then the row to the table body
				currOption[i].appendChild(tdTag);
				tableBody.appendChild(currOption[i]);
			} catch(e){
				// Do nothing
			}
		}
		/**	Set the pagination controls and add the table body to the table
		*	and then in turn that to the results div. **/
		paginationDivTopRef.appendChild(createPageNav(drawStart,drawLimit));
		tableChild.appendChild(tableBody);
		resultsDivRef.appendChild(tableChild);
		paginationDivBotRef.appendChild(createPageNav(drawStart,drawLimit));
	} else {
		// set up the no results return to the results div
		tableChild.appendChild(tableBody);
		resultsDivRef.appendChild(tableChild);
		headerTh = document.createElement('th');
		headerTh.innerHTML = "No Results Found";

		headerRow.appendChild(headerTh);

		tableBody.appendChild(headerRow);
		tableChild.appendChild(tableBody);
		resultsDivRef.appendChild(tableChild);
	}
}

/**	This function displays an individual businesses details **/
function showBusiness(index){

	// Get the results to be displayed based on the index passed
	thisResult = businessResults[index];

	/** Grab required divs, make references names different to
	*	element id to avoid issues with IE **/
	ajaxDivRef = document.getElementById('ajaxDiv');
	resultsDivRef = document.getElementById('resultsDiv');
	detailsDivRef = document.getElementById('detailDiv');
	paginationDivTopRef = document.getElementById('paginationDivTop');
	paginationDivBotRef = document.getElementById('paginationDivBottom');

	// Blank details div
	detailsDivRef.innerHTML = '';

	// Create the table to display the business details in
	tableChild = document.createElement('table');
	tableChild.cellSpacing = 0;
	tableChild.cellPadding = 0;
	tableChild.border = 0;
	tableChild.width = '100%';
	tableChild.className = "dataTbl";
	tableChild.summary = "List of businesses";

	// Create table body element required for IE
	tableBody = document.createElement('tbody');

	// Set up a spacer row that can be cloned after each section
	spacerRow = document.createElement('tr');
	spacerCell = document.createElement('td');
	spacerCell.className = 'spacerRow';
	spacerCell.innerHTML = '&nbsp;';
	spacerRow.appendChild(spacerCell);

	// Create an append headerRow
	headerRow = document.createElement('tr');
	headerTh = document.createElement('th');
	headerTh.colSpan = 2;
	headerTh.innerHTML = "General Details";
	headerRow.appendChild(headerTh);
	tableBody.appendChild(headerRow);

	// Row for registration date
	regDateRow = document.createElement('tr');
	regDateLabel = document.createElement('td');
	regDateLabel.style.width = '120px';
	regDateLabel.innerHTML = 'Date Registered';
	regDateValue = document.createElement('td');
	regDateValue.innerHTML = thisResult.getElementsByTagName('registered')[0].firstChild.nodeValue;
	regDateRow.appendChild(regDateLabel);
	regDateRow.appendChild(regDateValue);
	tableBody.appendChild(regDateRow);

	// Row for business name
	bizNameRow = document.createElement('tr');
	bizNameLabel = document.createElement('td');
	bizNameLabel.innerHTML = 'Name';
	bizNameValue = document.createElement('td');
	bizNameValue.innerHTML = thisResult.getElementsByTagName('name')[0].firstChild.nodeValue;
	bizNameRow.appendChild(bizNameLabel);
	bizNameRow.appendChild(bizNameValue);
	tableBody.appendChild(bizNameRow);

	// Row for business categories
	bizCatRow = document.createElement('tr');
	bizCatLabel = document.createElement('td');
	bizCatLabel.innerHTML = 'Business Category';
	bizCatValue = document.createElement('td');
	/** There may be multiple categories to be displayed so
	*	fetch them and then loop through and display them **/
	categories = thisResult.getElementsByTagName('categories')[0].getElementsByTagName('category');
	catOutput = '';
	for(catI=0,catMax=categories.length;catI<catMax;catI++){
		if(catOutput){
			catOutput = catOutput + '<br />' + categories[catI].firstChild.nodeValue;
		} else {
			catOutput = categories[catI].firstChild.nodeValue;
		}
	}
	bizCatValue.innerHTML = catOutput;
	bizCatRow.appendChild(bizCatLabel);
	bizCatRow.appendChild(bizCatValue);
	tableBody.appendChild(bizCatRow);

	// Row for service description
	prodServRow = document.createElement('tr');
	prodServLabel = document.createElement('td');
	prodServLabel.innerHTML = 'Service Description';
	prodServValue = document.createElement('td');
	prodServValue.innerHTML = thisResult.getElementsByTagName('prodserv')[0].firstChild.nodeValue;
	prodServRow.appendChild(prodServLabel);
	prodServRow.appendChild(prodServValue);
	tableBody.appendChild(prodServRow);
	// Clone spacerRow and append cloned row to table to create gap
	sRow1 = spacerRow.cloneNode(true);
	tableBody.appendChild(sRow1);

	// Header row for Directory Details section
	headerRow = document.createElement('tr');
	headerTh = document.createElement('th');
	headerTh.colSpan = 2;
	headerTh.innerHTML = "Directory Details";
	headerRow.appendChild(headerTh);
	tableBody.appendChild(headerRow);

	// Row for District
	districtRow = document.createElement('tr');
	districtLabel = document.createElement('td');
	districtLabel.innerHTML = 'District';
	districtValue = document.createElement('td');
	districtValue.innerHTML = thisResult.getElementsByTagName('district')[0].firstChild.nodeValue;
	districtRow.appendChild(districtLabel);
	districtRow.appendChild(districtValue);
	tableBody.appendChild(districtRow);

	// Row for Nearest Town
	townRow = document.createElement('tr');
	townLabel = document.createElement('td');
	townLabel.innerHTML = 'Nearest Town';
	townValue = document.createElement('td');
	townValue.innerHTML = thisResult.getElementsByTagName('maintown')[0].firstChild.nodeValue;
	townRow.appendChild(townLabel);
	townRow.appendChild(townValue);
	tableBody.appendChild(townRow);
	// Clone spacerRow and append cloned row to table to create gap
	sRow2 = spacerRow.cloneNode(true);
	tableBody.appendChild(sRow2);

	// Header row for Registrant
	headerRow = document.createElement('tr');
	headerTh = document.createElement('th');
	headerTh.colSpan = 2;
	headerTh.innerHTML = "Registrant's Details";
	headerRow.appendChild(headerTh);
	tableBody.appendChild(headerRow);

	// Row for registrant name
	rnameRow = document.createElement('tr');
	rnameLabel = document.createElement('td');
	rnameLabel.innerHTML = 'Name';
	rnameValue = document.createElement('td');
	rnameValue.innerHTML = thisResult.getElementsByTagName('rname')[0].firstChild.nodeValue;
	rnameRow.appendChild(rnameLabel);
	rnameRow.appendChild(rnameValue);
	tableBody.appendChild(rnameRow);

	// Row for position
	positionRow = document.createElement('tr');
	positionLabel = document.createElement('td');
	positionLabel.innerHTML = 'Position';
	positionValue = document.createElement('td');
	try{
		position =  thisResult.getElementsByTagName('position')[0].firstChild.nodeValue;
	} catch(e) {
		position = 0;
	}
	// If position hasn't been returned enter an N/A
	if(!(position)){
		position = 'N/A';
	}
	positionValue.innerHTML = position;
	positionRow.appendChild(positionLabel);
	positionRow.appendChild(positionValue);
	tableBody.appendChild(positionRow);
	// Clone spacerRow and append cloned row to table to create gap
	sRow3 = spacerRow.cloneNode(true);
	tableBody.appendChild(sRow3);

	// Header row for buiness address details
	headerRow = document.createElement('tr');
	headerTh = document.createElement('th');
	headerTh.colSpan = 2;
	headerTh.innerHTML = "Business Address";
	headerRow.appendChild(headerTh);
	tableBody.appendChild(headerRow);

	// If Address line 1 is present display row
	try{
		address1 =  thisResult.getElementsByTagName('address1')[0].firstChild.nodeValue;
	} catch (e) {
		address1 = 0;
	}
	if(address1){
		address1Row = document.createElement('tr');
		address1Label = document.createElement('td');
		address1Label.innerHTML = 'Address line 1';
		address1Value = document.createElement('td');
		address1Value.innerHTML = address1;
		address1Row.appendChild(address1Label);
		address1Row.appendChild(address1Value);
		tableBody.appendChild(address1Row);
	}

	// If Address line 2 is present display row
	try{
		address2 =  thisResult.getElementsByTagName('address2')[0].firstChild.nodeValue;
	} catch (e) {
		address2 = 0;
	}
	if(address2){
		address2Row = document.createElement('tr');
		address2Label = document.createElement('td');
		address2Label.innerHTML = 'Address line 2';
		address2Value = document.createElement('td');
		address2Value.innerHTML = address2;
		address2Row.appendChild(address2Label);
		address2Row.appendChild(address2Value);
		tableBody.appendChild(address2Row);
	}

	// If Address line 3 is present display row
	try{
		address3 =  thisResult.getElementsByTagName('address3')[0].firstChild.nodeValue;
	} catch (e) {
		address3 = 0;
	}

	if(address3){
		address3Row = document.createElement('tr');
		address3Label = document.createElement('td');
		address3Label.innerHTML = 'Address line 3';
		address3Value = document.createElement('td');
		address3Value.innerHTML = address3;
		address3Row.appendChild(address3Label);
		address3Row.appendChild(address3Value);
		tableBody.appendChild(address3Row);
	}

	// Row for county
	countyRow = document.createElement('tr');
	countyLabel = document.createElement('td');
	countyLabel.innerHTML = 'County';
	countyValue = document.createElement('td');
	countyValue.innerHTML = thisResult.getElementsByTagName('county')[0].firstChild.nodeValue;
	countyRow.appendChild(countyLabel);
	countyRow.appendChild(countyValue);
	tableBody.appendChild(countyRow);

	// Row for postcode
	postcodeRow = document.createElement('tr');
	postcodeLabel = document.createElement('td');
	postcodeLabel.innerHTML = 'postcode';
	postcodeValue = document.createElement('td');
	postcodeValue.innerHTML = thisResult.getElementsByTagName('postcode')[0].firstChild.nodeValue;
	postcodeRow.appendChild(postcodeLabel);
	postcodeRow.appendChild(postcodeValue);
	tableBody.appendChild(postcodeRow);
	// Clone spacerRow and append cloned row to table to create gap
	sRow4 = spacerRow.cloneNode(true);
	tableBody.appendChild(sRow4);

	// Header row for business contact details
	headerRow = document.createElement('tr');
	headerTh = document.createElement('th');
	headerTh.colSpan = 2;
	headerTh.innerHTML = "Business Contact Numbers";
	headerRow.appendChild(headerTh);
	tableBody.appendChild(headerRow);

	// Row for telephone number
	telephone1Row = document.createElement('tr');
	telephone1Label = document.createElement('td');
	telephone1Label.innerHTML = 'Telephone Number';
	telephone1Value = document.createElement('td');
	telephone1Value.innerHTML = thisResult.getElementsByTagName('telephone1')[0].firstChild.nodeValue;
	telephone1Row.appendChild(telephone1Label);
	telephone1Row.appendChild(telephone1Value);
	tableBody.appendChild(telephone1Row);

	// If alternative telephone number is returned display row
	try{
		telephone2 = thisResult.getElementsByTagName('telephone2')[0].firstChild.nodeValue;
	} catch (e) {
		telephone2 = 0;
	}

	if(telephone2){
		telephone2Row = document.createElement('tr');
		telephone2Label = document.createElement('td');
		telephone2Label.innerHTML = 'Number #2';
		telephone2Value = document.createElement('td');
		telephone2Value.innerHTML = telephone2;
		telephone2Row.appendChild(telephone2Label);
		telephone2Row.appendChild(telephone2Value);
		tableBody.appendChild(telephone2Row);
	}
	// Clone spacerRow and append cloned row to table to create gap
	sRow5 = spacerRow.cloneNode(true);
	tableBody.appendChild(sRow5);

	// Header row for Additional Information
	headerRow = document.createElement('tr');
	headerTh = document.createElement('th');
	headerTh.colSpan = 2;
	headerTh.innerHTML = "Additional Information";
	headerRow.appendChild(headerTh);
	tableBody.appendChild(headerRow);

	// If email address is returned display row
	try{
		email = thisResult.getElementsByTagName('email')[0].firstChild.nodeValue;
	} catch (e) {
		email = 0;
	}

	if(email){
		emailRow = document.createElement('tr');
		emailLabel = document.createElement('td');
		emailLabel.innerHTML = 'Email Address';
		emailValue = document.createElement('td');
		emailLink = document.createElement('a');
		emailLink.href = 'mailto:'+email
		emailLink.innerHTML = email;
		emailValue.appendChild(emailLink);
		emailRow.appendChild(emailLabel);
		emailRow.appendChild(emailValue);
		tableBody.appendChild(emailRow);
	}

	// If url is returned display row
	try{
		website = thisResult.getElementsByTagName('website')[0].firstChild.nodeValue;
	} catch (e) {
		website = 0;
	}

	if(website && (website != 'undefined')){
		websiteRow = document.createElement('tr');
		websiteLabel = document.createElement('td');
		websiteLabel.innerHTML = 'Website Address';
		websiteValue = document.createElement('td');
		websiteLink = document.createElement('a');

		// JR added
		var theWebsiteURL = website;
		if ('http://' == theWebsiteURL.substring(0, 7)){
			//
		}else{
			theWebsiteURL = 'http://' + website;
		}

		websiteLink.href = theWebsiteURL;
		websiteLink.target = 'business';
		websiteLink.innerHTML = theWebsiteURL;
		websiteValue.appendChild(websiteLink);
		websiteRow.appendChild(websiteLabel);
		websiteRow.appendChild(websiteValue);
		tableBody.appendChild(websiteRow);
	}
	// Clone spacerRow and append cloned row to table to create gap
	sRow6 = spacerRow.cloneNode(true);
	tableBody.appendChild(sRow6);

	// Apend the table body to the table, then that to the details div
	tableChild.appendChild(tableBody);
	detailsDivRef.appendChild(tableChild);

	// Create a back to results link and add that to the details div
	brTag = document.createElement('br')
	backDiv = document.createElement('div');
	try{
		backDiv.style.cssFloat = 'left';
	} catch (e) {
		backDiv.style.styleFloat = 'left';
	}
	backLink = document.createElement('a');
	backLink.href = 'javascript:backToSearch()';
	backLink.innerHTML = '&lt; Back';
	backDiv.appendChild(backLink);
	detailsDivRef.appendChild(brTag);
	detailsDivRef.appendChild(backDiv);

	/**	Hide the unneeded form, results and pagination divs and
	*	show the details div, and change the header to business details. **/
	paginationDivBotRef.style.display = 'none';
	resultsDivRef.style.display = 'none';
	paginationDivTopRef.style.display = 'none';
	ajaxDivRef.style.display = 'none';
	document.getElementsByTagName('h1')[0].innerHTML = 'BUSINESS DETAILS';
	detailsDivRef.style.display = 'block';
}


/** This function displays the form, results and pagination divs
*	and resets the page title. It also hides the details div **/
function backToSearch(){
	// Get required divs
	ajaxDivRef = document.getElementById('ajaxDiv');
	resultsDivRef = document.getElementById('resultsDiv');
	detailsDivRef = document.getElementById('detailDiv');
	paginationDivTopRef = document.getElementById('paginationDivTop');
	paginationDivBotRef = document.getElementById('paginationDivBottom');

	// Adjhust div display and reset title
	detailsDivRef.style.display = 'none';
	document.getElementsByTagName('h1')[0].innerHTML = 'Business Directory: Search';
	ajaxDivRef.style.display = 'block';
	paginationDivTopRef.style.display = 'block';
	resultsDivRef.style.display = 'block';
	paginationDivBotRef.style.display = 'block';

}

/** This function produces the pagination controls from passed parameters.
*	@drawStart (Int) - The record from which this page starts
*	@drawLimit (Int) - The number of record to dispaly per page
*
*	returns DOM node containing the pagination controls **/
function createPageNav(drawStart,drawLimit)
{
	/* force the draw variables to be integers */
	drawStart = drawStart * 1;
	drawLimit = drawLimit * 1;

	// Create a new div to conatin the navigation
	pagenav = document.createElement('div');
	pagenav.className = 'resultsPagination';

	/** Calculate the starting record of the previous page and
	*	if it's less than zero create link otherwise just
	*	create a span with the same content **/
	prevStart = drawStart - (drawLimit);
	if(prevStart < 0){
		prevLink = document.createElement('span');
	} else {
		prevLink = document.createElement('a');
		prevHref = "javascript:drawResults(" + prevStart + "," + drawLimit + ");";
		prevLink.href = prevHref
	}
	prevLink.innerHTML = "&lt; prev";

	/** Calculate the starting record of the next page and
	*	if it's greater than the total number of results create link
	*	otherwise just create a span with the same content **/
	nextStart = drawStart + drawLimit;
	if(nextStart > businessResults.length){
		nextLink = document.createElement('span');
	} else {
		nextLink = document.createElement('a');
		nextHref = "javascript:drawResults(" + nextStart + "," + drawLimit + ");";
		nextLink.href = nextHref;
	}
	nextLink.innerHTML = "next &gt;";

	// Set up info for display
	firstRecord = drawStart + 1;
	lastRecord = drawLimit + drawStart;
	if(lastRecord > businessResults.length){
		lastRecord = businessResults.length;
	}

	// Append collated information
	pagenav.appendChild(prevLink);
	pagenav.innerHTML = pagenav.innerHTML + '&nbsp;' + firstRecord + '&nbsp;&ndash;&nbsp;' + lastRecord + '&nbsp;of&nbsp;'+businessResults.length+'&nbsp;';
	pagenav.appendChild(nextLink);

	// return the completed node
	return pagenav;
}

/** AJAX request to fetch the possible business name suggestions **/
function loadBizNameSuggestions()
{

	// Create query string to pass search variables to xml request
	var qryStr = generateQueryString();

	nameXmlHttp = createXMLObj();
	nameXmlHttp.onreadystatechange=nameStateChangeHandler;
	nameXmlHttp.open("GET", 'getnamesxml.php?'+qryStr, true);
	nameXmlHttp.send(null);
}

/** Deals with the AJAX response as the business name request state changes **/
function nameStateChangeHandler()
{
	switch(nameXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			// Check that the document loaded is aok
			if(nameXmlHttp.status == 200){
				var xmlDoc=getXMLDom(nameXmlHttp);

				// Set local results array to contain the just fetched set.
				var suggestions = xmlDoc.getElementsByTagName('business');

				// Populate and show the suggestions iframe
				populateSuggestions('businessSuggestions',suggestions,'businessName','name');
			}
		break;
	}

}

/**
################ Currently unused ####################
*	Creates the AJAX request to get the possible
*	products or services.
################ Currently unused ####################
**/
function loadProdServNameSuggestions()
{

	// Create query string to pass search variables to xml request
	var qryStr = generateQueryString();

	prodservXmlHttp = createXMLObj();
	prodservXmlHttp.onreadystatechange=prodServStateChangeHandler;
	prodservXmlHttp.open("GET", 'getprodservsxml.php?'+qryStr, true);
	prodservXmlHttp.send(null);
}

/**
################ Currently unused ####################
*	Deals with the AJAX response as the product or
*	service request state changes
################ Currently unused ####################
**/
function prodServStateChangeHandler()
{
	switch(prodservXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			// Check that the document loaded is aok
			if(prodservXmlHttp.status == 200){
				var xmlDoc=getXMLDom(prodservXmlHttp);
				// Set local results array to contain the just fetched set.
				var suggestions = xmlDoc.getElementsByTagName('prodserv');

				// Populate and show the suggestions iframe
				populateSuggestions('prodServSuggestions',suggestions,'prodServ','name');
			}
		break;
	}

}

/**
*	Creates the AJAX request to get the possible postcodes.
**/
function loadPostcodeNameSuggestions()
{
	// Create query string to pass search variables to xml request
	var qryStr = generateQueryString();

	postcodeXmlHttp = createXMLObj();
	postcodeXmlHttp.onreadystatechange=postcodeStateChangeHandler;
	postcodeXmlHttp.open("GET", 'getpostcodesxml.php?'+qryStr, true);
	postcodeXmlHttp.send(null);
}

/**
*	Deals with the AJAX response as the postcode request state changes
**/
function postcodeStateChangeHandler()
{
	switch(postcodeXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			// Check that the document loaded is aok
			if(postcodeXmlHttp.status == 200){
				var xmlDoc=getXMLDom(postcodeXmlHttp);
				// Set local results array to contain the just fetched set.
				var suggestions = xmlDoc.getElementsByTagName('postcodes');
				// Populate and show the suggestions iframe
				populateSuggestions('postcodeSuggestions',suggestions,'postcode','postcode');
			}
		break;
	}

}

/**
*	Function used to populate and show a suggestions iframe
*	@iframeName		str		- The id of the suggestions iframe
*	@suggestions	array	- The array of suggestions
*	@nameInput		str		- The id of the text field into which suggestions would be put
*	@tagname		str		- The name of the tag returned by the xml
**/
function populateSuggestions(iframeName,suggestions,nameInput,tagname)
{
	/**	As the document object of an iframe differs depending upon the
	*	browser try one method then default to the other. **/
	try{
		var suggestionIframe = document.frames[iframeName].document;
		var suggestionBody = document.frames[iframeName].document;
	} catch(e) {
		var suggestionIframe = document.getElementById(iframeName).contentDocument;
		var suggestionBody = document.getElementById(iframeName).contentDocument.body;
	}
	suggestionIframe.id = 'suggestionsBody';
	suggestionBody.id = 'whiteBg';

	// Create list into which the suggestions shall be placed
	var suggList = suggestionBody.getElementsByTagName('ul')[0];
	suggList.innerHTML = '';

	// Loop through suggestions and append them to the list
	for(var i=0;i<suggestions.length;i++){
		var currOption = suggestionIframe.createElement('li');
		var suggestLink = suggestionIframe.createElement('a');
		var tagvalue = suggestions[i].getElementsByTagName(tagname)[0].firstChild.nodeValue;

		// limit length of suggestion
		var subtagvalue = tagvalue.substring(0,45);

		// if the limited value is not the same it has been shortened so tidy it up
		if(tagvalue != subtagvalue){
			/** find last space in limited string and chop
			*	the string down to that length **/
			lastspace = subtagvalue.lastIndexOf(' ');
			if(lastspace){
				subtagvalue = subtagvalue.substring(0,lastspace);
			}
			// String has been shortened so add suspension point.
			subtagvalue = subtagvalue+'&hellip;';
		}

		// Create link for call javascript in the parent to set the text field
		suggestLink.innerHTML	= subtagvalue;
		suggestLink.href = "javascript:parent.setText('"+tagvalue.replace("'", "\\'")+"','"+nameInput+"','"+iframeName+"');";
		// Set show on focus so suggestions box doesn't hide when required
		suggestLink.onfocus = "showSuggestions('"+iframeName+"')";

		// Add link and list item to the list
		currOption.appendChild(suggestLink);
		suggList.appendChild(currOption);
	}

	// if suggestions have been added show the suggestions iFrame
	if(i > 0){
		document.getElementById(iframeName).style.display = 'block';
	} else {
		document.getElementById(iframeName).style.display = 'none';
	}

}


/**
*	Creates the AJAX request to get the possible subcategories
*	`given the selected category.
**/
function loadSubSubCategories(){

	// Create query string to pass search variables to xml request
	var qryStr = generateQueryString();

	document.getElementById('businessSubSubCategory').style.display = 'none';
	document.getElementById('businessSubSubCategoryLabel').style.display = 'none';
	document.getElementById('businessSubSubCategoryBr').style.display = 'none';
	document.getElementById('businessSubSubCategory').style.zIndex = 0;

	if (searchVariables['businessSubCategory'] != "") {
		subcatXmlHttp = createXMLObj();
		subcatXmlHttp.onreadystatechange=subSubCatStateChangeHandler;
		subcatXmlHttp.open("GET", 'getcatsxml.php?'+qryStr, true);
		subcatXmlHttp.send(null);
	}
}

/**
*	Deals with the AJAX response as the subcategory request state changes
**/
function subSubCatStateChangeHandler()
{
	switch(subcatXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			// Check that the document loaded is aok
			if(subcatXmlHttp.status == 200){
				var xmlDoc=getXMLDom(subcatXmlHttp);
				// Set local results array to contain the just fetched set.
				var categories = xmlDoc.getElementsByTagName('category');
				// Get the sub category select
				categoryDD = document.getElementById('businessSubSubCategory');
				categoryDD.innerHTML = '';

				// set local blank array to contain options
				var currOption = new Array();

				// Create default option to allow all possible options to be selected
				defaultOption = document.createElement('option');
				defaultOption.value	= '';
				defaultOption.innerHTML	= 'Sub Sub Category';
				categoryDD.appendChild(defaultOption);

				// Loop through all results and add options
				for(var i=0;i<categories.length;i++){
					currOption[i] = document.createElement('option');

					currOption[i].value	= categories[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					currOption[i].innerHTML	= categories[i].getElementsByTagName('name')[0].firstChild.nodeValue;

					categoryDD.appendChild(currOption[i]);
				}

				// Check if results have been returned and display only if they have
				if(categoryDD.options.length > 1){
					categoryDD.style.display = 'inline';
					document.getElementById('businessSubSubCategoryLabel').style.display = 'block';
					document.getElementById('businessSubSubCategoryBr').style.display = 'inline';
				} else {
					categoryDD.style.display = 'none';
					document.getElementById('businessSubSubCategoryLabel').style.display = 'none';
					document.getElementById('businessSubSubCategoryBr').style.display = 'none';
				}
			}
		break;
	}

}
/**
*	Creates the AJAX request to get the possible subcategories
*	`given the selected category.
**/
function loadSubCategories(){

	// Create query string to pass search variables to xml request
	var qryStr = generateQueryString();

	document.getElementById('businessSubCategory').style.display = 'none';
	document.getElementById('businessSubCategoryLabel').style.display = 'none';
	document.getElementById('businessSubCategoryBr').style.display = 'none';
	document.getElementById('businessSubCategory').style.zIndex = 0;

	document.getElementById('businessSubSubCategory').style.display = 'none';
	document.getElementById('businessSubSubCategoryLabel').style.display = 'none';
	document.getElementById('businessSubSubCategoryBr').style.display = 'none';
	document.getElementById('businessSubSubCategory').style.zIndex = 0;

	if (searchVariables['businessCategory'] != "") {
		subcatXmlHttp = createXMLObj();
		subcatXmlHttp.onreadystatechange=subcatStateChangeHandler;
		subcatXmlHttp.open("GET", 'getcatsxml.php?'+qryStr, true);
		subcatXmlHttp.send(null);
	}
}

/**
*	Deals with the AJAX response as the subcategory request state changes
**/
function subcatStateChangeHandler()
{
	switch(subcatXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			// Check that the document loaded is aok
			if(subcatXmlHttp.status == 200){
				var xmlDoc=getXMLDom(subcatXmlHttp);
				// Set local results array to contain the just fetched set.
				var categories = xmlDoc.getElementsByTagName('category');
				// Get the sub category select
				categoryDD = document.getElementById('businessSubCategory');
				categoryDD.innerHTML = '';

				// set local blank array to contain options
				var currOption = new Array();

				// Create default option to allow all possible options to be selected
				defaultOption = document.createElement('option');
				defaultOption.value	= '';
				defaultOption.innerHTML	= 'Sub Category';
				categoryDD.appendChild(defaultOption);

				// Loop through all results and add options
				for(var i=0;i<categories.length;i++){
					currOption[i] = document.createElement('option');

					currOption[i].value	= categories[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					currOption[i].innerHTML	= categories[i].getElementsByTagName('name')[0].firstChild.nodeValue;

					categoryDD.appendChild(currOption[i]);
				}

				// Check if results have been returned and display only if they have
				if(categoryDD.options.length > 1){
					categoryDD.style.display = 'inline';
					document.getElementById('businessSubCategoryLabel').style.display = 'block';
					document.getElementById('businessSubCategoryBr').style.display = 'inline';
				} else {
					categoryDD.style.display = 'none';
					document.getElementById('businessSubCategoryLabel').style.display = 'none';
					document.getElementById('businessSubCategoryBr').style.display = 'none';
				}
			}
		break;
	}

}

/**
*	Creates the AJAX request to get the possible top level categories
**/
function loadCategories(){
	catXmlHttp = createXMLObj();
	catXmlHttp.onreadystatechange=catStateChangeHandler;
	catXmlHttp.open("GET", 'getcatsxml.php', true);
	catXmlHttp.send(null);
}

/**
*	Deals with the AJAX response as the category request state changes
**/
function catStateChangeHandler()
{
	switch(catXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			if(catXmlHttp.status == 200){
				var xmlDoc=getXMLDom(catXmlHttp);
				// Set local results array to contain the just fetched set.
				var categories = xmlDoc.getElementsByTagName('category');
				categoryDD = document.getElementById('businessCategory');
				categoryDD.innerHTML = '';
				currOption = new Array();


				// Create default option to allow all possible options to be selected
				defaultOption = document.createElement('option');
				defaultOption.value	= '';
				defaultOption.innerHTML	= 'Category';
				categoryDD.appendChild(defaultOption);

				// Loop through all results and add options
				for(var i=0;i<categories.length;i++){
					currOption[i] = document.createElement('option');

					currOption[i].value	= categories[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					currOption[i].innerHTML	= categories[i].getElementsByTagName('name')[0].firstChild.nodeValue;

					categoryDD.appendChild(currOption[i]);
				}
			}
		break;
	}

}

/**
*	Creates the AJAX request to get the possible areas served
**/
function loadAreas(){
	areaXmlHttp = createXMLObj();
	areaXmlHttp.onreadystatechange=areaStateChangeHandler;
	areaXmlHttp.open("GET", 'getareasxml.php', true);
	areaXmlHttp.send(null);
}

/**
*	Deals with the AJAX response as the area served request state changes
**/
function areaStateChangeHandler()
{
	switch(areaXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			if(areaXmlHttp.status == 200){
				var xmlDoc=getXMLDom(areaXmlHttp);
				// Set local results array to contain the just fetched set.
				var areas = xmlDoc.getElementsByTagName('area');
				areaDD = document.getElementById('areaServed');
				areaDD.innerHTML = '';
				currOption = new Array();

				// Create default option to allow all possible options to be selected
				defaultOption = document.createElement('option');
				defaultOption.value	= '';
				defaultOption.innerHTML	= 'Areas Served';
				areaDD.appendChild(defaultOption);

				// Loop through all results and add options
				for(var i=0;i<areas.length;i++){
					currOption[i] = document.createElement('option');

					currOption[i].value	= areas[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					currOption[i].innerHTML	= areas[i].getElementsByTagName('name')[0].firstChild.nodeValue;

					areaDD.appendChild(currOption[i]);
				}
			}
		break;
	}

}

/**
*	Creates the AJAX request to get the nearest towns served
**/
function loadTowns(){
	townXmlHttp = createXMLObj();
	townXmlHttp.onreadystatechange=townStateChangeHandler;
	townXmlHttp.open("GET", 'gettownsxml.php', true);
	townXmlHttp.send(null);
}


/**
*	Deals with the AJAX response as the nearest towns request state changes
**/
function townStateChangeHandler()
{
	switch(townXmlHttp.readyState){
		case 1:
		case 2:
		case 3:
		default:
			// Load not completed
		break;
		case 4:
			if(townXmlHttp.status == 200){
				var xmlDoc=getXMLDom(townXmlHttp);
				// Set local results array to contain the just fetched set.
				var towns = xmlDoc.getElementsByTagName('town');
				townDD = document.getElementById('nearTown');
				townDD.innerHTML = '';
				currOption = new Array();

				// Create default option to allow all possible options to be selected
				defaultOption = document.createElement('option');
				defaultOption.value	= '';
				defaultOption.innerHTML	= 'Nearby towns';
				townDD.appendChild(defaultOption);

				// Loop through all results and add options
				for(var i=0;i<towns.length;i++){
					currOption[i] = document.createElement('option');
					currOption[i].value	= towns[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					currOption[i].innerHTML	= towns[i].getElementsByTagName('name')[0].firstChild.nodeValue;
					townDD.appendChild(currOption[i]);
				}
			}
		break;
	}

}

/** Data loading functions - End **/


/** Utility Functions - Start **/
/**
 * Creates a browser specific XMLHttpRequest object for any browsers
 * that support the object, either by retunring that object of the
 * ActiveX equivalent.
**/
function createXMLObj()
{
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari etc.
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// IE et al.
		try {
			xmlHttp= new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				xmlHttp = null;
			}
		}
	}
	return xmlHttp;
}


/** Retrieve XML as a DOM can work with cross browser **/
function getXMLDom(requester){
	var xmlDocReturn = requester.responseXML;
	if (!(xmlDocReturn)){
		//Create a xml tag in run time
		var testandoAppend = document.createElement('xml');
		//Put the requester.responseText in the innerHTML of the xml tag
		testandoAppend.setAttribute('innerHTML',requester.responseText);
		//Set the xml tag's id to _formjAjaxRetornoXML
		testandoAppend.setAttribute('id','_formjAjaxRetornoXML');
		//Add the created tag to the page context
		document.body.appendChild(testandoAppend);
		//Just for check put the xmlhttp.responseXML in the innerHTML of the tag
		document.getElementById('_formjAjaxRetornoXML').innerHTML = requester.responseText;
		//Now we can get the xml tag and put it on a var
		xmlDocReturn = document.getElementById('_formjAjaxRetornoXML');
		//So we have a valid xml we can remove the xml tag document.body.removeChild(document.getElementById('_formjAjaxRetornoXML'));\n" +
	}
	return xmlDocReturn;
}

/** takes all search variables and create a query
*	string format string that is then returned. **/
function generateQueryString()
{
	var qryStr = 0;
	for(key in searchVariables){
		if(searchVariables[key] != ''){
			if(qryStr){
				qryStr += '&' + key + '=' + searchVariables[key];
			} else {
				qryStr = key + '=' + searchVariables[key];
			}
		}
	}
	return qryStr;
}

/** Hide the iFrame with the ID passed in. **/
function hideSuggestions(iFrame)
{
	suggestionIframe = document.getElementById(iFrame).style.display = 'none';
}

/** Show the iFrame with the ID passed in. **/
function showSuggestions(iFrame)
{
	suggestionIframe = document.getElementById(iFrame).style.display = 'block';
}

/** Utility Functions - End **/


/** Form assembling - Start **/


/** This function contains the code that prodces the inital search form **/
function createForm()
{

	// Fetch results and form div
	var ajaxDiv = document.getElementById('ajaxDiv');
	ajaxDiv.innerHTML = '';
	var resultsDiv = document.getElementById('resultsDiv');

	// Create the form
	var ajaxForm	= document.createElement('form');
	ajaxForm.id		= 'ajaxForm';
	ajaxForm.method	= 'post';

	// Create the Business name text field and label
	var bizNameLabel		= document.createElement('label');
	bizNameLabel.htmlFor		= 'businessName';
	bizNameLabel.innerHTML	= 'Business Name: ';
	var bizNameInput		= document.createElement('input');
	bizNameInput.id			= 'businessName';
	bizNameInput.name		= 'businessName';
	bizNameInput.type		= 'text';
	bizNameInput.value		= '';
	bizNameInput.onchange	= nameBlurHandler;
	bizNameInput.onkeyup	= nameKeyupHandler;
	bizNameInput.autocomplete = "off";
	var br1		= document.createElement('br');
	br1.clear	= 'all';

	// Create suggestions iframe and a br to clear it for IE.
	var bizNameSuggestions				= document.createElement('iframe');
	bizNameSuggestions.id				= 'businessSuggestions';
	bizNameSuggestions.src				= 'suggestions.html';
	bizNameSuggestions.onfocus			= "showSuggestions('businessSuggestions')";
	bizNameSuggestions.zIndex			= 1;
	var br2		= document.createElement('br');
	br2.clear	= 'all';
	br2.style.display = 'none';
	br2.style.lineHeight	= '0px';

	// Append everything for business name to the form
	ajaxForm.appendChild(bizNameLabel);
	ajaxForm.appendChild(bizNameInput);
	ajaxForm.appendChild(br1);
	ajaxForm.appendChild(bizNameSuggestions);
	ajaxForm.appendChild(br2);

	// Create the Buiness Category select field and label
	var bizCatLabel			= document.createElement('label');
	bizCatLabel.htmlFor			= 'businessCategory';
	bizCatLabel.innerHTML	= 'Business Category: ';
	var bizCatInput			= document.createElement('select');
	bizCatInput.id			= 'businessCategory';
	bizCatInput.name		= 'businessCategory';
	bizCatInput.onchange	= categoryChangeHandler;
	bizCatInput.onkeyup		= categoryChangeHandler;
	var br3		= document.createElement('br');
	br3.clear	= 'all';


	// Append everything for business category to the form
	ajaxForm.appendChild(bizCatLabel);
	ajaxForm.appendChild(bizCatInput);
	ajaxForm.appendChild(br3);

	// Create the Buiness Sub Category select field and label
	var bizSubCatLabel			= document.createElement('label');
	bizSubCatLabel.htmlFor			= 'businessSubCategory';
	bizSubCatLabel.id			= 'businessSubCategoryLabel';
	bizSubCatLabel.innerHTML	= 'Business Sub-category: ';
	bizSubCatLabel.style.display		= 'none';
	var bizSubCatInput				= document.createElement('select');
	bizSubCatInput.id				= 'businessSubCategory';
	bizSubCatInput.name				= 'businessSubCategory';
	bizSubCatInput.onchange			= subcategoryChangeHandler;
	bizSubCatInput.onkeydown		= subcategoryChangeHandler;
	bizSubCatInput.onload			= 'subCatSetup(this)';
	bizSubCatInput.style.display	= 'none';
	var br4					= document.createElement('br');
	br4.id					= 'businessSubCategoryBr';
	br4.style.display		= 'none';
	br4.clear				= 'all';

	// Append everything for business sub category to the form
	ajaxForm.appendChild(bizSubCatLabel);
	ajaxForm.appendChild(bizSubCatInput);
	ajaxForm.appendChild(br4);

	// Create the Buiness Sub Category select field and label
	var bizSubSubCatLabel			= document.createElement('label');
	bizSubSubCatLabel.htmlFor			= 'businessSubSubCategory';
	bizSubSubCatLabel.id			= 'businessSubSubCategoryLabel';
	bizSubSubCatLabel.innerHTML	= 'Business Sub-sub-category: ';
	bizSubSubCatLabel.style.display		= 'none';
	var bizSubSubCatInput				= document.createElement('select');
	bizSubSubCatInput.id				= 'businessSubSubCategory';
	bizSubSubCatInput.name				= 'businessSubSubCategory';
	bizSubSubCatInput.onchange			= subsubcategoryChangeHandler;
	bizSubSubCatInput.onkeydown		= subsubcategoryChangeHandler;
	bizSubSubCatInput.onload			= 'subSubCatSetup(this)';
	bizSubSubCatInput.style.display	= 'none';
	var br5					= document.createElement('br');
	br5.id					= 'businessSubSubCategoryBr';
	br5.style.display		= 'none';
	br5.clear				= 'all';

	// Append everything for business sub category to the form
	ajaxForm.appendChild(bizSubSubCatLabel);
	ajaxForm.appendChild(bizSubSubCatInput);
	ajaxForm.appendChild(br5);
		// Create the Area Served select field and label
	/*var areaServedLabel			= document.createElement('label');
	areaServedLabel.htmlFor			= 'areaServed';
	areaServedLabel.innerHTML	= 'Area Served: ';
	var areaServedInput			= document.createElement('select');
	areaServedInput.id			= 'areaServed';
	areaServedInput.name		= 'areaServed';
	areaServedInput.onchange	= areaChangeHandler;
	areaServedInput.onkeydown	= areaChangeHandler;
	areaServedInput.onload		= 'areaSetup(this)';
	var br5		= document.createElement('br');
	br5.clear	= 'all';

	// Append everything for area served to the form
	ajaxForm.appendChild(areaServedLabel);
	ajaxForm.appendChild(areaServedInput);
	ajaxForm.appendChild(br4);*/

	// Create the Nearest Town select field and label
	var nearTownLabel			= document.createElement('label');
	nearTownLabel.htmlFor			= 'nearTown';
	nearTownLabel.innerHTML		= 'Nearest main town: ';
	var nearTownInput			= document.createElement('select');
	nearTownInput.id			= 'nearTown';
	nearTownInput.name			= 'nearTown';
	nearTownInput.onchange		= townChangeHandler;
	nearTownInput.onkeydown		= townChangeHandler;
	nearTownInput.onload		= 'townSetup(this)';
	var br6		= document.createElement('br');
	br6.clear	= 'all';

	// Append everything for nearest town to the form
	ajaxForm.appendChild(nearTownLabel);
	ajaxForm.appendChild(nearTownInput);
	ajaxForm.appendChild(br6);

	// Create the Product or Service text field and label
	var prodServLabel		= document.createElement('label');
	prodServLabel.htmlFor		= 'prodServ';
	prodServLabel.innerHTML	= 'Keyword Search: ';
	var prodServInput		= document.createElement('input');
	prodServInput.id		= 'prodServ';
	prodServInput.name		= 'prodServ';
	prodServInput.type		= 'text';
	prodServInput.value		= '';
	prodServInput.onkeyup	= prodServBlurHandler;
// 19-02-2008 :: Commented out after comment from KT
//	prodServInput.onchange	= prodServBlurHandler;
//	prodServInput.onkeyup	= prodServKeyupHandler;
//	prodServInput.autocomplete = "off";
	var br7		= document.createElement('br');
	br7.clear	= 'all';

// 19-02-2008 :: Commented out after comment from KT
	// Create suggestions iframe and a br to clear it for IE.
//	var prodServSuggestions				= document.createElement('iframe');
//	prodServSuggestions.id				= 'prodServSuggestions';
//	prodServSuggestions.src				= 'suggestions.html';
//	prodServSuggestions.onfocus			= "showSuggestions('prodServSuggestions')";
//	var br8		= document.createElement('br');
//	br8.clear	= 'all';
//	br8.style.lineHeight	= '0px';

	// Append everything for product or service to the form
	ajaxForm.appendChild(prodServLabel);
	ajaxForm.appendChild(prodServInput);
	ajaxForm.appendChild(br7);

// 19-02-2008 :: Commented out after comment from KT
//	ajaxForm.appendChild(prodServSuggestions);
//	ajaxForm.appendChild(br8);

	// Create the Postcode text field and label
	var postcodeLabel		= document.createElement('label');
	postcodeLabel.htmlFor		= 'postcode';
	postcodeLabel.innerHTML	= 'Postcode: ';
	var postcodeInput		= document.createElement('input');
	postcodeInput.id		= 'postcode';
	postcodeInput.name		= 'postcode';
	postcodeInput.type		= 'text';
	postcodeInput.value		= '';
	postcodeInput.onchange	= 'void';
	postcodeInput.onchange	= postcodeBlurHandler;
	postcodeInput.onkeyup	= postcodeKeyupHandler;
	postcodeInput.autocomplete = "off";

	postcodeInput.setAttribute('autocomplete', 'off');

	var br9		= document.createElement('br');
	br9.clear	= 'all';

	// Create suggestions iframe and a br to clear it for IE.
	var postcodeSuggestions				= document.createElement('iframe');
	postcodeSuggestions.id				= 'postcodeSuggestions';
	postcodeSuggestions.src				= 'suggestions.html';
	postcodeSuggestions.onfocus			= "showSuggestions('postcodeSuggestions')";
	var br10		= document.createElement('br');
	br10.clear	= 'all';

	// Append everything for postcode to the form
	ajaxForm.appendChild(postcodeLabel);
	ajaxForm.appendChild(postcodeInput);
	ajaxForm.appendChild(br9);
	ajaxForm.appendChild(postcodeSuggestions);
	ajaxForm.appendChild(br10);


	// Create a div for the reset button
	var resetDiv = document.createElement('div');
	resetDiv.className = 'reset-div';

	// Create a p tag and html for the
	// 'Results are displayed below' message
	var resetP = document.createElement('p');
	resetP.id = 'results-message';

	// Create a reset button and add it to the form
	var resetLabel		= document.createElement('label');
	resetLabel.htmlFor		= 'reset';
	resetLabel.innerHTML	= '&nbsp;';
	resetLabel.style.display	= 'none';
	resetBut = document.createElement('input');
	resetBut.type = 'reset';
	resetBut.id = 'reset';
	resetBut.value = 'Reset';
	resetBut.style.width = 'auto';
	resetBut.onclick = resetForm;

	var submitLabel		= document.createElement('label');
	submitLabel.htmlFor		= 'submit';
	submitLabel.innerHTML	= '&nbsp;';
	submitLabel.style.display	= 'none';
	submitBut = document.createElement('input');
	submitBut.type = 'button';
	submitBut.id = 'searchButton';
	submitBut.value = 'Search';
	submitBut.style.width = 'auto';
	submitBut.style.marginRight = "5px";
	submitBut.onclick = loadResults;

	// Add to the reset div
	resetDiv.appendChild(submitLabel);
	resetDiv.appendChild(submitBut);
	resetDiv.appendChild(resetLabel);
	resetDiv.appendChild(resetBut);
	resetDiv.appendChild(resetP);

	ajaxForm.appendChild(resetDiv);

/** Started adding a Search button

	// Create a div for the submit button
	var submitDiv = document.createElement('div');
	resetDiv.className = 'submit-div';

	// Create a p tag and html for the
	// 'Results are displayed below' message
	var submitP = document.createElement('p');
	submitP.id = 'submit-message';

	// Create a submit button and add it to the form
	var submitLabel		= document.createElement('label');
	submitLabel.htmlFor		= 'submit';
	submitLabel.innerHTML	= '&nbsp;';
	submitLabel.style.display	= 'none';
	submitBut = document.createElement('input');
	submitBut.type = 'submit';
	submitBut.id = 'submit';
	submitBut.value = 'Submit';
	submitBut.style.width = 'auto';
	submitBut.onclick = submitForm;

	// Add to the reset div
	submitDiv.appendChild(submitLabel);
	submitDiv.appendChild(submitBut);
	submitDiv.appendChild(submitP);

	ajaxForm.appendChild(submitDiv);

**/

	// Add a br to clear the bottom of the form in IE
	var br11		= document.createElement('br');
	br11.clear		= 'all';
	ajaxForm.appendChild(br11);

	// Add the form to the div
	ajaxDiv.appendChild(ajaxForm);

	// Add a br to clear the bottom of the form in IE
//	var clearPara		= document.createElement('p');
//	clearPara.clear	= 'all';
//	clearPara.innerHTML = '&nbsp;';
//	ajaxDiv.appendChild(clearPara);


}


/** This function resets the results div to contain the instructions **/
function resetResults()
{
	// Variable name should be different to div id or it causes problems in IE.
	resultsDivRef = document.getElementById('resultsDiv');
	paginationDivTopRef = document.getElementById('paginationDivTop');
	paginationDivBotRef = document.getElementById('paginationDivBottom');
	resultsDivRef.innerHTML = '';
	paginationDivTopRef.innerHTML = '';
	paginationDivBotRef.innerHTML = '';
	h2Child = document.createElement('h2');
	h2Child.innerHTML = 'How to use:';
	paginationDivTopRef.appendChild(h2Child);

	// Reset the results message
	resultsMessage = document.getElementById('results-message');
	resultsMessage.innerHTML = '';

	pChild = document.createElement('p');

	var instructions = 'Looking for a business or supplier in your area? - Then search our Local Business Directory.';
	instructions += '<br /><br /><strong>Tip:</strong> Try searching for part of a word to get a greater range of results.';
	instructions += '<br /><br />For example, if you&rsquo;re looking for a ';
	instructions += 'plumber, just type <strong>plumb</strong> into the Keyword Search box to bring ';
	instructions += 'up search results for <strong>plumber, plumbers and plumbing</strong>.';

	pChild.innerHTML = instructions;
	resultsDivRef.appendChild(pChild);
}

/** Calls all the load functions for the drop downs **/
function setupForm($post)
{
	loadCategories();
	//loadAreas();
	loadTowns();
}

/** Builds the form, sets initial status and set intial state for results div **/
function buildForm()
{
	createForm();
	setupForm();
	resetResults();
}

/** Form assembling - End **/