var childrenPerRoom = 6;
var totalRooms = 3;

var defaultFormType = "Hotel"; // choices are "Flight", "Hotel", "Car", "Package"
var defaultPackageType = "HotelFlight"; // choices are "HotelFlightCar", "HotelFlight", "HotelFlightActivities", "HotelCar", "Hotel"
var defaultFlightType = "RoundTrip"; // choices are "RoundTrip", "OneWay"
var currentPackageType = "HotelFlight";
var currentFormType;
var global_packageSelectors;
var formDestination = "http://" + document.domain.replace("hotels.", "www.");

var global_typeforms;

var ie = document.all ? true : false;

function LoadTravelPlanner() {
	document.getElementById('travel_planner_url').value = window.location;
	currentFormType = defaultFormType;

	// Set up date range selection
	var travelDateSelector;
	if (travelDateSelector = document.getElementById('travelDates')) {
		travelDateSelector.onchange = updateTravelDates;
		travelDateSelector.onchange();

		var toAreaLocation;
		if (toAreaLocation = document.getElementById('toAreaLocation'))
			toAreaLocation.onchange();

		var toPackageLocationCode;
		if (toPackageLocationCode = document.getElementById('toPackageLocationCode'))
			toPackageLocationCode.onchange();

		var toAirportLocationCode;
		if (toAirportLocationCode = document.getElementById('toAirportLocationCode'))
			toAirportLocationCode.onchange();

		var fromCarLocationCode;
		if (fromCarLocationCode = document.getElementById('fromCarLocationCode'))
			fromCarLocationCode.onchange();
	}

	// Set up location search boxes
	var citySearches = document.getElementsByClass("citySearch", "input");
	for (i = 0; i < citySearches.length; i++) {
		citySearches[i].onkeyup = function (e) { 

			// All this just to clear the hidden field when input is edited
			if (!e) var e = window.event;
			if (e.keyCode != undefined && e.keyCode != 0 && e.keyCode < 32 && e.keyCode != 8)
				return;
			targ = getEventTarget(e);
			bucket = document.getElementById(targ.id + 'Code');
			bucket.value = '';
			if (targ.value.length == 3)
				bucket.value = targ.value;
			
			triggerLookupCity(e);
		}
		citySearches[i].onfocus = triggerLookupCity;
		citySearches[i].onblur = hideLookupCity; //window.setTimeout('hideLookupCity()', 10);
	}

	setupPackage();
	setupHotel();
	setupFlight();
	setupCar();
	
	setupChildAges();

	// Set up travel type selection (packages/hotels/flights)
	var typeSelectors = document.getElementsByClass("typeSelector", "input");

	for (i = 0; i < typeSelectors.length; i++) {
		typeSelectors[i].onclick = typeSelect;

	}

	for (i = 0; i < typeSelectors.length; i++) {
		if (typeSelectors[i].id == "type" + defaultFormType) {
			typeSelectors[i].checked = true;
			typeSelectors[i].onclick();
		}
	}

	document.getElementById('TravelPlanner').onsubmit = errorCheck;

}

function setupChildAges() {
	// Hotel children
	var room = 1;
	var theElement;
	while (theElement = document.getElementById('hotelChildrenRoom' + room)) {
		theElement.onchange = hotelChildrenAges;
		room++;
	}

	// Flight children
	if (theElement = document.getElementById('flightChildren')) {
		theElement.onchange = flightChildrenAges;
	}
}

function changeCalendarText(fromText, toText) {
	var theCode;
	var fromCalendar = document.getElementById('fromDate');
	var fromCalendarImage = fromCalendar.nextSibling.nextSibling;
	var toCalendar = document.getElementById('toDate');
	var toCalendarImage = toCalendar.nextSibling.nextSibling;

	theCode = new String(fromCalendar.onclick).replace(/(<span.*id=fromDateCalendarText.*>).*(<\/span>)/, "$1" + fromText + "$2");
	eval("fromCalendar.onclick = " + theCode);

	theCode = new String(fromCalendar.onfocus).replace(/(<span.*id=fromDateCalendarText.*>).*(<\/span>)/, "$1" + fromText + "$2");
	eval("fromCalendar.onfocus = " + theCode);

	theCode = new String(fromCalendarImage.onclick).replace(/(<span.*id=fromDateCalendarText.*>).*(<\/span>)/, "$1" + fromText + "$2");
	eval("fromCalendarImage.onclick = " + theCode);

	theCode = new String(toCalendar.onclick).replace(/(<span.*id=toDateCalendarText.*>).*(<\/span>)/, "$1" + toText + "$2");
	eval("toCalendar.onclick = " + theCode);

	theCode = new String(toCalendar.onfocus).replace(/(<span.*id=toDateCalendarText.*>).*(<\/span>)/, "$1" + toText + "$2");
	eval("toCalendar.onfocus = " + theCode);

	theCode = new String(toCalendarImage.onclick).replace(/(<span.*id=toDateCalendarText.*>).*(<\/span>)/, "$1" + toText + "$2");
	eval("toCalendarImage.onclick = " + theCode);
}

