// Set initial values for global variables
var num_RoomsRequired;
var obj_Occupancy;
var obj_ChildAges;
var minStringLen = 2;
var lastSearch = "";
var directionActive = "";
var currentSearch = 0;
var obj_Clear = js_DOMCreateDiv('hs_Clear', '');

/* Sets up the number of rooms and the like */
var arr_RoomData = [];
var arr_ChildAges = [];
for (i=0;i<6;i++) arr_RoomData[i] = {'a':2,'c':0,'s':false};

/************************************************************************/
/* Internal call functions												*/
/************************************************************************/


function js_SwitchFormFieldOnOff(formField, bol_Switch) {
	var formFieldElem = $(formField);
	formFieldElem.disabled = bol_Switch;
}

function js_DOMCreateDiv(str_Class, str_Text, obj_ChildNode) {
	el_NewDiv = document.createElement('div');
	if (str_Class.length > 0) {
		el_NewDiv.className=str_Class;
	}
	if (str_Text != '') {
		el_NewText = document.createTextNode(str_Text);
		el_NewDiv.appendChild(el_NewText);
	}
	if (obj_ChildNode)
		el_NewDiv.appendChild(obj_ChildNode);
	return el_NewDiv;
}

function js_DOMCreateP(str_Class, str_Text, obj_ChildNode) {
	el_NewDiv = document.createElement("P");
	if (str_Class.len > 0) {
		if (navigator.userAgent.indexOf('MSIE') == -1) 
			el_NewDiv.setAttribute("class", str_Class);
		else
			el_NewDiv.setAttribute("className", str_Class);
	}
	if (str_Text != '') {
		el_NewText = document.createTextNode(str_Text);
		el_NewDiv.appendChild(el_NewText);
	}
	if (obj_ChildNode)
		el_NewDiv.appendChild(obj_ChildNode);
	return el_NewDiv;
}

function js_checkChildAgesFilled(formEle) {
	while (formEle.tagName!=='FORM') formEle=formEle.parentNode;	
	rExp=/frm_Child[0-9]/gi;
	allSet=true;
	if(formEle.elements.length>0) for(i=0;i<formEle.elements.length;i++) if(formEle.elements[i].id.search(rExp)>-1 && formEle.elements[i].options[formEle.elements[i].selectedIndex].value==-1) allSet=false;
	return allSet;
}

function js_DOMCreateSelect(str_FieldName, num_Min, num_Max) {
	el_NewSelect = document.createElement('SELECT');
	el_NewSelect.setAttribute('name', str_FieldName);
	el_NewSelect.setAttribute('id', str_FieldName);
	rExp=/frm_Child[0-9]/gi;
	if (str_FieldName.search(rExp)>-1) {
		js_addOption(el_NewSelect,'-1','-',false);
		if(document.getElementById('holSearchSubmit')) {
			el_NewSelect.onchange=function(){js_checkChildAgesFilled(this)};
		}
	}
	rExp=/frm_AdultsRoom[0-9]/gi;
	for (j = num_Min; j <= num_Max; j++) 
		if ((str_FieldName.search(rExp)>-1) && (j==2))
			js_addOption(el_NewSelect, j, j, true);
		else
			js_addOption(el_NewSelect, j, j, false);
	return el_NewSelect;
}

function js_SelectRoomOccupants(num_Rooms) {
	var tot_adult = 0;
	var tot_child = 0;
	for (rl = 0; rl < num_Rooms; rl++) {
		num_RoomNum = rl + 1;
		var num_children = parseInt(obj_Occupancy["occupancy"][rl]["num_numchildren"]) + parseInt(obj_Occupancy["occupancy"][rl]["num_numinfants"]);
		js_selectValue('frm_AdultsRoom'+(num_RoomNum), obj_Occupancy["occupancy"][rl]["num_numadults"], false);
		js_selectValue('frm_ChildrenRoom'+(num_RoomNum), num_children, false);
		tot_adult += obj_Occupancy["occupancy"][rl]["num_numadults"];
		tot_child += obj_Occupancy["occupancy"][rl]["num_numchildren"];
		tot_child += obj_Occupancy["occupancy"][rl]["num_numinfants"];
	}
	js_selectValue('num_NumberOfAdults',tot_adult);
	js_selectValue('num_NumberOfChildren',tot_child);
}

function js_SelectChildAges() {
	if ($('s_site_dlf') && $('s_site_dlf').checked) {
		var num_Children = 0;
		num_Children = num_Children + parseInt($('num_NumberOfChildren').value);
		for (ch = 1; ch <= num_Children; ch++) {
			js_selectValue('frm_Child'+(ch), arr_ChildAges[ch-1], false);
		}
	}
}


// Function to add an option to a select list
function js_addOption(obj_docElem, str_value, str_text, bol_Selected) {
	var newElem = document.createElement("OPTION");
	newElem.value = str_value;
	newElem.text = str_text;
	if (bol_Selected) newElem.selected = 'selected';
	if (navigator.userAgent.indexOf('MSIE') == -1)
		obj_docElem.add(newElem, null);
	else
		obj_docElem.add(newElem);
}

