var Geo = new Class({
	initialize: function(id, targ) {
		this.country = $('geo-country-'+id);
		this.region = $('geo-region-'+id);
		this.city = $('geo-city-'+id);
		this.target = $(targ);
		this.partial = false;
		this.def = {country: 0, region: 0, city: 0};
		this.first = true;
	},
	populate: function(fld, data, type) {
		var st = ((type != 'country') && this.partial)?1:0;
		for (var i=fld.options.length-1; i>=st; i--) {
			fld.options[i] = null;
		}
		for (var i=0; i<data.length; i++) {
			var sel = (this.def[type] == data[i][type+'_id']);
			fld.options[st+i] = new Option(data[i].name, data[i][type+'_id'], sel, sel);
		} 
	},
	setDefault: function(def) {
		$extend(this.def, def);
		return this;
	},
	setPartial: function(val) {
		this.partial = val;
		return this;
	},
	toggle: function() {
		new Request.JSON({
			url: '/city_ajax.php',
			onSuccess: this.toggleCallback.bind(this)
		}).get();
	},
	toggleCallback: function(data) {
		this.populate(this.country, data, 'country');
		this.country.addEvent('change', this.toggleRegion.bind(this));
		this.toggleRegion();
	},
	toggleRegion: function() {
		new Request.JSON({
			url: '/city_ajax.php',
			onSuccess: this.toggleRegionCallback.bind(this)
		}).get({country: this.country.options[this.country.selectedIndex].value});
	},
	toggleRegionCallback: function(data) {
		this.populate(this.region, data, 'region');
		this.region.addEvent('change', this.toggleCity.bind(this));
		this.toggleCity();
	},
	toggleCity: function() {
		if (this.partial && (this.region.selectedIndex == 0)) {
			this.populate(this.city, [], 'city');
			this.updateTarget();
			return;
		}
		new Request.JSON({
			url: '/city_ajax.php',
			onSuccess: this.toggleCityCallback.bind(this)
		}).get({region: this.region.options[this.region.selectedIndex].value});
	},
	toggleCityCallback: function(data) {
		this.populate(this.city, data, 'city');
		this.city.addEvent('change', this.updateTarget.bind(this));
		this.updateTarget();
	},
	updateTarget: function() {
		this.target.value = this.country.options[this.country.selectedIndex].text;
		if (!this.partial || (this.region.selectedIndex > 0)) {
			this.target.value += ', '+this.region.options[this.region.selectedIndex].text;
		}
		if (!this.partial || (this.city.selectedIndex > 0)) {
			this.target.value += ', '+this.city.options[this.city.selectedIndex].text;
		}
		if (this.first) {
                  this.first = false; 
                } else {
                } 
	}
});

