/*
 * SCRIPT CALLED BY index.php FOR lib/candidates.php
 */
 

// ONLOAD FUNCTION --------------------------------------------------------------------------------------------------------------------
$(function() {
	checkSelectorChange();
});


// ARRAY CONTAINING CORRESPONDANCES BETWEEN CRITERIA AND select NAMES -----------------------------------------------------------------
var selectNameArray = [];
selectNameArray["architect"]	= "ar_name";
selectNameArray["client"]		= "cl_name";
selectNameArray["program"]		= "wo_program";
selectNameArray["process"]		= "wo_process";
selectNameArray["county"]		= "wo_county";
selectNameArray["city"]			= "wo_city";
selectNameArray["endYear"]		= "wo_endyear";


// FUNCTION CHECKING IF A NEW OPTION HAS BEEN SELECTED --------------------------------------------------------------------------------
function checkSelectorChange() {
	// select LISTENERS:
	$("#candidatesSelector li select").change(function() {
		// EXTRACT SELECTED CRITERION AND ITS VALUE (E.G. "architect" AND "32" -- ITS ID IN architects BASE):
		var changedCriterion = $(this).val().split("_")[0];
		var criterionValue = $(this).val().split("_")[1];
		
		// UN-SELECT ALL option TAGS:
		$("option").removeAttr("selected");
		// RE-SELECT ALL FIRST option OF EACH select:
		$("option:first-child").attr("selected", "selected");
		// IN THE select WHERE THE NEW OPTION HAS BEEN SELECTED, UN-SELECT FIRST OPTION:
		$("#" + selectNameArray[changedCriterion] + " option:first-child").removeAttr("selected");
		// RE-SELECT CHOSEN OPTION:
		$("option[value=" + changedCriterion + "_" + criterionValue + "]").attr("selected", "selected");

		// AJAX QUERY TO REBUILD THE CANDIDATE LIST USING lib/rebuildCandidateList.php SCRIPT:
		$.ajax({
			type:		"POST",
			beforeSend:	function() { $("#candidatesList").html("<img src='img/ui/loaderForCandidateList.gif' alt='Loader' width='32' height='32' />"); },
			success:	function(serverAnswer) { $("#candidatesList").html(serverAnswer); },
			url:		"lib/rebuildCandidateList.php",
			data:		"criterion=" + changedCriterion + "&" +
						"value=" + criterionValue,
			dataType:	"text",
			error:		function() { alert("Une erreur s'est produite."); }
			// async:		false
		});
	});
}

