var departureDetails;

function initForm() {
	// download departure details if the start date is set
	// can't call startDateChanged() directly in case all the details are specified in the request
	var startDate = dwr.util.getValue('startDate');
	if (startDate != '-1') {
		var language = dwr.util.getValue('language');
		var externalId = dwr.util.getValue('externalId');
		AjaxSearchUtil.getDepartureDetails(language, externalId, startDate,
			function(details) {
				if (details == null) {
					location.replace("/");
					return;
				}

				departureDetails = details;
				if (details.origins == null || details.origins.length == 0) {
					resetList('origin');
					dwr.util.setValue('originCell', msgOriginCell, { escapeHtml:false });
					dwr.util.setValue('originListCell', msgOriginCellValue, { escapeHtml:false });
					show('originCell', 'originListCell');
				}
			}
		);
	} 

	if (dwr.util.getValue('duration') != -1) {
		refreshRooms();
	}
	setDefaultInsurance();
}

function updateInsuranceCategories() {
	var startDate = dwr.util.getValue('startDate');
	AjaxSearchUtil.getInsuranceCategories(startDate,
		function(group) {
			hide('priceTable');
			show('noInsuranceAlert');
			acceptNoInsurance();
			
			// normal insurances
			dwr.util.removeAllRows('insurance-table-body', { filter:function(tr) {
				return (tr.id != 'insurance-cat-row');
			}});
			
			for (i = 0; i < group.categories.length; i++) {
				var groupCat = group.categories[i];
				if (groupCat.status == 1) {
					dwr.util.setValue('insErrorMsg', msgInsuranceError, { escapeHtml:false });
					show('insErrorMsg');
					continue;
				}
				
				var clone = dwr.util.cloneNode('insurance-cat-row', { idSuffix: groupCat.type });
				clone.style.display = '';
				var radio = clone.getElementsByTagName('input')[0];
				radio.setAttribute('value', groupCat.type);
				if (groupCat.type == group.selected) {
					radio.checked = 'checked';
				}

				dwr.util.setValue('insurance-cat-name' + groupCat.type, groupCat.listName);
			}
			
			// extra insurances
			displayExtraCategories(group);
			
			if (group.selected != null) {
				displayInsuranceDetails(group);
			}
		}
	);
}

function displayExtraCategories(group) {
	dwr.util.removeAllRows('insurance-extra-table-body', { filter:function(tr) {
		return (tr.id != 'insurance-extra-row');
	}});
	
	for (i = 0; i < group.extraCategories.length; i++) {
		var groupCat = group.extraCategories[i];
		var clone = dwr.util.cloneNode('insurance-extra-row', { idSuffix: groupCat.type });
		clone.style.display = '';
		var checkbox = clone.getElementsByTagName('input')[0];
		checkbox.setAttribute('name', 'selectedExtraInsurances(' + groupCat.type + ')');
		checkbox.setAttribute('value', groupCat.type);
		dwr.util.setValue('insurance-extra-name' + groupCat.type, groupCat.listName);
	}
}

function updateChart() {
	// base data
	var language = dwr.util.getValue('language');
	var externalId = dwr.util.getValue('externalId');
	
	// relevant IBE config
	var dateParamInStoreFormat = dwr.util.getValue('dateParamInStoreFormat'); 
	var durationParamInStoreFormat = dwr.util.getValue('durationParamInStoreFormat');
	
	// selections
	var startDate = dwr.util.getValue('startDate');
	var board = dwr.util.getValue('board');
	var duration = dwr.util.getValue('duration');
	
	AjaxSearchUtil.loadChartData(
			language, externalId, 
			dateParamInStoreFormat, durationParamInStoreFormat,
			startDate, board, duration,
			callbackUpdateChart);
}

function callbackUpdateChart(dataAsString) {
	tmp = findSWF("price_chart");
	x = tmp.load(dataAsString);
}

