var regattaDialog;
var regatta;
var regattaUUID;
var clubUUID;
var boatClassUUID;
var detailPageURL;

function initRegattaForm(regattaUUID, isCopy) {
	var _regattaUUID = regattaUUID;
	if (regattaUUID) {
		$.getJSON(
			sailCalPageURL,
			{
				"regattaUUID": _regattaUUID,
				"command": "loadRegatta",
				"mgnlCK": ieCacheKiller()
			},
			function(data, textStatus) {
				initRegattaFromWithData(data, textStatus, isCopy);
			}
		);
	} else {
		var data = new Object();
		data.data = new Object();
		initRegattaFromWithData(data);
	}
}

function initRegattaFromWithData(data, textStatus, isCopy) {
	if (data.errors) {
		alert("an error has occured when trying to load the regatta: " + data.errors);
	} else {
		// init regatta and form
		regatta = new Regatta(data.data.UUID);
		// add a few default values if the regatta was not loaded from the storage
		if (!regatta.UUID) {
			regatta.advertisementPermitted = true;
			regatta.registrationsVisible = true;
		}
		regattaDialog = new Dialog("regatta-modification-dialog");
		regattaDialog.dataObject = regatta;
		regattaDialog.steps[0].subSteps[0].extraValidate = validateRegattaDialogStep1_1;
		regattaDialog.steps[2].subSteps[0].extraValidate = validateRegattaDialogStep3_1;
		regattaDialog.steps[4].subSteps[0].extraValidate = validateRegattaDialogStep5_1;
		regattaDialog.saveCallback = function(data, textStatus) {
			if (data.errors) {
				var errorText = "an error has occured when trying to save the regatta:\n";
				for (var index in data.errors) {
					errorText += "- " + data.errors[index] + "\n";
				}
			} else {
				window.document.location.href = detailPageURL + "." + data.data.uuid + ".html"
			}
		}

		// set loaded values in regatta
		if (data.data) {
			for (var index in data.data) {
				regatta[index] = data.data[index];
			}
//			alert("regatta: " + JSON.stringify(regatta));
			// convert a few items that have not been transferred correctly by JSON
			for (var i=0; i<regatta.DATE_ATTRIBUTES.length; i++) {
				if (regatta[regatta.DATE_ATTRIBUTES[i]]) {
					var origValue = regatta[regatta.DATE_ATTRIBUTES[i]];
					if (origValue) {
						var convertedDate = Date.fromISOString(origValue);
						if (convertedDate) {
//							alert("date converted: "+regatta.DATE_ATTRIBUTES[i] + " = " + convertedDate);
							regatta[regatta.DATE_ATTRIBUTES[i] + "JSON"] = convertedDate;
						}
					}
				}
				delete regatta[regatta.DATE_ATTRIBUTES[i]];
			}
		}
		if (isCopy) {
			delete regatta.UUID;
		}
//		alert("regatta: " + JSON.stringify(regatta));

		// update the input elements in the form
		regattaDialog.updateDisplay();
		
		// init the multi-value input elements
		// clubs
		if (!regatta.clubUUIDs)  {
			regatta.clubUUIDs = new Array();
		}
		clubUUIDsInput = new ClubUUIDsMultiValueInput("regatta-dialog_club_list", regatta.clubUUIDs, "clubUUIDs", "clubUUIDsAdd", clubUUID);
		clubUUIDsInput.redraw();

		// boat classes
		if (!regatta.boatClasses) {
			regatta.boatClasses = new Array();
		}
		boatClassesInput = new BoatClassesMultiValueInput("regata-dialog_boatclasses_list", regatta.boatClasses, "boatClasses", "boatClassesAdd", boatClassUUID);
		boatClassesInput.redraw();
		
		// boat types
		if (!regatta.boatTypes) {
			regatta.boatTypes = new Array();
		}
		boatTypesInput = new MultiValueGridInputElement("regata-dialog_boattypes_list", regatta.boatTypes, "boatTypes", "boatTypesAdd");
		boatTypesInput.redraw();

		// forget about the jury members for now
		
		// registration notification addresses
		if (!regatta.registrationNotificationEmailAddresses) {
			regatta.registrationNotificationEmailAddresses = new Array();
		}
		regNotificationAddrInput = new MultiValueInputElement("regatta-dialog_notification_addresses_list", regatta.registrationNotificationEmailAddresses, 'registrationNotificationEmailAddresses', 'regNotificationAddrAdd');
		regNotificationAddrInput.redraw();

		// boat category products
		if (!regatta.categoryProducts) {
			regatta.categoryProducts = new Array();
		}
		categoryProductsInput = new MultiValueGridInputElement("regata-dialog_categoryproducts_list", regatta.categoryProducts, "categoryProducts", "categoryProductsAdd");
		categoryProductsInput.redraw();

		// optional products
		if (!regatta.optionalProducts) {
			regatta.optionalProducts = new Array();
		}
		optionalProductsInput = new MultiValueGridInputElement("regata-dialog_optionalproducts_list", regatta.optionalProducts, "optionalProducts", "optionalProductsAdd");
		optionalProductsInput.redraw();

		// update the date input elements in the form
		if (regatta.dateStartJSON) {
			$("#regatta-dialog_dateStart").datepicker("setDate", regatta.dateStartJSON);
		}
		if (regatta.dateEndJSON) {
			$("#regatta-dialog_dateEnd").datepicker("setDate", regatta.dateEndJSON);
		}
		regattaDialog.firstRaceDateTimePicker = new DateTimePicker("regatta-dialog_firstRace_day", "regatta-dialog_firstRace_time", regatta.firstRaceJSON);
		regattaDialog.firstRaceDateTimePicker.updateDateSource = function(newDate) {
			regatta.firstRaceJSON = newDate;
//			alert("updating \"firstRaceJSON\": "+newDate);
		}
		regattaDialog.lastRaceDateTimePicker = new DateTimePicker("regatta-dialog_lastRace_day", "regatta-dialog_lastRace_time", regatta.lastRaceJSON);
		regattaDialog.lastRaceDateTimePicker.updateDateSource = function(newDate) {
			regatta.lastRaceJSON = newDate;
		}
		if (regatta.registrationDeadlineJSON) {
			$("#regatta-dialog_registrationDeadline").datepicker("setDate", regatta.registrationDeadlineJSON);
		}
		if (regatta.registrationDeadline2JSON) {
			$("#regatta-dialog_registrationDeadline2").datepicker("setDate", regatta.registrationDeadline2JSON);
		}
		
		// add some custom "onchange" methods
		$("#regatta-dialog_dateStart").change(function() {
			regattaDialog.dataObject["dateStartJSON"] = $("#regatta-dialog_dateStart").datepicker("getDate");
		});
		$("#regatta-dialog_dateEnd").change(function() {
			regattaDialog.dataObject["dateEndJSON"] = $("#regatta-dialog_dateEnd").datepicker("getDate");
		});		
		$("#regatta-dialog_registrationDeadline").change(function() {
			regattaDialog.dataObject["registrationDeadlineJSON"] = $("#regatta-dialog_registrationDeadline").datepicker("getDate");
		});		
		$("#regatta-dialog_registrationDeadline2").change(function() {
			regattaDialog.dataObject["registrationDeadline2JSON"] = $("#regatta-dialog_registrationDeadline2").datepicker("getDate");
		});		
		$("#regatta-dialog_onlineRegistrationAllowed").click(function() {
			updateTransferPaymentInfoDisplay();
		});
		$("#regatta-dialog_transferPaymentAllowed").click(function() {
			updateTransferPaymentInfoDisplay();
		});
		
		// finally display dialog
		updateTransferPaymentInfoDisplay();
		$("#regatta-modification-dialog").dialog('open');
		regattaDialog.showStep(1, 1);
	}
}

