var	currentRequestDepartement	= 0;

$(window).load(function(){
	$("input#departement").keyup(function(e){
		if( $(this).attr("value").length == 2 ) {
			if( $(this).attr("value") == currentRequestDepartement ) {
				return;
			}
			
			currentRequestDepartement	= $(this).attr("value");
			
			var elem = $($("#spinner").html());
			$("#etablissements").append(elem);
			
			elem = $($("#spinner").html());
			$("#villes").append(elem);
			
			$.ajax({
				async: true,
				dataType: "html",
				type: "GET",
				url: "http://" + window.location.hostname + window.location.pathname + "?do=villes&departement=" + $(this).attr("value"),
				success: function(data, textStatus) {
					$("#etablissements").html('<span class="no_select">Sélectionnez une ville</span>');
					$("#villes").html(data);
					addEventsSelectEtablissements();
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$("#etablissements img").replaceWith("");
					$("#villes img").replaceWith("");
					
					currentRequestDepartement	= 0;
				}
			});
		}
	});
	
	addEventsSelectEtablissements();
});

function addEventsSelectEtablissements() {

	if( $("select#ville") ) {
	
		$("select#ville").change(function(e){
			var elem = $($("#spinner").html());
			$("#etablissements").append(elem);
			
			$.ajax({
				async: true,
				dataType: "html",
				type: "GET",
				url: "http://" + window.location.hostname + window.location.pathname + "?do=etablissements&ville=" + $(this).attr("value"),
				success: function(data, textStatus) {
					$("#etablissements").html(data);
				}
			});
		});
	
	}
}