var Selector = Class.create();
Selector.prototype = {
	initialize: function(){
		this.country = $('country_id');
		Event.observe('country_id', 'change', this.country_changed.bind(this));
	},
	
	country_changed: function() {
        this.clear_distr();
		var selected = this.country.options[this.country.selectedIndex].value;
		if (selected != '#') {
			new Ajax.Updater('selcity', '/dealer/citylist/', {
				parameters: { country: selected },
				onComplete: function() {this.prepare_city().bind(this);}.bind(this)
			});	
		} else {
			$('city_id').hide();
			this.clear_distr();
		}
	},
	
	prepare_city: function () {
		try {
			var city = $('city_id');
			if (city.length > 2) {
				Event.observe('city_id', 'change', this.city_changed.bind(this));
			} else {
				city.hide();
				city.selectedIndex = 1;
				this.city_changed();
			}
		} catch (e) {};
	},

	city_changed: function() {
		this.clear_distr();
		var city = $('city_id');
		var selected = city.options[city.selectedIndex].value;
        var country_selected = this.country.options[this.country.selectedIndex].value;
		if (selected != '#') {
			new Ajax.Updater('distributor_box', '/dealer/distibutor/', {
				parameters: { city: selected, country: country_selected }
			});	
		} else {
			this.clear_distr();
		}
	},
	
	clear_distr: function() {
		document.getElementById('distributor_box').innerHTML = "";
	}
}


Event.observe(window, 'load', function() {
  s = new Selector();
});