/**
 *
 * Validation de formulaire via jQuery
 * utilisant le plugin "metadata".
 *
 * ------------------------------------
 * @id       val
 * @version  0.1
 * @author   remi(at)ixmedia(point)com
 */

/**
 * La classe qui sera donn�e aux champs invalides
 *
 * @var string
 */
var valClasseChampInvalide = "champInvalide";

/**
 * Le sélecteur qui sera utilisé pour récupérer les
 * champs des formulaires
 *
 * @var string
 */
var valSelecteurChamps = 'form.valider input, form.valider textarea, form.valider select';


/**
 * Formats de validation
 * 
 * @var array
 */
var valFormatsValidation				= new Array();
valFormatsValidation['requis']			= /^.+$/;
valFormatsValidation['courriel']		= /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/;
valFormatsValidation['telephone']		= /^[0-9]{3}\-[0-9]{4}$/;
valFormatsValidation['telephone-ind']	= /^[0-9]{3}$/;
valFormatsValidation['numerique']		= /^[0-9]+$/;
valFormatsValidation['zip']				= /^[0-9]{5}\-[0-9]{4}$/gi;
valFormatsValidation['codepostal']		= /^([A-Z]{1}[0-9]{1}){3}$/gi;
valFormatsValidation['siteweb']			= /^(([a-zA-Z0-9\-\.]+.)?[a-zA-Z0-9\-\.\/]+\.[a-z\.]{2,8}\/?[a-zA-Z0-9\-\.\/]*)?$/i;



/**
 * Initialise le formulaire
 *
 * @return void
 */
$(document).ready(function () {
	$.meta.setType("class");
	$(valSelecteurChamps).valider(); // Au chargement de la page
	$(valSelecteurChamps).keyup(function(){ $(this).valider(); }); // Lorsque du texte est entré
	$(valSelecteurChamps).blur(function(){ $(this).valider(); }); // Lorsque le focus quitte le champ
});

/**
 * Valide un champ
 *
 * @return jQuery
 */

jQuery.fn.valider = function() {
	return this.each(function(){
		var champ = this;
		jQuery.each($(champ).data(), function(i, n){
			if (i == "format") {
				var formats = n;
				if (formats.length == 0) { return; }
				var valide;
				$.each(formats, function(i,n) {
					valide = ($(champ).validerRegex(valFormatsValidation[n])) ? true : false;					
				});
				if (valide===true) {
					jQuery(champ).removeClass(valClasseChampInvalide);
				} else {
					jQuery(champ).addClass(valClasseChampInvalide);
				}
			}
		});
	});
};


/**
 * Valide un champ a l'aide d'une expression régulière
 *
 * @param	jQuery	champ		  Le champ à valider
 * @param	RegExp	pattern		Le "pattern" de l'expression régulière
 * @return bool
 */
jQuery.fn.validerRegex = function(pattern) {
	var valide=false;
	this.each(function(){ valide = (jQuery(this).val().match(pattern) != null) ? true : false; });
	return valide;
}