function setupHotel() {
	// Hotel rooms
	document.getElementById('rooms').onchange = hotelRooms;

}

function setupPackage() {
	global_packageSelectors = document.getElementsByClass("packageSelector", "input");

	// Set up package type selection (flight+hotel, flight+hotel+activities, hotel+activities, hotel+car)
	for (i = 0; i < global_packageSelectors.length; i++) {
		global_packageSelectors[i].onclick = packageSelect;
		if (global_packageSelectors[i].id == "package" + defaultPackageType) {
			global_packageSelectors[i].checked = true;
		}
	}

}
function setupFlight() {
	// Set up flight search type selection (round trip, one way)
	var flightSelectors = document.getElementsByClass("flightSearchType", "input");
	for (i = 0; i < flightSelectors.length; i++) {
		flightSelectors[i].onclick = flightTypeSelect;
	}
	for (i = 0; i < flightSelectors.length; i++) {
		if (flightSelectors[i].id == "flight" + defaultFlightType) {
			flightSelectors[i].checked = true;
			if (defaultFormType == "Flight")
				flightSelectors[i].onclick();
		}
	}

}
function setupCar() {
	// Car dropoff location differs
//	document.getElementById('carToDiffers').onchange = carToDiffers;
}

// Access functions
document.getElementsByClass = function (needle, tag) {
	if (tag == null) tag = "*";
	var TravelPlannerElements = document.getElementById('TravelPlannerContent').getElementsByTagName(tag);
	var retvalue = new Array();
	var i;
	theNeedle = " " + needle + " ";

	// Sure would be nice if IE supported Array.prototype.filter...
	for (i = 0; i < TravelPlannerElements.length; i++)
	{
		if ((" " + TravelPlannerElements[i].className + " ").indexOf(needle) != -1)
			retvalue.push(TravelPlannerElements[i]);
	}

	return retvalue;
}

function jscss(action, object, class1, class2) {
  switch (action){
    case 'swap':
      object.className=!jscss('check',object,class1)?object.className.replace(class2,class1): object.className.replace(class1,class2);
    break;
    case 'add':
      if(!jscss('check',object,class1)){object.className+=object.className?' '+class1:class1;}
    break;
    case 'remove':
      var rep=object.className.match(' '+class1)?' '+class1:class1;
      object.className=object.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+class1+'\\b').test(object.className)
    break;
  }
}

