$(function() {
	
	var suchergebnis = $('.anzeigen-liste');
	if (suchergebnis.size()) {
		suchergebnis.tabs();
		suchergebnis.find('h2').hide();
	}
	
	var anzeigeAnlegenForms = $('form:has(.fieldname-schwarzes_brett_anzeige__email)');
	if (anzeigeAnlegenForms.size()) {
		anzeigeAnlegenForms.hide();
	
		var selectOptionsHtml = '<option value="none">- ' + Messages.getString('label__select_empty_option') + ' -</option>';
		var erroneousForm = false;
		var erroneousFormTerminFields = false;
		anzeigeAnlegenForms.each(function(offset) {
			var form = $(this);
			var heading = form.find('h2').text();
			selectOptionsHtml += '<option value="' + (offset) + '">' + heading + '</option>';
			
			var produktionRow = form.find('.row:has(select[name$="__produktion_document_id"])');
					
			var datumRow = form.find('.row:has(input[name$="__datum"])').hide();
			var uhrzeitRow = form.find('.row:has(input[name$="__uhrzeit"])').hide();
			var spielstaetteRow = form.find('.row:has(select[name$="__spielstaette_document_id"])').hide();
			
			var spielstaetteNameToIdMap = {};
			spielstaetteRow.find('option').each(function() { if ($(this).attr('value')) spielstaetteNameToIdMap[$(this).text()] = $(this).attr('value'); });
			
			var terminAuswahlRow = spielstaetteRow.clone().show();
			terminAuswahlRow.find('label').text(Messages.getString('label__schwarzes_brett_anzeige_form_termin_auswahl'));
			terminAuswahlRow.find('option').remove();
			terminAuswahlRow.find('select').removeAttr('name');
			produktionRow.after(terminAuswahlRow);
			
			var terminSelect = terminAuswahlRow.find('select');
			var produktionSelect = produktionRow.find('select');
			var datumField = datumRow.find('input');
			var uhrzeitField = uhrzeitRow.find('input');
			var spielstaetteSelect = spielstaetteRow.find('select');
			
			if ((erroneousForm === false) && form.find('.error').size()) {
				erroneousForm = offset;
				erroneousFormTerminFields = datumField.add(uhrzeitField).add(spielstaetteSelect);
			}
			
			var produktionsTermine = {};
			var produktionsInformationenMatch = /^(.*) \((.*)\)$/;
			var spielstaettenInformationenMatch = /\b[^;]+/g;
			var spielstaettenMatchesMatch = /^(.*): (.*)$/;
			var terminInformationenMatch = /\b[^,]+/g;
			var datumMatch = /\d{2}\.\d{2}\.\d{4}/;
			var uhrzeitMatch = /\d{2}\:\d{2}/;
			
			var newProduktionsOptionsHtml = '';
			var selectedProduktionId = produktionSelect.val(); 
			produktionSelect.find('option').each(function() {
				var option = $(this);
				var terminOptionen = $([]);
				
				var value = option.attr('value');
				var text = option.text();
				if (value) {
					var produktionsId = value;
					
					if (!produktionsTermine[produktionsId]) produktionsTermine[produktionsId] = [];
					
					var produktionsInformationen = text;
					var matches = produktionsInformationen.match(produktionsInformationenMatch);
					if (!matches) return;
				
					var produktionsName = matches[1];
					var spielstaettenInformationen = matches[2];
					
					var spielstaettenMatches = spielstaettenInformationen.match(spielstaettenInformationenMatch);
					if (!spielstaettenMatches) return;
					
					$.each(spielstaettenMatches, function() {
						var spielstaettenMatch = this;
						var spielstaetteMatches = spielstaettenMatch.match(spielstaettenMatchesMatch);
						if (!spielstaetteMatches) return;

						var spielstaetteName = spielstaetteMatches[1];
						var terminInformationen = spielstaetteMatches[2];
						
						var termineMatches = terminInformationen.match(terminInformationenMatch);
						if (!termineMatches) return ;
						$.each(termineMatches, function() {
							var termineMatch = this;
							var datum = termineMatch.match(datumMatch);
							var uhrzeit = termineMatch.match(uhrzeitMatch);
							
							produktionsTermine[produktionsId].push({
									datum: datum,
									uhrzeit: uhrzeit,
									spielstaetteName: spielstaetteName,
									spielstaetteId: spielstaetteNameToIdMap[spielstaetteName]
							});
						});
					});
					
					newProduktionsOptionsHtml += '<option value="' + produktionsId + '">' + produktionsName + '</option>';
				} else {
					newProduktionsOptionsHtml += '<option value="' + value + '">' + text + '</option>';
				}
				option.text(produktionsName);
			});
			produktionSelect.html(newProduktionsOptionsHtml);
			produktionSelect.width('400px');
			if (selectedProduktionId) produktionSelect.val(selectedProduktionId);
			
			produktionSelect.change(function() {
				var isGesuchForm = form.is(':has(input[name="submitted-form"][value$="\_gesuch\_form"])');
				var emptyTerminOptionlabel = isGesuchForm ? Messages.getString('label__schwarzes_brett_anzeige_aufgeben_form_termin_beliebig') : Messages.getString('label__select_empty_option');
				var newTerminOptionsHtml = '<option value="">- ' + emptyTerminOptionlabel + ' -</option>';
				if ($(this).val()) {
					var labelTemplate = Messages.getString('label__schwarzes_brett_anzeige_aufgeben_form_termin_select_option');
					$.each(produktionsTermine[$(this).val()], function(id, termin) {
						var label = labelTemplate;
						label = label.replace('%s', termin['spielstaetteName']);
						label = label.replace('%s', termin['datum']);
						label = label.replace('%s', termin['uhrzeit']);
						newTerminOptionsHtml += '<option value="' + id + '">' + label + '</option>';  
					});
				}
				terminSelect.html(newTerminOptionsHtml);
			});
			
			terminSelect.change(function() {
				if ($(this).val()) {
					var produktionId = produktionSelect.val();
					var terminId = $(this).val();
					var terminInformation = produktionsTermine[produktionId][terminId]; 
					var datum = terminInformation['datum'];
					var uhrzeit = terminInformation['uhrzeit'];
					var spielstaetteId = terminInformation['spielstaetteId'];
				} else {
					var datum = '', uhrzeit = '', spielstaetteId = '';
				}
				datumField.val(datum);
				uhrzeitField.val(uhrzeit);
				spielstaetteSelect.val(spielstaetteId);
			});
			
			produktionSelect.change();
			if (produktionSelect.val()) {
				if (datumField.val() && uhrzeitField.val() && spielstaetteSelect.val()) {
					$.each(produktionsTermine[produktionSelect.val()], function(id, termin) {
						if ((termin['datum'] == datumField.val()) &&
							(termin['uhrzeit'] == uhrzeitField.val()) &&
							(termin['spielstaetteId'] == spielstaetteSelect.val())
						) {
							terminSelect.val(id);
							return false;
						}
					});
				}
			}
		});
		
		var formIdentifier = anzeigeAnlegenForms.eq(0).find('div:has(input[name="submitted-form"])').clone().wrap('<div />').parent();
		var submitButtons = anzeigeAnlegenForms.eq(0).find('.groupname-submit').clone().wrap('<div />').parent();
		submitButtons.find('.action-save').remove();
		
		var formSelectForm = anzeigeAnlegenForms.eq(0).before('<form action="./" method="post">' + formIdentifier.html() + '<div class="row validator-required"><label>' + Messages.getString('label__schwarzes_brett_anzeige_aufgeben_form_select') + '</label><div class="field"><select>' + selectOptionsHtml + '</select></div></div>' + submitButtons.html() + '</form>').prev();
		var formSelect = formSelectForm.find('select');
		
		formSelect.change(function() {
			anzeigeAnlegenForms.hide();
			if ($(this).val() != "none") {
				anzeigeAnlegenForms.eq($(this).val()).show();
				formSelectForm.find('.groupname-submit').hide();
			} else {
				formSelectForm.find('.groupname-submit').show();
			}
		});
	
		if (erroneousForm !== false) {
			formSelect.val(erroneousForm).change();
			var errorFlash = $('.flash.failure');
			if (errorFlash.size()) {
				var requiredErrorMessage = Messages.getString('error__field_required');
				var newError = false;
				erroneousFormTerminFields.each(function() {
					var errorMessage = $(this).closest('.row').find('label').text() + ': ' + requiredErrorMessage;
					errorLi = errorFlash.find('li:contains("' + errorMessage + '")');
					if (errorLi.size()) {
						if (!newError) newError = errorLi.after('<li>' + Messages.getString('label__schwarzes_brett_anzeige_form_termin_auswahl') + ': ' + requiredErrorMessage).next();
						errorLi.remove();
					}
				});
			}			
		}
	}

});
