var searchForm;

function replaceForm(xmlDoc)
{
	try {
		var rootNode = xmlDoc.documentElement;
		var traverseNode = rootNode.firstChild;

		while (traverseNode != null)
		{
			if (traverseNode.nodeType != 1 || traverseNode.nodeName != "list_box")
			{
				// Continue searching with next sibling.
				traverseNode = traverseNode.nextSibling;
				continue;
			}

			if (traverseNode.nodeName == "list_box")
			{
				// Retrieve value from <list_box>
				var optionListName = traverseNode.getAttribute("name");
				//alert(optionListName);

				// Create reference to list box.
				var listBoxRef = searchForm.elements[optionListName];
				var alreadySelected = false;

				// Check whether listbox exists on form. If not, no bother proceeding...
				if (listBoxRef != null)
				{
					var allListBoxOptions= listBoxRef.options;
					var selectedListBoxOptionValue = allListBoxOptions[listBoxRef.selectedIndex].value;

					var optionNode = traverseNode.firstChild;
					var optionArray = new Array();
					do
					{
						if (optionNode != null && optionNode.nodeName == "#text")
						{
							// Skip text nodes.
							optionNode = optionNode.nextSibling;
							continue;
						}

						// Retrieve data from <option> node.
						if (optionNode != null && optionNode.nodeName == "option")
						{
							// Add option to list
							var valueAttr = optionNode.getAttribute("value");
							optionNode.normalize();
							var nameAttr = optionNode.firstChild;
							// Only get the nodeValue if an option text is available (location names, ...)
							nameAttr = (nameAttr == null) ? "" : nameAttr.nodeValue;
							nameAttr = unescape(nameAttr);
							//alert ("sibling name:" + optionNode.nodeName + "\n name: " + nameAttr + "\n Value:" + valueAttr );
							var selected = false;
							if (valueAttr == selectedListBoxOptionValue && alreadySelected == false)
							{
								// Mark current option as selected
								selected = true;
								alreadySelected = true;
							}
							else
							{
								// Current option is not selected.
								selected = null;
							}
							var myOption = new Option(nameAttr, valueAttr, selected, selected);
							optionArray.push(myOption);
						}
						else
						{
							//alert ("No option node!");
						}
						optionNode = optionNode.nextSibling;
					}while (optionNode != null)

					if (listBoxRef != null)
					{
						//alert("Option " + allListBoxOptions[selectedListBoxOptionValue].text);

						// Remove previous options from list box
						while (listBoxRef.length > 0)
						{
							listBoxRef.remove(0);
						}

						// Add new options to list box.
						for (var i = 0 ; i < optionArray.length; i++)
						{
							listBoxRef.options[i] = optionArray[i];
						}
					}
				}
			}
			// Next item
			traverseNode = traverseNode.nextSibling;
		}
	}
	catch (e)
	{
		var s = ((typeof e) == 'string') ? e : e.message;
		alert('Error in replaceForm():\n' + s);
	}
}

function showWaitMessageInListBoxes()
{
	var listBoxesArray = new Array ( "regionId", "journeyTypeId", "duration" );

	for (var i = 0; i < listBoxesArray.length; i++)
	{
		var listBoxRef = searchForm.elements[listBoxesArray[i]];
		if (listBoxRef != null)
		{
			listBoxRef.options[listBoxRef.selectedIndex].text = ajaxWaitMessage;
		}
	}
}

function errorHandler(responseCode, resposeMsg)
{
	alert('Error! HTTP response ' + responseCode + ' ' + resposeMsg);
	// Retries? Repairs?
	window.location.reload();
}

function httpRequest(method, url, data, xmlResponseHandler, errorHandler, asText)
{
	var debug = '';
	var xmlHttpReq = null;
	try {
		debug = 'obtaining XMLHTTP client object';
		xmlHttpReq = new XMLHttpRequest();
	}
	catch (tryMicro) {
		try	{
			xmlHttpReq  = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (otherMicros) {
			try {
				xmlHttpReq  = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (failed) {
				xmlHttpReq  = null;
			}
		}
	}
	try {
		if (xmlHttpReq == null)	{
			throw 'No suitable AJAX object';
		}
		debug = 'checking request method';
		if (method == null)	{
			method = 'GET';
		}
		if (method == 'GET') {
			url = url + '?' + data;
		}
		debug = 'calling open()';
		xmlHttpReq.open(method, url, true);
		debug = 'setting parameters';
		if (method == 'POST') {
			xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
		xmlHttpReq.setRequestHeader('Pragma', 'no-cache');
		xmlHttpReq.setRequestHeader('Cache-Control', 'no-cache');
		debug = 'setting callback method';
		xmlHttpReq.onreadystatechange = function() {
			if (xmlHttpReq.readyState == 4)	{
				if (xmlHttpReq.status == 200) {
					xmlResponseHandler((asText) ? xmlHttpReq.responseText : xmlHttpReq.responseXML);
				}
				else {
					if (typeof errorHandler == 'function') {
						errorHandler(xmlHttpReq.status, xmlHttpReq.statusText);
					}
				}
			}
		}
		debug = 'calling send()';
		xmlHttpReq.send(data);
	}
	catch (e) {
		try {
			var s = 'Error ' + debug + ':\n';
			if ((typeof e) == 'string') {
				s += e;
			}
			else {
				for (var i in e) {
					s += '\n' + i + ': ' + e[i];
				}
			}
			alert('Error in httpRequest():\n' + s);
		}
		catch (e2) {
			var s2 = ((typeof e2) == 'string') ? e : e.message;
			alert('Flip: ' + s2);
		}
	}
}

function selectionChanged(formObj, changedName)
{
	var loc = window.location;
	var url = loc.protocol + '//' + loc.host + loc.pathname.substring(0, loc.pathname.lastIndexOf('/'));
	url += '/searchOptions.tsi';

	searchForm = formObj;

	var data = '';
	data += 'regionId=' + escape(formObj.regionId.value);
	data += '&journeyTypeId=' + escape(formObj.journeyTypeId.value);
	data += '&startDate=' + escape(formObj.startDate.value);
	data += '&numberOfAdults=' + escape(formObj.numberOfAdults.value);
	data += '&numberOfChildren=' + escape(formObj.numberOfChildren.value);
	data += '&numberOfInfants=' + escape(formObj.numberOfInfants.value);
	data += '&duration=' + escape(formObj.duration.value);
	data += '&action=change';
	data += '&changedName=' + changedName;

	// Show please wait message in list boxes
	showWaitMessageInListBoxes();

	httpRequest('GET', url, data, replaceForm, errorHandler);
}
