var TRIP_DEFAULT = 0;		// Default (all options available)
var TRIP_MULTINIGHT = 1;	// Overnight (or multi-night) only
var TRIP_DAYTRIP = 2;		// Daytrip only
var TRIP_SOLDOUT = 3;		// Sold out?
var TRIP_NOFLIGHT = 4;	// Hotel & match but no flight

var FLIGHT_TAX = 70;	// Tax per person per flight

/* Create a new XMLHttpRequest object to talk to the Web server */
function makeXmlHttpRequest() {
	var ajaxRequest;
	
	try {					// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e) {			// Internet Explorer Browsers
		try {
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {	// Something went wrong
				alert("Browser not supported");
				return null;
			}
		}
	}
	return ajaxRequest;
}

function get_form_values(thisform) {
	var str = "";

	for (i = 0; i < thisform.elements.length; i++) {
		fobj = thisform.elements[i];
		par = fobj.parentNode;
		if (par.style.display != 'none') {
			switch (fobj.type) {
				case 'text':
				case 'hidden':
				case 'password':
				case 'textarea':
					str += fobj.name + '=' + escape(fobj.value) + '&';
					break;
				case "checkbox":
				case "radio":
					if (fobj.checked && !fobj.disabled) {
						str += fobj.name + "=" + escape(fobj.value) + "&";
					}
					break;
				case 'select-one':
					if (fobj.selectedIndex >= 0) {
						var fsel = fobj[fobj.selectedIndex];
						var val = (fsel.value.length > 0) ? fsel.value : fsel.text;
						str += fobj.name + '=' + escape(val) + '&';
					}
					break;
			}
		}
	}
	str = str.substr(0,(str.length - 1));
	return str;
}
    
function lookup_events(thisform,output_elem_id) {
	var str = get_form_values(thisform);

	xmlHttp = makeXmlHttpRequest();
	xmlHttp.open("POST", "ajax_events.php", true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlHttp.setRequestHeader("Content-length", str.length);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var response = xmlHttp.responseText;
			document.getElementById(output_elem_id).innerHTML = response;
			showTab(null, output_elem_id);
		}
	}
	xmlHttp.send(str);
}

function showHide(showsct, hidesct) {
	document.getElementById(showsct).style.display = "block";
	document.getElementById(hidesct).style.display = "none";
	return false;
}

function toggleEventDetail(elem_id) {
	var elem = document.getElementById(elem_id);
	
	// Show or hide?
	if (elem.style.display == "block") {
		elem.style.display = "none";
		return false;
	}

	// Make sure all other forms are hidden
	var elemkids = getElementsByClass('itin_detail', null, 'div');
	for (var i=0; i<elemkids.length; i++) {
			elemkids[i].style.display = 'none';
	}
	
	// Need to fetch event data?
	if (elem.innerHTML.length > 0) {	// No
		elem.style.display = "block";
		return false;
	}
	
	// Get the event details
	var url = url_prefix + "ajax_events.php?get_event_data=true&evt_id=" + escape(elem_id);
	var xmlHttp = makeXmlHttpRequest();
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var response = xmlHttp.responseText;
			if (response.length > 0) {
				var cost_elem_id = 	'evt' + elem_id.replace(/\D/g, '') + '_';
				elem.innerHTML = response;
				elem.style.display = "block";
				on_change_hotel(cost_elem_id);
				//calc_booking_cost(cost_elem_id);
			}
		}
	}
	xmlHttp.send(null);
	return false;
}

function get_roomtype_allocation(elem_id,roomtype) {
	return Number(document.getElementById(elem_id + 'hotel_' + roomtype).value);
}

function set_roomtype_allocation(elem_id,roomtype,val) {
	var rm = document.getElementById(elem_id + 'hotel_' + roomtype);
	rm.value = val;
}

function book_events(elem_id) {
	// Check data before user goes into booking process
	
	// Check that if they have selected a flights option they have also entered a number of flight tickets
	var dep_apt_name = get_selected_name(elem_id + 'dep_apt');
	var bFlightSelected = (dep_apt_name != 'No flight');
	var num_flights = Number(get_selected_value(elem_id + 'num_flights'));
	if (bFlightSelected && (num_flights <= 0)) {	// shouldn't be possible anyway
		alert('Please select a number of flight tickets');
		return false;
	}
	
	// TODO: Check that they have selected room types if they have a hotel
	var hotel_id = get_hotel_id(elem_id);

	/*
	If there is an odd number travelling (ie 1/ 3 /5 / 7 or 9 persons) they must choose rooms to suit 
	the numbers travelling or the booking is not permitted (simlar to the current match ticket v persons ratio)
	*/
	if (hotel_id != 0) {
		// Check that the number of people in the booking matches the number of beds/rooms
		var num_adults = Number(get_selected_value(elem_id + 'hotel_persons'));
		var num_children = Number(get_selected_value(elem_id + 'hotel_children'));
		//var num_tickets = Number(get_selected_value(elem_id + 'num_tickets'));
		var max_tickets = Math.max(num_flights, (num_adults + num_children));
		var num_single_rooms = get_roomtype_allocation(elem_id, 'singles');
		
		if ((max_tickets == 1) && (num_single_rooms < 1)) {
			// HACK: Silently fix the room allocations
			set_roomtype_allocation(elem_id, 'singles', 1);
			set_roomtype_allocation(elem_id, 'twins', 0);
			set_roomtype_allocation(elem_id, 'doubles', 0);
			set_roomtype_allocation(elem_id, 'triples', 0);
			set_roomtype_allocation(elem_id, 'family', 0);
			//alert('Please select a single room');
			return false;
		}
	}
	
	return true;
}

