/***************************\
*							*
*		BookForm			*
*							*
\***************************/

var bookAccordion;
var bookSteps = new Array();
var bookHistory = true;

/**
 * replacement of loadBookFrame function
 */
function gotoBookPage(divId, buttonId) {
	document.body.scrollTop = 0;
	if ($(buttonId))
		$(buttonId).style.display = 'none';
	ytw_call('modSearch', 'load_bookframe', [ divId ], bookHistory);
}
/*
 * Loads/initializes the Accordion(s)
 * Constructed this way for hooks
 */
function loadAccordions() {
	bookAccordion = new accordion('bookform');
	bookAccordion.bookHistory = bookHistory;
}

/*
 * Performs a call to have the first bookstep loaded
 */
function loadFirstBookStep() {
	// Load the content, have the first bookstep open
	ytw_call('modSearch', 'activate_book_step', ['firstload', 'trip', null], bookHistory);
}

// This function loads the target_bookstep
function submitBookStep(target_bookstep) {
	if (target_bookstep==bookSteps['payment']-1) {
		showBookingLoader();
		current_bookstep = bookAccordion.showAccordion.previous(0).id;
		form_name = current_bookstep+'ContentForm';
		jQuery('#bookButton').removeAttr('href');
		ytw_call('modSearch', 'activate_book_step', [current_bookstep, 'payment', xajax.getFormValues(form_name, true), 'bookform'], bookHistory);
	} else {
		showBookingLoader(target_bookstep);
		bookAccordion.request($$('#bookform .accordion_toggle')[target_bookstep]);
	}
}

// Allows or disables skipping to the given bookstep in the gui
function enableBookStep(index, value) {
  if (value) {
    $$('#bookform .accordion_toggle')[index - 1].removeClassName("accordion_toggle_disabled");
  } else {
    $$('#bookform .accordion_toggle')[index - 1].addClassName("accordion_toggle_disabled");
  }
}

// callback function called by server
function activateBookStep(index) {
	
	hideBookingLoader();
	
	showBookStep(index);

	
	
	// Only steps before the current one are clickable, later ones must be reached
	// using the "next step" buttons. This is to make sure all validation steps are done.
	for (var stepName in bookSteps) {
		var i = parseInt(bookSteps[stepName]);
		enableBookStep(i, i < index)
		
	}
	
}

// Called by activateBookStep. This function is overridden in bookform_no_accordion.js
function showBookStep(index) {
  bookAccordion.activate($$('#bookform .accordion_toggle')[index-1]);
}

/*
 * This function is called when the bookForm is loaded (ajaxed in)
 */
function bookForm_init() {
	bookForm_init_standard();
	loadAccordions();
	loadFirstBookStep();
}

/*
 * This function is called when a new bookpage is loaded (ajaxed in)
 * This tries to initialize everything so we don't have to bother to call the right
 * init function for every step (since some steps are merged in certain sites,
 * but not always).
 */
function bookPage_init() {
	bookForm_init_standard();
}

/*
 * This function is called by bookForm_init() and contains the standard tasks. Used so bookForm_init can be overwritten without havving multiple files to edit
 *
 */
function bookForm_init_standard() {
    //initializes trip
	trip_init();
	travelers_init();
	mainbooker_init();

	trip_load_validation();
	transport_load_validation();
	travelers_load_validation();
	transport_init();
	extras_init();
	extras_load_validation();

	mainbooker_load_validation();
}

// callback function called by server when form was invalid
function validate_form(formid) {
	if (formid == "trip") {
		trip_form_validation.validate();
	} else if (formid == "transport") {
		transport_form_validation.reset();
		transport_form_validation.validate();
	} else if (formid == "travelers") {
		travelers_form_validation.reset();
		travelers_form_validation.validate();
	} else if (formid == "mainbooker") {
		mainbooker_transport_validation.validate();
	}
}

/*
 * Set by the php. Only used when the bookform doesn't use an Accordion.
 */
