/*
# $Id$
*/

/*
# @namespace PropertyLocation
*/
var PropertyLocation = {

	/*
	# @variable object config
	# Stores configuration settings.
	#
	# string jsonField	= ID of the hidden field that stores JSON location structure
	*/
	config: {
		jsonField: 'fe-propertylocation'
	},

	/*
	# @function void prepareUi( object config )
	# config	= Configuration settings
	#
	# Prepare the UI.
	#
	# See "PropertyLocation.config" for valid configuration variables.
	*/
	prepareUi: function(config) {

		// Handler: Property postcode
		$$('#loc-postcode input').addEvent('change', function() {
	
			// If the postcode is usable (contains enough characters), then start
			// populating the other location fields
			var postcode = $$('#loc-postcode input')[0].value;
			//if(postcode.match(/^[a-z]{1,2}[0-9]{1,2}/i)) {
				var pl = JSON.decode($(PropertyLocation.config.jsonField).value);
				pl.postcode = postcode;
				pl.region = pl.county = pl.city = pl.neighbourhood = null;
				$(PropertyLocation.config.jsonField).value = JSON.encode(pl);
				PropertyLocation.reload('postcode');
			//}
		});
		$$('#loc-postcode input').addEvent('keyup', function(ev) {
			if(ev.key=='enter') {
				this.fireEvent('change');
			}
		});
	
		// Handler: Property region
		$$('#loc-region select').addEvent('change', function() {
			var pl = JSON.decode($(PropertyLocation.config.jsonField).value);
			pl.region = this.value;
			pl.postcode = pl.county = pl.city = pl.neighbourhood = null;
			$(PropertyLocation.config.jsonField).value = JSON.encode(pl);
			PropertyLocation.reload('region');
		});
	
		// Handler: Property county
		$$('#loc-county select').addEvent('change', function() {
			var pl = JSON.decode($(PropertyLocation.config.jsonField).value);
			pl.county = this.value;
			pl.city = pl.neighbourhood = null;
			$(PropertyLocation.config.jsonField).value = JSON.encode(pl);
			PropertyLocation.reload('county');
		});
	
		// Handler: Property city
		$$('#loc-city select').addEvent('change', function() {
			var pl = JSON.decode($(PropertyLocation.config.jsonField).value);
			pl.city = this.value;
			pl.neighbourhood = null;
			$(PropertyLocation.config.jsonField).value = JSON.encode(pl);
			PropertyLocation.reload('city');
		});
	
		// Handler: Property neighbourhood
		$$('#loc-neighbourhood select').addEvent('change', function() {
			var pl = JSON.decode($(PropertyLocation.config.jsonField).value);
			pl.neighbourhood = this.value;
			$(PropertyLocation.config.jsonField).value = JSON.encode(pl);
			PropertyLocation.reload('neighbourhood');
		});
	},

	/*
	# @function void reloadPropertyLocation( string changer )
	# changer	= The field that has caused this change
	#
	# Reloads the dropdown(s) according to any changes made to the property location
	# UI elements.
	*/
	propertyReloaderBusy: false,
	propertyLocationCache: {},
	reload: function(changer, data) {
	
		// Pull data from cache if it's available
		if(PropertyLocation.propertyLocationCache[$(PropertyLocation.config.jsonField).value]) {
			data = PropertyLocation.propertyLocationCache[$(PropertyLocation.config.jsonField).value];
		}
	
		// Populate if data has been defined
		if(data) {
	
			// Get current location data
			var pl = JSON.decode($(PropertyLocation.config.jsonField).value);
	
			// Populate: Postcode
			var elPostcode = $$('#loc-postcode input')[0];
			var re = new RegExp("^"+data.selected.postcode, "i");
			elPostcode.value = elPostcode.value.match(re) ? elPostcode.value : (data.selected.postcode===null ? '' : data.selected.postcode);
	
			// Populate: Region
			var elRegion = $$('#loc-region select')[0].empty();
			(new Element('option', {value: '', html: '---'})).inject(elRegion);
			for(var i=0; i<data.region.length; i++) {
				(new Element('option', {value: data.region[i], html: data.region[i]})).inject(elRegion);
			}
			elRegion.value = pl.region = data.selected.region;
	
			// Populate: County
			var elCounty = $$('#loc-county select')[0].empty();
			(new Element('option', {value: '', html: '---'})).inject(elCounty);
			for(i=0; i<data.county.length; i++) {
				(new Element('option', {value: data.county[i], html: data.county[i]})).inject(elCounty);
			}
			elCounty.value = pl.county = data.selected.county;
	
			// Populate: City
			var elCity = $$('#loc-city select')[0].empty();
			(new Element('option', {value: '', html: '---'})).inject(elCity);
			for(i=0; i<data.city.length; i++) {
				(new Element('option', {value: data.city[i], html: data.city[i]})).inject(elCity);
			}
			elCity.value = pl.city = data.selected.city;
	
			// Populate: Neighbourhood
			var elNeighbourhood = $$('#loc-neighbourhood select')[0].empty();
			(new Element('option', {value: '', html: '---'})).inject(elNeighbourhood);
			for(i=0; i<data.neighbourhood.length; i++) {
				(new Element('option', {value: data.neighbourhood[i], html: data.neighbourhood[i]})).inject(elNeighbourhood);
			}
			elNeighbourhood.value = pl.neighbourhood===null ? '' : pl.neighbourhood;
	
			// Cache
			PropertyLocation.propertyLocationCache[$(PropertyLocation.config.jsonField).value] = data;
	
			// Store current location data
			$(PropertyLocation.config.jsonField).value = JSON.encode(pl);
		
			// End
			PropertyLocation.propertyReloaderBusy = false;
			$$('#loc-fields input,#loc-fields select').set('disabled', false);
			if(changer=='postcode') {
				$$('#loc-postcode input')[0].blur();
				$$('#loc-postcode input')[0].focus();
			}
		}
	
		// Load from server
		else {
	
			// Don't oeprate if we're already busy loading
			if(PropertyLocation.propertyReloaderBusy) {
				return false;
			}
			PropertyLocation.propertyReloaderBusy = true;
		
			// Disable all fields
			$$('#loc-fields input,#loc-fields select').set('disabled', true);
		
			// Load data set from server
			var req = new Request({
				url: '/geo/all-by-object',
				method: 'get',
				onComplete: function(r) {
		
					// Check for errors
					r = JSON.decode(r);
					if(r.errorCode!=0) {
						alert(r.errorMessage);
						PropertyLocation.propertyReloaderBusy = false;
						$$('#loc-fields input,#loc-fields select').set('disabled', false);
						return;
					}
		
					// Load
					PropertyLocation.reload(changer, r);
				}
			});
			req.send($H({
				object: $(PropertyLocation.config.jsonField).value
			}).toQueryString());
		}
	}
};