function enableControls() {
	enable('ibeType', 'countryList', 'regionList', 'destinationList', 'dateIntervalList', 'submit-button');
}

function disableControls() {
	disable('ibeType', 'countryList', 'regionList', 'destinationList', 'dateIntervalList', 'submit-button');
}

function getCountryId() {
	var countryId = dwr.util.getValue("countryList");
	return (countryId == "ALL" || countryId == "-1" || countryId == "") ? null : countryId;
}

function getRegionId() {
	var regionId = dwr.util.getValue("regionList");
	return (regionId == "ALL" || regionId == "-1"|| regionId == "") ? null : regionId;
}

function getDestinationId() {
	var destinationList = dwr.util.byId('destinationList');
	if (destinationList != null) {
		var destinationId = dwr.util.getValue('destinationList');
		return (destinationId == "ALL" || destinationId == "-1" || destinationId == "") ? null : destinationId;
	}
	
}

var intervalRegexp = /date BETWEEN ([0-9]{4})\.([0-9]{2})\.([0-9]{2}) AND ([0-9]{4})\.([0-9]{2})\.([0-9]{2})/i;

function getDateInterval() {
	var dateInterval = dwr.util.getValue("dateIntervalList");

	if (dateInterval == "all" || dateInterval == "-1"|| dateInterval == "") {
		return null;
	} else if (dateInterval == "exact") {
		return dwr.util.getValue("date_search_idopont").replace(/\./g, "");
	}
	
	var matches = dateInterval.match(intervalRegexp);
	if (matches) {
		var startDate = matches[1] + matches[2];
		
		if (startDate == matches[4] + matches[5]) {
			return startDate;
		} else {
			var date = parseInt(matches[2] + matches[3], 10);
			return matches[1] + (date >= parseInt(seasonStartSummer.replace(".", ""), 10) &&
					date < parseInt(seasonStartWinter.replace(".", ""), 10) ? "S" : "W");
		}
	}
	
	return null;
}

function dateListChanged(select) {
	if (select.selectedIndex != -1) {
		if (dwr.util.getValue("dateIntervalList").toLowerCase() == "exact") {
			disableControls();
			var countryId = getCountryId();
			var regionId = getRegionId();
			var destinationId = getDestinationId();
			var ibeConfigId = dwr.util.getValue("ibeType");
			AjaxSearchUtil.getStartDates(countryId, regionId, destinationId, ibeConfigId, recreateCalendar);
			// must check for null (bug?)
			if (jQuery("#date_holder") != null) {
				jQuery("#date_holder").show();
				jQuery("#date_holder_items").show();
			}
			jQuery("#searchDateRow").css('visibility', 'visible');
		} else {
			jQuery('#calendarRow').hide();
			jQuery('#searchDateDiv').hide();
			var searchDateRow = dwr.util.byId('searchDateRow');
			if (searchDateRow != null) {
				searchDateRow.style.visibility = 'hidden';
			}
			// must check for null (bug?)
			if (jQuery("#date_holder") != null) {
				jQuery("#date_holder").hide();
				jQuery("#date_holder_items").hide();
			}
		}
	}
	
	if (jQuery("#slider").length > 0) {
		var dateInterval = dwr.util.getValue("dateIntervalList").toLowerCase();
		if (dateInterval != "exact") {
			refreshSlider();
		}
	}
}

function refreshSlider() {
	var countryId = getCountryId();
	var regionId = getRegionId();
	var destinationId = getDestinationId();
	var ibeConfigId = dwr.util.getValue("ibeType");
	var dateInterval = dwr.util.getValue("dateIntervalList").toLowerCase();
	var startDate = null;
	if (dateInterval == "exact") {
		startDate = dwr.util.getValue("date_search_idopont");
	}
	AjaxSearchUtil.getPriceRange(countryId, regionId, destinationId, ibeConfigId, dateInterval, startDate,
		recreateSlider);
}

function recreateSlider(rangeValues) {
	recreateSliderHook(rangeValues[0], rangeValues[1]);
	enableControls();
}

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 (var i = 0; i < selectableDates.length; i++) { 
		if ('' + date.getFullYear() + LZ(date.getMonth() + 1) + LZ(date.getDate()) == selectableDates[i]) { 
			return [true, '']; 
		} 
	} 
	return [false, '']; 
}