function setBookSteps(booksteps) {
	try {
		bookSteps = booksteps.evalJSON(true); // true set for validation against cross site scripting!
	} catch(se) {
		console.info("Error occured while parsing imported JSON");
	}
}

/**
 * Enables book history
 */
function enableBookHistory(){
	bookHistory = true;
}

/**
 * Disable book history
 */
function disableBookHistory(){
	bookHistory = false;
}

/***************************\
*							*
*		Trip				*
*							*
\***************************/

///////////////////// 			Init		/////////////////////
/*
 * This function is called when the trip bookstep is loaded
 */
function trip_init() {
	if ($('tripContentForm')) {
		trip_form_validation = new Validation('tripContentForm', {immediate : true});
	}
}

///////////////////// 		Variables		/////////////////////
var book_trip_housing_options, book_trip_housing_choices; // Global variables used by various functions

///////////////////// Submit and  	/////////////////////
function trip_submit(nextbookstep) {
	// If the form validated and the result is succes, we proceed to the next bookstep
	trip_form_validation = new Validation('tripContentForm', {immediate : true});
	//trip_load_validation();
	if (trip_form_validation.validate()) {
		submitBookStep(nextbookstep);
		try {
			pageName = "bookform/" + nextStepName;
			piwikTracker.setDocumentTitle(pageName);
			piwikTracker.trackPageView();
		} catch( err ) {}
	}
}

// Validate if there are enough rooms selected
function trip_load_validation() {
	Validation.addAllThese([
		['validate-too-many-rooms','', function (value, element) {
			var people = parseInt($('adults').value);
			people += parseInt($('children').value);

			var minOccupation = 0;

			$$('#room-options .room-option').each(function(elem) {
				var room_type = elem.down('.room-type').value;
				var min = book_trip_housing_options[room_type]["minOccupation"];
				var number = elem.down('.room-number').value;

				minOccupation += number*min;
			});

			return (people >= minOccupation);
		}],
		['validate-too-little-rooms','', function (value, element) {
			var people = parseInt($('adults').value);
			people += parseInt($('children').value);

			var maxOccupation = 0;

			$$('#room-options .room-option').each(function(elem) {
				var room_type = elem.down('.room-type').value;
				var max = book_trip_housing_options[room_type]["maxOccupation"];
				var number = elem.down('.room-number').value;
				maxOccupation += number*max;
			});

			return (people <= maxOccupation);
		}],
		// Validate if there are enough of the selected rooms available
		// (NOTE: this is only required because the user could add a room of the same type and set the preferred number at the max,
		// if the number of available rooms of a certain type would be updated when the same type of room is selected, this validation
		// would no longer be required (client-side))
		['validate-rooms-available','', function (value, element) {
			var selected_rooms = new Array();

			($$('#room-options .room-option')).each(function(elem) {
				var room_type = elem.down('.room-type').value;
				var number = elem.down('.room-number').value;
				if (selected_rooms[room_type] == null) {
					selected_rooms[room_type] = parseInt(number);
				} else {
					selected_rooms[room_type] += parseInt(number);
				}
			});

			for (i=0; i<selected_rooms.size(); i++) {
				if (selected_rooms[i] > book_trip_housing_options[i]["available"]) return false;
			}

			return true;
		}]
	]);
}

///////////////////// 		GUI Support		/////////////////////

// This function does an ajax call wich will return a new list with the available room options, taken into account the new choice.
// The name of the form should be supplied, to make things easier to adjust in the template. When add == true, one room will be added.
function trip_update_rooms(form_name, target_css_id, add) {
	trip_form = xajax.getFormValues(form_name)
	ytw_call('modSearch', 'trip_update_rooms', [trip_form, target_css_id, (add ? 1 : 0)]);

	showBookingLoader();
}

// This function is called by modSearch as a callback from the trip_update_rooms function.
function trip_update_rooms_callback() {
	hideBookingLoader();

	// Run the validation check again, to see if there are enough rooms now.
	trip_form_validation = new Validation('tripContentForm', {immediate : true});
	trip_form_validation.validate()
}