// Function to select a value in the select list
function js_selectValue(str_formID, str_changeToValue, bol_CallOnChange) {
	var obj_SelectList = $(str_formID);
	if (obj_SelectList) {
		var num_SelectListItems = obj_SelectList.childNodes.length;
		if (num_SelectListItems != 0) {
			for (i=0; i<num_SelectListItems; i++) {
				if (obj_SelectList.childNodes[i].value == str_changeToValue) {
					obj_SelectList.childNodes[i].selected = true;
					if (bol_CallOnChange)
						obj_SelectList.onchange();
					return true;
				}
			}
		}
	}
}

// Function to remove the first child of a select list
function js_removeFirstChild(obj_docElem) {
	obj_docElem.removeChild(obj_docElem.firstChild);
}

// Function to remove all items from a select list
function js_removeAllChildren(obj_docElem) {
	if (obj_docElem !== null && obj_docElem.firstChild) {
		while (obj_docElem.firstChild) {
			obj_docElem.removeChild(obj_docElem.firstChild);
		}
	}
}

/************************************************************************/
/* External call functions												*/
/************************************************************************/

// Function to initialise the search form
function initHolidaySearchForm() {
	for (i=1;i<10;i++) {
		if ($('JSonly_'+i)) {
			$('JSonly_'+i).style.display = 'block';
		} else break;
	}
	for (i=1;i<10;i++) {
		if ($('JSonlyrow_'+i)) {
			$('JSonlyrow_'+i).style.display = 'table-row';
		} else break;
	}
	try {$('cal1input').style.backgroundImage='url(/images/icon_calendar.gif)';} catch (e) {}
	try {$('cal2input').style.backgroundImage='url(/images/icon_calendar.gif)';} catch (e) {}
	try {$('cal3input').style.backgroundImage='url(/images/icon_calendar.gif)';} catch (e) {}
	try {$('cal4input').style.backgroundImage='url(/images/icon_calendar.gif)';} catch (e) {}
	if ($('hs_ChildAges')) $('hs_ChildAges').style.display = 'block';
	
	if ($('hs_site_select')) {
		$('hs_site_select').style.display = 'block';
		if ($('s_site_dla')) $('s_site_dla').checked = false;
		if ($('s_site_dlh')) $('s_site_dlh').checked = false;
		if ($('s_site_dlf')) $('s_site_dlf').checked = true;
		try {ms_SetSite('DLF');} catch (e) {}
	} else {
		js_OutputChildAges();
		js_SelectChildAges();
	}
}

function js_OutputRoomOccupants(num_Rooms) {
	obj_Occupants = $('hs_Occupants');
	num_RoomsRequired = num_Rooms;
	js_removeAllChildren(obj_Occupants);
	for (i = 1; i <= num_Rooms; i++) {
		// Create select lists
		obj_AdultsSelect = js_DOMCreateSelect('frm_AdultsRoom'+i, 1, 9);
		obj_ChildrenSelect = js_DOMCreateSelect('frm_ChildrenRoom'+i, 0, 9);
		// Create div's
		obj_RoomNumber = js_DOMCreateDiv('hs_OccupantsRoomNumber', 'Room '+i);
		obj_Adults = js_DOMCreateDiv('hs_OccupantsAdults', '', obj_AdultsSelect);
		obj_Children = js_DOMCreateDiv('hs_OccupantsChildren', '', obj_ChildrenSelect);
		if (navigator.userAgent.indexOf('MSIE') == -1)
			obj_Children.onchange = js_OutputChildAges;
		// Append the div's to the main object
		obj_Occupants.appendChild(obj_RoomNumber);
		obj_Occupants.appendChild(obj_Adults);
		obj_Occupants.appendChild(obj_Children);
		obj_Occupants.appendChild(obj_Clear);
		if (navigator.userAgent.indexOf('MSIE') != -1)
			eventAttached = document.getElementById('frm_ChildrenRoom'+i).attachEvent('onchange', js_OutputChildAges);
	}
	js_OutputChildAges();
}

function js_OutputChildAges() {
	obj_ChildAges = $('hs_ChildAges');
	// If there is not a first room then it will need populating 
	if (!$('frm_ChildrenRoom1')) {
		if ($('frm_nights')) {
			js_OutputRoomOccupants($('frm_nights').value);
		} else {
			js_OutputRoomOccupants(1);	
		}
	}
	if (obj_ChildAges !== null) {
		js_removeAllChildren(obj_ChildAges);
		var num_Children = 0;
		
		// If it is flight only use a different one
		if ($('s_site_dlf') && $('s_site_dlf').checked) {
			num_Children = $('num_NumberOfChildren').value;	
		} else {
			for (i = 1; i <= num_RoomsRequired; i++) {
				num_Children = num_Children + parseInt($('frm_ChildrenRoom'+i).value)
			}
		}
		
		if (num_Children != 0) {
			obj_IntroText = js_DOMCreateDiv('hs_ChildIntroText', 'Please specify the ages of children at time of travel.');
			obj_ChildAges.appendChild(obj_IntroText);
			obj_ChildAges.appendChild(obj_Clear);
			for (i = 1; i <= num_Children; i++) {
				// Create select lists
				obj_ChildAgeSelect = js_DOMCreateSelect('frm_Child'+i, 0, 17);
				// Create div's
				obj_ChildNumber = js_DOMCreateDiv('hs_ChildrenNumber', 'Child '+i);
				obj_ChildAge = js_DOMCreateDiv('hs_Children', '', obj_ChildAgeSelect);
				obj_Clear = js_DOMCreateDiv('hs_Clear', '');
				// Append the div's to the main object
				obj_ChildAges.appendChild(obj_ChildNumber);
				obj_ChildAges.appendChild(obj_ChildAge);
				obj_ChildAges.appendChild(obj_Clear);
			}
			obj_ChildAges.style.display = 'block';
		} else {
			obj_ChildAges.style.display = 'none';
		}
	}
}