function resetRegattaForm(initRegatta) {
	if (initRegatta) {
		regatta = new Regatta(regattaUUID);
	}
	regattaDialog = new Dialog("regatta-modification-dialog");
	regattaDialog.dataObject = regatta;
	// link the multi value input elements
	regatta["clubUUIDs"] = clubUUIDsInput.values;
	regatta["registrationNotificationEmailAddresses"] = regNotificationAddrInput.values;
	regatta["boatClasses"] = boatClassesInput.values;
	regatta["boatTypes"] = boatTypesInput.values;
	regatta["categoryProducts"] = categoryProductsInput.values;
	regatta["optionalProducts"] = optionalProductsInput.values;
	$("#regatta-dialog_firstRace_day").change(setDateAndTime('regatta-dialog_firstRace_day', 'regatta-dialog_firstRace_time', 'firstRaceJSON', regattaDialog));
	$("#regatta-dialog_firstRace_time").change(setDateAndTime('regatta-dialog_firstRace_day', 'regatta-dialog_firstRace_time', 'firstRaceJSON', regattaDialog));
	$("#regatta-dialog_lastRace_day").change(setDateAndTime('regatta-dialog_lastRace_day', 'regatta-dialog_lastRace_time', 'lastRaceJSON', regattaDialog));
	$("#regatta-dialog_lastRace_time").change(setDateAndTime('regatta-dialog_lastRace_day', 'regatta-dialog_lastRace_time', 'lastRaceJSON', regattaDialog));
	$("#regatta-modification-dialog input.date").change(function() {
		regattaDialog.dataObject[$(this).attr("name") + "JSON"] = $(this).datepicker("getDate");
	});
	regattaDialog.steps[0].subSteps[0].extraValidate = validateRegattaDialogStep1_1;
	regattaDialog.steps[2].subSteps[0].extraValidate = validateRegattaDialogStep3_1;
	regattaDialog.steps[4].subSteps[0].extraValidate = validateRegattaDialogStep5_1;
	// update data object with the values set in the form -> not needed anymore after change to 
	// js initialization of dialog
	regattaDialog.updateDataObject();
	regattaDialog.showStep(1, 1);
}

