var Registration = {
	countryChanged : function(select) {
		countryId = select.options[select.selectedIndex].value;
		Registration.clearTowns();
		Registration.updateRegions(countryId);
	},

	regionChanged : function(select) {
		regionId = select.options[select.selectedIndex].value;
		Registration.clearTowns();
		Registration.updateTowns(regionId);
	},

	updateRegions : function(countryId) {
		var request = new Request.JSON({
			url: '/locations.js?parent_id=' + countryId,
			method: 'get',
			onComplete: function(json) {
				select = document.getElementById('region2');
				select.options.length = 0;
				addOption(select, '', '');
				for (var i = 0; i < json.length; i++) {
					addOption(select, json[i][1], json[i][0]);
				}
			}
		}).send();
	},

	updateTowns : function(regionId) {
		var request = new Request.JSON({
			url: '/locations.js?parent_id=' + regionId,
			method: 'get',
			onComplete: function(json) {
				towns = document.getElementById('towns2');
				towns.innerHTML = '';
				
				selectAll = document.createElement('A');
				selectAll.setAttribute('href', 'javascript:void(0);');
				selectAll.setAttribute('onclick', 'Registration.selectAllTowns();');
				selectAll.innerHTML = 'Select all';

				clearAll = document.createElement('A');
				clearAll.setAttribute('href', 'javascript:void(0);');
				clearAll.setAttribute('onclick', 'Registration.clearAllTowns();');
				clearAll.innerHTML = 'Clear all';

				spacer = document.createElement('span');
				spacer.innerHTML = ' | ';

				towns.appendChild(selectAll);
				towns.appendChild(spacer);
				towns.appendChild(clearAll);
				towns.appendChild(document.createElement('BR'));

				for (var i = 0; i < json.length; i++) {
					Registration.addTown(json[i][1], json[i][0]);
				}
			}
		}).send();
	},

	addTown : function(name, value) {
		container = document.getElementById('towns2');

		div = document.createElement('DIV');
		div.setAttribute('class', 'checkbox');

		checkbox = document.createElement('INPUT');
		checkbox.setAttribute('type', 'checkbox');
		checkbox.setAttribute('name', 'locations[]');
		checkbox.setAttribute('id', 'town_' + value);
		checkbox.setAttribute('value', value);
	
		div.appendChild(checkbox);

		label = document.createElement('LABEL');
		label.setAttribute('for', 'town_' + value);
		label.innerHTML = name;

		div.appendChild(label);

		container.appendChild(div);
	},

	clearTowns : function() {
		document.getElementById('towns2').innerHTML = '';
	},

	selectAllTowns : function() {
		$$('.checkbox input').each(function(el) { el.checked = true; });
	},

	clearAllTowns : function() {
		$$('.checkbox input').each(function(el) { el.checked = false; });
	}
}