// Removes a row to select a room type and board
// Further it will update the calc-table by doing an ajax call
// For the ajax call we need the form_name and the
function trip_remove_room_option(element, form_name, target_css_id) {
	$(element.parentNode).remove();

	// Also update the calc-table
	trip_form = xajax.getFormValues(form_name);
	showBookingLoader();
	ytw_call('modSearch', 'trip_update_rooms', [trip_form, target_css_id, 0]);
}

function trip_update_travelers_selection(name, value) {
	showBookingLoader();

	params = new Array();
	params[name] = value;
	ytw_call('modSearch', 'trip_update_travelers_selection', [ params ]);
}

/*
 * This function is always called by modSearch after the trip_update_travelers_selection ajax call.
 * When revert == true, old_values should be restored in the travelers selection
 */
function trip_update_travelers_selection_callback() {
	hideBookingLoader();

	if (revert) {
		$$('#adults option').each(function(elem) {
			if (elem.value == adults) {	elem.selected = true; }
		});
		$$('#children option').each(function(elem) {
			if (elem.value == children) { elem.selected = true; }
		});
		$$('#babies option').each(function(elem) {
			if (elem.value == babies) {	elem.selected = true; }
		});
	}
}

function showBookingLoader(divId) {
	// Show the bookingLoader
	if ($('bookingLoaderContainer')) {
		$('bookingLoaderContainer').style.display='block';
	}

	// Disable buttons in bookform
	$$("#bookform select").each(function(element) {
		element.disabled = true;
	});
	// Disable buttons to next bookstep
	$$("#bookform input").each(function(element) {
		element.disabled = true;
	});
}

function hideBookingLoader() {
	// In case the resultsloader is showing when we came from the detailpage..:
	if(typeof hideResultLoader == 'function') {
		hideResultLoader(); // See if it exists even.. because on some occasions it doesn't and this crashes..
	}
	// Hide the bookingLoader
	if ($('bookingLoaderContainer')) {
		$('bookingLoaderContainer').style.display='none';
	}
	
	// Enable buttons in bookform
	$$("#bookform select").each(function(element) {
		element.disabled = false;
	});
	// Enable buttons to next bookstep
	$$("#bookform input").each(function(element) {
		element.disabled = false;
	});
}

function showErrorMsg(msg) {
	if(typeof hideResultLoader == 'function') {
		hideResultLoader(); // See if it exists even.. because on some occasions it doesn't and this crashes..
	}

	var el = $('errorMsg');
	if (el) {
		el.style.display = 'block';
	} else {
		alert(msg);
	}
}

///////////////////// Getters and Setters	/////////////////////

// Sets (after validation) the book_options to a JSON array string
function set_housing_options(json_housing_options) {
	// Fix some input..
	while (json_housing_options.indexOf("\n") != -1) {
		json_housing_options = json_housing_options.replace("\n", ""); // Remove newlines (No clue why they are in there)
	}

	while (json_housing_options.indexOf("&amp;") != -1) {
		json_housing_options = json_housing_options.replace("&amp;", "&"); // Remove ampersands
	}

	try {
		book_trip_housing_options = json_housing_options.evalJSON(true); // true set for validation!
	} catch(se) {
		console.info("Error occured while parsing imported JSON");
		return;
	}
}

// Sets (after validation) the book_choices to a JSON array string
function set_housing_choices(json_housing_choices) {
	book_trip_housing_choices = json_housing_choices.evalJSON(true); // true set for validation!
}

/***************************\
*							*
*		Transport			*
*							*
\***************************/

/*
 * This function is called when the transport bookstep is loaded
 */
function transport_init() {
	if ($('transportContentForm')) {
		transport_form_validation = new Validation('transportContentForm', {stopOnFirst:false, focusOnError : false});
	}
}