function updateLakeOtherDisplay() {
	if ($("#regatta-dialog_lakeUUID").val() == "lake_other") {
		$("#regatta-dialog_lakeOther").removeAttr("disabled");
		$("#regatta-dialog_lakeOther_input_row").slideDown();
	} else {
		$("#regatta-dialog_lakeOther").attr("disabled", "disabled");
		$("#regatta-dialog_lakeOther_input_row").slideUp();
		delete regattaDialog.dataObject["lakeOther"];
	}
}

function updateOnlineRegistrationOnlyDisplay() {
	if ($("#regatta-dialog_transferPaymentAllowed").is(":checked")) {
		$("#regatta-dialog_transfer_payment_info textarea").removeAttr("disabled");
		$("#regatta-dialog_transfer_payment_info").slideDown();
	} else {
		$("#regatta-dialog_transfer_payment_info textarea").attr("disabled", "disabled");
		$("#regatta-dialog_transfer_payment_info").slideUp();
	}
}
function updateTransferPaymentInfoDisplay() {
	if ($("#regatta-dialog_onlineRegistrationAllowed").is(":checked")) {
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only textarea").removeAttr("disabled");
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only input").removeAttr("disabled");
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only select").removeAttr("disabled");
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only").slideDown();
		updateOnlineRegistrationOnlyDisplay();
	} else {
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only textarea").attr("disabled", "disabled");
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only input").attr("disabled", "disabled");
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only select").attr("disabled", "disabled");
		$("#regatta-dialog_step_5_1 .regatta-dialog_online_registration_only").slideUp();
		updateOnlineRegistrationOnlyDisplay();
	}
}
/* custom validation of regatta dialog steps ******************************************************/
function validateRegattaDialogStep1_1(errorMessages) {
	// make sure the start date has a valid format
	var dateStart = null;
	if ($("#regatta-dialog_dateStart").val()) {
		dateStart = regattaDialog.dataObject["dateStartJSON"];
		if (!dateStart) {
			errorMessages["dateStart"] = "error_invalid_date_format";
			errorMessages.noOfErrors++;
		} else {
			// make sure the end date (if set) is not before the start date
			if ($("#regatta-dialog_dateEnd").val()) {
				var dateEnd = regattaDialog.dataObject["dateEndJSON"];
				if (!dateEnd) {
					errorMessages["dateEnd"] = "error_invalid_date_format";
					errorMessages.noOfErrors++;
				} else {
					if (dateEnd < dateStart) {
						errorMessages["dateEnd"] = "error_may_not_be_earlier_than_date_start";
						errorMessages.noOfErrors++;
					}
				}
			}
		}
	}
	// if lake_uuid is set to "lake_other" then the other lake has to be provided
	if ($("#regatta-dialog_lakeUUID").val() == "lake_other") {
		var lakeOther = $("#regatta-dialog_lakeOther").val();
		if (!lakeOther || lakeOther.length == 0) {
			errorMessages["lakeOther"] = "error_no_other_lake_provided";
			errorMessages.noOfErrors++;
		}
	}
	// make sure that at least one organizing club has been selected
	if (!$("#regatta-dialog_clubOther").val()) {
		var clubSelected = false;
		for (var i=0; i<clubUUIDsInput.values.length; i++) {
			if (clubUUIDsInput.values[i] && clubUUIDsInput.values[i].length > 0) {
				clubSelected = true;
				break;
			}
		}
		if (!clubSelected) {
			errorMessages["club"] = "error_no_club_selected_or_entered";
			errorMessages.noOfErrors++;
		}
	}
	// at least one boat class or boat type has to be specified
	var boatClassOrTypeSelected = false;
	var regattaCategoriesSelected = true;
	for (var i=0; i<boatClassesInput.values.length; i++) {
		boatClassOrTypeSelected = true;
		var boatClassUUID = boatClassesInput.values[i].boatClassUUID;
		var regattaTypeUUID = boatClassesInput.values[i].regattaTypeUUID;
		if (!boatClassUUID || boatClassUUID.length == 0) {
			if (!errorMessages["regattaCategories"]) {
				errorMessages.noOfErrors++;
			}
			errorMessages["regattaCategories"] = "error_incomplete_boatclass_row";
			break;
		} else  {
			if (!regattaTypeUUID || regattaTypeUUID.length == 0) {
				if (!errorMessages["regattaCategories"]) {
					errorMessages.noOfErrors++;
				}
				errorMessages["regattaCategories"] = "error_no_regatta_category_selected";
				break;
			}
		}
	}
	for (var i=0; i<boatTypesInput.values.length; i++) {
		if (boatTypesInput.values[i].boatTypeUUID && boatTypesInput.values[i].boatTypeUUID.length > 0) {
			boatClassOrTypeSelected = true;
			if (!boatTypesInput.values[i].regattaTypeUUID || boatTypesInput.values[i].regattaTypeUUID.length == 0) {
				if (!errorMessages["regattaCategories"]) {
					errorMessages.noOfErrors++;
				}
				errorMessages["regattaCategories"] = "error_no_regatta_category_selected";
			}
		}
	}
	if (!boatClassOrTypeSelected) {
		errorMessages["boatClassType"] = "error_no_boatclass_or_type_selected";
		errorMessages.noOfErrors++;
	}
}