function findSWF(movieName) {
	if (navigator.appName.indexOf("Microsoft")!= -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function startDateChanged() {
	resetRooms();
	wasFormValid = false;
	disableNextButtons();

	var startDate = dwr.util.getValue('startDate');
	if (startDate != '-1') {
		disable('origin', 'board', 'duration');
		var language = dwr.util.getValue('language');
		var externalId = dwr.util.getValue('externalId');
		AjaxSearchUtil.getDepartureDetails(language, externalId, startDate,
			function(details) {
				if (details == null) {
					location.replace("/");
					return;
				}

				departureDetails = details;
				if (details.origins == null || details.origins.length == 0
						|| details.origins[0].key == '') {
					resetList('origin');
					dwr.util.setValue('originCell', msgOriginCell, { escapeHtml:false });
					dwr.util.setValue('originListCell',msgOriginCellValue, { escapeHtml:false });
					show('originCell', 'originListCell');
					// the key is the empty string if no origin was found
					updateBoards(departureDetails.boards['']);
				} else {
					updateOrigins(details.origins);
				}
			
				enable('origin', 'board', 'duration');
			}
		);
	} else {
		resetList('origin', chooseOption);
		resetList('board', chooseOption);
		resetList('duration', chooseOption);
		dwr.util.setValue('progressMsg', progressTravelData);
	}
}

function updateOrigins(origins) {
	if (origins.length > 1) {
		resetList('origin', chooseOption);
	} else {
		resetList('origin');
	}

	dwr.util.addOptions('origin', origins, 'key', 'value');
	originChanged();
}

function originChanged() {
	var origin = dwr.util.getValue('origin');
	if (origin != -1) {
		updateBoards(departureDetails.boards[origin]);
	} else {
		resetList('board', chooseOption);
		resetList('duration', chooseOption);
		refreshRooms();
	}
}
				
function updateBoards(boards) {
	if (boards.length > 1) {
		resetList('board', chooseOption);
	} else {
		resetList('board');
	}

	dwr.util.addOptions('board', boards, 'key', 'value');
	boardChanged();
}

function boardChanged() {
	var origin = dwr.util.getValue('origin');
	var board = dwr.util.getValue('board');
	if (board != -1) {
		updateDurations(departureDetails.durations[origin][board]);
	} else {
		resetList('duration', chooseOption);
		refreshRooms();
	}
}

function updateDurations(durations) {
	if (durations.length > 1) {
		resetList('duration', chooseOption);
		dwr.util.addOptions('duration', durations);
		if (chooseOption == null) {
			refreshRooms();
		}
	} else {
		resetList('duration');
		dwr.util.addOptions('duration', durations);
		refreshRooms();
	}
}

function numberOfAdultsChanged(select) {
	hide('detailsError');
	updateRoomAmountSelect();
	optimizeRooms();
}

function numberOfChildrenChanged(select) {
	var n = parseInt(select.options[select.selectedIndex].value);
	if (n == 0) {
		hide('childTable');
	} else {
		show('childTable');
	}

	// template row is +1
	n += 1;
	var tbody = document.getElementById('childBody');
	var rows = tbody.getElementsByTagName('tr');
	var i;

	// remove extra rows, if any
	for (i = rows.length - 1; i >= n; i--) {
		tbody.removeChild(rows[i]);
	}
	
	// add new rows, if needed
	var templateRow = document.getElementById('childTemplate');
	for (i = rows.length; i < n; i++) {
		var rowIndex = i - 1;
		var newRow = templateRow.cloneNode(true);
		newRow.setAttribute('id', 'child' + rowIndex);
		
		var regexp = /#/g;
		var input = newRow.getElementsByTagName('input')[0];
		input.id = input.id.replace(regexp, rowIndex);
		input.name = input.name.replace(regexp, rowIndex);
		input.onkeypress = dateMask;
		
		var span = newRow.getElementsByTagName('span')[0];
		span.id = span.id.replace(regexp, rowIndex);
		dwr.util.setValue(span, rowIndex + 1);
		
		var selects = newRow.getElementsByTagName('select');
		for (var j = 0; j < selects.length; j++) {
			var select = selects[j];
			select.id = select.id.replace(regexp, rowIndex);
			select.name = select.name.replace(regexp, rowIndex);
		}
		
		tbody.appendChild(newRow);
		newRow.style.display = '';
	}

	hide('detailsError');
	updateRoomAmountSelect();
	optimizeRooms();
}

function childYearChanged(select) {
	childMonthChanged(select);
}

function childMonthChanged(select) {
	var index = select.id.substr(-1, 1);
	setDayOptions('childYear' + index, 'childMonth' + index, 'childDay' + index);
	
	childDayChanged(select);
}

function childDayChanged(select) {
	var index = select.id.substring(select.id.length - 1);
	
	var year = dwr.util.getValue('childYear' + index);
	var month = dwr.util.getValue('childMonth' + index);
	var day = dwr.util.getValue('childDay' + index);
	
	var date = year + '.' + (month >= 10 ? month : '0' + month) + '.' + (day >= 10 ? day : '0' + day);
	dwr.util.setValue('childDateOfBirth' + index, date);

	optimizeRooms();
}

var wasFormValid = false;
function toggleControls() {
	var isFormValid = validateForm('dateofbirth');

	if (isFormValid == wasFormValid) return;
	wasFormValid = isFormValid;
	
	if (isFormValid) {
		dwr.util.setValue('progressMsg', progressAccomodation);
		optimizeRooms();
	} else {
		dwr.util.setValue('progressMsg', progressBirthdate);
		hide('insurance');
		disableNextButtons();
	}
}

function enableNextButtons() {
	if (dwr.util.byId('top-next-button') != null) {
		dwr.util.byId('top-next-button').className = '';
	}
	dwr.util.byId('bottom-next-button').className = '';
	enable('top-next-button', 'bottom-next-button');
}

function disableNextButtons() {
	if (dwr.util.byId('top-next-button') != null) {
		dwr.util.byId('top-next-button').className = 'disabled';
	}
	dwr.util.byId('bottom-next-button').className = 'disabled';
	disable('top-next-button', 'bottom-next-button');
}

function getBirthdates() {
	var nc = dwr.util.getValue('numChildren');
	var birthdates = new Array();
	for (i = 0; i < nc; i++) {
		birthdates[i] = dwr.util.getValue('childDateOfBirth' + i);
	}
	
	return birthdates;
}

var roomsToBook = new Object();
var peopleInRooms = 0;
var savedRooms;

function showPassengers() {
	var n = parseInt(dwr.util.getValue('numAdults')) + parseInt(dwr.util.getValue('numChildren'));
	dwr.util.setValue('roomPassengers', n);
	dwr.util.setValue('roomPassengersLeft', n - peopleInRooms);
	show('roomPassengersDiv');
}

function updateRooms(option) {
	roomsToBook[option.id] = option.value;
	optimizeRooms();
}

var autoOptimize = false;
var savedAutoOptimize;

function showRoomSelectionDialog() {
	savedAutoOptimize = autoOptimize;
	autoOptimize = false;
	roomDetails = null;
	
	// deep copy roomsToBook to savedRooms
	savedRooms = new Object();
	jQuery.extend(savedRooms, roomsToBook);
	
	peopleInRooms = 0;
	
	// set the selected room amounts to zero
	for (var i in roomsToBook) {
		roomsToBook[i] = 0;
	}
	
	// selectElements[0] is the template row, start from index 1
	var roomSelectionTable = dwr.util.byId('roomSelectionTable');
	var selectElements = roomSelectionTable.getElementsByTagName('select');
	for (var i = 1; i < selectElements.length; i++) {
		dwr.util.setValue(selectElements[i], '0');
	}	
	showPassengers();
	
	jQuery("#szallas_dialog-confirm").dialog({
		resizable: false,
		width:750,
		modal: true,
		buttons: {
			'Kiválasztás': manualRoomSelectionOk,
			'Vissza': manualRoomSelectionCancel
		}
	});
}

function manualRoomSelectionOk() {
	var result = new Object();
	result.rooms = roomDetails;
	result.amounts = new Object();
	result.totalPrice = 0;
	result.totalAmount = 0;
	
	for (var i = 0; i < roomDetails.length; i++) {
		var room = roomDetails[i];
		if (result.amounts[room.key]) {
			result.amounts[room.key]++;
		} else {
			result.amounts[room.key] = 1;
		}
		
		for (var j = 0; j < room.occupation.length; j++) {
			result.totalAmount++;
			result.totalPrice += room.occupation[j].price;
		}
	}
	
	autoOptimize = savedAutoOptimize;
	displaySelectedRooms(result);
	jQuery('#bestSelectedLabel').slideUp('slow');
	show('backToBestButton');

	jQuery(this).dialog('close');
}

function manualRoomSelectionCancel() {
	roomsToBook = savedRooms;
	
	// the user might have tried rooms and changed the selected rooms in the session
	// reset the original state by calling optimizeRooms()
	optimizeRooms();
	autoOptimize = savedAutoOptimize;
	
	jQuery(this).dialog('close');
}

function optimizeRooms() {
	jQuery('#content-wrapper').css('cursor','wait');
	if ((autoOptimize && validateForm('dateofbirth'))
			|| validateForm('room', 'dateofbirth')) {
		disable('startDate', 'origin', 'board', 'duration', 'numAdults', 'numChildren',
				'selectedInsurance', 'insurance-stx');
		var startDate = dwr.util.getValue('startDate');
		var nAdults = dwr.util.getValue('numAdults');
		var nChildren = dwr.util.getValue('numChildren');
		var birthdates = getBirthdates();
		
		if (autoOptimize) {
			AjaxSearchUtil.autoOptimizeRooms(startDate, nAdults, nChildren, birthdates,
					displayAutoOptimizationResult);
		} else {
			AjaxSearchUtil.optimizeRooms(nAdults, nChildren, birthdates, roomsToBook,
					displayOptimizationResult);
		}
	} else {
		showPassengers();
		dwr.util.setValue('progressMsg', progressAccomodation);
		hide('insurance', 'roomError');
		unhighlightRoom();
		disableNextButtons();
	}
	jQuery('#content-wrapper').css('cursor','default');
}

function displayAutoOptimizationResult(result) {
	if (result.rooms.length == 0) {
		hide('bestRoomsTable', 'bestRoomsTotal');
		show('bestRoomsError');
		enable('startDate', 'origin', 'board', 'duration', 'numAdults', 'numChildren');
		jQuery('#bestSelectedLabel').hide();
		jQuery('.details-ok').hide();
		jQuery('.details-error').show();
	} else {
		displaySelectedRooms(result);
		show('bestRoomsTable', 'bestRoomsTotal');
		hide('bestRoomsError', 'backToBestButton');
		jQuery('#bestSelectedLabel').slideDown('slow');
		jQuery('.details-ok').show();
		jQuery('.details-error').hide();
		updateInsuranceCategories();
		refreshDiscounts();
	}
}

function displaySelectedRooms(result) {
	// set the selected room amounts to zero
	for (var i in roomsToBook) {
		roomsToBook[i] = 0;
	}

	// remove all rows except for the header and the template 
	dwr.util.removeAllRows('bestRoomsTable', { filter:function(tr) {
		return (tr.id != 'bestRoomTemplate');
	}});
	
	for (var i = 0; i < result.rooms.length; i++) {
		var id = String(i);
		var clone = dwr.util.cloneNode('bestRoomTemplate', { idSuffix:id });
		clone.style.display = '';

		var room = result.rooms[i];
		dwr.util.setValue('bestDescription' + id, room.description);
		dwr.util.setValue('bestType' + id, room.roomType, { escapeHtml:false });
		dwr.util.setValue('bestAccessories' + id, room.accessories);
		dwr.util.setValue('bestBeds' + id, room.normalBeds);
		dwr.util.setValue('bestExtraBeds' + id, room.extraBeds);
		dwr.util.setValue('bestMaxAge' + id, room.extraBedMaxAge);
		
		for (var j = 0; j < room.occupation.length; j++) {
			var oid = id + '_' + j;
			clone = dwr.util.cloneNode('bestOccupationTemplate' + id, { idSuffix: '_' + j });
			clone.style.display = '';
			
			var occupation = result.rooms[i].occupation[j];
			dwr.util.setValue('bestPassenger' + oid, occupation.passenger);
			dwr.util.setValue('bestPrice' + oid, occupation.price);
			/*dwr.util.byId('bestPrice-div').style.color = 'black';*/
			if (occupation.originalPrice > occupation.price) {
				show('bestOriginalPrice-div' + oid);
				dwr.util.setValue('bestOriginalPrice' + oid,occupation.originalPrice);
				dwr.util.byId('bestPrice-div' + oid).style.color = 'red';
			}
		}
		
		roomsToBook[room.key] = result.amounts[room.key];
	}
	
	dwr.util.setValue('bestTotalPrice', result.totalPrice);
	dwr.util.setValue('bestTotalAmount', result.totalAmount);
	
	peopleInRooms = parseInt(
			dwr.util.getValue('numAdults')) + parseInt(dwr.util.getValue('numChildren'));

	enable('startDate', 'origin', 'board', 'duration', 'numAdults', 'numChildren',
			'selectedInsurance', 'insurance-stx');
}

var roomDetails = null;
function displayOptimizationResult(result) {
	var n = parseInt(dwr.util.getValue('numAdults')) + parseInt(dwr.util.getValue('numChildren'));
	peopleInRooms = n - result.peopleLeft;
	
	if (result.peopleLeft == 0) {
		hide('roomPassengersDiv');
	} else {
		showPassengers();
	}
	
	if (result.status == 'OK') {
		roomDetails = result.roomDetails;
		hide('roomError');
		unhighlightRoom();
		dwr.util.setValue('progressMsg', progressInsurance);
		jQuery("#insurance").show();
		updateInsuranceCategories();
		refreshDiscounts();
	} else {
		dwr.util.setValue('progressMsg', progressAccomodation);
		hide('insurance', 'roomError');
		unhighlightRoom();
		disableNextButtons();
		
		if (result.status != 'DONT_FIT') {
			dwr.util.setValue('roomErrorMsg', result.message, { escapeHtml:false });
			if (result.cause != null) {
				dwr.util.setValue('roomErrorCause', result.cause, { escapeHtml:false });
				show('roomErrorCause');
			} else {
				hide('roomErrorCause');
			}
			show('roomError');
			highlightRoom(result.roomKey);
		}
	}
	
	enable('startDate', 'origin', 'board', 'duration', 'numAdults', 'numChildren',
			'selectedInsurance', 'insurance-stx');
}

var highlightedRoom = null;;
function highlightRoom(key) {
	//key = key.replace(' ', '\u00A0');	// &nbsp;
	
	var i = 0;
	var span;
	while ((span = dwr.util.byId('roomType' + i++)) != null) {
		var x = span.firstChild.nodeValue;
		if (span.firstChild.nodeValue == key) {
			break;
		}
	}
	
	highlightedRoom = dwr.util.byId('roomTemplateRow' + (i - 1));
	highlightedRoom.className = 'highlight';
}

function unhighlightRoom() {
	if (highlightedRoom != null) {
		highlightedRoom.className = '';
	}
}

function resetRooms() {
	// set the selected room amounts to zero
	for (var i in roomsToBook) {
		roomsToBook[i] = 0;
	}

	hide('roomSelectionBox', 'roomError', 'insurance');

	// remove all rows except for the header and the template 
	dwr.util.removeAllRows('roomSelectionTable', { filter:function(tr) {
		return (tr.id != 'roomHeader' && tr.id != 'roomTemplateRow');
	}});
}

/**
 * Downloads and displays the list of available rooms, if all the necessary input is filled. 
 */
function refreshRooms() {
	setDefaultInsurance();
	// set the number of passengers on the form
	var n = parseInt(dwr.util.getValue('numAdults')) + parseInt(dwr.util.getValue('numChildren'));
	dwr.util.setValue('roomPassengers', n);
	
	// remove rows added in a previous call
	resetRooms();
	
	// one or more input is missing: display the info box and return
	var origin = dwr.util.getValue('origin');
	var board = dwr.util.getValue('board');
	var duration = dwr.util.getValue('duration');
	if (origin == -1 || board == -1 || duration == -1) {
		dwr.util.setValue('progressMsg', progressTravelData);
		hide('insurance');
		return;
	}

	// create the rows
	disable('startDate', 'origin', 'board', 'duration');
	
	var language = dwr.util.getValue('language');
	var externalId = dwr.util.getValue('externalId');
	var startDate = dwr.util.getValue('startDate');
	AjaxSearchUtil.getRoomDetails(
			language, externalId, startDate, origin, board, duration, displayRooms);
	
	// display the rooms
	toggleControls();
	show('roomSelectionBox');
}

function displayRooms(rooms) {
	var numAdults = parseFloat(dwr.util.getValue('numAdults'));
	var numChildren = parseFloat(dwr.util.getValue('numChildren'));
	
	if (rooms[0].objectOrPerson == 'O') {
		show('apartmanInfo');
	}
	show('roomSelectionTable');
	for (var i = 0; i < rooms.length; i++) {
		var id = String(i);
		var clone = dwr.util.cloneNode('roomTemplateRow', { idSuffix:id });
		clone.style.display = '';

		dwr.util.setValue('roomDescription' + id, rooms[i].description);
		dwr.util.setValue('roomType' + id, rooms[i].roomType, { escapeHtml:false });
		dwr.util.setValue('roomAccessories' + id, rooms[i].accessories);
		dwr.util.setValue('normalBeds' + id, rooms[i].normalBeds);
		dwr.util.setValue('extraBeds' + id, rooms[i].extraBeds);
		dwr.util.setValue('extraBedMaxAge' + id, rooms[i].extraBedMaxAge);
		
		var convertedPrice = rooms[i].convertedPrice;
		if (convertedPrice == 0) {
			dwr.util.setValue('rPrice' + id, rooms[i].price);
			show('room-one-currency' + id);
		} else {
			dwr.util.setValue('rFirstPrice' + id, rooms[i].price);
			dwr.util.setValue('rSecondPrice' + id, convertedPrice);
			show('room-two-currencies' + id);
		}
		
		var originalPrice = rooms[i].originalPrice;
		if (originalPrice != null && originalPrice > rooms[i].price) {
			dwr.util.setValue('rPriceOld' + id, originalPrice);
			show('room-one-currency-old' + id);
		}
		
		if (rooms[i].state == 'OK') {
			var tr = dwr.util.byId('roomToBook' + id);
			var select = tr.getElementsByTagName('select')[0];
			select.id = rooms[i].key;
			addOptions(numAdults, numChildren, rooms[i].normalBeds, select);
		} else if (rooms[i].state == 'FL' || rooms[i].state == 'MT') {
			// flight and maintenance
			dwr.util.setValue('roomToBook' + id, '&ndash;', { escapeHtml:false });
		} else {
			dwr.util.setValue('roomToBook' + id, rooms[i].stateString);
		}
	}
	
	// do not show '*' for full-price catalogs (e.g. flight tickets)
	if (rooms[0]) {
		dwr.util.setValue('roomPriceStar', rooms[0].fullPrice ? '' : '*');
	}

	// display 'flight booked out' message
	if (rooms[0] && (rooms[0].state == 'FL' || rooms[0].state == 'MT')) {
		dwr.util.setValue('roomErrorMsg', rooms[0].stateString, { escapeHtml:false });
		show('roomError', 'roomErrorMsg');
		hide('roomErrorCause');
		document.getElementById('roomSelectionBox').style.height = '100%';
	}
	
	optimizeRooms();
	enable('startDate', 'origin', 'board', 'duration');
}

function refreshDiscounts() {
	AjaxSearchUtil.getDiscounts(displayDiscounts);
}

function displayDiscounts(discounts) {
	// remove all rows except for the template
	dwr.util.removeAllRows('discountBody', { filter: function(tr) {
		return (tr.id != 'discountTemplate');
	}});
	
	var discountBox = dwr.util.byId('szallas-foglalas-kedvezmeny');
	if (discountBox) {
		if (discounts.length == 0) {
			discountBox.style.display = 'none';
		} else {
			discountBox.style.display = '';
		}
		
		for (var i = 0; i < discounts.length; i++) {
			var id = String(i);
			var clone = dwr.util.cloneNode('discountTemplate', { idSuffix:id });
			clone.style.display = '';
			
			dwr.util.setValue('key' + id, discounts[i].key);
			dwr.util.setValue('value' + id, discounts[i].value);
		}
	}
}

function updateRoomAmountSelect() {
	var numAdults = parseFloat(dwr.util.getValue('numAdults'));
	var numChildren = parseFloat(dwr.util.getValue('numChildren'));

	var id = 0;
	var tr = dwr.util.byId('roomToBook' + id);
	while (tr != null) {
		var select = tr.getElementsByTagName('select')[0];
		var normalBeds = dwr.util.byId('normalBeds' + id);
		addOptions(numAdults, numChildren, normalBeds.firstChild.nodeValue, select);
		id++;
		tr = dwr.util.byId('roomToBook' + id);
	}
	
}

function addOptions(numAdults, numChildren, normalBeds, select) {
	var oldValue = resetList(select.id);
	
	// add 'max' number of options to select the amount of rooms
	var beds = parseFloat(normalBeds.substring(0, normalBeds.indexOf(' ')));
	var max = Math.ceil((numAdults + numChildren) / beds);
	if (max < 1) max = 1;
	for (var j = 0; j <= max; j++) {
		var o = new Option(j, j);
		select.options[j] = o;
	}
	
	dwr.util.setValue(select.id, oldValue);
}

var nInsurance = 0;
var extraClicked = false;
function updateInsurance(extra) {
	if (!validateForm()) return;

	nInsurance = document.getElementById('insurance-table-body').getElementsByTagName('tr').length;
	extraClicked = extra;
	disable('startDate', 'origin', 'board', 'duration', 'numAdults', 'numChildren',
			'selectedInsurance', 'insurance-stx');
	disableNextButtons();

	var selectedInsurance = dwr.util.getValue('selectedInsurance');
	
	// clears the extra insurance checkboxes if the main insurance is changing
	var selectedExtra = '';
	if (extraClicked) {
		var extraTable = dwr.util.byId('insurance-extra-table-body');
		var list = extraTable.getElementsByTagName('input');
		for (var i = 0; i < list.length; i++) {
			var checkbox = list.item(i);
			if (checkbox.checked) {
				selectedExtra += checkbox.value + ',';
			}
		}
		
		if (selectedExtra.length > 0) {
			selectedExtra = selectedExtra.substr(0, selectedExtra.length - 1);
		}
	}

	AjaxSearchUtil.getInsurances(selectedInsurance, selectedExtra, displayInsuranceDetails);
}

function setInsuranceStatus(flag) {
	if (flag) {
		jQuery('#insurance-details-ok').show();
		jQuery('#insurance-details-error').hide();
		enableNextButtons();
	} else {
		disableNextButtons();
		jQuery('#insurance-details-ok').hide();
		jQuery('#insurance-details-error').show();
	}
}

function acceptNoInsurance() {
	setInsuranceStatus(document.getElementById('insurance-no-accepted').checked);
}

function displayInsuranceDetails(insurances) {
	if (! extraClicked) {
		displayExtraCategories(insurances);
	}
	extraClicked = false;
	
	var insuranceDetails = insurances.details;
	if (insuranceDetails.length == 0) {
		hide('priceTable');
		var noInsuranceAcceptBox = document.getElementById('insurance-no-accepted');
		noInsuranceAcceptBox.checked = false;
		
		if (nInsurance > 2) {
			show('noInsuranceAlert');
		} else {
			// hide warning if this is the only one option
			hide('noInsuranceAlert');
			noInsuranceAcceptBox.checked = true;
		}
		
		setInsuranceStatus(noInsuranceAcceptBox.checked);
		enable('startDate', 'origin', 'board', 'duration', 'numAdults', 'numChildren',
				'selectedInsurance', 'insurance-stx');
		return;
	} else {
		setInsuranceStatus(true);
	}
		
	dwr.util.removeAllRows('priceBody', { filter:function(tr) {
		return tr.id != 'insuranceHeader' && tr.id != 'insuranceItem' && tr.id != 'insuranceTotal';
	}});

	var sum = 0, sum2 = 0;
	for (var i = 0; i < insuranceDetails.length; i++) {
		var insurance = insuranceDetails[i];
		sum += insurance.price;
		if (insurance.convertedPrice != null) {
			sum2 += insurance.convertedPrice;
		}
		
		var item = dwr.util.cloneNode('insuranceItem', { idSuffix: String(i) });
		dwr.util.setValue('priceLabel' + i, insurance.description);
		
		if (insurance.convertedPrice == null) {
			dwr.util.setValue('iPrice' + i, insurance.price + ' ' + currency);
		} else {
			dwr.util.setValue('iPrice' + i, insurance.convertedPrice + ' ' + secondCurrency);
			dwr.util.setValue('iSecondPrice' + i, insurance.price + ' ' + currency);
			show('iSecondPriceTd' + i);
		}
		item.style.display = '';
	}

	if (sum2 == 0) {
		dwr.util.setValue('iPriceTotal', sum + ' ' + currency);
	} else {
		dwr.util.setValue('iPriceTotal', sum2 + ' ' + secondCurrency);
		dwr.util.setValue('iSecondPriceTotal', sum + ' ' + currency);
		show('iSecondPriceTotalTd');
	}
	
	dwr.util.setValue('progressMsg', '');
	show('priceTable');
	hide('noInsuranceAlert');
	enableNextButtons();
	enable('startDate', 'origin', 'board', 'duration', 'numAdults', 'numChildren',
			'selectedInsurance', 'insurance-stx');
}

function validateForm() {
	var options = parseOptions(arguments);
	var i;

	// validate children date of birth
	if (options.dateofbirth) {
		var nc = dwr.util.getValue('numChildren');
		for (i = 0; i < nc; i++) {
			var dateOfBirth = dwr.util.getValue('childDateOfBirth' + i);
			if (dateOfBirth.length < 10) return false;
		}
	}
	
	// validate names
	if (options.name) {
		var firstName;
		var lastName;
		var nc = dwr.util.getValue('numChildren');
		for (i = 0; i < nc; i++) {
			firstName = dwr.util.getValue('childFirstName' + i);
			lastName = dwr.util.getValue('childLastName' + i);
			if (firstName == '' || lastName == '') return false;
		}
		
		var na = dwr.util.getValue('numAdults');
		for (i = 0; i < na; i++) {
			firstName = dwr.util.getValue('adultFirstName' + i);
			lastName = dwr.util.getValue('adultLastName' + i);
			if (firstName == '' || lastName == '') return false;
		}
	}

	// validate rooms
	if (options.room) {
		var hasRoom = false;
		for (i in roomsToBook) {
			if (roomsToBook[i] > 0) {
				hasRoom = true;
				break;
			}
		}
		if (!hasRoom) {
			peopleInRooms = 0;
			return false;
		}
	}
	
	// insurance
	if (options.insurance) {
		var selectedInsurance = dwr.util.getValue('selectedInsurance');
		if (selectedInsurance == null || selectedInsurance == false) {
			return false;
		}
	}

	return true;
}

function parseOptions() {
	var opts = arguments[0];
	// no options: validate all
	if (opts.length == 0) {
		return { dateofbirth: true, room: true, insurance: true };
	}
	
	var i;
	var options;
	if (/^no-/.test(opts[0])) {
		// first arg starts with 'no-', change to exclude mode
		options = { dateofbirth: true, room: true, insurance: true };
		for (i = 0; i < opts.length; i++) {
			var o = opts[i].substr(3);
			options[o] = false;
		}
	} else {
		// include mode
		options = { dateofbirth: false, room: false, insurance: false };
		for (i = 0; i < opts.length; i++) {
			options[opts[i]] = true;
		}
	}
	
	return options;
}

var ratingTooltipId = '';
function showSubRating(e) {
	var sourceDiv = e.target || e.srcElement;

	if (sourceDiv.id.indexOf('rating-container-') == 0) {
		ratingTooltipId = '#' + sourceDiv.id.replace(/rating-container-/, 'rating-tooltip-');
	}
	jQuery(ratingTooltipId).show();
	
	moveSubRating(e);
}

function moveSubRating(e) {
	jQuery(ratingTooltipId).css({
		top: (e.pageY - 300) + "px",
		left: (e.pageX - 100) + "px"
	});
}

function hideSubRating() {
	jQuery(ratingTooltipId).hide();
}

function setDefaultInsurance() {
	nInsurance = document.getElementById('insurance-table-body').getElementsByTagName('tr').length;
	if(nInsurance > 2){
		document.getElementById("default_radio_button").checked = true;
		document.getElementById("insurance-no-accepted").checked = false;
		setInsuranceStatus(false);
	}
}