///////////////////// Submit and Validation	/////////////////////
function transport_submit(nextbookstep) {
	// Something changed, this will now have to be done here.
	transport_form_validation = new Validation('transportContentForm', {stopOnFirst:false, focusOnError : false});
	// If the form validated and the result is succes, we proceed to the next bookstep
	if (transport_form_validation.validate()) {
		submitBookStep(nextbookstep);
		try {
			pageName = "bookform/" + nextStepName;
			piwikTracker.setDocumentTitle(pageName);
			piwikTracker.trackPageView();
		} catch( err ) {}
	}
}

function transport_load_validation() {
	Validation.add('validate-one-required-enhanced','', function (value, element) {
		name = element.name;
		form_id = element.up('form').id;

		set = false;
		$$("#"+form_id+" input").each(function(input) {
			if (input.type == "radio" && input.name == name) {
				if (input.checked) {
					set = true;
				}
			}
		});

		return set;
	},{});
}

///////////////////// 		GUI Support		/////////////////////

// Hover/Select effects for the transport option buttons (because CSS :hover only works for the a-tag in IE..)
// Also used for setting the selected choice
function select_element(id) {
	element = $(id);
	element.checked = true;

	// Get the parent element that is the whole option (wich is the element's granddaddy)
	option = element.ancestors()[1];

	// Set the other options NOT selected
	option.siblings().each(function(elem) {
		if (elem.hasClassName("option-selected")) {
			elem.removeClassName("option-selected");
		}
	});

	option.addClassName("option-selected");
}

function hover_element(id) {
	element = $(id);
	// Get the parent element that is the whole option (wich is the element's granddaddy)
	option = element.ancestors()[1];
	option.addClassName("option-hover");
}

function leave_element(id) {
	element = $(id);
	// Get the parent element that is the whole option (wich is the element's granddaddy)
	option = element.ancestors()[1];
	option.removeClassName("option-hover");
}

// This function sets the given string as the innerHTML of the given targetCssId
function transport_set_data(data, targetCssId) {
	target_div = $(targetCssId);
	target_div.innerHTML = data;
}

/***************************\
*							*
*		Travelers			*
*							*
\***************************/

/*
 * This function is called when the travelers bookstep is loaded
 */
function travelers_init() {
	if ($('travelersContentForm')) {
		travelers_form_validation = new Validation('travelersContentForm', {stopOnFirst : true, focusOnError : false});
	}
}

///////////////////// 		Variables		/////////////////////
// The departure date in an array
var travelers_departure_date = new Array();

///////////////////// Submit and Validation	/////////////////////
function travelers_submit(nextbookstep) {
	// Something changed when xajax was updated. We now have to do this here.
	travelers_form_validation = new Validation('travelersContentForm', {stopOnFirst : true, focusOnError : false});
	// If the form validated and the result is succes, we proceed to the next bookstep
	if (travelers_form_validation.validate()) {
		submitBookStep(nextbookstep);
		try {
			pageName = "bookform/" + nextStepName;
			piwikTracker.setDocumentTitle(pageName);
			piwikTracker.trackPageView();
		} catch( err ) {}
	}
}