function validateRegattaDialogStep3_1(errorMessages) {
	// if firstRace_date or firstRace_time is not empty then we need to have a valid firstRace Date
/*	if ($("#regatta-dialog_firstRace_day").val() || $("#regatta-dialog_firstRace_time").val()) {
		if (!regattaDialog.dataObject["firstRaceJSON"]) {
			errorMessages["firstRace"] = "error_invalid_date_format";
			errorMessages.noOfErrors++;
		} else {
			// if a firstRace date is set, it should not be before dateStart
			var dateStart = regattaDialog.dataObject["dateStartJSON"];
			var firstRace = regattaDialog.dataObject["firstRaceJSON"];
			if (dateStart && dateStart instanceof Date && firstRace < dateStart) {
//				alert("dateStart: "+dateStart + "\nfirstRace: "+firstRace);
				errorMessages["firstRace"] = "error_first_race_before_date_start";
				errorMessages.noOfErrors++;
			}
		}
	}*/
	
	// validate first race
	if (!regattaDialog.firstRaceDateTimePicker.isValid()) {
		errorMessages["firstRace"] = "error_invalid_date_format";
		errorMessages.noOfErrors++;
	} else if (regatta.firstRaceJSON && regatta.dateStartJSON && regatta.firstRaceJSON.isBefore(regatta.dateStartJSON)) {
		errorMessages["firstRace"] = "error_first_race_before_date_start";
		$(".message_firstRace").text(" (" + regatta.dateStartJSON.toString(dateFormat) + ")");
		$(".message_firstRace").show();
		errorMessages.noOfErrors++;
	} else if (regatta.firstRaceJSON && regatta.dateEndJSON) {
		var dateEndEndOfDay = regatta.dateEndJSON.clone();
		dateEndEndOfDay.clearTime();
		dateEndEndOfDay.addDays(1);
		if (!regatta.firstRaceJSON.isBefore(dateEndEndOfDay)) {
			errorMessages["firstRace"] = "error_first_race_after_date_end";
			$(".message_firstRace").text(" (" + regatta.dateEndJSON.toString(dateFormat) + ")");
			$(".message_firstRace").show();
			errorMessages.noOfErrors++;
		}
	}
	
	// validate last race
	if (!regattaDialog.lastRaceDateTimePicker.isValid()) {
		errorMessages["lastRace"] = "error_invalid_date_format";
		errorMessages.noOfErrors++;
	} else if (regatta.lastRaceJSON && regatta.dateStartJSON && regatta.lastRaceJSON.isBefore(regatta.dateStartJSON)) {
		errorMessages["lastRace"] = "error_last_race_before_date_start";
		$(".message_lastRace").text(" (" + regatta.dateStartJSON.toString(dateFormat) + ")");
		$(".message_lastRace").show();
		errorMessages.noOfErrors++;
	} else if (regatta.lastRaceJSON && regatta.dateEndJSON) {
		var dateEndEndOfDay = regatta.dateEndJSON.clone();
		dateEndEndOfDay.clearTime();
		dateEndEndOfDay.addDays(1);
		if (!regatta.lastRaceJSON.isBefore(dateEndEndOfDay)) {
			errorMessages["lastRace"] = "error_last_race_after_date_end";
			$(".message_lastRace").text(" (" + regatta.dateEndJSON.toString(dateFormat) + ")");
			$(".message_lastRace").show();
			errorMessages.noOfErrors++;
		}
	}
	
	// if lastRace_date or lastRace_time is not empty then we need to have a valid lastRace Date
	if ($("#regatta-dialog_lastRace_day").val() || $("#regatta-dialog_lastRace_time").val()) {
		if (!regattaDialog.dataObject["lastRaceJSON"]) {
			errorMessages["lastRace"] = "error_invalid_date_format";
			errorMessages.noOfErrors++;
		}
	}

	// if lastRace_date or lastRace_time is not empty then we need to have a valid lastRace Date
	if ($("#regatta-dialog_lastRace_day").val() || $("#regatta-dialog_lastRace_time").val()) {
		if (!regattaDialog.dataObject["lastRaceJSON"]) {
			errorMessages["lastRace"] = "error_invalid_date_format";
			errorMessages.noOfErrors++;
		} else {
			// if a lastRace date is set, it should not be after dateEnd
			var dateEnd = regattaDialog.dataObject["dateEndJSON"];
			var lastRaceDate = new Date(regattaDialog.dataObject["lastRaceJSON"]);
			lastRaceDate.setHours(0);
			lastRaceDate.setMinutes(0);
			lastRaceDate.setSeconds(0);
			lastRaceDate.setMilliseconds(0);
			if (dateEnd && dateEnd instanceof Date && lastRaceDate > dateEnd) {
//				alert("dateEnd: "+dateEnd + "\ndate lastRace: "+lastRaceDate);
				errorMessages["lastRace"] = "error_last_race_after_date_end";
				errorMessages.noOfErrors++;
			} else if (regattaDialog.dataObject["firstRaceJSON"] && regattaDialog.dataObject["firstRaceJSON"] > regattaDialog.dataObject["lastRaceJSON"]) {
//				alert("firstRace: "+regattaDialog.dataObject["firstRace"]+"\nlastRace: "+regattaDialog.dataObject["lastRace"]);
				// firstRace has to be smaller than lastRace
				errorMessages["lastRace"] = "error_last_race_before_first_race";
				errorMessages.noOfErrors++;
			}
		}
	}
	// if lastRace_date or lastRace_time is not empty then we need to have a valid lastRace Date
	if ($("#regatta-dialog_lastRace_day").val() || $("#regatta-dialog_lastRace_time").val()) {
		if (!regattaDialog.dataObject["lastRaceJSON"]) {
			errorMessages["lastRace"] = "error_invalid_date_format";
			errorMessages.noOfErrors++;
		}
	}
}

