window.onload=function( ) {
	var codepostal = document.getElementById("cp");
	codepostal.onkeyup = function( ){
	    	//On lance la requête dès que le champ "codepostal" a été rempli
		if ((codepostal.value) && (codepostal.value.length > 4)) {
			getNomVille(codepostal.value) ;
		} ;
  	} ;
  	if ((codepostal.value) && (codepostal.value.length > 4)) {
			getNomVille(codepostal.value) ;
	}
} ;

function getNomVille(_cp){
	if(_cp.length > 0){
		httpRequest("GET","./form_cp2ville.php?codepostal="+ encodeURIComponent(_cp), true,traiteReponse);
	} else {
		document.getElementById("idcodepostal").value="";
	}
}

function traiteReponse( ){
	var xmlReturnVal;
	try{
		if(request.readyState == 4){
			if(request.status == 200){
				var retour=request.responseText;
				if(retour != "") {
					id_nom = retour.split('$');
					id = id_nom[0] ;
					nom = id_nom[1] ;
					id_array = id.split('|');
					nom_array = nom.split('|');
					nb_element=id_array.length;
					//réinitialisation
					document.getElementById("idcodepostal").length=0;
					document.getElementById("idcodepostal").options[0]=new Option("Précisez SVP","0");
					for (i=0; i<nb_element; i++){
						if(i==0) {
							// supression de 10 lignes vides avant le premier caractère
							for (j=0; j<10; j++){
								id_array[i]=id_array[i].replace("\n","");
							}
						}
						document.getElementById("idcodepostal").options[i] = new Option(nom_array[i],id_array[i]);
					}
				}
			} else {
				//request.status est 503
				//si l'application est indisponible;
				//500 si elle rencontre un bug
				alert('Un problème de communication est survenu entre l objet XMLHttpRequest et le programme côté serveur.');
			}
		}//fin boucle if
	} catch (err) {
		//réinitialisation
		document.getElementById("idcodepostal").length=0;
		document.getElementById("idcodepostal").options[0]=new Option("","0");
		alert('Ce code postal ne correspond pas à une commune');
		/*alert('Le serveur ne paraît pas disponible '+'pour cette application. Veuillez'+' réessayer dans un instant. \nErreur: '+err.message);*/
	}
}