String.prototype.trim = function () {
  return this.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function getEventTarget(theEvent) {
	var targ;
	if (theEvent.target) targ = theEvent.target;
	else if (theEvent.srcElement) targ = theEvent.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

// Look up location
var theIndex = 0;
var xmlhttp = new Array();
function loadXMLDoc(url) {
	{
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		// JScript gives us Conditional compilation, we can cope with old IE versions.
		// and security blocked creation of the objects.
		try {
			xmlhttp[theIndex] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp[theIndex] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp[theIndex] = false;
			}
		}
		@end @*/

		if (!xmlhttp[theIndex] && typeof XMLHttpRequest!='undefined') {
		  xmlhttp[theIndex] = new XMLHttpRequest();
		}
	}
	var myIndex = theIndex;
	try {
		xmlhttp[theIndex].onreadystatechange = function () { finishLookupCity(myIndex); }
		xmlhttp[theIndex].open("GET", url, true);
		xmlhttp[theIndex].send(null)
	} catch (e) {
		return false;
	}
}

var targetList = new Array();
var bucketList = new Array();
function lookupCity(target, bucket) {
	var fieldLength = 40;
	var city = target.value;
	var locationOptions = document.getElementById('locationOptions');
	if (!locationOptions) return false;
	locationOptions.style.left = (findPosX(target) + 1) + 'px';
	locationOptions.style.top = (findPosY(target) + target.offsetHeight + 1) + 'px';
	locationOptions.style.display = "block";
	
	theIndex++;

	targetList[theIndex] = target;
	bucketList[theIndex] = bucket;

	var xmlDoc = "http://" + document.domain + "/findCityList.php?city=" + city + "&length=" + fieldLength; 

	loadXMLDoc(xmlDoc);
}

function finishLookupCity (index) {
	var targ = targetList[index];
	var bucket = bucketList[index];
	var http = xmlhttp[index];
	try {
		if (http.readyState== 4 && http.status == 200)
			xmlDoc = http.responseXML;
		else
			return;
	}
	catch (e) {
		return;
	}

	document.getElementById('locationOptions').innerHTML = "";
	

	//Start Quirksmode script
	var x = xmlDoc.getElementsByTagName('location');
	var newEl = document.createElement('TABLE');
	newEl.className = 'locationTable';
	var tmp = document.createElement('TBODY');
	newEl.appendChild(tmp);

	var noBucketSet = true;

	// Create the data rows
	for (i=0;i<x.length;i++)
	{
		var row = document.createElement('TR');
		row.onmouseover = function() {this.style.backgroundColor='#A1F710';}
		row.onmouseout = function() {this.style.backgroundColor='';}
		for (j=0;j<2;j++)
		{
			if (x[i].childNodes[j].nodeType != 1) continue;
			row.setAttribute('id', x[i].childNodes[j].firstChild.nodeValue);
			break;
		}

		// Create the data cells
		var theId = "";
		for (j=0;j<x[i].childNodes.length;j++)
		{
			if (x[i].childNodes[j].nodeType != 1) continue;
			if (x[i].childNodes[j].nodeName == 'locationId') theId = x[i].childNodes[j].firstChild.nodeValue;
			if (x[i].childNodes[j].nodeName != 'locationText') continue;
			var container = document.createElement('TD');
			var theLink = document.createElement('a');
			if (!x[i].childNodes[j].firstChild) continue;
			var theText = x[i].childNodes[j].firstChild.nodeValue
			var theData = document.createTextNode(theText);
			theLink.href = "javascript:void(0);";
			theLink.theId = theId;
			theLink.theText = theText;
			theLink.theTarg = targ;
			theLink.theBucket = bucket;
			theLink.onclick = function() { 
				selectRow(this.theId, this.theText, this.theTarg, this.theBucket); 
				document.getElementById('locationOptions').innerHTML = "";
			}

			if (noBucketSet == true) {
				//bucket.value = theId; // Removed this to stop auto-filling field until clicked
				noBucketSet = false;
			}

			if (index != theIndex)
				return;

			theLink.appendChild(theData);
			container.appendChild(theLink);
			row.appendChild(container);
		}
		tmp.appendChild(row);
	}

	hideElement('SELECT', document.getElementById('locationOptions'));
	document.getElementById('locationOptions').appendChild(newEl);

	//end Quirksmode script
}

function selectRow(data, text, targ, bucket) {
	bucket.value = data;
	targ.value = text;
}

// General display functions
function setDisplay(theElement, renderSetting, defaultRender) {
	if (!(theElement) || !(theElement.style))
		return false;

	if (defaultRender == undefined)
		defaultRender = "inline";

	if (renderSetting === 'toggle')
		theElement.style.display = theElement.display == "none" ? defaultRender : "none";
	else
		theElement.style.display = renderSetting ? defaultRender : "none";
}

function showForm(formClass) {

	// Show form elements with passed class
	var formTypes = new Array("flight", "hotel", "package", "car", "packagehoteltype");

	for (type in formTypes) {

		if (formTypes[type] == formClass.toLowerCase())
			continue;

		theGroup = document.getElementsByClass(formTypes[type] + "Form", "input");
		theGroup = theGroup.concat(document.getElementsByClass(formTypes[type] + "Form", "label"));
		theGroup = theGroup.concat(document.getElementsByClass(formTypes[type] + "Form", "select"));
		theGroup = theGroup.concat(document.getElementsByClass(formTypes[type] + "Form", "br"));
		theGroup = theGroup.concat(document.getElementsByClass(formTypes[type] + "Form", "div"));
		for (i = 0; i < theGroup.length; i++) {
			if (theGroup[i].style.display != 'none') {
				setDisplay(theGroup[i], false);
				theGroup[i].disabled = true;
			}
		}
	}

	theGroup = document.getElementsByClass(formClass.toLowerCase() + "Form", "input");
	theGroup = theGroup.concat(document.getElementsByClass(formClass.toLowerCase() + "Form", "label"));
	theGroup = theGroup.concat(document.getElementsByClass(formClass.toLowerCase() + "Form", "select"));
	theGroup = theGroup.concat(document.getElementsByClass(formClass.toLowerCase() + "Form", "br"));
	theGroup = theGroup.concat(document.getElementsByClass(formClass.toLowerCase() + "Form", "div"));
	for (i = 0; i < theGroup.length; i++) {
		setDisplay(theGroup[i], true);
		theGroup[i].disabled = false;
	}
}

// Form selection functions

function typeSelect() {
	// Display only the relevant form(s)

	// Determine which type is selected
	var type = (this.id).substring("type".length);
	if (type == "")
		return true;

	currentFormType = type;

	changeElementNames(type.toLowerCase());
	changeElementLabels(type.toLowerCase());

	// Highlight the appropriate type
	var typeList = new Array("Package", "Flight", "Hotel", "Car");
	var SelectorContainer;
	for (i in typeList) {
		if (SelectorContainer = document.getElementById(typeList[i] + "SelectorContainer"))
			if (typeList[i] == type)
				jscss("add", SelectorContainer, "activeTab");
			else
				jscss("remove", SelectorContainer, "activeTab");
	}

	// Display the appropriate forms
	showForm(type);

	// Show/hide elements based on user selections
	switch (type) {
		case 'Flight': 
			flightTypeSelect(); 
			break;
		case 'Package': 
			packageSelect(); 
			break;
		case 'Hotel':
			hotelTypeSelect(); 
			break;
		case 'Car':
			carTypeSelect();
			break;
	}
}

function flightChildSetup() {
	var child = 1;
	while (theElement = document.getElementById('ageChild' + child)) {
		theElement.onchange = flightChildrenAges;
		child++;
	}
	flightChildrenAges();
}

function hotelChildSetup() {
	var child = 1;
	while (theElement = document.getElementById('ageChild' + child)) {
		theElement.onchange = hotelChildrenAges;
		child++;
	}
}

function hotelTypeSelect() {
	hotelChildSetup();
	hotelRooms();

	document.TravelPlanner.action = formDestination + '/hotels_results.php';

	changeCalendarText("Select your check in date.", "Select your check out date.");
}

function flightTypeSelect() {
	flightChildSetup();

	document.TravelPlanner.action = formDestination + '/Flights/flightResults.php';
	//document.TravelPlanner.action = 'http://www.bookit-dev.com/library/flights/2.0/';

	// Highlight the appropriate type
	var typeList = new Array("RoundTrip", "OneWay"); 
	var SelectorContainer;
	
	// Determine whether one way or round trip selected
	var theSelector;
	var SelectorContainer;
	for (i in typeList) {
		if (theRadio = document.getElementById("flight" + typeList[i]))
			theSelector = theRadio.checked ? theRadio : theSelector;
	}

	if (theSelector == undefined)
		return true;

	var currentFlightType = (theSelector.id).substring("flight".length);

	for (i in typeList) {
		if (SelectorContainer = document.getElementById(typeList[i] + "FlightSelectorContainer"))
			if (typeList[i] == currentFlightType)
				jscss("add", SelectorContainer, "activePackage");
			else
				jscss("remove", SelectorContainer, "activePackage");
	}

	// Show or hide return date
	setDisplay(document.getElementById("toDateLabel"), currentFlightType == "RoundTrip", "");
	setDisplay(document.getElementById("toDate"), currentFlightType == "RoundTrip", "");

	changeCalendarText("Select your depart date.", "Select your return date.");
}

function carTypeSelect() {
	document.TravelPlanner.action = formDestination + '/Car/carResults.php';

	changeCalendarText("Select your pick up date.", "Select your drop off date.");
}

function packageSelect() {
	// Determine which type is selected
	var theSelector;
	var SelectorContainer;
	var typeList = new Array("HotelFlightCar", "HotelFlight", "HotelFlightActivities", "HotelCar", "Hotel");

	document.TravelPlanner.action = formDestination + '/package_results.php';

	for (i = 0; i < global_packageSelectors.length; i++) {
		theSelector = global_packageSelectors[i].checked ? global_packageSelectors[i] : theSelector;
	}

	if (theSelector == undefined)
		return true;

	currentPackageType = (theSelector.id).substring("package".length);

	var showPackageContents = true;

	// Determine which forms to show
	switch (currentPackageType) {
		case 'HotelFlightCar':
		case 'HotelFlight':
		case 'HotelFlightActivities':
			showForm("package");
			hotelChildSetup();
			break;
		case 'Hotel':
			// special case - hide the package form contents, show the hotel
			showForm("packagehoteltype");
			hotelTypeSelect(); 
			break;
		default:
			return true;
	}

	hotelRooms(); 

	// Highlight the appropriate type
	var SelectorContainer;
	for (i in typeList) {
		if (SelectorContainer = document.getElementById(typeList[i] + "PackageSelectorContainer"))
			if (typeList[i] == currentPackageType)
				jscss("add", SelectorContainer, "activePackage");
			else
				jscss("remove", SelectorContainer, "activePackage");
	}

	changeCalendarText("Select your depart date.", "Select your return date.");
}

// Changing element names

{ // Form element names
var fixedElementNames = new Array();
var sequentialElementNames = new Array();
var variableElementNames = new Array();

fixedElementNames['package'] = new Array();
fixedElementNames['package']['fromDate'] = 'fd';
fixedElementNames['package']['fromDayPart'] = 'ft';
fixedElementNames['package']['fromFlexDays'] = 'dfd';
fixedElementNames['package']['toDate'] = 'td';
fixedElementNames['package']['toDayPart'] = 'tt';
fixedElementNames['package']['toFlexDays'] = 'rfd';
fixedElementNames['package']['exactDates'] = 'dtst';
fixedElementNames['package']['1to3Days'] = 'dtst';
fixedElementNames['package']['fexibleDates'] = 'dtst';
fixedElementNames['package']['fromLocation'] = 'packageFrom';
fixedElementNames['package']['fromLocationCode'] = 'fl';
fixedElementNames['package']['toPackageLocation'] = 'packageTo';
fixedElementNames['package']['toPackageLocationCode'] = 'ptl';
fixedElementNames['package']['rooms'] = 'rm';

variableElementNames['package'] = new Array();
variableElementNames['package']['ageChild'] = 'ar{Math.ceil(i/childrenPerRoom)}m{(i-1)%childrenPerRoom+1}';
variableElementNames['package']['seatChild'] = 'sr{Math.ceil(i/childrenPerRoom)}m{(i-1)%childrenPerRoom+1}';
variableElementNames['package']['lapChild'] = 'sr{Math.ceil(i/childrenPerRoom)}m{(i-1)%childrenPerRoom+1}';

sequentialElementNames['package'] = new Array();
sequentialElementNames['package']['hotelAdultsRoom'] = 'ap';
sequentialElementNames['package']['hotelChildrenRoom'] = 'mp';

fixedElementNames['flight'] = new Array();
fixedElementNames['flight']['fromDate'] = 'flightFromDate';
fixedElementNames['flight']['fromDayPart'] = 'leave_time';
fixedElementNames['flight']['fromFlexDays'] = 'depart_flex_date';
fixedElementNames['flight']['toDate'] = 'flightToDate';
fixedElementNames['flight']['toDayPart'] = 'return_time';
fixedElementNames['flight']['toFlexDays'] = 'return_flex_date';
fixedElementNames['flight']['exactDates'] = 'date_search_type';
fixedElementNames['flight']['1to3Days'] = 'date_search_type';
fixedElementNames['flight']['fexibleDates'] = 'date_search_type';
fixedElementNames['flight']['fromLocation'] = 'flightFrom';
fixedElementNames['flight']['fromLocationCode'] = 'departure_name';
fixedElementNames['flight']['toAirportLocation'] = 'flightTo';
fixedElementNames['flight']['toAirportLocationCode'] = 'return_name';

sequentialElementNames['flight'] = new Array();
sequentialElementNames['flight']['ageChild'] = 'flightChildrenAge';
sequentialElementNames['flight']['seatChild'] = 'flightChildrenSeatLap';
sequentialElementNames['flight']['lapChild'] = 'flightChildrenSeatLap';

fixedElementNames['hotel'] = new Array();
fixedElementNames['hotel']['fromDate'] = 'ARR_DATE_HM';
fixedElementNames['hotel']['toDate'] = 'DEP_DATE_HM';
fixedElementNames['hotel']['rooms'] = 'ROOMS_HM';

variableElementNames['hotel'] = new Array();
variableElementNames['hotel']['ageChild'] = 'ar{Math.ceil(i/childrenPerRoom)}m{(i-1)%childrenPerRoom+1}';

sequentialElementNames['hotel'] = new Array();
//sequentialElementNames['hotel']['ageChild'] = 'hotelChildrenAge';
sequentialElementNames['hotel']['hotelAdultsRoom'] = 'ADULT_HM_ROOM_';
sequentialElementNames['hotel']['hotelChildrenRoom'] = 'CHILD_HM_ROOM_';

fixedElementNames['car'] = new Array();
fixedElementNames['car']['fromDate'] = 'carFromDate';
fixedElementNames['car']['toDate'] = 'carToDate';
/*
fixedElementNames['car']['toAirportLocation'] = 'carFrom';
fixedElementNames['car']['toAirportLocationCode'] = 'carFromLocation';
fixedElementNames['car']['toAirportLocation'] = 'carTo';
fixedElementNames['car']['toAirportLocationCode'] = 'carToLocation';
*/
}

function changeElementNames(formType) {
    // formType should be one of package, flight, hotel, car
    for (var id in fixedElementNames[formType]) {
		if (theElement = document.getElementById(id))
        	theElement.name = fixedElementNames[formType][id];
    }

	for (var id in sequentialElementNames[formType]) {
		var i = 1;
		var theElement;
		while (theElement = document.getElementById(id + i)) {
			theElement.name = sequentialElementNames[formType][id] + i;
			i++;
		}
	}

	for (var id in variableElementNames[formType]) {
		var i = 1;
		var theElement;
		while (theElement = document.getElementById(id + i)) {
			var str = variableElementNames[formType][id];
			var matches;
			while (matches = str.match(/{(.*?)}/)) {
				str = str.replace(matches[0], eval(matches[1]));
			}
			theElement.name = str;
			i++;
		}
	}
}

// Changing label text
{ // Form element labels
var fixedLabelNames = new Array();

fixedLabelNames['package'] = new Array();
fixedLabelNames['package']['fromLocationLabel'] = 'From';
fixedLabelNames['package']['toLocationLabel'] = 'To';
fixedLabelNames['package']['fromDateLabel'] = 'Depart';
fixedLabelNames['package']['toDateLabel'] = 'Return';
fixedLabelNames['package']['fromDateCalendarText'] = 'Select your depart date.';
fixedLabelNames['package']['toDateCalendarText'] = 'Select your return date.';

fixedLabelNames['flight'] = new Array();
fixedLabelNames['flight']['fromLocationLabel'] = 'From';
fixedLabelNames['flight']['toLocationLabel'] = 'To';
fixedLabelNames['flight']['fromDateLabel'] = 'Depart';
fixedLabelNames['flight']['toDateLabel'] = 'Return';
fixedLabelNames['flight']['fromDateCalendarText'] = 'Select your depart date.';
fixedLabelNames['flight']['toDateCalendarText'] = 'Select your return date.';

fixedLabelNames['hotel'] = new Array();
fixedLabelNames['hotel']['fromDateLabel'] = 'Check In';
fixedLabelNames['hotel']['toDateLabel'] = 'Check Out';
fixedLabelNames['hotel']['toLocationLabel'] = 'Destination';
fixedLabelNames['hotel']['fromDateCalendarText'] = 'Select your check in date.';
fixedLabelNames['hotel']['toDateCalendarText'] = 'Select your check out date.';

fixedLabelNames['car'] = new Array();
fixedLabelNames['car']['toLocationLabel'] = 'Pick up / Drop off Location';
fixedLabelNames['car']['fromDateLabel'] = 'Pick Up Date';
fixedLabelNames['car']['toDateLabel'] = 'Drop Off Date';
fixedLabelNames['car']['fromDateCalendarText'] = 'Select your pick up date.';
fixedLabelNames['car']['toDateCalendarText'] = 'Select your drop off date.';
}
function changeElementLabels(formType) {
    // formType should be one of package, flight, hotel, car
    for (var id in fixedLabelNames[formType]) {
		if (theElement = document.getElementById(id))
        	theElement.innerHTML = fixedLabelNames[formType][id];
    }
}


// Specific display functions

var targ;
var bucket;
function triggerLookupCity(e) {
	if (!e) var e = window.event;
	if (e.keyCode != undefined && e.keyCode != 0 && e.keyCode < 32 && e.keyCode != 8) {
		return;
	}

	targ = getEventTarget(e);

	if (e.type == 'focus')
		targ.select();

	bucket = document.getElementById(targ.id + 'Code');

	if (targ.value.length < 3) return;

	if (e.type != 'focus' && targ.value.length == 3)
		bucket.value = targ.value;

	// fetch suggestions for targ
	if (typeof lookupTimer == 'number')
		clearTimeout(lookupTimer);
	lookupTimer = window.setTimeout('lookupCity(targ, bucket)', 300);
	//lookupCity(targ, bucket);
}

	/* hides <select> and <applet> objects (for IE only) */
	function hideElement( elmID, overDiv ) {
		if(ie) {
			for(i = 0; i < document.all.tags( elmID ).length; i++) {
				obj = document.all.tags( elmID )[i];
				if(!obj || !obj.offsetParent) continue;

				// Find the element's offsetTop and offsetLeft relative to the BODY tag.
				objLeft   = obj.offsetLeft;
				objTop    = obj.offsetTop;
				objParent = obj.offsetParent;

				while(objParent.tagName.toUpperCase() != 'BODY') {
					objLeft  += objParent.offsetLeft;
					objTop   += objParent.offsetTop;
					objParent = objParent.offsetParent;
				}

				objHeight = obj.offsetHeight;
				objWidth  = obj.offsetWidth;

				if((overDiv.offsetLeft + overDiv.offsetWidth) <= objLeft);
				else if((overDiv.offsetTop + overDiv.offsetHeight) <= objTop);
				/* CHANGE by Charlie Roche for nested TDs*/
				else if(overDiv.offsetTop >= (objTop + objHeight + obj.height));
				/* END CHANGE */
				else if(overDiv.offsetLeft >= (objLeft + objWidth));
				else {
					obj.style.visibility = 'hidden';
				}
			}
		}
	}

	/*
	* unhides <select> and <applet> objects (for IE only)
	*/
	function showElement(elmID) {
		if(ie) {
			for(i = 0; i < document.all.tags( elmID ).length; i++) {
				obj = document.all.tags(elmID)[i];
				if(!obj || !obj.offsetParent) continue;
				obj.style.visibility = '';
			}
		}
	}

function hideLookupCity(e) {
	//hideIt();
	var t = self.setTimeout('hideIt()', 500);
}

function hideIt() {
	document.getElementById('locationOptions').style.display = "none";
	showElement('SELECT');
}

function flightChildrenAges() {
	var numChildren = (document.getElementById('flightChildren').value * 1);

	for (room = 1; room <= totalRooms; room++) {
		var containers = document.getElementsByClass('hotelChildrenContainerRoom' + room, "div");
		containers.push(document.getElementById('hotelChildrenContainerRoom' + room));
		for (index in containers) {
			setDisplay(containers[index], false, "block");
		}
	}

	var child = 1;
	while (theElement = document.getElementById('ageChild' + child)) {
		var showChild = child <= numChildren;
		setDisplay(document.getElementById('ageChildContainer' + child), showChild, "");
		var childAge = theElement.value;
		setDisplay(document.getElementById('seatLapContainer' + child), showChild && (childAge == "0-1" || childAge == "1"), "");
		document.getElementById('ageChild' + child).disabled = !showChild;
		document.getElementById('lapChild' + child).disabled = !showChild;
		document.getElementById('seatChild' + child).disabled = !showChild;
		child++;
	}
}

function hotelChildrenAges() {
	var numRooms = document.getElementById('rooms').value;
	var room = 1;
	var theElement;
	var totalChild = 1;

	while (theElement = document.getElementById('hotelChildrenRoom' + room)) {
		var numChildren = (theElement.value * 1);

		var containers = document.getElementsByClass('hotelChildrenContainerRoom' + room, "div");
		containers.push(document.getElementById('hotelChildrenContainerRoom' + room));
		for (var index = 0; index < containers.length; index++) {
			setDisplay(containers[index], room <= numRooms && numChildren > 0, "block");
		}

		var roomChild = 1;
		
		while ((theElement = document.getElementById('ageChild' + totalChild)) && roomChild <= childrenPerRoom) {
			var childAge = theElement.value;

			// show child if: enough rooms selected, child is less than children in room
			var showChild = room <= numRooms;
			showChild = showChild && roomChild <= numChildren;

			// show seat/lap if: enough children selected, child is of age, form contains flight
			var showSeatLap = showChild 
			showSeatLap = showSeatLap && (childAge == "0-1" || childAge == "1");
			showSeatLap = showSeatLap && (currentFormType == 'Package' || currentFormType == 'Flight');
			showSeatLap = showSeatLap && !(currentFormType == 'Package' && (currentPackageType == 'HotelCar' || currentPackageType == 'Hotel'));

			setDisplay(document.getElementById('ageChildContainer' + totalChild), showChild, "");
			setDisplay(document.getElementById('seatLapContainer' + totalChild), showSeatLap, "");
			document.getElementById('ageChild' + totalChild).disabled = !showChild;
			document.getElementById('lapChild' + totalChild).disabled = !showSeatLap;
			document.getElementById('seatChild' + totalChild).disabled = !showSeatLap;

			roomChild++;
			totalChild++;
		}
		room++;
	}
}

function hotelRooms() {
	var numRooms = document.getElementById('rooms').value;
	setDisplay(document.getElementById('LabelhotelAdultsRoom1'), numRooms > 1, "");
	setDisplay(document.getElementById('LabelhotelChildrenRoom1'), numRooms > 1, "");
	var room = 2;
	var theElement;
	while (theElement = document.getElementById('hotelRoom' + room + 'Container')) {
		setDisplay(theElement, room <= numRooms, "");
		//setDisplay(document.getElementById('hotelAdultsRoom' + room + 'Container'), room <= numRooms, "");
		//setDisplay(document.getElementById('hotelChildrenRoom' + room + 'Container'), room <= numRooms, "");
		room++;
	}

	hotelChildrenAges();
}

function carToDiffers() {
	var theBox = document.getElementById('carToDiffers');
	if (typeof(theBox) == undefined)
		return false;
	var styleVisibility = theBox.checked ? "" : "none";
	var dropOffs = document.getElementsByClass('carToContainer');
		for (i = 0; i < dropOffs.length; i++)
			dropOffs[i].style.display = styleVisibility;
}

var formError = false;
// Form validation functions
function displayErrors(element, errorDiv) {
	formError = true;
	jscss("add", element[0], "error");
	if (errorDiv.innerHTML == "")
		errorDiv.innerHTML = "Please fill in the fields noted above.<br/>\n";
	errorDiv.style.display = "block";
}

function clearErrors(form, div) {
	formError = false;
	var my_array;
	if (form == undefined)
		my_array = document.getElementsByTagName("*");
	else
		my_array = form.elements;
	for (i=0; i < my_array.length; i++)
		jscss("remove", my_array[i], "error");
	if (div != undefined) {
		div.innerHTML = "";
		div.style.display = "none";
	}
}

function errorCheck() {
	var errorDiv = document.getElementById('errors');
	var theForm = document.getElementById('TravelPlanner');
	clearErrors(theForm, errorDiv);

	var checkType = currentFormType;
	if (checkType == 'Package') {
		if (currentPackageType == 'Hotel')
			checkType = 'Hotel';
/*
		else if (currentPackageType == 'Car')
			checkType = 'Car';
		else
			checkType = 'Flight';
*/
	}

	// dates must be right
	var mustBeDates = new Array(
		new Array(document.getElementById('fromDate'), "The 'Depart' date is not valid."),
		new Array(document.getElementById('toDate'), "The 'Return' date is not valid.")
	);

	// Check for fields that must be present
	// destination must be populated if not car
	// source location must be populated if not hotel-only
	var mustNotBeEmpty = new Array();
	var toPackageLocation;
	var toAirportLocation;

	if (checkType == 'Hotel') {
		mustNotBeEmpty.push(new Array(document.getElementById('toAreaLocation'), "The 'To' city is missing"));
		//ack!
		if (document.getElementById('toAreaLocation').value == '1-SELECTED')
			displayErrors(new Array(document.getElementById('toAreaLocation'), "Please select an area"), errorDiv);
	}
	else if (checkType == 'Flight') {
		mustNotBeEmpty.push(new Array(document.getElementById('fromLocation'), "The 'From' city is missing"));

		if (toAirportLocation = document.getElementById('toAirportLocation')) {
			mustNotBeEmpty.push(new Array(toAirportLocation, "The 'To' city is missing"));
			if (toAirportLocation.value == 'SELECTED')
				displayErrors(new Array(toAirportLocation, "Please select an area"), errorDiv);
		}
		else if (toAirportLocation = document.getElementById('toAirportLocationCode')) {
			mustNotBeEmpty.push(new Array(toAirportLocation, "The 'To' city is missing"));
			if (toAirportLocation.value == 'SELECTED')
				displayErrors(new Array(toAirportLocation, "Please select an area"), errorDiv);
		}

	}
	else if (checkType == 'Package') {
		mustNotBeEmpty.push(new Array(document.getElementById('fromLocation'), "The 'From' city is missing"));

		if (toPackageLocation = document.getElementById('toPackageLocation')) {
			mustNotBeEmpty.push(new Array(toPackageLocation, "The 'To' city is missing"));
			if (toPackageLocation.value == 'SELECTED')
				displayErrors(new Array(toPackageLocation, "Please select an area"), errorDiv);
		}
		else if (toPackageLocation = document.getElementById('toPackageLocationCode')) {
			mustNotBeEmpty.push(new Array(toPackageLocation, "The 'To' city is missing"));
			if (toPackageLocation.value == 'SELECTED')
				displayErrors(new Array(toPackageLocation, "Please select an area"), errorDiv);
		}
	}
	else if (checkType == 'Car') {
		if (fromCarLocation = document.getElementById('fromCarLocation')) {
			mustNotBeEmpty.push(new Array(fromCarLocation, "The 'From' city is missing"));
			if (fromCarLocation.value == 'SELECTED')
				displayErrors(new Array(fromCarLocation, "Please select an area"), errorDiv);
		}
		else if (fromCarLocation = document.getElementById('fromCarLocationCode')) {
			mustNotBeEmpty.push(new Array(fromCarLocation, "The 'From' city is missing"));
			if (fromCarLocation.value == 'SELECTED')
				displayErrors(new Array(fromCarLocation, "Please select an area"), errorDiv);
		}
	}


/*
		var fromCarLocation;
		if ((fromCarLocation = document.getElementById('fromCarLocation')) && checkType == 'Car')
			mustNotBeEmpty.push(new Array(fromCarLocation, "The 'Pick Up / Drop Off' city is missing"));
*/

	// For flights:
	if (checkType == 'Flight') {
		// No need for return date if one way
		if (oneWay = document.getElementById('flightOneWay'))
			if (flightOneWay.checked)
				mustBeDates.pop();
	}

	for (i = 0; i < mustBeDates.length; i++) {
		if (!isDate(mustBeDates[i][0].value)) { displayErrors(mustBeDates[i], errorDiv); }	
	}

	for (i = 0; i < mustNotBeEmpty.length; i++) {
		if (mustNotBeEmpty[i][0].value.trim() == "") { displayErrors(mustNotBeEmpty[i], errorDiv) }	
	}

	// This is a pitiful test, but we'll run with it for right now.
	return !formError;
}

function updateTravelDates() {
	var theDateString = document.getElementById('travelDates').value;
	if (theDateString == '')
		return handleEmptyTravelDates();

	var startDate = document.getElementById('fromDate');
	var endDate = document.getElementById('toDate');
	var dateArray = theDateString.split(":");
	startDate.value = dateArray[0];
	endDate.value = dateArray[1];

	if (travelDatesRow = document.getElementById("travelDatesContainer")) {
		travelDatesRow.style.display = '';

		var dateContainer;
		if (dateContainer = document.getElementById("dateContainer"))
			dateContainer.style.display = 'none';
	}
	
}

function handleEmptyTravelDates() {
	var travelDates;
	if (travelDates = document.getElementById("travelDates")) {
		travelDates.options.length = 0;
		travelDates.size = 1;
		travelDates.options[0] = new Option("None", "");
		travelDates.disabled = true;

		if (travelDatesRow = document.getElementById("travelDatesContainer"))
			travelDatesRow.style.display = 'none';

		var dateContainer;
		if (dateContainer = document.getElementById("dateContainer"))
			dateContainer.style.display = '';
	}
}