function validateRegattaDialogStep5_1(errorMessages) {
	// only validate if online registrations are allowed
	if ($("#regatta-dialog_onlineRegistrationAllowed").is(":checked")) {
		// at least one payment method has to be checked
		if ($("#regatta-dialog_payment_options input[type='checkbox']:checked").size() == 0) {
			errorMessages["paymentOptions"] = "error_no_payment_option_selected";
			errorMessages.noOfErrors++;
		} else if ($("#regatta-dialog_transferPaymentAllowed").is(":checked")) {
			// make sure bank details have been provided
			var bankDetails = $("#regatta-dialog_committeeBankDetails").val();
			if (!bankDetails || bankDetails.length == 0) {
				errorMessages["committeeBankDetails"] = "error_mandatory";
				errorMessages.noOfErrors++;
			}
		}
		
		// make sure that at least one notification email address has been provided
		if (!regNotificationAddrInput.values || regNotificationAddrInput.values.length == 0) {
			errorMessages["registrationNotificationEmailAddesses"] = "error_mandatory";
			errorMessages.noOfErrors++;
		} else {
			var notificationEmailAddressesVaild = true;
			for (var i=0; i<regNotificationAddrInput.values.length; i++) {
				var email = regNotificationAddrInput.values[i];
				if (!email || email.length == 0) {
					// TODO: add email validation
					if (!errorMessages["registrationNotificationEmailAddesses"]) {
						errorMessages.noOfErrors++;
					}
					errorMessages["registrationNotificationEmailAddesses"] = "error_empty_or_invalid";
				}
			}
		}
		
		// there must be a registration deadline set
		if (!regatta.registrationDeadlineJSON) {
			errorMessages["registrationDeadline"] = "error_mandatory";
			errorMessages.noOfErrors++;
		} else if (regatta.dateStartJSON.isBefore(regatta.registrationDeadlineJSON)) {
			errorMessages["registrationDeadline"] = "error_registration_deadline_after_start";
			$(".message_registrationDeadline").text(" (" + regatta.dateStartJSON.toString(dateFormat) + ")");
			$(".message_registrationDeadline").show();
			errorMessages.noOfErrors++;
		}

		// at least one category product has to be entered - all products need to be complete
		if (!categoryProductsInput.values || categoryProductsInput.values.length == 0) {
			errorMessages["categoryProducts"] = "error_mandatory";
			errorMessages.noOfErrors++;
		} else {
//			var categoryProductsValid = true;
			for (var i=0; i<categoryProductsInput.values.length; i++) {
				var productTitle = categoryProductsInput.values[i].title;
				var productPrice = categoryProductsInput.values[i].price;
				if (!productTitle || productTitle.length == 0 || !productPrice || productPrice.length == 0 || isNaN(productPrice) || productPrice < 0) {
					errorMessages["categoryProducts"] = "error_empty_or_invalid";
					errorMessages.noOfErrors++;
				}
			}
		}

		// all optional products need to be complete
		if (optionalProductsInput.values && optionalProductsInput.values.length > 0) {
			for (var i=0; i<optionalProductsInput.values.length; i++) {
				var productTitle = optionalProductsInput.values[i].title;
				var productPrice = optionalProductsInput.values[i].price;
				if (!productTitle || productTitle.length == 0) {
					alert("product mandatory!");
					errorMessages["optionalProducts"] = "error_empty_or_invalid";
					errorMessages.noOfErrors++;
					break;
				} else if (!productPrice || productPrice.length == 0) {
					alert("price " + i + " mandatory!");
					errorMessages["optionalProducts"] = "error_empty_or_invalid";
					errorMessages.noOfErrors++;
					break;
				} else if (isNaN(productPrice) || productPrice < 0) {
					alert("price " + i + " not valid!");
					errorMessages["optionalProducts"] = "error_empty_or_invalid";
					errorMessages.noOfErrors++;
					break;
				}
			}
		}
	}
}

