var csactionLocalisation = 'commun/localisation/';

erreurAjax = function() {
	alert('Ajax Error !') ;
}

ajaxLocalisation = function(arrayParams, successFunction, urlAjax){
	var config = new Object();
	config.data = arrayParams;
	config.success = successFunction;
	config.error = erreurAjax;
	config.type = 'GET';
	config.url = urlAjax;
	$.ajax(config);
}

chargerRegions = function(parent, fonctionSuccess){
	var params = {csaction: csactionLocalisation+'regions_generer', parentId: parent};
	ajaxLocalisation(params, fonctionSuccess, 'index.php') ;
}

chargerVilles = function(parent, fonctionSuccess){
	var params = {csaction: csactionLocalisation+'villesFromRegion_generer', parentId: parent};
	ajaxLocalisation(params, fonctionSuccess, 'index.php');
}

/*** FONCTIONS D'APPEL AUX CHARGEMENTS AJAX **/
initLocalisation = function(){
	$('select#liste_pays').change(miseAJourRegion);
	$('select#liste_regions').change(miseAJourVilles);
	if(!$('select#liste_regions option').length){
		$('select#liste_pays').change();
	}
}

$(initLocalisation);

disableSelect = function(selecteur){
 	$(selecteur).attr('disabled', 'disabled');
 	$(selecteur).html('<option value="loading">Chargement en cours...</option>');
}

miseAJourRegion = function(){
	modifs = function(data){
 		$('select#liste_regions').html('<option label="Toutes" value="all">Toutes</option>'+data);
 		$('select#liste_regions').attr('disabled', '');
//		if(data.length>0){
			$('select#liste_regions').change();
//		}
 	}
 	var selecteur = 'select#liste_regions, select#liste_villes';
 	disableSelect(selecteur);
 	if(this.selectedIndex < 0){
 		chargerRegions(0, modifs);
 	}
 	else
 	{
		chargerRegions(this.options[this.selectedIndex].value, modifs);
	}
}

miseAJourVilles = function(){
	modifs = function(data){
		$('select#liste_villes').html('<option label="Toutes" value="all">Toutes</option>'+data);
 		$('select#liste_villes').attr('disabled', '');
//		if(data.length>0){
			$('select#liste_villes').change();
//		}
	};
 	var selecteur = 'select#liste_villes';
 	disableSelect(selecteur);
 	if(this.selectedIndex < 0){
 		chargerVilles(0, modifs);
 	}
 	else
 	{
		chargerVilles(this.options[this.selectedIndex].value, modifs);
	}
}