function get_selected_name(elem_id) {
	var fobj = document.getElementById(elem_id);
	var nam = '';
	var val;
	
	if (fobj.selectedIndex >= 0) {
		var fsel = fobj[fobj.selectedIndex];
		val = fsel.text;
	}
	return val;
}

function get_selected_value(elem_id) {
	var fobj = document.getElementById(elem_id);
	var val = '';
	
	if (fobj.selectedIndex >= 0) {
		var fsel = fobj[fobj.selectedIndex];
		val = (fsel.value.length > 0) ? fsel.value : fsel.text;
	}
	return val;
}

function set_selected_value(elem_id, val) {
	var fobj = document.getElementById(elem_id);
	var selected_val;
	
	for (var i = 0; i < fobj.options.length; i++) {
		selected_val = (fobj[i].value.length > 0) ? fobj[i].value : fobj[i].text;
		if (selected_val == val) {
			fobj[i].selected = true;
			break;
		}
	}
}

function get_num_children(elem_id,aged_under) {
	var child_ages = document.getElementById(elem_id + 'child_ages');
	var num_children = Number(get_selected_value(elem_id + 'hotel_children'));
	var num_listed_children = 0;

	// Retrieve name/age details from hidden fields
	var child_info_ary = child_ages.value.split(';');
	for (var i = 0; i < num_children; i++) {
		if (child_info_ary.length > i) {
			var ary = child_info_ary[i].split(',');
			var age = isNaN(ary[1]) ? 0 : Number(ary[1]);
			if ((age > 0) && (age < aged_under)) {
				num_listed_children++;
			}
		}
	}
	return num_listed_children;
}

function get_num_child_discounts(elem_id) {
	var num_persons = Number(get_selected_value(elem_id + 'hotel_persons'));
	var num_children = Number(get_selected_value(elem_id + 'hotel_children'));
	var num_named_children = get_num_children(elem_id, 16);
	var num_family_rooms = Number(document.getElementById(elem_id + 'hotel_family').value);
	var num_child_reduction = 0;
	var num_children_too_old = 0;
	var num_filled_rooms = 0;
	
	/* CHILD DISCOUNT
	There is a child discount for each child in a family room which is shared with 2 adults.
	There are a maximum of 2 children in a family room.
	The discount only applies if the children are under 16 and sharing a family room with 2 adults.
	*/
	
	// Check if children are listed by name/age, if not assume the number given is accurate
	if (num_named_children > 0) {
		num_children_too_old = num_children - num_named_children;
		num_children_too_old = (num_children_too_old < 0) ? 0 : num_children_too_old;
	}
	num_children = num_named_children;
	
	var num_adult_filled_rooms = parseInt((num_persons + num_children_too_old)/2);
	var num_child_filled_rooms = parseInt(num_children/2);
	num_filled_rooms = (num_family_rooms > num_adult_filled_rooms) ?
		num_adult_filled_rooms : num_family_rooms;
	num_filled_rooms = (num_filled_rooms > num_child_filled_rooms) ?
		num_child_filled_rooms : num_filled_rooms;
	num_child_reduction = num_filled_rooms * 2;
	if ((num_child_reduction < num_children) &&
		(num_filled_rooms < num_adult_filled_rooms) &&
		(num_family_rooms > 0)) {
		num_child_reduction++;
	}

	return num_child_reduction;
}