function toggle_advSearch() {
	if($('hs_adv_hide')) var B=$('hs_adv_hide').style.display;
	if($('hs_adv_show')) var A=$('hs_adv_show').style.display;
	//fix for IE
	if(A === '') A = 'block';
	if(B === '') B = 'block';
	if (A && B) {
		$('hs_adv_show').style.display=B;
		$('hs_adv_hide').style.display=A;
		if($('hs_adv_1')) $('hs_adv_1').style.display=A;
		if($('hs_adv_2')) $('hs_adv_2').style.display=A;
		if($('hs_adv_3')) $('hs_adv_3').style.display=A;
		if($('hs_adv_4')) $('hs_adv_4').style.display=A;
	}
}

function js_hideAllPopups() {
		try {hidePopups();} catch (e) {}
		if($('cal1anchor')) $('cal1anchor').style.display = 'none';
		if($('cal2anchor')) $('cal2anchor').style.display = 'none';
		if($('cal3anchor')) $('cal3anchor').style.display = 'none';
		if($('frm_departure_suggestions')) $('frm_departure_suggestions').style.display = 'none';
		if($('frm_destination_suggestions')) $('frm_destination_suggestions').style.display = 'none';
		if ($("hideDiv"))
		{
			$("hideDiv").style.display = 'none';
		}
		if (navigator.userAgent.match('MSIE 6')) {
			if($('NoA')) $('NoA').style.visibility = 'visible';
			if($('NoC')) $('NoC').style.visibility = 'visible';
		}
		if($('submitButton')) $('submitButton').disabled=false;
}

	
	function js_updateNights(num_Nights) {
		var inwardDate = document.getElementById("cal1input");
		var outwardDate = document.getElementById("cal2input");
		
		var endDate = new Date(inwardDate.value.substr(6,4),(inwardDate.value.substr(3,2)-1),inwardDate.value.substr(0,2));
		
		endDate.setTime(endDate.getTime()+(num_Nights*24*60*60*1000));
		outwardDate.value = lZero(endDate.getDate(),2)+"/"+lZero(endDate.getMonth()+1,2)+"/"+lZero(endDate.getFullYear(),2);
		
		DLHNS.calendar.cal2.select((endDate.getMonth()+1)+"/"+endDate.getDate()+"/"+endDate.getFullYear());
		DLHNS.calendar.cal2.setYear(endDate.getFullYear());
		DLHNS.calendar.cal2.setMonth(endDate.getMonth());
		DLHNS.calendar.cal2.render();
	}
	
	// FUNCTIONS FOR AJAX FLIGHT SEARCH (FREEFORM)
	
	
	function js_suggestAirport(airportDirection,searchString) {
		if ( searchString != lastSearch) {
			directionActive = airportDirection;
			//js_hideAllPopups();
			if (searchString.length >= minStringLen) {
				// Perform search
					// Search token
					currentSearch++;
					// Update last search variable
					lastSearch = searchString;
					
					// Generate query string with string attached, not forgetting to specify if it's departure or destination
					var url = '/flight_search_ajax.cfm';
					var pars = 'method=suggestAirport&currentSearch='+currentSearch+'&direction='+directionActive+'&searchString='+searchString;
		
					// If it is destination field, then make sure that there is a departure airport selected
					if (directionActive == 'destination' && document.getElementById('frm_departure_point').value != "") {
						// If so then append to query string
						pars += '&deptCode='+document.getElementById('frm_departure_point').value;
						try {document.getElementById('frm_destination_point').value = ''} catch (e) {}
					} 
					if (directionActive == 'departure' && document.getElementById('frm_destination_point').value != "") {
						pars += '&destCode='+document.getElementById('frm_destination_point').value;
						try {document.getElementById('frm_departure_point').value = ''} catch (e) {}
					}
		
					// Submit the query string and then this function is done
					var myAjax = new Ajax.Request(	url, 
							{
								method: 'get', 
								parameters: pars, 
								onComplete: js_updateSuggestionField
							});
			} else {
				// If string is too short, clear out element
				js_hideAllPopups();
				var obj_divElement = document.getElementById('frm_'+directionActive+'_suggestions');
				while (obj_divElement.firstChild) obj_divElement.removeChild(obj_divElement.firstChild);
				lastSearch = "";
			}
		}
	}
	
	function js_hideAndSelect() {
		// Find selected index
		selIndex = js_findSelectedIndex();
		// If there is a selected index, then execute onclick
		if (!isNaN(selIndex) && directionActive) {
			document.getElementById('frm_'+directionActive+'_suggestions').style.display = 'none';
			if (document.getElementById('li_' + directionActive + '_' + selIndex + '_text')) {
				document.getElementById('frm_'+directionActive+'_name').value = document.getElementById('li_' + directionActive + '_' + selIndex + '_text').value;
				lastSearch = document.getElementById('li_' + directionActive + '_' + selIndex + '_text').value;
			} 
			if (document.getElementById('li_' + directionActive + '_' + selIndex + '_value')) document.getElementById('frm_'+directionActive+'_point').value = document.getElementById('li_' + directionActive + '_' + selIndex + '_value').value;
			
			// Unset these variables
			directionActive = "";
		}
		
		// Finally hide the element and show selects again
		js_hideAllPopups();
	}
	
	function js_findSelectedIndex() {
		// Need to first see if there is a list in the defined direction
		if (document.getElementById(directionActive+'_ul')) {
			list = document.getElementById(directionActive+'_ul');
			// Then need to find out how many children
			nChildren = list.childNodes.length;
			if (nChildren > 0) {
				// Then need to go through the children to find which is currently selected
				for (i = 0; i < nChildren; i++) {
					if (list.childNodes[i] && list.childNodes[i].className && list.childNodes[i].className == 'frm_suggest_list_hover') {
						return i;
					}
				}
			}
		}
		// If none is selected then false needs to be returned
		return false;
	}
	
	function js_highlightSelection(selIndex) {
		// Determine previously selected index
		curIndex = js_findSelectedIndex();
		if (document.getElementById(directionActive+'_ul') && curIndex !== selIndex) {
			list = document.getElementById(directionActive+'_ul');
			
			if (selIndex == 'n' || selIndex == 'p') {
				if (selIndex == 'n' && curIndex < list.childNodes.length - 1) {
					selIndex = curIndex + 1;
				} else if (selIndex == 'p' && curIndex > 0) {
					selIndex = curIndex - 1;
				}
			}
			if (!isNaN(selIndex)) {
				// Find current selected index, and unset that
				list.childNodes[selIndex].className = 'frm_suggest_list_hover';
				if (curIndex !== false) list.childNodes[curIndex].className = '';
			}
		}
	}
	function js_moveSelection(e) {
		if (!e) e = window.event;
		if (e.keyCode == 38) {
			// Move up
			js_highlightSelection('p');
		} else if (e.keyCode == 40) {
			// Move down
			js_highlightSelection('n');
		} else if (e.keyCode == 9 || e.keyCode == 13) {
			// Tab so deselect
			js_hideAndSelect();
		} else if ((e.keyCode == 8 || e.keyCode == 46) && document.getElementById('frm_'+directionActive+'_point').value != '') {
			// If something has been deleted unset airport code and all that jazz
			document.getElementById('frm_'+directionActive+'_point').value = '';
			while (document.getElementById('frm_'+directionActive+'_suggestions').firstChild) document.getElementById('frm_'+directionActive+'_suggestions').removeChild(document.getElementById('frm_'+directionActive+'_suggestions').firstChild);
		}
	}
	
	function js_updateSuggestionField(responseData) {
		// Need text field, div, and hidden
		var xml_data = responseData.responseXML;
		var searchid = xml_data.getElementsByTagName('r')[0].getAttribute('sid');
		var searchterm = document.getElementById('frm_' + directionActive + '_name').value;
		// If this matches the current search id, continue
		if (searchid == currentSearch && searchterm.length >= minStringLen) {
			var obj_divElement = document.getElementById('frm_'+directionActive+'_suggestions');
			anchorElement('frm_'+directionActive+'_suggestions','anchor_' + directionActive);
			
			var num_Elements = xml_data.getElementsByTagName('p').length;
			// Clear out the div
			while (obj_divElement.firstChild) obj_divElement.removeChild(obj_divElement.firstChild);
			// If there are any results then enter them,hiding stuff first
			obj_divElement.style.display = 'none';
			if (num_Elements > 0) {
				// Regexp string for the entered text
				rExp = new RegExp('('+searchterm+')','gi');
				
				// Now cycle through any results adding to the div
				newUL = document.createElement('ul');
				newUL.id = directionActive+'_ul';
				for (var i = 0; i < num_Elements; i++) {
					airportCode = xml_data.getElementsByTagName('p')[i].getAttribute('v');
					airportName = xml_data.getElementsByTagName('p')[i].firstChild.data;
					divText = airportName.replace(rExp,'<span class="selHighlight">$1</span>');
					newUL.innerHTML += '<li onmouseover="js_highlightSelection(' + i + ')" onclick="js_hideAndSelect()"><input type="hidden" id="li_' + directionActive + '_' + i + '_value" value="' + airportCode + '" /><input type="hidden" id="li_' + directionActive + '_' + i + '_text" value="' + airportName + '" />' + divText + '</li>';
				}
				obj_divElement.appendChild(newUL);
				
				// And display, hiding selects for IE
				if (navigator.userAgent.match('MSIE 6')) {
					if ($('NoA')) $('NoA').style.visibility = 'hidden';
					if ($('NoC')) $('NoC').style.visibility = 'hidden';
				}
				// Disable submit button until done to prevent submission on enter
				if ($('submitButton')) $('submitButton').disabled=true;
				obj_divElement.style.display = 'block';
				// Highlight first choice
				js_highlightSelection(0);
			} else {
				// No results, say so
				obj_divElement.innerHTML += '<div class="noFFResults"><i>no results found</i></div>'
				obj_divElement.style.display = 'block';
			}
			if (document.getElementById("hideDiv") && !navigator.userAgent.match(/MSIE [5-7]\.\d+/))
			{
				document.getElementById("hideDiv").style.display = 'block';
			}
		}
	}
	
	function fs_deptClearOnFirstClick() {
		$('frm_departure_point').value = '';
		$('frm_departure_name').value = '';
		$('frm_departure_name').onclick = js_hideAllPopups;
		js_hideAllPopups();
	}
	
	function ms_SetSite(site_id) {
		switch (site_id) {
			case 'DLF' :
				if ($('dlh_dayslater')) $('dlh_dayslater').style.display = 'none';
				if ($('dlh_dest_point')) $('dlh_dest_point').style.display = 'none';
				if ($('dlh_dept_point')) $('dlh_dept_point').style.display = 'none';
				if ($('dla_dest_point')) $('dla_dest_point').style.display = 'none';
				if ($('hs_dates')) $('hs_dates').style.display = 'none';
				if ($('hs_duration')) $('hs_duration').style.display = 'none';
				if ($('hs_rooms')) $('hs_rooms').style.display = 'none';
				if ($('hs_rooms_occ')) $('hs_rooms_occ').style.display = 'none';
				if ($('hs_extras')) $('hs_extras').style.display = 'none';
				if ($('hs_extras_switch')) $('hs_extras_switch').style.display = 'none';
				
				if ($('dlf_dest_point')) $('dlf_dest_point').style.display = 'block';
				if ($('hs_dept_header')) $('hs_dept_header').style.display = 'block';
				if ($('dlf_dept_point')) $('dlf_dept_point').style.display = 'block';
				if ($('dlf_dates')) $('dlf_dates').style.display = 'block';
				if ($('dlf_rooms')) $('dlf_rooms').style.display = 'block';
				break;
				
			case 'DLH' :
				if ($('dla_dest_point')) $('dla_dest_point').style.display = 'none';
				
				if ($('dlh_dest_point')) $('dlh_dest_point').style.display = 'block';
				if ($('hs_dept_header')) $('hs_dept_header').style.display = 'block';
				if ($('dlh_dept_point')) $('dlh_dept_point').style.display = 'block';
				if ($('dlh_dayslater')) $('dlh_dayslater').style.display = 'block';
				
			case 'DLA' :
				if (site_id == 'DLA') {
					if ($('dlh_dest_point')) $('dlh_dest_point').style.display = 'none';
					if ($('hs_dept_header')) $('hs_dept_header').style.display = 'none';
					if ($('dlh_dept_point')) $('dlh_dept_point').style.display = 'none';
					if ($('dlh_dayslater')) $('dlh_dayslater').style.display = 'none';
					
					if ($('dla_dest_point')) $('dla_dest_point').style.display = 'block';
				}
				
				if ($('dlf_dest_point')) $('dlf_dest_point').style.display = 'none';
				if ($('dlf_dept_point')) $('dlf_dept_point').style.display = 'none';
				if ($('dlf_dates')) $('dlf_dates').style.display = 'none';
				if ($('dlf_rooms')) $('dlf_rooms').style.display = 'none';
				
				if ($('hs_dates')) $('hs_dates').style.display = 'block';
				if ($('hs_duration')) $('hs_duration').style.display = 'block';
				if ($('hs_rooms')) $('hs_rooms').style.display = 'block';
				if ($('hs_rooms_occ')) $('hs_rooms_occ').style.display = 'block';
				if ($('hs_extras')) $('hs_extras').style.display = 'block';
				if ($('hs_extras_switch')) $('hs_extras_switch').style.display = 'block';
				
				break;
		}
		js_OutputChildAges();
		js_SelectChildAges();
	}

