$(document).ready(function($){

	$("#cpv_postal").keyup(function(){
			cp = $(this);
			ville = $("#cpv_ville");
			chercher(cp, ville);
	})
	$("#cpv_ville").change(function(){
		val = this.options[this.selectedIndex].text;
		cpo = val.split('(');
		  if(cpo!='Choisissez'){
				cpo = cpo[1].split(')');
				cp = cpo[0];
				$("#cpv_postal").val(cp);
		  }
		
	})

})

chercher = function(cp, ville){
		
		
		cpval = $(cp).val();
		if(cpval.length>1){
			$(ville).hide();
			var noCache = new Date().getTime();
			param = { 'cp': cpval };
			$.ajax({
				url: '/outils/villes.php',
				contentType: 'application/json',
				dataType: 'json',
				cache: false,
				data: param,
				success: function(res){
					remplir(ville, cp, res);
					$(ville).show();
				}	
			})
		}
}

remplir = function(ville, cp, res){
	var option = '<option value="">Choisissez</option>';
	if(res){
		if(res.length>1){
			for (var i = 0; i < res.length; i++) {
				option = option + '<option value="' + res[i]['nom'] + '">' + res[i]['nom'] + ' ('+ res[i]['postal'] +')</option>';
			}
		}else{
			option = option + '<option selected value="' + res[0]['nom'] + '">' + res[0]['nom'] + '</option>';
			$(cp).val(res[0]['postal']);
		}
		$(ville).html(option);
	}else{
		option = option + '<option selected value="">Aucune ville correspondante</option>';
		$(ville).html(option);
	}
				
}