function party_numbers(elem_id,hotel_id) {
	this.num_insured = 0;
	this.num_child_reduction = get_num_child_discounts(elem_id);
	this.num_persons = Number(get_selected_value(elem_id + 'hotel_persons'));
	this.num_children = Number(get_selected_value(elem_id + 'hotel_children'));
	this.num_tickets = Number(get_selected_value(elem_id + 'num_tickets'));
	this.num_hotel_guests = this.num_persons + this.num_children;
	this.num_flights = Number(get_selected_value(elem_id + 'num_flights'));
	this.num_single_rooms = Number(document.getElementById(elem_id + 'hotel_singles').value);
	//this.num_twin_rooms = Number(document.getElementById(elem_id + 'hotel_twins').value);
	//this.num_double_rooms = Number(document.getElementById(elem_id + 'hotel_doubles').value);

	if (hotel_id == 0) {
		this.num_hotel_guests = 0;
		this.num_persons = 0;
		this.num_children = 0;
		this.num_child_reduction = 0;
		this.num_room_places = 0;
	} else {
		this.num_room_places = get_roomtype_allocation(elem_id, 'singles') +
			(get_roomtype_allocation(elem_id, 'twins') * 2) +
			(get_roomtype_allocation(elem_id, 'doubles') * 2) +
			(get_roomtype_allocation(elem_id, 'triples') * 3) +
			(get_roomtype_allocation(elem_id, 'family') * 2) +
			this.num_child_reduction;
	}
	
	var dep_apt_name = get_selected_name(elem_id + 'dep_apt');
	if (dep_apt_name == "No flight") {
		this.num_flights = 0;
	}

	this.num_party = Math.max(this.num_hotel_guests, this.num_tickets, this.num_flights);

	var num_tickets = this.num_tickets;
	var num_flights = this.num_flights;
	var num_hotel_guests = this.num_hotel_guests;

	// Ticket options
	this.num_THF_price = Math.min(num_tickets, num_hotel_guests, num_flights);
	num_tickets -= this.num_THF_price;
	num_flights -= this.num_THF_price;
	num_hotel_guests -= this.num_THF_price;
	
	this.num_TH_price = Math.min(num_tickets, num_hotel_guests);
	num_tickets -= this.num_TH_price;
	num_hotel_guests -= this.num_TH_price;

	this.num_TF_price = Math.min(num_tickets, num_flights);
	num_tickets -= this.num_TF_price;
	num_flights -= this.num_TF_price;

	this.num_T_price = num_tickets;
	
	// Non-ticket options
	this.num_HF_price = Math.min(num_hotel_guests, num_flights);
	num_flights -= this.num_HF_price;
	num_hotel_guests -= this.num_HF_price;
	
	this.num_H_price = num_hotel_guests;
	this.num_F_price = num_flights;
	
	// Functions
	this.display_cost_items = display_cost_items;
}

function display_cost_items(elem_id) {
	var item_elem = document.getElementById(elem_id + 'cost_items');
	var disp_text =
		this.num_THF_price + ' x ticket+hotel+flight<br />' +
		this.num_TH_price + ' x ticket+hotel<br />' +
		this.num_TF_price + ' x ticket+flight<br />' +
		this.num_T_price + ' x ticket<br />' +
		this.num_HF_price + ' x hotel+flight<br />' +
		this.num_H_price + ' x hotel<br />' +
		this.num_F_price + ' x flight';
	
	item_elem.innerHTML = disp_text;
}

function price_model(elem_id) {
	var price_text = document.getElementById(elem_id + 'prices').value;
	var ary = price_text.split(",");

	this.elem_id = elem_id;
	// PRC_ID, Ticket, Ticket_Hotel, Ticket_Flight, Ticket_Hotel_Flight,
	// Extra_Night_3, Single_Supplement_3, Extra_Night_4, Single_Supplement_4, Extra_Night_5, Single_Supplement_5, 
	// Child_Red, Travel_Ins, Ferry,
	// ORK, NOC, KIR, SNN, WAT, GWY
	this.prc_id = ary[0];
	this.T_price = Number(ary[1]);
	this.TH_price = Number(ary[2]);
	this.TF_price = Number(ary[3]);
	this.THF_price = Number(ary[4]);
	this.H_price = this.TH_price - this.T_price;
	this.F_price = this.TF_price - this.T_price;
	this.HF_price = this.THF_price - this.T_price;
	this.extra_night_3 = Number(ary[5]);
	this.single_supplement_3 = Number(ary[6]);
	this.extra_night_4 = Number(ary[7]);
	this.single_supplement_4 = Number(ary[8]);
	this.extra_night_5 = Number(ary[9]);
	this.single_supplement_5 = Number(ary[10]);
	this.child_reduction = Math.abs(Number(ary[11]));				// negative value?
	this.travel_insurance = Number(ary[12]);
	this.ferry_price = Number(ary[13]);
	this.apt_supplements =  new Array();

	this.single_supplement = 0;
	this.first_night_price = 0;
	this.extra_night_price = 0;
	this.extra_nights_cost = 0;

	
	// Regional airport supplements
	this.apt_supplements['ORK'] = Math.abs(Number(ary[14]));
	this.apt_supplements['NOC'] = Math.abs(Number(ary[15]));
	this.apt_supplements['KIR'] = Math.abs(Number(ary[16]));
	this.apt_supplements['SNN'] = Math.abs(Number(ary[17]));
	this.apt_supplements['WAT'] = Math.abs(Number(ary[18]));
	this.apt_supplements['GWY'] = Math.abs(Number(ary[19]));
	
	// Functions
	//this.calc_hotel_extras = calc_hotel_extras;
	this.calc_hotel_costs = calc_hotel_costs;
	this.calc_total_price = calc_total_price;
	this.enable_available_items = enable_available_items;
}