/************************************************************************
	MSO7141 - functions under here are probably redundant
************************************************************************/

/*
function js_DateAdd(timeU,byMany,dateObj) {
	var millisecond=1;
	var second=millisecond*1000;
	var minute=second*60;
	var hour=minute*60;
	var day=hour*24;
	var year=day*365;

	var newDate;
	var dVal=dateObj.valueOf();
	switch(timeU) {
		case "ms": newDate=new Date(dVal+millisecond*byMany); break;
		case "s": newDate=new Date(dVal+second*byMany); break;
		case "mi": newDate=new Date(dVal+minute*byMany); break;
		case "h": newDate=new Date(dVal+hour*byMany); break;
		case "d": newDate=new Date(dVal+day*byMany); break;
		case "y": newDate=new Date(dVal+year*byMany); break;
	}
	return newDate;
}

// Function to update a select list from the XML data
function js_updateSelectList(responseData) {
	var xml_data = responseData.responseXML;
	var obj_selectElement = $(xml_data.getElementsByTagName('response')[0].getAttribute('related-element'));
	var str_caseID = xml_data.getElementsByTagName('response')[0].getAttribute('id');
	var str_xmlCoreNode = xml_data.getElementsByTagName('response')[0].getAttribute('xml-core-node');
	var num_Elements = xml_data.getElementsByTagName(str_xmlCoreNode).length - 1;
	for (var i = 0; i <= num_Elements; i++) {
		js_addOption(	obj_selectElement,
						xml_data.getElementsByTagName('value').item(i).firstChild.data,
						xml_data.getElementsByTagName('text').item(i).firstChild.data);
	}
	js_removeLoading(obj_selectElement);
	switch (str_caseID)
	{
		case 'departureCountries':
			if (str_SelectedCountry != "")
				js_selectValue(obj_selectElement, str_SelectedCountry);
			break
		case 'departureAirports':
			if (str_SelectedDeptAirport != "")
				js_selectValue(obj_selectElement, str_SelectedDeptAirport);
			break
		case 'destinationAirports':
			if (str_SelectedDestAirport != "")
				js_selectValue(obj_selectElement, str_SelectedDestAirport);
			break
	}
}

// Function to add an option to a select list
function js_addOption(obj_docElem, str_value, str_text) {
	var newElem = document.createElement("OPTION");
	newElem.value = str_value;
	newElem.text = str_text;
	if (navigator.userAgent.indexOf('MSIE') == -1)
		obj_docElem.add(newElem, null);
	else
		obj_docElem.add(newElem);
}

// Function to remove the first child of a select list
function js_removeLoading(obj_docElem) {
	obj_docElem.firstChild.text = 'Please select...';
}

// Function to remove the first child of a select list
function js_removeFirstChild(obj_docElem) {
	obj_docElem.removeChild(obj_docElem.firstChild);
}

// Function to remove all items from a select list
function js_removeAllSelectListOptions(obj_docElem) {
	if (obj_docElem.firstChild) {
		while (obj_docElem.firstChild) {
			obj_docElem.removeChild(obj_docElem.firstChild);
		}
	}
}

// Function to read a value from the cookie 
function js_ReadCookie(name) {
	arg = name + "=";
	alen = arg.length;
	clen = document.cookie.length;
	i = 0;
	while (i < clen) {
		j = i + alen;
		if (document.cookie.substring(i,j) == arg) {
			return js_ReadCookieVal(j);
		}
		i=document.cookie.indexOf(" ",i) + 1;
		if (i === 0) {break;}
	}
}

function js_ReadCookieVal(offset) {
   endstr = document.cookie.indexOf(";",offset);
   if (endstr == -1) {endstr=document.cookie.length;}
   return unescape(document.cookie.substring(offset,endstr));
}

function js_selectValue(str_formID, str_changeToValue) {
	var obj_SelectList = $(str_formID);
	if (obj_SelectList !== null) {
		var num_SelectListItems = obj_SelectList.childNodes.length;
		if (num_SelectListItems != 0) {
			for (i=0; i<num_SelectListItems; i++) {
				if (obj_SelectList.childNodes[i].value == str_changeToValue) {
					obj_SelectList.childNodes[i].selected = true;
					obj_SelectList.onchange();
					return true;
				}
			}
		}
	}
}

function js_SwitchFormFieldOnOff(formField, bol_Switch) {
	var formFieldElem = $(formField);
	formFieldElem.disabled = bol_Switch;
}





var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var days = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var mtend = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
function js_getDateInfo(num_year, num_month, num_day, str_formID) {
	var hlpr = mtend[num_month];
	if (num_day < mtend[num_month] + 1) {
		if (num_month == 1 && num_year % 4 == 0) { hlpr++; }
		var dat_theDate = new Date(num_year, num_month, num_day);
		if ($(str_formID))
			$(str_formID).value = days[dat_theDate.getDay()];
	} else {
		alert('Oops! '+months[num_month]+' only has '+mtend[num_month]+' days. Please reselect your date of travel.');
		if (str_formID.indexOf('Departing') != -1) {
			$('dateDayDeparting').selectedIndex = mtend[num_month] - 1;
			js_getDateInfo(num_year, num_month, mtend[num_month], str_formID);
		} else {
			$('dateDayReturning').selectedIndex = mtend[num_month] - 1;
			js_getDateInfo(num_year, num_month, mtend[num_month], str_formID);
		}
	}
}

function js_DateAdd(timeU,byMany,dateObj) {
	var millisecond=1;
	var second=millisecond*1000;
	var minute=second*60;
	var hour=minute*60;
	var day=hour*24;
	var year=day*365;

	var newDate;
	var dVal=dateObj.valueOf();
	switch(timeU) {
		case "ms": newDate=new Date(dVal+millisecond*byMany); break;
		case "s": newDate=new Date(dVal+second*byMany); break;
		case "mi": newDate=new Date(dVal+minute*byMany); break;
		case "h": newDate=new Date(dVal+hour*byMany); break;
		case "d": newDate=new Date(dVal+day*byMany); break;
		case "y": newDate=new Date(dVal+year*byMany); break;
	}
	return newDate;
}
*/