function setDateAndTime(dateFieldID, timeFieldID, targetFieldName, dialog) {
	// get the date and time values
	var dateString = $("#" + dateFieldID).val();
	var timeString = $("#" + timeFieldID).val();
	var dateTime = null;
	if (dateString && dateString.length > 0) {
		if (!timeString || timeString.length == 0) {
			timeString = "12:00";
			$("#" + timeFieldID).val(timeString);
		}
		// try to convert the date and time string to a Date objecct
		dateTime = Date.parseExact(dateString + " " + timeString, "dd.MM.yyyy HH:mm");
	}
	if (dateTime != null) {
		dialog.dataObject[targetFieldName] = dateTime;
//		alert("setting " + targetFieldName + ": "+dateTime);
	} else {
		dialog.dataObject[targetFieldName] = null;
//		alert("deleting " + targetFieldName);
	}
}

/* ClubUUIDsMultiValueInput **********************************************************************/
function ClubUUIDsMultiValueInput(id, values, jsonInputID, addButtonID, userClubUUID) {
	var _that = this;
	this.inheritFrom = MultiValueInputElement;
	this.inheritFrom(id, values, jsonInputID, addButtonID);
	this.userClubUUID = userClubUUID;

	this.redraw = function() {
		$("#" + this.id + " .datarow").remove();
		for (var i=0; i<this.values.length; i++) {
			var value = this.values[i];
			
			var newDataRow = $("#" + this.id + " .template").clone().appendTo("#" + this.id).removeClass("template").addClass("datarow");
			newDataRow.index = "" + i;
			$(newDataRow).attr("rel", "" + i + ".row"	);
			if (this.userClubUUID && this.userClubUUID.length > 0 && this.userClubUUID == value) {
				var clubName = $("select option[value='" + value + "']", newDataRow).text();
				$("*", newDataRow).remove();
				$(newDataRow).text(clubName);
			} else {
				$("select", newDataRow).each(function(index) {
					if ($("option[value='" + _that.values[i] + "']", this).size() == 1) {
						$("option:selected", this).removeAttr("selected");
						$("option[value='" + _that.values[i] + "']", this).attr("selected", "selected");
					}
					$(this).attr("name", "" + i + "." + $(this).attr("name"));
					$(this).change(function() {
						var name = $(this).attr("name");
						var myIndex = name.substring(0, name.indexOf(".", 0));
	//					alert("changing value in of " + myIndex);
						_that.values[myIndex] = $("option:selected", this).val();
						if (_that.jsonInputID) {
							$("#" + _that.jsonInputID).val(JSON.stringify(_that.values));
						}
					});
				});
				
				$(".button_delete", newDataRow).click(function() {
					var row = $(this).parents(".datarow", newDataRow).attr("rel");
					row = row.substring(0, row.indexOf(".", 0));
					_that.values.splice(row, 1); 
					_that.redraw();
					if (_that.jsonInputID) {
						$("#" + _that.jsonInputID).val(JSON.stringify(_that.values));
					}
				});
			}
		}
	}
}

