var request;

//Check the navigator used to initialize correctly the Ajax
if (navigator.appName == "Microsoft Internet Explorer") 
{ 
	request = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
else 
{ 
	request = new XMLHttpRequest();
}


//Function of validation of the postal code
function checkCode(code)
{
	//Check is the postal code is empty
	if (code == '') 
	{ 
 
	}
	//Check if the code has less than 5 numbers  - Display error if needed
	else if (code.length < 5) 
	{ 
		document.getElementById('messageCode').innerHTML = '<span id="messageCodeResult" class="error">Le code postal doit comporter 5 chiffres</span>';
	} 
	//Check if the code has 5 numbers 
	else if (code.length == 5) 
	{ 
		
		var success = 4;
		
		request.abort();
		
		//Initialize the request
		request.open("GET", "/search/codeajax/code/" + code, true);
		
		//Manage the result
		request.onreadystatechange=function() 
		{ 
			//If the request is correctly executed, we display the result
			if (request.readyState == success) 
			{ 
				document.getElementById('messageCode').innerHTML = request.responseText;
			}
		};
		
		request.send(null);
	}
	//If the is more than 5 characters, display an error
	else
	{
		document.getElementById('messageCode').innerHTML =  '<span id="messageCodeResult" class="error">Le code postal ne peut être compos&eacute; de plus de 5 chiffres</span>';
	}
}



//Function which checks if the form is well completed
function testSearch()
{
	var string = 'Le code postal est valide';
	
	//If the city is not specified, we erase the corresponding field
	if(document.getElementById("city").value == "n'importe où") document.getElementById("city").value = "";
	
	//Call the checkcode function to validate postal code field
	checkCode(document.getElementById("city").value);
	
	//Check if the postal code if validated
	if(((document.getElementById("messageCodeResult").innerHTML) == string) || (document.getElementById("city").value == ""))
	{
		return true;
	}
	//Else, block the form
	else
	{
		return false;
	}
}


