
/* FUNCTIONS : ============================================================================ */

//Supprime un caractère dans la chaine

function hardcoreTrim(s) {
	// Remove leading spaces and carriage returns
	while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r')) {
		s = s.substring(1,s.length);
	}
	// Remove trailing spaces and carriage returns
	while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r')) {
		s = s.substring(0,s.length-1);
	}
	// Replace multiple spaces within the string
	while (s.indexOf("  ") != -1) {
		s = s.substring(0, s.indexOf("  ")) + s.substring(s.indexOf("  ")+1, s.length);
	}
	return s;
}

function checkAndSubmit(formId, fieldEl) {
	var el = hardcoreTrim(fieldEl.value);
	if ( (el != "") && (el.length >= 4) ) {
		fieldEl.value = el;
		document.getElementById(formId).submit();
		return true;
	} else {
		alert('La recherche doit porter sur des mots d\'au moins 4 lettres...');
		return false;
	}
}

/* BEHAVIOURS EVENTS : ============================================================================ */

var myrules = {

	// si touche "Entrée" -> valider le champs "motscles" et soumettre le formulaire "recherche"
	'#motscles' : function(el){
		el.onfocus = function(el){
			// cross-browser friendly keypress event handler
			var k = document.all?window.event.keyCode:el.which;
			if(k == 13) {
				checkAndSubmit('recherche', el);
				return false;
			} else {
				return true;
			}
		}
	}
	,
	
	// si click bouton "ok" -> valider le champs "motscles" et soumettre le formulaire "recherche"
	'#chercher' : function(el){
		el.onclick = function(){
			var field = document.getElementById('motscles');
			checkAndSubmit('recherche', field);
			document.getElementById('motscles').focus();
			return false;
		}
	}
};

Behaviour.register(myrules);

/* ONLOAD EVENTS : ============================================================================ */

Behaviour.addLoadEvent(function() {
	//document.getElementById('motscles').focus();
	// more load operations
	// ...
});
