/**
 * InfoViaKort Search class
 * 
 * @events dateChange
 */

// cookie hack
function getSearchDate() {
	return $('searchDate').value;
}
function setSearchDate(date) {
	$('searchDate').value = date;
}

var InfoViaKortSearch = new Class({
	
	Implements: Events,

	currentDay: null,
	currentMonth: null,
	currentYear: null,
	
	selectedDay: null,
	selectedMonth: null,
	selectedYear: null,
	
	searchForm: null,
	searchButton: null,
	
	searchInput: null,
	searchDaySelect: null,
	searchMonthYearSelect: null,
	
	searchSelectedId: null,
	searchSelectedValue: null,

	autoCompleter: null,
	dateSelect: null,

	initialize: function()
	{
		this.initSearchDate();
		//this.initFynbusSearch();
		this.initAutocompleter();
	},

	initFynbusSearch: function()
	{
		/*
	    $('fynbusSearchButton').addEvent('click', function() {$('fynbusSearchForm').submit();});
	    $('fynbusSearchQuery').addEvent('focus', function() {
	    	if (!this.initialValue) this.initialValue = this.value;
	    	if (this.value == this.initialValue) this.value = '';
	    });
	    $('fynbusSearchQuery').addEvent('blur', function() {
	    	if (!this.value.trim()) this.value = this.initialValue;
	    });*/
	},
	
	initAutocompleter: function()
	{
		this.autoCompleter = new Autocompleter.Request.JSON(this.searchInput, 'url', {
			postVar: 'search',
			customChoices: $('autocompleter-searchresult'),
			selectFirst: false,
			selectMode: 'type-ahead',
			minLength: 2,
			multiple: false,
			separator: ';',
			relative: false,
			injectChoice: function(choice) {
				var el = new Element('li').set('html', this.markQueryValue(choice.text));
				el.inputValue = choice.text;
				el.title = choice.id;
				this.addChoiceEvents(el).inject(this.choices);
			}
		});
	    
	    this.autoCompleter.addEvent('onShow', function(input,result) {
	    	result.removeClass('hide');
	    	result.getParent().removeClass('hide');
	    });
	    
	    this.autoCompleter.addEvent('onSelection', function(input,selection,inputValue,suggestionValue) {
	    	this.searchSelectedId = selection.title;
	    	this.searchSelectedValue = inputValue;
	    }.bind(this));
	},
	
	submitSearch: function()
	{
		// Submit ID from Autocompleter
		if (this.searchSelectedId && this.searchSelectedValue == this.searchInput.value) {
			var currentModule = infoViaKort.getCurrentModule();
			var currentAction = infoViaKort.getModuleAction().substring(0, infoViaKort.getModuleAction().length-1); 
			var currentParameter = infoViaKort.getCurrentParameter();
			infoViaKort.redirect(currentModule + "/" + currentAction + "/" + this.searchSelectedId);
			return;
		}
		this.searchForm.submit();
	},
	
	initSearchDate: function()
	{
		this.searchForm = $('searchForm');
		this.searchButton = $('searchButton');
		
		this.searchForm.addEvent('keypress', function(e) {var event = new Event(e); if (event.key == "enter") this.submitSearch();}.bind(this));
	    this.searchForm.addEvent('submit', function(event) {new Event(event).stop(); this.submitSearch(); return false;}.bind(this));
	    this.searchButton.addEvent('click', this.submitSearch.bind(this));
	    
	    this.searchInput = $('searchQuery');
	    this.searchInput.focus();
	    
	    var currentDate = new Date();

			if (getSearchDate()) {
	    	var cookieDate = getSearchDate();
	    	currentDate.setFullYear(cookieDate.substr(0,4).toInt(),cookieDate.substr(4,2).toInt()-1,cookieDate.substr(6,2).toInt());
			}
	    /*if (Cookie.read('searchDate')) {
	    	var cookieDate = Cookie.read('searchDate');
	    	currentDate.setFullYear(cookieDate.substr(0,4).toInt(),cookieDate.substr(4,2).toInt()-1,cookieDate.substr(6,2).toInt());
	    }*/
	    this.currentDay = currentDate.getDate();
		this.currentMonth = currentDate.getMonth()+1;
		this.currentYear = currentDate.getFullYear();
		
		var searchIntervalStart = $('searchIntervalStart').value;
		var searchIntervalEnd = $('searchIntervalEnd').value;
		var intervalStart = new Date();
		var intervalEnd = new Date();
		intervalStart.setFullYear(searchIntervalStart.substring(0,4).toInt(), (searchIntervalStart.substring(4,6).toInt())-1, searchIntervalStart.substring(6,8).toInt());
		intervalEnd.setFullYear(searchIntervalEnd.substring(0,4).toInt(), (searchIntervalEnd.substring(4,6).toInt())-1, searchIntervalEnd.substring(6,8).toInt());
		this.dateSelect = new DateSelect(intervalStart, intervalEnd);

	   this.searchDaySelect = $('searchDays');
		this.searchMonthYearSelect = $('searchMonthYears');
		
		this.searchDaySelect.addEvent('change', this.searchDayChange.bind(this));
		this.searchMonthYearSelect.addEvent('change', this.searchMonthYearChange.bind(this));
		
		this.searchMonthYearSelect.empty();
		this.searchMonthYearSelect.adopt(this.dateSelect.getMonthOptions(this.currentMonth, this.currentYear));
		
		this.searchMonthYearChange();
	},
	
	searchDayChange: function()
	{
		var updated = this.updateSearchDateValues();
		this.fireSearchDateEvents(updated);
	},
	
	searchMonthYearChange: function()
	{
		var updated = this.updateSearchDateValues();
		this.searchDaySelect.empty();
		this.searchDaySelect.adopt(this.dateSelect.getDayOptions(this.selectedMonth, this.selectedYear, this.selectedDay));
		this.fireSearchDateEvents(updated);
	},
	
	updateSearchDateValues: function()
	{
		var selectedDay = this.dateSelect.getSelectionValue(this.searchDaySelect);
		if (selectedDay) {
			this.selectedDay = selectedDay.toInt();
		} else {
			this.selectedDay = this.currentDay;
		}
		var selectedYearMonth = this.dateSelect.getSelectionValueAsYearMonth(this.searchMonthYearSelect);
		if (selectedYearMonth) {
			this.selectedMonth = selectedYearMonth['month'].toInt();
			this.selectedYear = selectedYearMonth['year'].toInt();
		} else {
			this.selectedMonth = this.currentMonth;
			this.selectedYear = this.currentYear;
		}
		
		if (selectedDay || selectedYearMonth) {
			return true;
		}
		
		return false;
	},
	
	updateSelectionFromInput: function(dateInput)
	{
		if (!dateInput.value) return;
		
		this.selectedDay = dateInput.value.substring(6,8).toInt();
		this.selectedMonth = dateInput.value.substring(4,6).toInt();
		this.selectedYear = dateInput.value.substring(0,4).toInt();
		
		this.searchMonthYearSelect.empty();
		this.searchMonthYearSelect.adopt(this.dateSelect.getMonthOptions(this.selectedMonth, this.selectedYear));

		this.searchDaySelect.empty();
		this.searchDaySelect.adopt(this.dateSelect.getDayOptions(this.selectedMonth, this.selectedYear, this.selectedDay));
		
		var updated = this.updateSearchDateValues();
		this.fireSearchDateEvents(updated);
		
		// Important to reset hidden calendar input to prevent setting last picked calendar date
		dateInput.value = '';
	},
	
	fireSearchDateEvents: function(updated)
	{
		if (!this.searchDaySelect || !this.searchDaySelect.options[0]) return;
		
		var firstDay = this.searchDaySelect.options[0].value;
		var lastDay = this.searchDaySelect.options[this.searchDaySelect.options.length-1].value;
		if (this.selectedDay > lastDay) {
			updated = true;
			this.selectedDay = lastDay;
		} else if (this.selectedDay < firstDay) {
			updated = true;
			this.selectedDay = firstDay;
		}
		if (updated) {
			for (var i=0; i<this.searchDaySelect.options.length; i++) {
				if (this.searchDaySelect.options[i].value == this.selectedDay) {
					this.searchDaySelect.selectedIndex = i;
					break;
				}
			}
			var cookieDate = this.selectedYear.toString() + (this.selectedMonth < 10 ? "0" + this.selectedMonth.toString() : this.selectedMonth.toString()) + (this.selectedDay < 10 ? "0" + this.selectedDay.toString() : this.selectedDay.toString());
			if (this.selectedYear == new Date().getFullYear() && this.selectedMonth == new Date().getMonth()+1 && this.selectedDay == new Date().getDate()) {
				//if (Cookie.read('searchDate')) Cookie.dispose('searchDate', {domain: document.location.host, path: '/'});
				setSearchDate('');
			} else {
				//Cookie.write('searchDate', cookieDate, {domain: document.location.host, path: '/'});
				setSearchDate(cookieDate);
			}
			this.fireEvent('dateChange', {'year':this.selectedYear, 'month':this.selectedMonth, 'day':this.selectedDay});
		}
	}
});