window.addEvent('domready', function() {
	//Transform the edit field by a select field
	oldEdtCity = $('edtCity');
	newEdtCity = $(document.createElement('select'));
	newEdtCity.setAttribute('id', 'edtCity');
	newEdtCity.setAttribute('name', 'city');
	newEdtCity.options[0] = new Option('-- Entrez votre code postal --', '-- Entrez votre code postal --');
	oldEdtCity.parentNode.replaceChild(newEdtCity, oldEdtCity);
	//Adding events to the fields
	$$('input', 'select', 'textarea').each(function(input) {
		input.onfocus = function(e) {
			var target = new Event(e).target;
			$(target).addClass('focus');
			$(target.parentNode).addClass('focus');
		}.bind(this);
		input.onblur = function(e) {
			var target = new Event(e).target;
			$(target).removeClass('focus');
			$(target.parentNode).removeClass('focus');
		};
	});
	//Adding event watcher on the postcode field
	$('edtPostcode').onkeyup = function(e) {
		var target = new Event(e).target;
		if (target.getValue().length == 4) {
			new Ajax('_ajax.php?' + Object.toQueryString({'task': 'postcode', 'cp': $('edtPostcode').getValue()}), { method: 'get', onComplete: function(responseText) {
				//Function that will populate the select with cities returned by the ajax request
				var response = Json.evaluate(responseText);
				var cities = $('edtCity').options;
				cities.length = 0;
				if (response.cities[0] == '') {
					//As the postcode didnt return any city, change the select box into an input so the user can type in the city
					//TODO not yet done, has to change back to a select if a new request is done
					cities[0] = new Option('-- Aucune ville correspondante --', '-- Aucune ville correspondante --');
				}
				else {
					cities[0] = new Option('-- Choisissez --', '-- Choisissez --');
					response.cities.each(function(city) {
						cities[cities.length] = new Option(city, city);
					});
				}
			}}).request();
		}
	};
});