/* BoatClassesMultiValueInput *********************************************************************/
function BoatClassesMultiValueInput(id, values, jsonInputID, addButtonID, boatClassUUID) {
	var _that = this;
	this.inheritFrom = MultiValueGridInputElement;
	this.inheritFrom(id, values, jsonInputID, addButtonID);
	this.boatClassUUID = boatClassUUID;

	this.redraw = function() {
		$("#" + this.id + " .datarow").remove();
		for (var i=0; i<this.values.length; i++) {
			var value = this.values[i];
			
			var newDataRow = $("#" + this.id + " .template").clone().appendTo("#" + this.id).removeClass("template").addClass("datarow");
			newDataRow.index = "" + i;
			$(newDataRow).attr("rel", "" + i + ".row"	);
			if (this.boatClassUUID && this.boatClassUUID.length > 0 && this.boatClassUUID == value['boatClassUUID']) {
				var boatClassName = $("select option[value='" + value['boatClassUUID'] + "']", newDataRow).text();
				$("select[name='boatClassUUID']", newDataRow).replaceWith(boatClassName);
				$(".button_delete", newDataRow).replaceWith("&nbsp;");
			}
			$("select", newDataRow).each(function(index) {
				var name = $(this).attr("name");
				if ($("option[value='" + _that.getValue(i, name) + "']", this).size() == 1) {
					$("option:selected", this).removeAttr("selected");
					$("option[value='" + _that.getValue(i, name) + "']", this).attr("selected", "selected");
				}
				$(this).attr("name", "" + i + "." + $(this).attr("name"));
				$(this).change(function() {
					var name = $(this).attr("name");
					var myIndex = name.substring(0, name.indexOf(".", 0));
					name = name.substring(name.indexOf(".", 0) + 1);
					_that.setValue($("option:selected", this).val(), myIndex, name);
					if (_that.jsonInputID) {
						$("#" + _that.jsonInputID).val(JSON.stringify(_that.values));
					}
				});
			});
			
			$(".button_delete", newDataRow).click(function() {
				var row = $(this).parents(".datarow", newDataRow).attr("rel");
				row = row.substring(0, row.indexOf(".", 0));
				_that.values.splice(row, 1); 
				_that.redraw();
				if (_that.jsonInputID) {
					$("#" + _that.jsonInputID).val(JSON.stringify(_that.values));
				}
			});
		}
	}
}
/* Regatta ****************************************************************************************/
function Regatta(uuid) {
	this.DATE_ATTRIBUTES = ["dateStart", "dateEnd", "firstRace", "lastRace", "registrationDeadline", "registrationDeadline2"];
	var _that = this;
	if (uuid && uuid.length > 0) {
		this.UUID = uuid;
	}
}