function calc_hotel_costs(hotel_id,hotel_type,num_nights) {
	if (isNaN(hotel_id) || (Number(hotel_id) > 0)) {	// no id means "no hotel" was selected		
		// Hotel type options
		// NIGHT 1 SUPPLEMENT: twice the difference between the 4/5* supplement and the 3* one
		switch (hotel_type) {
			case 4:
				this.first_night_price = (this.extra_night_4 - this.extra_night_3) * 2;
				this.extra_night_price = this.extra_night_4;
				this.single_supplement = this.single_supplement_4;
				break;
			case 5:
				this.first_night_price = (this.extra_night_5 - this.extra_night_3) * 2;
				this.extra_night_price = this.extra_night_5;
				this.single_supplement = this.single_supplement_5;
				break;
			default:
				this.first_night_price = 0;
				this.extra_night_price = this.extra_night_3;
				this.single_supplement = this.single_supplement_3;
				break;
		}
		
		this.extra_nights_cost = (num_nights-1) * this.extra_night_price;
	}
}

function calc_total_price(party,num_nights,reg_supplement) {
	var total = (party.num_T_price * this.T_price)
		+ (party.num_TH_price * this.TH_price)
		+ (party.num_TF_price * this.TF_price)
		+ (party.num_THF_price * this.THF_price)
		+ (party.num_H_price * this.H_price)
		+ (party.num_F_price * this.F_price)
		+ (party.num_HF_price * this.HF_price)
		+ (reg_supplement * party.num_party)
		+ (this.single_supplement * party.num_single_rooms * num_nights)
		+ (this.first_night_price * party.num_hotel_guests)
		+ (this.extra_nights_cost * party.num_hotel_guests)
		+ (this.travel_insurance * party.num_insured)
		- (this.child_reduction * party.num_child_reduction * num_nights);
	return total;
}

function get_hotel_id(elem_id) {
		var hotel_info = get_selected_value(elem_id + 'hotel_id');
		var hotel_info_ary = hotel_info.split(",");
		var hotel_id = hotel_info_ary[0];
		return hotel_id;
}

function enable_hotel_options(elem_id,enabled) {
	var hotel_elem = document.getElementById(elem_id + 'hotel_id');
	var hotel_date_elem = document.getElementById(elem_id + 'hotel_date');
	var hotelbtn_elem = document.getElementById(elem_id + 'hotelpopupbtn');
	var nights_elem = document.getElementById(elem_id + 'hotel_nights');
	var adults_elem = document.getElementById(elem_id + 'hotel_persons');
	var children_elem = document.getElementById(elem_id + 'hotel_children');
	var roomsbtn_elem = document.getElementById(elem_id + 'roomsbtn');
	var agesbtn_elem = document.getElementById(elem_id + 'agesbtn');
	var disabled = !enabled;
	
	if (enabled) {
		var hotel_id = get_hotel_id(elem_id);
		var num_children = Number(get_selected_value(elem_id + 'hotel_children'));	
		var no_hotel_selected = (hotel_id == 0);
		var hotel_id_selected = (Number(hotel_id) > 0);
		var no_children_selected = isNaN(num_children) || (num_children <= 0);

		hotel_elem.disabled = disabled;
		
		// If no hotel selected all elements except hotel select box disabled
		disabled |= no_hotel_selected;	
		hotel_date_elem.disabled = disabled;
		nights_elem.disabled = disabled;
		adults_elem.disabled = disabled;
		children_elem.disabled = disabled;
		roomsbtn_elem.disabled = disabled;
		
		// If no specific hotel selected then hotel details button disabled
		disabled |= !hotel_id_selected;
		hotelbtn_elem.disabled = disabled;
		
		// If no children then child ages button disabled
		disabled |= no_children_selected;
		agesbtn_elem.disabled = disabled;
	} else {
		hotel_date_elem.disabled = disabled;
		nights_elem.disabled = disabled;
		adults_elem.disabled = disabled;
		children_elem.disabled = disabled;
		hotelbtn_elem.disabled = disabled;
		roomsbtn_elem.disabled = disabled;
		agesbtn_elem.disabled = disabled;
		hotel_elem.selectedIndex = -1;
		hotel_date_elem.selectedIndex = -1;
		set_hotel_nights(elem_id, 0, 0);
	}
}