function travelers_load_validation() {
	Validation.addAllThese([
		['validate-required-checkbox','U moet akkoord gaan met de algemene voorwaarden', function(value, elem) {

			return elem.checked;
		}],
		['validate-required-all-first-names', 'Niet alle voornamen zijn ingevuld.', function(value, elem) {
			result = true;

			$$('.travelers-info .option .first-name').each(function(element) {
				if (!Validation.get('validate-required-name-dutch').test(element.value, element)) {
					result = false;
				}
			});

			return result;
		}],
		['validate-required-all-last-names', 'Niet alle achternamen zijn ingevuld.', function(value, elem) {
			result = true;

			$$('.travelers-info .option .last-name').each(function(element) {
				if (!Validation.get('validate-required-name-dutch').test(element.value, element)) {
					result = false;
				}
			});
			return result;
		}],
		['validate-required-name-dutch', 'Voer uw volledige naam in, zoals aangegeven in uw paspoort.', {
			minLength : 2,
			pattern : new RegExp("[AaoOuUiIeE]")
			// We used a pattern here, but we couln't match ealpa characters (ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ etc..)
			// for backwards-compatibility-reasons we left this function here.
			//minLength : 2,
			/*pattern : new RegExp("^[A-Za-z \-\'\.]+$")*/
		}],
		['validate-all-dates', 'Niet alle opgegeven data zijn geldig.', function(value, elem) {
			result = true;

			$$('.travelers-info .option .travelers-day-select').each(function(element) {
				if (!Validation.get('validate-date').test(element.value, element)) {
					result = false;
				}
			});

			return result;
		}],
		['validate-date', 'Een opgegeven datum is ongeldig.', function(value, elem) {
			// elem has to be an input field whose parent contain the day, month and year input fields
			element = Element.extend(elem);
			ancestors = element.ancestors();

			parentnode = ancestors[0];

			day = parseInt(parentnode.down('.travelers-day-select').value);
			month = parseInt(parentnode.down('.travelers-month-select').value);
			year = parseInt(parentnode.down('.travelers-year-select').value);

			switch (month) {
				case 1:	case 3:	case 5:
				case 7:	case 8:	case 10:
				case 12:
					valid_number_of_days = 31;
					break;
				case 4:	case 6:
				case 9:	case 11:
					valid_number_of_days = 30;
					break;
				case 2:
					valid_number_of_days = (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
					break;
			}

			if (day > valid_number_of_days) {
				return false;
			}

			return true;
		}],
		['validate-each-room-has-adult','', function (value, element) {
			var hasAdultInRoom = new Object();

			$$('.travelers-info .option').each(function(elem) {
				var traveler_type = elem.down('.traveler_type').value;
				if(traveler_type == 'adults') {
					var housing_unit_id = elem.down('.room-assignment').value;
					hasAdultInRoom[housing_unit_id] = true;
				}
			});

			var options = $$('.travelers-info .option')[0].down('.room-assignment');
			for(i=0;i<options.length;i++) {
				if(!hasAdultInRoom[options.item(i).value]) {
					return false;
				}
			}

			return true;
		}],
		['validate-each-room-min-occupation','', function (value, element) {
			//alert('validate-each-room-min-occupation A');
			var numberPeopleInRoom = new Object(); //excluding babies
			var housing_options = traveler_get_housing_options();
			//alert('validate-each-room-min-occupation B');
			$$('.travelers-info .option').each(function(elem) {
				var traveler_type = elem.down('.traveler_type').value;
				if(traveler_type == 'adults' || traveler_type == 'children') {
					var housing_code = elem.down('.room-assignment').value;
					//alert('code: '+housing_code);
					if(numberPeopleInRoom[housing_code] > 0) {
						numberPeopleInRoom[housing_code]++;
					} else {
						numberPeopleInRoom[housing_code] = 1;
					}
					//alert(numberPeopleInRoom[housing_code]);
				}
			});
			//alert('validate-each-room-min-occupation C');
			var options = $$('.travelers-info .option')[0].down('.room-assignment');
			for(i=0;i<options.length;i++) {
				var key = options.item(i).value;
				var room_type = key.substr(0,key.length-1);
				if(numberPeopleInRoom[key] < housing_options[room_type]["minOccupation"]) {
					//alert("npir: "+numberPeopleInRoom[key]+" < hortmo: "+housing_options[room_type]["minOccupation"]);
					return false;
				}
			}

			return true;
		}],
		['validate-each-room-max-occupation','', function (value, element) {
			//alert('validate-each-room-max-occupation A');
			var numberPeopleInRoom = new Object(); //excluding babies
			var housing_options = traveler_get_housing_options();
			//alert('validate-each-room-max-occupation B');
			$$('.travelers-info .option').each(function(elem) {
				var traveler_type = elem.down('.traveler_type').value;
				if(traveler_type == 'adults' || traveler_type == 'children') {
					var housing_code = elem.down('.room-assignment').value;
					if(numberPeopleInRoom[housing_code] > 0) {
						numberPeopleInRoom[housing_code]++;
					} else {
						numberPeopleInRoom[housing_code] = 1;
					}
				}
			});
			//alert('validate-each-room-max-occupation C');
			var options = $$('.travelers-info .option')[0].down('.room-assignment');
			for(i=0;i<options.length;i++) {
				var key = options.item(i).value;
				var room_type = key.substr(0,key.length-1);
				if(numberPeopleInRoom[key] > housing_options[room_type]["maxOccupation"]) {
					//alert("npir: "+numberPeopleInRoom[key]+" > hortmo: "+housing_options[room_type]["maxOccupation"]);
					return false;
				}
			}

			return true;
		}]
	]);
}

//reindex the book_trip_housing_options for traveler use
function traveler_get_housing_options() {
	var result = new Object();
	for(var i in book_trip_housing_options) {
		result[book_trip_housing_options[i]["unitId"]] = book_trip_housing_options[i];
	}
	return result;
}

// This function makes sure that only one mainbooker-checkbox is selected
function select_mainbooker(checkbox) {
	// Show or hide the possible mainbookers?
	if (checkbox.checked) {
		checkboxes = $$('.travelers_mainbooker_checkbox');

		// Uncheck all checkboxes:
		checkboxes.each(function(element) {
			element.checked = false;
		});
		// And re-check the original one
		checkbox.checked = true;
	}
}

// This function is called by modSearch to set the departure date. The departure date is required for the validation of the travelers birthdays
function travelers_set_departure_date(day, month, year) {
	travelers_departure_date['day'] = day;
	travelers_departure_date['month'] = month;
	travelers_departure_date['year'] = year;
}

function travelers_validate_supplied_date(e) {

}


/***************************\
*							*
*		Shops				*
*							*
\***************************/

function shop_submit(nextbookstep) {
	submitBookStep(nextbookstep);
}




/***************************\
*							*
*		Extras				*
*							*
\***************************/

/*
 * This function is called when the extras bookstep is loaded
 */
function extras_init() {
	if ($('extrasContentForm')) {
		extra_form_validation = new Validation('extrasContentForm', {stopOnFirst : false, focusOnError : false});
	}
}

///////////////////// 		Variables		/////////////////////


///////////////////// Submit and Validation	/////////////////////
function extras_submit(nextbookstep) {
	extra_form_validation = new Validation('extrasContentForm', {stopOnFirst : false, focusOnError : false});
	extra_form_validation.reset();
	// If the form validated and the result is succes, we proceed to the next bookstep
	if (extra_form_validation.validate()) {
		submitBookStep(nextbookstep);
		try {
			pageName = "bookform/" + nextStepName;
			piwikTracker.setDocumentTitle(pageName);
			piwikTracker.trackPageView();
		} catch( err ) {}
	}
}

function extras_get_rental_information(provider, transportRentalId, targetCssId) {
	ytw_call('modSearch', 'extras_get_rental_information', [provider, transportRentalId, targetCssId]);
}

/** This function opens or closes a panel
 * var id	is the id of the panel that must be switched (i.e. 'transportRentals')
 */
function extras_switch(id) {
	panel = $(id);

	if (panel.getStyle('display') != 'none') {
		panel.setStyle({'display' : 'none'});
	} else {
		panel.setStyle({'display' : 'block'});
	}
}

function checkExtraAssignment(elem) {
	if(elem.value == 0) {
		if(elem.checked == true) {
			var newElem = elem.up().next('label');
			while(newElem) {
				newElem.down().checked = true;
				newElem = newElem.next('label');
			}
		} else {
			var newElem = elem.up().next('label');
			while(newElem) {
				newElem.down().checked = false;
				newElem = newElem.next('label');
			}
		}
	} else {
		if(elem.checked == false) {
			var newElem = elem.up().previous('label', elem.value-1);
			newElem.down().checked = false;
		} else {
			var firstElem = elem.up().previous('label', elem.value-1);
			var all_selected = true;
			var newElem = firstElem.next('label');
			while(newElem) {
				all_selected = all_selected && newElem.down().checked;
				newElem = newElem.next('label');
			}
			if(all_selected) {
				firstElem.down().checked = true;
			}
		}
	}
}

function extras_load_validation() {
	Validation.addAllThese([
		['validate-extra-assignment','', function(value, elem) {
			if(elem.value != 0) {
				return true;
			}
			var result = elem.checked;
			var newElem = elem.up().next('label');
			while(newElem) {
				result = result || newElem.down().checked;
				newElem = newElem.next('label');
			}
			return result;
		}],
		['validate-extra-date', '', function(value, elem) {
			var startdate = elem.value;
			var parent = elem.up('.information-item');
			var enddate = parent.next('.information-item').down('select').value;

			//manipulate the dates so that Date can understand them
			startdate = startdate.split('T');
			startdate = startdate[0].replace('-', '/').replace('-', '/');
			startdate = Date.parse(startdate);
			enddate = enddate.split('T');
			enddate = enddate[0].replace('-', '/').replace('-', '/');
			enddate = Date.parse(enddate);

			var start = new Date();
			var end = new Date();
			start.setTime(startdate);
			end.setTime(enddate);

			return start <= end;
		}]
	]);
}

/***************************\
*							*
*		Overview			*
*							*
\***************************/

///////////////////// Submit and Validation	/////////////////////
function overview_submit(nextbookstep) {
	if (mainbooker_submit()) {
		submitBookStep(nextbookstep);
	}
}

/***************************\
*							*
*		Mainbooker			*
*							*
*	merged with Overview	*
*							*
\***************************/

/*
 * This function is called when the mainbooker bookstep is loaded
 */
function mainbooker_init() {
	if ($('mainbookerContentForm')) {
	    // Our validation object
		mainbooker_form_validation = new Validation('mainbookerContentForm', {immediate : true, onElementValidate : mainbooker_validation_callback });

		// Our list of example text for the input fields ([fieldname] => 'example')
		mainbooker_examples = new Array();

		// Get all elements that could contains example texts:
		$$('#mainbookerContentForm .has-example').each(function(element) {
			// Save the example
			mainbooker_examples[element.name] = $(element.id+"_example").value;

			// When the field is empty, set the example text:
			if (element.value == "") {
				mainbooker_field_raise_example(element, false);
	        }
		});
	}
}

///////////////////// Submit and Validation	/////////////////////
// Submits the form when valid
function mainbooker_submit() {
	// First, clear all fields that only contain example values
	$$('#mainbookerContentForm .example').each(function(elem) {
		mainbooker_field_drop_example(elem);
	});

	// Something changed when xajax was updated. We now have to do this here.
	mainbooker_form_validation = new Validation('mainbookerContentForm', {immediate : true});

	//mainbooker_form_validation.reset();
	return mainbooker_form_validation.validate();
}

function mainbooker_load_validation() {
	Validation.addAllThese([
		['validate-required-dutch', 'Dit veld is vereist.', { minLength : 1 }],
		['validate-zipcode-dutch', '', {
			minLength : 1,
			maxLength : 7,
			pattern : new RegExp("^[0-9]{4} ?[A-Za-z]{2}$")
		}],
		['validate-telephonenumber-dutch', '', {
			minLength : 1,
			pattern : new RegExp("^\\+?([0-9]{2,3}( *|-)){0,2}[0-9]{6,10}$")
		}],
		['validate-emailaddress-dutch', '', {
			minLength : 1,
			pattern : new RegExp("^.+@.+\\..+$")
		}],
		['validate-required-checkbox','U moet akkoord gaan met de algemene voorwaarden', function(value, elem) {
			return elem.checked;
		}]
	]);
}

function mainbooker_validation_callback(result, element) {
	if (!result && mainbooker_examples[element.name] != undefined) {
	    mainbooker_field_raise_example(element, false);
	}
}

///////////////////// 		GUI Support		/////////////////////
// This function unsets the example class on an input field
function mainbooker_field_drop_example(element) {
	if (element.hasClassName("example")) {
		// When the element has the class example, the value in the field is the example, so we save it!
		mainbooker_examples[element.name] = element.value;

		element.removeClassName("example");
		element.value = "";
		Validation.reset(element);
	}
}

// This functions sets the example class on an input field, and takes the example text from the array mainbooker_examples
// The example should be set when validate = false, or when validate = true && Validation.validate(element)
function mainbooker_field_raise_example(element, validate) {
	show = true;
	if (validate) show = !Validation.validate(element);

	if (show) {
		element.addClassName("example");
		element.value = mainbooker_examples[element.name];
	}
}

function select_country(target) {
	if ($(target +'_country').value == 'Nederland' || $(target+'_country').value == 'Koninkrijk der Nederlanden') {
		$(target + '_zipcode').addClassName('validate-zipcode-dutch');
		$(target + '_telephonenr').addClassName('validate-telephonenumber-dutch');
	} else {
		// do not validate zipcodes and telephone numbers
		$(target + '_zipcode').removeClassName('validate-zipcode-dutch');
		$(target + '_telephonenr').removeClassName('validate-telephonenumber-dutch');
		$('homecontact_telephonenr').removeClassName('validate-telephonenumber-dutch');
		$('advice-validate-zipcode-dutch-' + target + '_zipcode').style.display = 'none';
		$('advice-validate-telephonenumber-dutch-' + target + '_telephonenr').style.display = 'none';
	}
}

/**
 * OVERVIEW
 */

function replaceSpecialchars( obj ) {
	var chars = new Array();
	chars['À'] = 'A';
	chars['Á'] = 'A';
	chars['Â'] = 'A';
	chars['Ã'] = 'A';
	chars['Ä'] = 'A';
	chars['Å'] = 'A';
	chars['Æ'] = 'A';
	chars['Ç'] = 'C';
	chars['È'] = 'E';
	chars['É'] = 'E';
	chars['Ê'] = 'E';
	chars['Ë'] = 'E';
	chars['Ì'] = 'I';
	chars['Í'] = 'I';
	chars['Î'] = 'I';
	chars['Ï'] = 'I';
	chars['Ñ'] = 'N';
	chars['Ò'] = 'O';
	chars['Ó'] = 'O';
	chars['Ô'] = 'O';
	chars['Õ'] = 'O';
	chars['Ö'] = 'O';
	chars['Ø'] = 'O';
	chars['Ù'] = 'U';
	chars['Ú'] = 'U';
	chars['Û'] = 'U';
	chars['Ü'] = 'U';
	chars['Ý'] = 'Y';
	chars['ß'] = 's';
	chars['à'] = 'a';
	chars['á'] = 'a';
	chars['â'] = 'a';
	chars['ã'] = 'a';
	chars['ä'] = 'a';
	chars['å'] = 'a';
	chars['æ'] = 'ae';
	chars['ç'] = 'c';
	chars['è'] = 'e';
	chars['é'] = 'e';
	chars['ê'] = 'e';
	chars['ë'] = 'e';
	chars['ì'] = 'i';
	chars['í'] = 'i';
	chars['î'] = 'i';
	chars['ï'] = 'i';
	chars['ñ'] = 'n';
	chars['ò'] = 'o';
	chars['ó'] = 'o';
	chars['ô'] = 'o';
	chars['õ'] = 'o';
	chars['ö'] = 'o';
	chars['ø'] = 'o';
	chars['ù'] = 'u';
	chars['ú'] = 'u';
	chars['û'] = 'u';
	chars['ü'] = 'u';
	chars['ý'] = 'y';
	chars['ÿ'] = 'y';
	
	if (obj.value.length > 0) {
		var change = false;
		var newValue = obj.value;
		for (i=0;i<obj.value.length;i++) {
			if (chars[obj.value.substring(i, i+1)] != null) {
				newValue =	(i>0 ? newValue.substring(0, i) : '')
							+ chars[obj.value.substring(i, i+1)]
							+(i<=newValue.length ? newValue.substring(i+1, newValue.length+1) : '');
				change = true;
			}
		}
		if (change == true) {
			obj.value = newValue;
		}
	}
}


