
var Rejseplanen = new Class({

	form: null,
	
	dateSelect: null,
	daySelect: null,
	monthYearSelect: null,
	
	currentDay: null,
	currentMonth: null,
	currentYear: null,
	
	selectedDay: null,
	selectedMonth: null,
	selectedYear: null,
	
	initialize: function()
	{
		this.form = $('rejseplanenForm');
		this.form.onsubmit = function(event) {new Event(event).stop(); return false;}

		$('rejseplanenSubmit').addEvent('click', function() {this.form.submit();}.bind(this));
		
		var hour = new Date().getHours();
		var minute = new Date().getMinutes();
		$('rejseplanenTime').value = (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute);
		
		this.daySelect = $('rejseplanenDay'); 
		this.monthYearSelect = $('rejseplanenMonthYear');
		
		this.currentDay = new Date().getDate();
		this.currentMonth = new Date().getMonth()+1;
		this.currentYear = new Date().getFullYear();
		
		this.dateSelect = new DateSelect(new Date(), new Date());
		this.dateSelect.intervalStart.setFullYear(this.currentYear, this.currentMonth-1, this.currentDay);
		this.dateSelect.intervalEnd.setFullYear(this.currentYear, this.currentMonth-1, this.currentDay);
		this.dateSelect.intervalEnd.setMonth(this.currentMonth+1);
		this.dateSelect.intervalEnd.setDate(this.dateSelect.daysInMonth(this.dateSelect.intervalEnd.getMonth()+1, this.dateSelect.intervalEnd.getFullYear()));
		
		this.daySelect.addEvent('change', this.updateDateValues.bind(this));
		this.monthYearSelect.addEvent('change', this.buildDateOptions.bind(this));

		this.monthYearSelect.empty();
		this.monthYearSelect.adopt(this.dateSelect.getMonthOptions(this.currentMonth, this.currentYear));

		this.buildDateOptions();
	},
	
	buildDateOptions: function()
	{
		this.updateDateValues();
		this.daySelect.empty();
		this.daySelect.adopt(this.dateSelect.getDayOptions(this.selectedMonth, this.selectedYear, this.selectedDay));
	},
	
	updateDateValues: function()
	{
		var selectedDay = this.dateSelect.getSelectionValue(this.daySelect);
		if (selectedDay) {
			this.selectedDay = selectedDay.toInt();
		} else {
			this.selectedDay = this.currentDay;
		}
		var selectedYearMonth = this.dateSelect.getSelectionValueAsYearMonth(this.monthYearSelect);
		if (selectedYearMonth) {
			this.selectedMonth = selectedYearMonth['month'].toInt();
			this.selectedYear = selectedYearMonth['year'].toInt();
		} else {
			this.selectedMonth = this.currentMonth;
			this.selectedYear = this.currentYear;
		}
		$('rejseplanenDate').value = this.selectedDay+'.'+this.selectedMonth+'.'+this.selectedYear;
	}
});