function enable_flight_options(elem_id,enabled,no_flight_selected) {
	var dep_apt_elem = document.getElementById(elem_id + 'dep_apt');
	var dep_date_elem = document.getElementById(elem_id + 'dep_date');
	var num_flights_elem = document.getElementById(elem_id + 'num_flights');
	var disabled = !enabled;
		
	dep_apt_elem.disabled = disabled;
	dep_date_elem.disabled = disabled || no_flight_selected;
	num_flights_elem.disabled = disabled || no_flight_selected;
	if (disabled || no_flight_selected) {
		//dep_apt_elem.selectedIndex = -1;
		//dep_date_elem.selectedIndex = -1;
		num_flights_elem.selectedIndex = -1;
	}
}

function enable_available_items() {
	if ((this.TH_price <= 0) && (this.THF_price <= 0)) {
		enable_hotel_options(this.elem_id, false);	// fix hotel availability if TH and THF prices are 0
	}
	
	if ((this.TF_price <= 0) && (this.THF_price <= 0)) {
		enable_flight_options(this.elem_id, false, false);	// fix flight availability if TF and THF prices are 0
	}
}

function calc_booking_cost(elem_id) {
	var dep_apt_info, dep_apt_info_ary, dep_apt_id, dep_apt_code, dep_apt_name;
	var total_item = document.getElementById(elem_id + 'cost');

	if (total_item.innerHTML == 'SOLD OUT') {	// Is it sold out?
		return true;
	}

	// Make sure we're not selling ticket-only stuff
	set_fixture_options(elem_id);

	
	var hotel_info = get_selected_value(elem_id + 'hotel_id');
	var hotel_info_ary = hotel_info.split(",");
	var hotel_id = hotel_info_ary[0];
	var hotel_type = hotel_info_ary[1] ? Number(hotel_info_ary[1]) : 3;
	var num_nights = (hotel_id == 0) ? 0 : Number(get_selected_value(elem_id + 'hotel_nights'));
	var dep_date = get_selected_value(elem_id + 'dep_date');
	var party = new party_numbers(elem_id, hotel_id);
	var prc_model = new price_model(elem_id);

	//party.display_cost_items(elem_id);
	
	// Selected airport information
	dep_apt_info = get_selected_value(elem_id + 'dep_apt');
	if (dep_apt_info.length > 0) {
		dep_apt_info_ary = dep_apt_info.split(",");
		dep_apt_id = Number(dep_apt_info_ary[0]);
		dep_apt_code = dep_apt_info_ary[1];
	}
	dep_apt_name = get_selected_name(elem_id + 'dep_apt');
	
	var reg_supplement = 0;
	var reg_supplement_text = '';
	if (dep_apt_code && (dep_apt_code != 'DUB')) {
		// Calculate regional supplement figure if it exists
		var suppl = prc_model.apt_supplements[dep_apt_code];
		if (suppl == 999) {	// default value which means no supplement specified
			reg_supplement_text = ' plus regional airport supplement';
		} else {
			reg_supplement = suppl;
		}
	}
	
	// Calculate the cost of the booking on the form and output it to the given elem
	// Itinerary cost is a full amount minus discounts based on a PriceModel record
	
	// Hotel costs
	prc_model.calc_hotel_costs(hotel_id, hotel_type, num_nights);

	var total = prc_model.calc_total_price(party, num_nights, reg_supplement);
	var tax = party.num_flights * FLIGHT_TAX;	// Calculate the tax, which is per (return?) flight
	var total_text = 'to be determined';
	var disabled = false;

	// HACK: Disable ticket-only option if there's no price and no hotel/flight selected
	if ((total <= 0) || (total ==  '0')){
		total_text = 'Not available';
		total = '';
		disabled = true;
	}
	
	// HACK: Disable if num_guests doesn't match num_tickets and/or num_flights
	/*if ((party.num_hotel_guests > party.num_tickets) ||
		(party.num_hotel_guests > party.num_flights)) {
		//alert('Too many hotel guests');
		disabled = true;
	}*/
	
	// HACK: Disable if num_guests and room allocations don't match
	var room_select_text = '';
	//alert('hotel_id: ' + hotel_id + ' num_hotel_guests: ' + num_hotel_guests + ' num_room_places: ' + num_room_places);
	if ((hotel_id != 0) && (party.num_hotel_guests < party.num_room_places)) {
		total_text = 'Please select hotel rooms for the party';
		total = '';
		disabled = true;
	}
	
	if (!isNaN(total) && (total > 0)) {
		total_text = '&euro;' + (total - tax);
		if (tax > 0) {
			total_text += ' plus &euro;' + tax + ' tax';
		}
		total_text += reg_supplement_text;
	}
	total_item.innerHTML = total_text;
	document.getElementById(elem_id + 'book_btn').disabled = disabled;
	
	return true;
}

