var LocationSearch	= new Class({
	
	initialize: function() {
		this.form	= $('location-search');
		this.form.getElements('input[name=type]').addEvent('click', this.toggleSearchType.bind(this));
		
		this.region	= this.form.getElement('select[name=region]').addEvent('change', this.loadFacilities.bind(this));
		this.hosRegion	= this.form.getElement('select[name=hospital-region]').addEvent('change', this.loadHospitals.bind(this));
		this.toggleSearchType();
		this.loadFacilities();
		this.loadHospitals();
	},
	
	toggleSearchType: function() {
		var type	= this.form.getElement('input[name=type][checked]').get('value');
		this.form.getElements('fieldset').setStyle('display', 'none');
		$('search-type-'+type).setStyle('display', '');
	},
	
	loadFacilities: function() {
		$('facility-select').empty();
		var rid	= this.region.get('value');
		if(rid == '') return;
		
		new Request.HTML({
			url: Site.url+'/locations/facility-list',
			update: $('facility-select')
		}).post({'rid':rid});
	},
	
	loadHospitals: function() {
		$('hospital-select').empty();
		var rid	= this.hosRegion.get('value');
		if(rid == '') {
			$('hospital-text').setStyle('display', '');
			return;
		} else {
			$('hospital-text').setStyle('display', 'none');
		}
		
		var url		= new URI();
		var params	= url.getData();
		
		new Request.HTML({
			url: Site.url+'/request/hospital-list',
			update: $('hospital-select')
		}).get({
			'rid': rid,
			'format': 'view',
			'hospital_id': params.hospital_id
		});
	}
	
});

window.addEvent('domready', function() { 
	new LocationSearch(); 
	new AutoComplete.ZipCode($('location-zip'));
	new AutoComplete.City($('location-city'));
	new AutoComplete.Hospital($('location-hospital'));
} );