function ibeTypeChanged(radioButton) {
	disableControls();
	var selectedCountry = resetList("countryList", countryListDefaultOptions);
	
	var language = dwr.util.getValue("language");
	var ibeConfigId = radioButton.value;

	AjaxSearchUtil.getIbeConfigData(agentId, ibeConfigId, friendlyUrl, language, function(configData) {
		dwr.util.setValue('seoUrl', configData.seoUrl);
		
		var attributes = configData.searchAttributes;
		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');
			}
		
		dwr.util.addOptions("countryList", configData.countries, "countryId", "name");
		dwr.util.setValue('countryList', selectedCountry);
		countryListChanged();
	});
	
	handleDestinationDisplay();
}

function countryListChanged() {
	var selectedRegion = resetList("regionList", regionListDefaultOptions);
	if (typeof destinationListDefaultOptions != "undefined") {
		resetList("destinationList", destinationListDefaultOptions);
	}
	
	dateString = '';
	dwr.util.setValue('searchDate', '');
	
	var countryId = getCountryId();
	if (countryId != null) {
		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
			stylishRegionListChanged();
		});
	} else {
		// immediate invocation
		stylishRegionListChanged();
	}
	
	
}

function stylishRegionListChanged() {
	// update jQuery Stylish Select options
	if (typeof(noStylish) == "undefined") {
		if (jQuery('#regionList') != null && jQuery('#regionList').resetSS) {
			jQuery('#regionList').resetSS();
			jQuery('#regionList').unbind('change').bind('change', ssRegionChanged);
		}
	}
	
	regionListChanged();
}

function stylishDestinationListChanged() {
	// update jQuery Stylish Select options
	if (typeof(noStylish) == "undefined") {
		if (typeof(detailedSearch) != "undefined" && detailedSearch == 0) {
			destinationListChanged();
			return;
		}
		if (jQuery('#destinationList') != null && jQuery('#destinationList').resetSS) {
			jQuery('#destinationList').resetSS();
			jQuery('#destinationList').unbind('change').bind('change', ssDestinationChanged);
		}
	}
	destinationListChanged();
}

function regionListChanged() {
	disableControls();
	
	var regionId = getRegionId();
	var language = dwr.util.getValue("language");
	var ibeConfigId = dwr.util.getValue("ibeType");

	if (destinationComboEnabled && regionId != null) {
		AjaxSearchUtil.getDestinationsForRegion(regionId, language, ibeConfigId,
			function(listOfDestinations) {
				var selectedDestination = resetList("destinationList", destinationListDefaultOptions);
				dwr.util.addOptions("destinationList", listOfDestinations, "destinationId", "name");
				dwr.util.setValue("destinationList", selectedDestination);
				stylishDestinationListChanged();
			}
		);
	}  else {
		stylishDestinationListChanged();
	}
	
}

function destinationListChanged() {
	var currentDateInterval = resetList("dateIntervalList", dateIntervalListDefaultOptions);
	
	var countryId = getCountryId();
	var regionId = getRegionId();
	var language = dwr.util.getValue("language");
	var ibeConfigId = dwr.util.getValue("ibeType");
	
	AjaxSearchUtil.getIntervalsForRegion(countryId, regionId, language, ibeConfigId,
		function(intervalList) {
			dwr.util.addOptions("dateIntervalList", intervalList, "key", "value");
			dwr.util.setValue("dateIntervalList", currentDateInterval);
			
			if (navigator.appVersion.indexOf("MSIE 7.")==-1) {
				if (jQuery('#dateIntervalList') != null && jQuery('#dateIntervalList').resetSS) {
					jQuery('#dateIntervalList').resetSS();
					jQuery('#dateIntervalList').unbind('change').bind('change', ssDateChanged);
				}
			}
			else {
				if (dwr.util.byId('dateIntervalList') != null
						&& dwr.util.byId('dateIntervalList').resetSS) {
					dwr.util.byId('#dateIntervalList').resetSS();
					dwr.util.byId('#dateIntervalList').unbind('change').bind('change', ssDateChanged);
				}
			}
			
			dateListChanged(dwr.util.byId("dateIntervalList"));
			enableControls();
		}

	);
}

