function enableControls() {
	enable('ibeType', 'countryList', 'regionList', 'destinationList', 'dateIntervalList', 'submit-button');
}

function disableControls() {
	disable('ibeType', 'countryList', 'regionList', 'destinationList', 'dateIntervalList', 'submit-button');
}

function dateListChanged(select) {
	if (select.options[select.selectedIndex].value == "EXACT") {
		disableControls();
		var countryId = dwr.util.getValue("country") == "ALL" ? null : dwr.util.getValue("country");
		var regionId = dwr.util.getValue("region") == "ALL" ? null : dwr.util.getValue("region");
		var ibeConfigId = dwr.util.getValue("ibeType");
		AjaxSearchUtil.getStartDates(countryId, regionId, ibeConfigId, recreateCalendar);
	} else {
		jQuery('#calendarRow').hide();
		jQuery('#searchDateDiv').hide();
		var searchDateRow = dwr.util.byId('searchDateRow');
		if (searchDateRow != null) {
			searchDateRow.style.visibility = 'hidden';
		}
	}
}

function LZ(x) { return (x < 0 || x > 9 ? "" : "0") + x; }

function parseDate(ds) {
	ds = ds.replace(/[^0-9]/g, '');
	var d = new Date(ds.substr(0, 4), parseInt(ds.substr(4, 2), 10) - 1, ds.substr(6, 2));
	return d; 
}

function showCalendar() {
	jQuery('#calendarRow:hidden').slideDown('slow');
}

function dateChanged(date) {
	dateString = date;
	dwr.util.setValue('searchDate', date);
	jQuery('#calendarRow').slideUp('slow');
}

var selectableDates;
function recreateCalendar(dates) {
	selectableDates = dates;
	
	var max;
	if (selectableDates.length == 0) {
		var today = new Date();
		selectableDates[0] = '' + today.getFullYear() + LZ(today.getMonth() + 1) + LZ(today.getDate());
		max='2y';
	} else {
		max = parseDate(selectableDates[selectableDates.length-1]);
	} 
	
	var min = parseDate(selectableDates[0]);
	
	recreateCalendarHook(min, max);
	enableControls();
}

function checkSelectableDates(date) {
	for (i = 0; i < selectableDates.length; i++) { 
		if ('' + date.getFullYear() + LZ(date.getMonth() + 1) + LZ(date.getDate()) == selectableDates[i]) { 
			return [true, '']; 
		} 
	} 
	return [false, '']; 
}

// TODO refactor the multiple AJAX calls into a single one 
function ibeTypeChanged(radioButton) {
	disableControls();
	var selectedCountry = resetList("countryList", countryListDefaultOptions);
	
	var language = dwr.util.getValue("language");
	var ibeConfigId = radioButton.value;

	//TODO:remove-me???
	AjaxSearchUtil.getAgentHomeUrl(ibeConfigId, friendlyUrl, function(homeUrl) {
		if (homeUrl != null && homeUrl != '') {
			dwr.util.byId('searchForm').action = homeUrl;
		}
	});
	
	//TODO:1
	AjaxSearchUtil.getIbeCountryList(language, ibeConfigId, function(countryList) {
		dwr.util.addOptions("countryList", countryList, "countryId", "name");
		dwr.util.setValue('countryList', selectedCountry);
		countryListChanged();
	});
	
	//TODO:1
	AjaxSearchUtil.getIbeSearchAttributes(agentId, ibeConfigId, friendlyUrl, function(attributes) {
		dwr.util.removeAllRows('searchAttributesTable',
			{ filter: function(tr) { return tr.id != 'attributeRow'; }});
		if (attributes.length > 0) {
			for (var i = 0; i < attributes.length; i++) { 
				var id = attributes[i].searchKey;
				var clone = dwr.util.cloneNode('attributeRow', { idSuffix:id });
				clone.style.display = '';
	
				dwr.util.setValue('attibuteKey' + id, id);
				dwr.util.setValue('attributeName' + id, attributes[i].name);
			}
			show('searchAttributes');
		} else {
			hide('searchAttributes');
		}
	});
	
	//TODO: 1 : Affiliate miatt? egyesíthető?
	
	handleDestinationDisplay();
}

function countryListChanged() {
	var selectedRegion = resetList("regionList", regionListDefaultOptions);

	dateString = '';
	dwr.util.setValue('searchDate', '');
	
	var countryId = dwr.util.getValue("country");
	if (countryId != "ALL") {
		disableControls();
		var language = dwr.util.getValue("language");
		var ibeConfigId = dwr.util.getValue("ibeType");
	
		AjaxSearchUtil.getRegionsForCountry(countryId, language, ibeConfigId, function(regionList) {
			dwr.util.addOptions("regionList", regionList, "regionId", "name");
			dwr.util.setValue('regionList', selectedRegion);
			// deferred invocation
			regionListChanged();
		});
	} else {
		// immediate invocation
		regionListChanged();
	}
}

