var httpRequest = getXmlHttpRequestObject();

function getXmlHttpRequestObject()
{
	if(window.XMLHttpRequest) return new XMLHttpRequest();
	
	else if(window.ActiveXObject)
	{
		try { return new ActiveXObject("Microsoft.XMLHTTP"); }
		
		catch(e)
		{
			try { return new ActiveXObject("Msxml2.XMLHTTP"); }
      
			catch(e)
			{
				alert('Impossible de créer un objet ActiveX avec votre navigateur.');
				
				return false;
			}
		}
	}
}

function get_depts(country)
{
	document.getElementById('dept_box').disabled = true;
	document.getElementById('city_box').disabled = true;
	
	document.getElementById('user_flag').src = '/imgs/flags3/blank.png';
	
	while(document.getElementById('dept_box').options.length > 1) document.getElementById('dept_box').options[1] = null;
	while(document.getElementById('city_box').options.length > 1) document.getElementById('city_box').options[1] = null;
		
	if(httpRequest && country)
	{
		httpRequest.open('GET','/home/ajax/get_depts.html?country='+ country,true);
		httpRequest.onreadystatechange = function() { load_depts(httpRequest,country); };
		httpRequest.send(null);
	}
}

function load_depts(httpRequest,country)
{
	if(httpRequest.readyState == 4 && httpRequest.status == 200)
	{
		xmldoc = httpRequest.responseXML;
		departement_nodes = xmldoc.getElementsByTagName('departement');
		n_departement = departement_nodes.length;
		
		for(i = 0; i < n_departement; i++)
		{
			dept_id = departement_nodes[i].getElementsByTagName('id')[0].firstChild.nodeValue;
			dept_name = departement_nodes[i].getElementsByTagName('name')[0].firstChild.nodeValue;
			
			document.getElementById('dept_box').options[i+1] = new Option(dept_name,dept_id);
		}
		
		if(document.getElementById('dept_box').options.length > 1)
		{
			document.getElementById('dept_box').disabled = false;
		
			document.images['user_flag'].src = '/imgs/flags3/'+ country +'.png';
		}
	}
}

function get_cities(country,dept)
{
	document.getElementById('city_box').disabled = true;
	
	while(document.getElementById('city_box').options.length > 1) document.getElementById('city_box').options[1] = null;
	
	if(httpRequest && country && dept)
	{
		httpRequest.open('GET','/home/ajax/get_cities.html?country='+ country +'&dep='+ dept,true);
		httpRequest.onreadystatechange = function() { load_cities(httpRequest); };
		httpRequest.send(null);
	}
}

function load_cities(httpRequest)
{
	if(httpRequest.readyState == 4 && httpRequest.status == 200)
	{
		xmldoc = httpRequest.responseXML;
		city_nodes = xmldoc.getElementsByTagName('city');
		n_city = city_nodes.length;
		
		for(i = 0; i < n_city; i++)
		{
			city_id = city_nodes[i].getElementsByTagName('id')[0].firstChild.nodeValue;
			city_name = city_nodes[i].getElementsByTagName('name')[0].firstChild.nodeValue;
			
			document.getElementById('city_box').options[i+1] = new Option(city_name,city_id);
		}
		
		if(document.getElementById('city_box').options.length > 1) document.getElementById('city_box').disabled = false;
	}
}