function set_date_options(elem_id) {
	var restrictions_elem = document.getElementById(elem_id + 'restrictions');
	var dep_date = Number(get_selected_value(elem_id + 'dep_date'));
	
	if (restrictions_elem) {	// Date restrictions, so change hotel nights according to selected date value
		var restrict_info_ary = restrictions_elem.value.split(';');
		
		for (var i = 0; i < restrict_info_ary.length; i++) {
			var ary = restrict_info_ary[i].split(',');
			var date = Number(ary[0]);
			var numnights = Number(ary[1]);
			
			if (dep_date == date) {		// Set  num_nights for selected date
				set_hotel_nights(elem_id, numnights, numnights);
			}
		}
	}
}

function set_hotel_options(elem_id) {
	var hotel_id = get_hotel_id(elem_id);
	var minnights = Number(document.getElementById(elem_id + 'hotel_min_nights').value);
	var maxnights = Number(document.getElementById(elem_id + 'hotel_max_nights').value);

	// Check if its set to no hotel or not, if so clear/hide room options
	enable_hotel_options(elem_id, true);

	if (hotel_id == 0) {	// HIDE
		set_hotel_nights(elem_id, 0, 0);
	} else {	// Set hotel popup details
		set_hotel_nights(elem_id, ((minnights > 1) ? minnights : 1), maxnights);
	}
}

function set_child_options(elem_id) {
	var num_children = Number(get_selected_value(elem_id + 'hotel_children'));
	var agesbtn_elem = document.getElementById(elem_id + 'agesbtn');
	
	// Check if there are children or not, if so enable/disable ages button
	agesbtn_elem.disabled = isNaN(num_children) || (num_children <= 0);
}

function set_hotel_nights(elem_id,minnights,maxnights) {
	var nights_elem = document.getElementById(elem_id + 'hotel_nights');
	var dep_apt_name = get_selected_name(elem_id + 'dep_apt');
	
	if (dep_apt_name &&
		(dep_apt_name != 'No flight') &&
		(dep_apt_name != 'Dublin')) {	// Min 2 night stay if its a regional (i.e. non-Dublin) airport
		minnights = (minnights > 2) ? minnights : 2;
	}
	maxnights = (minnights > maxnights) ? minnights : maxnights;
	
	// Save selected numnights and then restore it after we've finished messing with the list (if its still there)
	var selected_nights = get_selected_name(elem_id + 'hotel_nights');
	var j = -1;
	
	// Remove all nights from list
	while (nights_elem.options.length > 0) {
		nights_elem.remove(0);
	}
	// Add valid nights to list
	for (var i = minnights; i <= maxnights; i++) {
		var dt = document.createElement('option');		
		dt.text = i;
		try {
			nights_elem.add(dt, null); // standards compliant
		} catch(ex) {
			nights_elem.add(dt); // IE only
		}
		if (dt.text == selected_nights) {
			j = nights_elem.options.length-1;
		}
	}
	if (j >= 0) {	// Restore previously selected option
		nights_elem[j].selected = true;
	}
}

function set_airport_options(elem_id,reset_selected) {
	var availability = Number(document.getElementById(elem_id + 'availability').value);
	var dep_apt_name = get_selected_name(elem_id + 'dep_apt');
	var dep_apt_elem = document.getElementById(elem_id + 'dep_apt');
	var hotel_elem = document.getElementById(elem_id + 'hotel_id');
	var hotel_id = get_hotel_id(elem_id);
	var sDaytripOptionName = 'Day trip';
	var bIsRegionalAirport = (dep_apt_name != 'Dublin');
	var bEnableFlightOptions = (availability != TRIP_NOFLIGHT);
	var bNoFlightSelected = (dep_apt_name == 'No flight');

	// TODO: set hotel and flight options based on availability
	
	//If hotel selected and THF is 0 then disable flight options
	var prc_model = new price_model(elem_id);
	var hotel_selectedIndex = hotel_elem.selectedIndex;
	bEnableFlightOptions &= ((prc_model.THF_price > 0) || (hotel_id == 0));
	
	//Add/remove daytrip option from hotel dropdown
	if (bIsRegionalAirport) {	// No daytrip option in dropdown for regional (i.e. non-Dublin) airports
		if (hotel_elem.options[0].text == sDaytripOptionName) {
			hotel_elem.remove(0);
		}
	} else {	// Daytrip option in dropdown
		if ((availability == TRIP_DAYTRIP) || (availability == TRIP_DEFAULT)) {
			if (hotel_elem.options[0].text != sDaytripOptionName) {
				var dt = document.createElement('option');
				
				dt.text = sDaytripOptionName;
				dt.value = 0;
				try {
					hotel_elem.add(dt, hotel_elem.options[0]); // standards compliant
				} catch(ex) {
					hotel_elem.add(dt, 0); // IE only
				}
			}
		}
	}	
		
	// If no flight tickets selected set to same number as hotel occupants (adults and children)
	if (bEnableFlightOptions && !bNoFlightSelected && (hotel_id != 0)) {
		var num_flights = Number(get_selected_value(elem_id + 'num_flights'));
		var num_adults = Number(get_selected_value(elem_id + 'hotel_persons'));
		var num_children = Number(get_selected_value(elem_id + 'hotel_children'));
		if (num_flights <= 0) {
			set_selected_value(elem_id + 'num_flights', num_adults + num_children);
		}
	}

	// Try and reset hotel value to previously selected one
	if ((hotel_selectedIndex >= 0) && reset_selected) {
		hotel_elem.options[hotel_selectedIndex].selected = true;		
	}
	enable_flight_options(elem_id, bEnableFlightOptions, bNoFlightSelected);
}