function doSearch(form) {
	if (dwr.util.getValue('dateIntervalList') == 'EXACT' && dwr.util.getValue('searchDate') == '') {
		alert(msgSelectDate);
		return false;
	}

	if (typeof detailedSearch != "undefined") {
		dwr.util.setValue("detailedSearch", detailedSearch);
		
		if (detailedSearch == 1 && form.searchString.value != "") {
			return doFreeSearch(form);
		} else if (detailedSearch == 0) {
			form.searchString.value = "";
		}
	}

	var url = '';
	if (site && site.indexOf('affiliate.') == 0) {
		url += dwr.util.getValue('friendlyUrl');
	}
	
	var dateInterval = getDateInterval();
	
	if (getCountryId() != null) {
		var countryList = dwr.util.byId('countryList');
		url += '/' + canonicalString(countryList.options[countryList.selectedIndex].text);
	} else if (dateInterval != null || (site && site.indexOf('affiliate.') == 0)) {
		url += '/barmely-orszag';
	}
		
	if (getRegionId() != null) {
		var regionList = dwr.util.byId('regionList');
		url += '/' + canonicalString(regionList.options[regionList.selectedIndex].text);
	}
	
	if (getDestinationId() != null) {
		var destinationList = dwr.util.byId('destinationList');
		url += '/' + canonicalString(destinationList.options[destinationList.selectedIndex].text);
	}

	if (url != '') {
		url += document.getElementsByName('seoUrl').item(0).value;
	}
	
	if (dateInterval != null) {
		url += "/" + dateInterval;
	}
	
	if (url != '') {
		form.action = url;
	} else if (site == 'neckermann.hu' || 'lastminute.hu') {
		blockuiPopup('#searchFormAlert');
		return false;
	} else if (emptySearchEnabled) {
		alert(searchErrorTooFewParameters);
		return false;
	}
	
	
	// forget the filters set by the user for a new search
	if (typeof form.categoryFilter != 'undefined') {
		form.categoryFilter.value = 'ALL';
	}
	if (typeof form.boardFilter != 'undefined') {
		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 doFreeSearch(form) {
	$.blockUI({ message: jQuery('#loading'), css: { border: 'none' }});
	
	AjaxSearchUtil.freeSearch(form.searchString.value, dwr.util.getValue('language'), function(data) {
		if (data == null) {
			blockuiPopup('#filterError');
		} else if (data.length == 0) {
			blockuiPopup('#noMatch');
		} else {
			if (data.length == 1) {
				document.location.href = data[0].url;
			} else {
				var list = jQuery("#resultList");
				list.html("");
				for (var i = 0; i < data.length; i++) {
					list.append("<p style='color: #888888;'>" +
						"<a href='" + data[i].url + "'>" + data[i].name + "</a><br />" +
						data[i].location + "<br />["  + data[i].externalId + "]</p>");
				}
				$.blockUI({
				     message: $("#resultListBlock"),
					 css: {
			              width: "410px", height: "210px", top: "150px", left: "285px",
			              border: "0", background: "none", color: "#646464", cursor: "default"
				}});
				$("#resultListBlock .info_top").height($("#resultListBlock .info_top_right").height());
			}
		}
	});
	
	return false;
}

function doFreeSearchTesco(form) {
	var code = form.code.value;
	var language = dwr.util.getValue('language');
	
	AjaxSearchUtil.freeSearch(code, language, function(data) {
		if (data == null) {
			show('codeError');
			setTimeout("jQuery('#codeError').slideUp('slow')", 5000);
		} else if (data.length == 0) {
			show('codeEmpty');
			setTimeout("jQuery('#codeEmpty').slideUp('slow')", 5000);
		} else {
			if (data.length == 1) {
				document.location.href = data[0].url;
			} else {
				var list = jQuery('#codeSearchResult');
				list.html('');

				for (var i = 0; i < data.length; i++) {
					list.append('<p><a href="' + data[i].url + '">' + data[i].name + '</a> ['
						+ data[i].externalId + ']<br/>' + data[i].location + '</p>');
				}
				
				jQuery("#codeSearchPopup").dialog({
					resizable: false, width: 500, modal: true, closeOnEscape: true,
					title: 'Találatok', buttons: { 'Mégsem': codeSearchPopupCancel }
				});
			}
		}
	});
	
	return false;
}

function codeSearchPopupCancel() {
	jQuery(this).dialog('close');
}

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) {
			document.location.href = url;
		} 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)
			 + '/' + 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';
	}
}

