
/* *** RECHERCHER EN CLIQUANT SUR LE BOUTTON 'GO' *** */
$("#searchButton").click(function(event){
	document.location="/recherche-articles-deco.php?kw="+$('#searchField').val();
});

/* *** MASQUER L'AUTOCOMPLETEUR EN QUITTANT LA RECHERCHE *** */
$("#searchField").blur(function(event){
	setTimeout('$("#autoCompleter").hide()', 100);
});

/* *** GERER LE COMPORTEMENT DE L'AUTOCOMPLETEUR EN FONCTION DE LA SAISIE *** */
$("#searchField").keyup(function(event){
	//Key = UP
	if(event.keyCode == '38'){ selectPrevious(); }
	//Key = DOWN
	else if(event.keyCode == '40'){ selectNext(); }
	//Key = RETURN
	else if(event.keyCode == '13'){ 
			if($("#selectedLi").val() > 0 ) { openSelection(); } //ouvre l'elt selectionné
		 	else{ $("#searchButton").click(); } //ou alors lance simplement la recherche
	}
	//OTHER Keys - then load autocompleter
	else{ loadAutoCompleter(this.value); }
});

/* *** SELECTIONNER SUIVANT *** */
function selectNext(){
	if( $("#selectedLi").val() ){
		var current = $("#selectedLi").val();
		var next = ( parseInt(current) + 1 );
		if( $("#autoCompLi_"+next) != null ){
			highlightoff("autoCompLi_"+current);
			highlighton("autoCompLi_"+next);
			$("#selectedLi").val(next);
		}
	}
}

/* *** SELECTIONNER PRECEDANT *** */
function selectPrevious(){
	var current = $("#selectedLi").val();
	var previous = ( parseInt(current) - 1 );
	if( $("#selectedLi").val() > 0 ){
		highlightoff("autoCompLi_"+current);
		highlighton("autoCompLi_"+previous);
		current = $("#selectedLi").val(previous);
	}
}

/* *** OUVRIR LE LIEN SELECTIONNE *** */
function openSelection(){
	if( $("#selectedLi").val() ){
		var current = $("#selectedLi").val();
		var link = $("#autoCompLink_"+current);
		if( link != null && link.attr("href") != null && link.attr("href") != "" ){
			document.location=link.attr("href");
		}
	}
}

/* *** LOAD AUTOCOMPLETER *** */
function loadAutoCompleter(enteredString){
	
	var html = '<div style="display:none;" id="autoCompleter"></div>';
	$("#wrap").append( html );
	
	if( enteredString.length >= 3 ){
		
		getArticlesInAutoCompletion(enteredString);
		
		if( $("#autoCompleter").html().length > 5 ){
			$("#autoCompleter").show();
			selectNext();
		}else{
			$("#autoCompleter").hide();
		}
	}
	else{$("#autoCompleter").hide();}
}

/* *** GET AUTOCOMPLETER CONTENT *** */
function getArticlesInAutoCompletion(keyWords){
	//$("#autoCompleter").html('<center><img src="/img/slider/ajax-loader.gif" /></center>');
	$.ajax({
		type: "GET",
		url: "/ajax/getArticlesInAutoCompletion.inc.php?keyWords="+keyWords, //+"&cat="+document.forms.F_SEARCH.cat.value,
		success: function(res){
			$("#autoCompleter").html(res);
		}
	});	
}

/* *** MANAGE AUTOCOMPLETER HOVER *** */
function highlighton(eltId){
	$("#"+eltId).css({'background':'#eceae8', 'color':'#fff'});
}
function highlightoff(eltId){
	$("#"+eltId).css({'background':'#fff', 'color':'#333'});
}