function js_checkFlightSearchForm(formObj) {
	if (formObj.frm_country_point) {
		if ( !(formObj.frm_country_point.value) || (formObj.frm_country_point.value == 0) ) {
			alert('Please select a departure country, departure airport and destination airport. Thank you.');
			return false;
		}
	}
	if (formObj.frm_departure_name) {
		if ( !(formObj.frm_departure_name.value) || (formObj.frm_departure_name.value.length == 0) ) {
			alert('Please select a departure airport and destination airport. Thank you.');
			return false;
		}
	}
	if (formObj.frm_destination_name) {
		if ( !(formObj.frm_destination_name.value) || (formObj.frm_destination_name.value.length == 0) ) {
			alert('Please select a departure airport and destination airport. Thank you.');
			return false;
		}
	}
	/*
	if (formObj.frm_departure_point) {
		if ( !(formObj.frm_departure_point.value) || (formObj.frm_departure_point.value == 0) ) {
			alert('Please select a departure airport and destination airport. Thank you.');
			return false;
		}
	}
	if (formObj.frm_destination_point) {
		if ( !(formObj.frm_destination_point.value) || (formObj.frm_destination_point.value == 0) ) {
			alert('The route you have selected is not available.\nPlease adjust your route and try again. Thank you.');
			return false;
		}
	}
	*/
	if (formObj.cal1input) {
		if (checkYCalDate(1) == false) {
			alert('Please enter departure date in the format DD/MM/YYYY');
			return false;
		}
	}
	if (formObj.cal2input) {
		if (checkYCalDate(2) == false) {
			alert('Please enter returning date in the format DD/MM/YYYY');
			return false;
		}
	}
	if ((formObj.cal1input) && (formObj.cal2input)) {
		if (compareDates(formObj.cal1input.value, formObj.cal2input.value) < 0 && formObj.typeOfFlightReturn == false) {
			alert('Your return date cannot be before your departure please.\nPlease check and try again.');
			return false;
		}
	}
	return true;
}

