/**
* EVENTS
**/
$j(function(){
	// Event on load
	$(document).ready(function(){
		getCountByDepartment();
	})
	
	//Events on Location
	$j("select#edit-location").keyup(function(){
		this.delay = 300;

		// Initiate delayed search
		if (this.timer) {
			clearTimeout(this.timer);
		}
		this.timer = setTimeout(function() {
			//getQualificationList();
		}, this.delay);
	})

	$j("select#edit-location").change(function(){

		if($j("select#edit-location").val() != 0){
			getCountTopExpertUserByDepartment();
		}else if($j("#edit-qualificationBrandId").val() != 0){
			getCountTopExpertUserByQualification();
		}
	})
})


/**
* QUALICATION
**/
function getCountTopExpertUserByQualification() {

	$j("img#loadingNbUser").show();
	// Ajax GET request for autocompletion
  	var qualif = $j("#edit-qualificationBrandId").val();
	var department = $j("select#edit-location").val();
	
	//Mise a jour du nb de candidat en fonction de la qualif selectionnee
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "/jquery/getTopExpertByQualification/qualification/"+qualif+"/department/"+department,
		success: function (j) {
			// Parse back result
			if (j.length > 0) {
				var options = '';

				options =  ' ' +j[0].labelValue + ' ' ;

				$j("span#edit-nbCandidat").html(options);
				$j("#no-result-comments").fadeOut("fast");
			} else {
				options =  ' ' + j.length + ' ' ;
				$j("span#edit-nbCandidat").html(options);
				//$j("input#edit-category").attr("disabled", "disabled");
				$j("#no-result-comments").fadeIn();
				//envoi des stats vers xiti
  				tagNoResult()
			}
			$j("img#loadingNbUser").hide();
		}
	})
}

/**
* LOCATION
**/
function getCountTopExpertUserByDepartment() {
	$j("img#loadingNbUser").show();

	var qualif = $j("#edit-qualificationBrandId").val();	
	var department = $j("select#edit-location").val();
	
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "/jquery/getTopExpertByDepartment/qualif/"+qualif+"/department/"+department,
		success: function (j) {
			// Parse back result
			if (j.length>0) {
				var options = '';

				options = ' ' + j[0].labelValue + ' ';
				if ($j("span#edit-nbCandidat").length > 0){
					$j("span#edit-nbCandidat").html(options);
				}
				$j("#no-result-comments").fadeOut("fast");
			} else {
				options = ' ' + j.length + ' ';
				if ($j("span#edit-nbCandidat").length > 0){
					$j("span#edit-nbCandidat").html(options);
				}
				$j("#no-result-comments").fadeIn();
				
				//envoi des stats vers xiti
  				tagNoResult()
			}
			$j("img#loadingNbUser").hide();
		}
	})
}

/*
 * fonction qui formate une chaine de caracteres pour l'envoyer en nom de page xiti
 */

function cleanString(str){
	str = str.replace(/[àâäá]/g, "a");
	str = str.replace(/[îïí]/g, "i");
	str = str.replace(/[ôöó]/g, "o");
	str = str.replace(/[ùûü]/g, "u");
	str = str.replace(/[éèêë]/g, "e");
	str = str.replace(/[ç]/g, "c");
	str = str.replace(/[ñ]/g, "n");
	str = str.replace(/[^a-z0-9_:~\\\-\.]/gi, "_");
	
	return str.toLowerCase();
}


function tagNoResult(){
	var obj = $j("#edit-qualification");
	
	var qualif = $j("#edit-qualificationBrandId").val();	
	var department = $j("select#edit-location").val();
	
	var xtPageName = "Requete_sans_resultat";
	
	if (qualif != 0 && $j("#edit-qualification").val().length){
	  	xtPageName += "::" + $j("#edit-qualification").val();
	}
	if (department != 0){
	  	xtPageName += "::" + $j("select#edit-location :selected").html();
	}

	return xt_click(obj[0], 'C', xtn2, cleanString(xtPageName),'A');
	
}

/*
 *  COUNT TOP EXP BY DEPARTEMENT AND UPDATE SELECT OPTIONS
 */
function getCountByDepartment(qualif){
	//Mise a jour de la liste de departement en fonction du metier et de la qualif selectionnee
	if (qualif == undefined){
		var qualif = $j("#edit-qualificationBrandId").val();
	}

	if (qualif != ''){
		$j("img#loadingLocation").show();
		$.ajax({
			type: "GET",
			dataType: "json",
			url: "/jquery/getCountTopExpertsByDepartment/"+qualif,
			success: function (data) {
				// Parse back result
				updateDepartmentList(data)
	
				$j("img#loadingLocation").hide();
			}
		})
	}
	
}

function updateDepartmentList(data){
	var regex = new RegExp("[(][0-9]+[)]$");
	var options = ''
	var optionsSelectedValue = $j("#edit-location :selected").val()
	
	// boucle sur la liste de departement
	$j("#edit-location > option").each(function(){
		
		var toReplace = regex.exec( $j(this).html() )
		var optionsValue = $j(this).val();
		var optionsText =  $j(this).html().replace( toReplace , '' );
		var optionsCSS = '';
		
		if (data != undefined && data.length > 0) {
			// ajout css + nb de topexp pour les departements trouves
			for (index in data){
				
				if ( optionsValue == data[index]['deptId'] ){
					
					optionsCSS = 'departmentfound'
					
					if ( regex.test( optionsText ) ){
						optionsText.replace( toReplace , '('+data[index]['nbTopExp']+')' )
					}else{							
						optionsText = optionsText + ' ('+data[index]['nbTopExp']+')'
					}
					break;
				}
			}
		}
		options += '<option value="'+optionsValue+'" '
		options += (optionsCSS.length) ? ' class="'+optionsCSS+'" ' : ''
		options += (optionsSelectedValue == optionsValue) ? ' selected="selected" ' : ''
		options += ' >'+optionsText+'</option>'
	})
	
	$j("#edit-location").html(options)
}