function regionListChanged() {
	var currentDateInterval = resetList("dateIntervalList", dateIntervalListDefaultOptions);
	var selectedDestination = resetList("destinationList", destinationListDefaultOptions);
	disableControls();
	
	var countryId = dwr.util.getValue("country") == "ALL" ? null : dwr.util.getValue("country");
	var regionId = dwr.util.getValue("region") == "ALL" ? null : dwr.util.getValue("region");
	var language = dwr.util.getValue("language");
	var ibeConfigId = dwr.util.getValue("ibeType");

	if (destinationComboEnabled && regionId != null) {
		AjaxSearchUtil.getDestinationsForRegion(regionId, language, ibeConfigId,
			function(destinationList) {
				dwr.util.addOptions("destinationList", destinationList, "destinationId", "name");
				dwr.util.setValue("destinationList", selectedDestination);
			}
		);
	}
	
	AjaxSearchUtil.getIntervalsForRegion(countryId, regionId, language, ibeConfigId,
		function(intervalList) {
			dwr.util.addOptions("dateIntervalList", intervalList, "key", "value");
			dwr.util.setValue("dateIntervalList", currentDateInterval);
			dateListChanged(dwr.util.byId('dateIntervalList'));
			enableControls();
		}
	);
}

function doSearch(form) {
	if (dwr.util.getValue('dateIntervalList') == 'EXACT' && dwr.util.getValue('searchDate') == '') {
		alert(msgSelectDate);
		return false;
	}

	var url = '';
	
	if (dwr.util.getValue('countryList') != 'ALL') {
		var countryList = dwr.util.byId('countryList');
		url += '/' + canonicalString(countryList.options[countryList.selectedIndex].text);
	}
	if (dwr.util.getValue('regionList') != 'ALL') {
		var regionList = dwr.util.byId('regionList');
		url += '/' + canonicalString(regionList.options[regionList.selectedIndex].text);
	}
	
	var destinationList = dwr.util.byId('destinationList');
	if (destinationList != null && dwr.util.getValue('destinationList') != 'ALL') {
		url += '/' + canonicalString(destinationList.options[destinationList.selectedIndex].text);
	}
	
	if (url != '') {
		url += friendlyUrl;
		var ibeTypes = document.getElementsByName('ibeType');
		if (ibeTypes.length > 1) {
			url += '/' + canonicalString(getAgentConfigText());
		}
		form.action = url;
	}
	
	// forget the filters set by the user for a new search
	form.categoryFilter.value = 'ALL';
	form.boardFilter.value = 'ALL';

	return true;
}

function getAgentConfigText() {
	var ibeTypes = document.getElementsByName('ibeType');
	for (var i = 0; i < ibeTypes.length ; i++) {
		if (ibeTypes.item(i).type == 'hidden') {
			// if the current IBE look and feel does not support multiple configurations per page
			return dwr.util.getValue('ibeTypeLabel');
		}
		if (ibeTypes.item(i).checked) {
			var span = ibeTypes.item(i).parentNode.getElementsByTagName('span').item(0);
			return span.innerHTML;
		}
	}
}

function doSearchByProductCode(form) {
	// code without the 'HUN_' prefix
	var code = form.code.value;
	
	// 12345X		->	HUN__12345X
	// FERN_12345X	->	HUN_FERN_12345X
	code = code.indexOf('_') > -1 ? 'HUN_' + code : 'HUN__' + code;
	
	var language = dwr.util.getValue('language');
	AjaxSearchUtil.searchByProductCode(code, language, function(url) {
		if (url != null) {
			var f = dwr.util.byId('codeSearchForm');
			f.action = url;
			f.submit();
		} else {
			show('codeError');
			setTimeout("jQuery('#codeError').slideUp('slow')", 5000);
		}
	});
	
	return false;
}

function selectRegional(country, countryName, region, regionName) {
	prepareLoading();
	dwr.util.setValue("countryList", country);
	dwr.util.addOptions("regionList", [ { value:region, text:regionName } ], "value", "text");
	dwr.util.setValue("regionList", region);

	var url = '/' + canonicalString(countryName) + '/' + canonicalString(regionName)
			+ friendlyUrl + '/' + canonicalString(getAgentConfigText());
			
	var form = dwr.util.byId("searchForm");
	form.action = url;
	form.submit();
}

function resetInputHelperAttributes() {
	var div = document.getElementById('inputHelpersAccordion');
	
	var inputs = div.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) {
		var name = inputs.item(i).getAttribute('name');
		dwr.util.setValue(name, null);
	}
	
	var selects = div.getElementsByTagName('select');
	for (var i = 0; i < selects.length; i++) {
		var name = selects.item(i).getAttribute('name');
		dwr.util.setValue(name, '-');
	}
	
	hide('inputHelperText');
}

function handleDestinationDisplay() {
	var country = dwr.util.getValue('countryList');
	if (country == '') {
		dwr.util.byId('kereso').style.display = 'none';
		dwr.util.byId('no-offer').style.display = '';
	} else {
		dwr.util.byId('kereso').style.display = '';
		dwr.util.byId('no-offer').style.display = 'none';
	}
}