function js_activeChildrenAge(num_Children) {
	str_childages = $('frm_CA').value;
	js_showChildrenAge(num_Children);
}

function js_showChildrenAge(num_Children) {
	num_ChildrenSelected = num_Children;
	if (str_childages) {
		var aCA = str_childages.split(",");
	}
	$('fscadd').innerHTML='';
	if (num_Children > 0) {
		var divTag = document.createElement('div');
		var od='<div>';
		for (i=1; i<=num_Children; i++) {
			k=i-1;
			od+='<div class="flightSearchChild">Child '+i+'<br><select id="num_Children'+i+'" name="num_Children'+i+'" onChange="js_updateChildAges()"><option value="">Select</option>';
			for (j=0; j<=17; j++) {
				if (j==0) {
					if ((aCA) && (parseInt(aCA[k]) == 0))
						od+='<option value="0" selected>&lt;1</option>';
					else
						od+='<option value="0">&lt;1</option>';
				} else {
					if ((aCA) && (parseInt(aCA[k]) == j)) 
						od+='<option value="'+j+'" selected>'+j+'</option>';
					else
						od+='<option value="'+j+'">'+j+'</option>';
				}
			}
			od+='</select></div>';
		}
		od+='</div><div style="clear:both;padding-top:5px;"></div>';
		divTag.innerHTML = od;
		$('fscadd').appendChild(divTag);
		$('childrenAges').style.display = '';
	} else {
		$('childrenAges').style.display = 'none';
	}
	js_updateChildAges();
}

