var countrySelect;
var destinationSelect;
var golfcourseSelect;

$(document).ready(function() {
	countrySelect     = $('#golf_search select:eq(0)');
	destinationSelect = $('#golf_search select:eq(1)');
	golfcourseSelect  = $('#golf_search select:eq(2)');
	
	countrySelect.change(function() { selectCountry() });
	destinationSelect.change(function() { selectDestination() });
	
	// Einmaliges Ausführen nach Laden der Seite
	selectCountry();
});

function selectCountry() {
	destinationSelect.find('option').remove();
	var selectedCountry = countrySelect.find('option:selected').text();
	jQuery.each(destinations, function(countryName, destinationsOfCountry) {
		if (countryName == selectedCountry) {
			for (destinationKey in destinationsOfCountry) {
				if (destinationKey == activeDestination) {
					destinationSelect.append('<option value="'+ destinationKey +'" selected="selected">'+ destinationsOfCountry[destinationKey] +'</option>');
				}
				else {
					destinationSelect.append('<option value="'+ destinationKey +'">'+ destinationsOfCountry[destinationKey] +'</option>');
				}
			}
		}
	});
	
	selectDestination();
}

function selectDestination() {
	golfcourseSelect.find('option').remove();
	var selectedDestination = destinationSelect.find('option:selected').attr('value');
	
	// Fallback für fehlerhaftes Browser-Verhalten (Safari)
	if (!selectedDestination) {
		selectedDestination = destinationSelect.find('option:eq(0)').attr('value');
	}
	
	jQuery.each(golfcourses, function(destinationKey, golfcoursesOfDestination) {
		if (destinationKey == selectedDestination) {
			for (golfcourseKey in golfcoursesOfDestination) {
				if (golfcourseKey == activeGolfcourse) {
					golfcourseSelect.append('<option value="'+ golfcourseKey +'" selected="selected">'+ golfcoursesOfDestination[golfcourseKey] +'</option>');
				}
				else {
					golfcourseSelect.append('<option value="'+ golfcourseKey +'">'+ golfcoursesOfDestination[golfcourseKey] +'</option>');
				}
			}
		}
	});
}