function set_fixture_options(elem_id) {
	var prc_model = new price_model(elem_id);
	
	// No ticket-only price, so set max tickets to buy as the maximum of flight or hotel bookings
	//if (prc_model.T_price <= 0) {
		var num_flights = Number(get_selected_value(elem_id + 'num_flights'));
		var num_adults = Number(get_selected_value(elem_id + 'hotel_persons'));
		var num_children = Number(get_selected_value(elem_id + 'hotel_children'));
		var num_tickets = Number(get_selected_value(elem_id + 'num_tickets'));
		var max_tickets = Math.max(num_flights, (num_adults + num_children));
		
		if (num_tickets > max_tickets) {
			alert('Match ticket can only be purchased with a hotel and/or flight');
			//alert(elem_id + 'num_tickets');
			set_selected_value(elem_id + 'num_tickets', max_tickets);
		}
	//}
}

function on_change_date(elem_id) {
	set_date_options(elem_id);
	return calc_booking_cost(elem_id);
}

function on_change_hotel(elem_id) {
	set_airport_options(elem_id, false);
	set_hotel_options(elem_id);
	return calc_booking_cost(elem_id);
}

function on_change_children(elem_id) {
	set_child_options(elem_id);
	return calc_booking_cost(elem_id);
}

function on_change_airport(elem_id) {
	set_airport_options(elem_id, false);
	set_hotel_options(elem_id);
	return calc_booking_cost(elem_id);
}

function on_change_tickets(elem_id) {
	return calc_booking_cost(elem_id);
}