function js_updateChildAges() {
	var ff=$('frm_CA');
	var al='';
	if (num_ChildrenSelected > 0) {
		for (i=1; i<=num_ChildrenSelected; i++) {
			if ($('num_Children'+i)) {
				var ca=$('num_Children'+i).value;
				al+=ca+',';
			}
		}
		al=al.substring(0,al.length-1);
		ff.value=al;
	} else {
		if (str_childages) str_childages = '';
		ff.value = '';
	}
}




/* MSO7139 :: generates new style dropdowns for rooms and child ages */
function hsf_ParseRooms() {
	/* Use arr_RoomData to populate the rooms */
	var canvas = $('hsf_roomcanvas');
	var c_child = 0;
	var el_list = [];
	var t_div;var t_txt;var t_opt;var t_sel;
	var tempchild;
	
	/* Empty canvas */
	while (canvas.firstChild) canvas.removeChild(canvas.firstChild);
	for (var i=0;i<arr_RoomData.length;i++) {
		if (arr_RoomData[i].s) {
			// Generate the room
				// Title
					//t_txt = document.createTextNode('Room '+(i+1)+':');
					t_txt = document.createTextNode('\u00a0');
					t_div = document.createElement('div');t_div.className = 'hsf_left';t_div.appendChild(t_txt);
					el_list[el_list.length]=t_div;
				// Dropdowns - adult
					t_sel = document.createElement('select');
					//t_sel.name = 'frm_AdultsRoom'+(i+1);
					t_sel.name = 'num_NumberOfAdults';
					t_sel.id = 'f_ar_'+(i+1);
					t_sel.onchange = function(n_room) {hsf_SetRoomOcc(n_room,'a',$('f_ar_'+n_room).value);}.bind(this,(i+1));
					for (j=1;j<7;j++) {
						t_opt = document.createElement('option');
						t_opt.value = j;
						if (j == arr_RoomData[i].a) t_opt.selected=true;
						t_txt = document.createTextNode(j);
						t_opt.appendChild(t_txt);
						t_sel.appendChild(t_opt);
					}
					t_div = document.createElement('div');t_div.className = 'hsf_centerhalf';t_div.appendChild(t_sel);
					el_list[el_list.length]=t_div;
				// Dropdowns - child
					t_sel = document.createElement('select');
					//t_sel.name = 'frm_ChildrenRoom'+(i+1);
					t_sel.name = 'num_NumberOfChildren';
					t_sel.id = 'f_cr_'+(i+1);
					t_sel.onchange = function(n_room) {hsf_SetRoomOcc(n_room,'c',$('f_cr_'+n_room).value);}.bind(this,(i+1));
					for (j=0;j<6;j++) {
						t_opt = document.createElement('option');
						t_opt.value = j;
						if (j == arr_RoomData[i].c) t_opt.selected=true;
						t_txt = document.createTextNode(j);
						t_opt.appendChild(t_txt);
						t_sel.appendChild(t_opt);
					}
					t_div = document.createElement('div');t_div.className = 'hsf_centerhalf';t_div.appendChild(t_sel);
					el_list[el_list.length]=t_div;
					
					t_div = document.createElement('div');t_div.className='hsf_clear';
					el_list[el_list.length]=t_div;
					
				// Child ages 
					if (arr_RoomData[i].c > 0) {
						for (j=0;j<arr_RoomData[i].c;j++) {
							c_child++;
							switch (c_child%10) {
								case 1 : c_ext = 'st'; break;
								case 2 : c_ext = 'nd'; break;
								case 3 : c_ext = 'rd'; break;
								default : c_ext = 'th'; break;
							}
							
							this_age = 99;
							if (arr_ChildAges.length > j) this_age = arr_ChildAges[j];
							else arr_ChildAges[j] = this_age;
							
							t_txt = document.createTextNode('Age of '+c_child+c_ext+' \'under 18\' at time of travel');
							t_div = document.createElement('div');t_div.className = 'hsf_lefthalf';t_div.appendChild(t_txt);
							el_list[el_list.length]=t_div;
							
							t_sel = document.createElement('select');
							t_sel.name = 'num_Children'+c_child;
							t_sel.id = 'f_c_'+c_child;
							t_sel.onchange = function(n_child) {hsf_SetChildage(n_child,$('f_c_'+n_child).value);}.bind(this,c_child);
							t_opt = document.createElement('option');
							t_opt.value = '-';t_txt = document.createTextNode(t_opt.value);
							t_opt.appendChild(t_txt);t_sel.appendChild(t_opt);
							for (k=0;k<18;k++) {
								t_opt = document.createElement('option');
								t_opt.value = k;t_txt = document.createTextNode(t_opt.value);
								if (arr_ChildAges[c_child-1] == k) t_opt.selected = true;
								t_opt.appendChild(t_txt);t_sel.appendChild(t_opt);
							}
							t_div = document.createElement('div');t_div.className = 'hsf_centerhalf';t_div.appendChild(t_sel);
							el_list[el_list.length]=t_div;
							
							t_div = document.createElement('div');t_div.className='hsf_clear';
							el_list[el_list.length]=t_div;
						}
					}
		} else {break;}
	}
	for (i=0;i<el_list.length;i++) canvas.appendChild(el_list[i]);
}

