var searchCountryId = '';
var searchCityId = '';

$(function() {
	$('#country').autocomplete(baseUrl + '/ajax/getcountries/', {
		width: 260,
		selectFirst: false
	});
	
	$('#country').result(function(event, data, formatted) {
		searchCountryId = data[1];
		searchRebindAll();
	});
	
	$('#country').blur(function(){
		if ('' == $('#country').val()) {
			searchCountryId = '';
			searchRebindAll();
		}
	});

	$('#city').autocomplete(baseUrl + '/ajax/getcities/', {
		width: 260,
		selectFirst: false		
	});
	
	$('#city').result(function(event, data, formatted) {
		searchCityId = data[1];
		searchRebindAll();
	});

	$('#city').blur(function(){
		if ('' == $('#city').val()) {
			searchCityId = '';
			searchRebindAll();
		}
	});
	
	$('#hotel_name').autocomplete(baseUrl + '/ajax/gethotels/', {
		width: 260,
		selectFirst: false		
	});
	
	$('#hotel_name').result(function(event, data, formatted) {
		searchRebindAll();
	});
});

function searchFlushCache() {
	$('#city').flushCache();
	$('#country').flushCache();
	$('#hotel_name').flushCache();
}

function searchRebindAll() {
	searchFlushCache();
	searchRebindCityAutoComplete();
	searchRebindHotelAutoComplete();
}

function searchRebindCityAutoComplete() {
	// Does not work
//	$('#city').unautocomplete();
	
	$('#city').removeData('events');
	
	$('#city').autocomplete(baseUrl + '/ajax/getcities/', {
		width: 260,
		selectFirst: false,		
		extraParams: {country: searchCountryId}
	});

	$('#city').result(function(event, data, formatted) {
		searchCityId = data[1];
		searchFlushCache();
		searchRebindHotelAutoComplete();
	});

	$('#city').blur(function(){
		if ('' == $('#city').val()) {
			searchCityId = '';
			searchRebindHotelAutoComplete();
		}
	});
}

function searchRebindHotelAutoComplete() {
	$('#hotel_name').removeData('events')
	
	$('#hotel_name').autocomplete(baseUrl + '/ajax/gethotels/', {
		width: 260,
		selectFirst: false,		
		extraParams: {country: searchCountryId, city: searchCityId}
	});

	$('#hotel_name').result(function(event, data, formatted) {
		searchFlushCache();
	});
}