function on_load_fixture(elem_id) {
	set_child_options(elem_id);
	set_airport_options(elem_id, true);
	set_hotel_options(elem_id);
	var prc_model = new price_model(elem_id);
	prc_model.enable_available_items();

	return calc_booking_cost(elem_id);
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function popcal(cal, elem, anchor, startelem) {
	var id1 = document.getElementById(elem);
	var id2 = document.getElementById(startelem);
	if (id2) {
		cal.select(id1,anchor,'dd/MM/yyyy', (id1.value=='') ? id2.value : null);
	} else {
		cal.select(id1,anchor,'dd/MM/yyyy');
	}
	return false;
}

function popuprooms(rm, anchor_name, evt_id) {
	var sg = document.getElementById(evt_id + 'hotel_singles');
	var tw = document.getElementById(evt_id + 'hotel_twins');
	var db = document.getElementById(evt_id + 'hotel_doubles');
	var tp = document.getElementById(evt_id + 'hotel_triples');
	var fm = document.getElementById(evt_id + 'hotel_family');
	var evt = document.getElementById('rooms_event_id');
	var hotel_id = get_hotel_id(evt_id);
	var disable_rooms = (!isNaN(hotel_id) && (Number(hotel_id) > 0));
	var sg1 = document.getElementById('rooms_num_singles');
	var tp1 = document.getElementById('rooms_num_triples');
	var fm1 = document.getElementById('rooms_num_family');
	
	// Only allow triple and family rooms if the hotel id is unspecified
	tp1.disabled = disable_rooms;
	fm1.disabled = disable_rooms;
	
	// NFL EVENT KLUDGE
	if (evt_id == 'evt1183_') {
		sg1.disabled = true;
		tp1.disabled = true;
		fm1.disabled = true;
	}
	
	// Get room info from hidden field and use it to populate room form elements
	// Set the event ID to put it back into the room form
	evt.value = evt_id;
	set_selected_value('rooms_num_singles', sg.value);
	set_selected_value('rooms_num_twins', tw.value);
	set_selected_value('rooms_num_doubles', db.value);
	
	if (disable_rooms) {
		set_selected_value('rooms_num_triples', 0);
		set_selected_value('rooms_num_family', 0);
	} else {
		set_selected_value('rooms_num_triples', tp.value);
		set_selected_value('rooms_num_family', fm.value);
	}

	rm.showPopup(anchor_name);
	return false;
}

function set_rooms(rm, thisform) {
	var evt = document.getElementById('rooms_event_id');
	var evt_id = evt.value;
	var sg = document.getElementById(evt_id + 'hotel_singles');
	var tw = document.getElementById(evt_id + 'hotel_twins');
	var db = document.getElementById(evt_id + 'hotel_doubles');
	var tp = document.getElementById(evt_id + 'hotel_triples');
	var fm = document.getElementById(evt_id + 'hotel_family');
	
	// Take data from the rooms form and put in into the hidden vars in the event form
	// Also set text description of rooms booked
	sg.value = get_selected_value('rooms_num_singles');
	tw.value = get_selected_value('rooms_num_twins');
	db.value = get_selected_value('rooms_num_doubles');
	tp.value = get_selected_value('rooms_num_triples');
	fm.value = get_selected_value('rooms_num_family');
	var txt = '';
	if ((db.value.length > 0) && (Number(db.value) > 0)) {
		txt = db.value + ' double';
	}
	if ((tw.value.length > 0) && (Number(tw.value) > 0)) {
		if (txt.length > 0) {
			txt += ', ';
		}
		txt += tw.value + ' twin';
	}
	if ((sg.value.length > 0) && (Number(sg.value) > 0)) {
		if (txt.length > 0) {
			txt += ', ';
		}
		txt += sg.value + ' single';
	}
	if ((tp.value.length > 0) && (Number(tp.value) > 0)) {
		if (txt.length > 0) {
			txt += ', ';
		}
		txt += tp.value + ' triple';
	}
	if ((fm.value.length > 0) && (Number(fm.value) > 0)) {
		if (txt.length > 0) {
			txt += ', ';
		}
		txt += fm.value + ' family';
	}
	
	var disp = document.getElementById(evt_id + 'hotel_rooms');
	//disp.value = txt;
	disp.innerHTML = txt;
	
	// Recalculate the cost based on the room selections
	//var cost_elem_id = 'evt' + evt_id.replace(/\D/g, '') + '_';
	calc_booking_cost(evt_id);
	
	rm.hidePopup();
	return false;
}

function popupages(ag, anchor_name, elem_id) {
	var num_children = Number(get_selected_value(elem_id + 'hotel_children'));
	var child_ages = document.getElementById(elem_id + 'child_ages');
	var disp_table = document.getElementById(ag.divName + '_names');
	var evt = document.getElementById('child_ages_event_id');

	evt.value = elem_id;
	// Add the number of rows we need
	// Get the number of children specified in the main booking form and then create name/age input line for each one.
	
	// Retrieve existing name/age details from hidden fields if it already exists
	var child_info_ary = child_ages.value.split(';');
	var txt = '<table><tr><th>Name</th><th>Age</th></tr>';
	for (var i = 0; i < num_children; i++) {
		var name = '';
		var age = '';
		
		if (child_info_ary.length > i) {
			var ary = child_info_ary[i].split(',');
			name = ary[0];
			age = isNaN(ary[1]) ? '' : ary[1];
		}
		
		txt += '<tr><td>' +
			'<input type="text" size="20" value="' + name + '" id="hotel_child_name_' + i + '">' +
			'</td><td>' +
			'<input type="text" size="2" value="' +age + '" id="hotel_child_age_' + i + '">' +
			'</td></tr>';
	}
	txt += '</table>';
	disp_table.innerHTML = txt;
	
	ag.showPopup(anchor_name);
	return false;
}

function set_ages(ag, thisform) {
	var evt = document.getElementById('child_ages_event_id');
	var evt_id = evt.value;
	var c = document.getElementById(evt_id + 'child_ages');
	var num_children = Number(get_selected_value(evt_id + 'hotel_children'));
	var txt = '';

	// Take data from child ages form popup and put into hidden field
	for (var i = 0; i < num_children; i++) {
		txt += document.getElementById('hotel_child_name_' + i).value + ',' +
			document.getElementById('hotel_child_age_' + i).value + ';';
	}

	ag.hidePopup();
	c.value = txt;
	// Recalculate the cost based on the room selections
	calc_booking_cost(evt_id);
	
	return false;
}

function popup_hotel(ht,elem_id) {
	var hotel_id = get_hotel_id(elem_id);
	
	if ((hotel_id != 0) && (Number(hotel_id) > 0)) {
		//win.hidePopup();
		ht.setUrl('popup_hotel.php?hotelid=' + hotel_id);
		ht.showPopup(elem_id + 'hotelpopupbtn');
	}
}

var url_prefix = '';
var cal1 = new CalendarPopup('caldiv1');
cal1.showNavigationDropdowns();
cal1.offsetX = 0;

var rm1 = new PopupWindow('roomsdiv1');
rm1.autoHide();
rm1.offsetX = 150;

var ag1 = new PopupWindow('agesdiv1');
ag1.autoHide();
ag1.offsetX = 100;

var ht1 = new PopupWindow(); 
ht1.autoHide(); 
ht1.setSize(500, 400);