function hsf_SetRoomOcc(n_room,s_type,n_number) {
	switch (s_type) {
		case 'c' :	arr_RoomData[n_room-1].c = n_number;
					hsf_ParseRooms();
					break;
		case 'a' :	arr_RoomData[n_room-1].a = n_number;
					break;
	}
}

function hsf_SetChildage(n_child,n_number) {
	arr_ChildAges[n_child-1] = n_number;
}

function hsf_SetNumRooms(n_rooms) {
	for(var i=0;i<n_rooms;i++) arr_RoomData[i].s = true;
	if (n_rooms < arr_RoomData.length) for(var j=n_rooms;j<arr_RoomData.length;j++)  arr_RoomData[j].s = false;
	hsf_ParseRooms();
}

function anchorElement(str_moveme,str_anchor) {
	var pos_x = -144;
	var pos_y = -22;
	// Ok so find out if the anchor exists
	if ($(str_moveme) && $(str_anchor)) {
		// Now set this to element
		var obj_anchor = $(str_anchor);
		var obj_moveme = $(str_moveme);
		while (obj_anchor.tagName !== 'BODY') {
			if (obj_anchor.offsetLeft) 
			{
				pos_x = pos_x + obj_anchor.offsetLeft;
			}	
			if (obj_anchor.offsetTop) 
			{
				pos_y = pos_y + obj_anchor.offsetTop;
			}
			if (obj_anchor.offsetParent) 
			{
				obj_anchor = obj_anchor.offsetParent;
			}
			else
			{
				 break;
			}
		}
		obj_moveme.style.left = pos_x+'px';
		obj_moveme.style.top = pos_y+'px';
	}
}
