// Fonction de check des valeurs
function BBTool_check( type, inputValue) {

	//On test si le type de check a effectuer n est pas une formule
	if(type.indexOf("?")!=-1) {
		// On recupere la formule en virant le "?"
		var rule = type.slice(1,type.length);
			type = "rule";
	}
	switch(type) {
	
		// Formule
		// Les formules commencent par un ? et sont notees entre ()
		// Les expressions entre [] sont remplacees par les valeurs des champs dont le nom est indique entre []
		// Ex: [mail]==[mail2] -> Test si la valeur du champ dont l'ID est "mail" est la meme que celle du champ dont l'ID est "mail2"
		case "rule":
			var regExp = /\[([^\]]+)\]/g;
			return !eval(rule.replace(regExp, "jQuery('#$1').attr('value')"));
			break;
			
		// Texte uniquement
		case "alpha":
		  	return !inputValue.match(/^[a-zA-Z-,' \u00E0-\u00EF\u00F0-\u00F6\u00F9-\u00FC]+$/);
			//return !inputValue.match(/^[a-zA-Z-' ]+$/);
			//return false;
			break;
			
		// Alpha numerique
		case "aNum":
			return !inputValue.match(/^[0-9a-zA-Z-,' \u00E0-\u00EF\u00F0-\u00F6\u00F9-\u00FC]+$/);
			break;
			
		// Numerique
		case "num":
			return !inputValue.match(/^[0-9]+$/);
			break;
			
		// Adresse email
		case "mail":
			return !inputValue.match(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/)
			break;
			
		// Numero de telephone
		case "phone":
			var inputValue = jQuery.trim(inputValue.replace(/ /g, ""));
				inputValue = inputValue.replace(/\./g, "");
				inputValue = inputValue.replace(/\-/g, "");
			if (BBVars.currentCountry == 'fr' && inputValue.length != 10) return true;
		  	return !inputValue.match(/^[0-9]+$/);
			break;
			
		// Code postal
		case "zip":
			if(BBVars.currentCountry == 'fr') {
				if (inputValue.length != 5 || !inputValue.match(/^[0-9]+$/)) return true;
			}
			return false;
		
		// Mot de passe
		case "pass":
			/*if(BBVars.currentCountry == 'fr') {
				if (inputValue.length != 5 || !inputValue.match(/^[0-9]+$/)) return true;
			}*/
			return false;
			
		// Date
		case "date":
			var inputValue = inputValue.replace(/ /g, "");
				inputValue = inputValue.replace(/\./g, "");
				inputValue = inputValue.replace(/\-/g, "");
				inputValue = inputValue.replace(/\//g, "");
				inputValue = inputValue.replace(/\\/g, "");
				
			if(BBVars.currentCountry == 'fr') {
				if (inputValue.length != 8 || !inputValue.match(/^[0-9]+$/)) return true;
			}
			return false;
			
		// Checkbox
		case "cBox":
			return !inputValue;
			break;
		default:
			return (inputValue) ? false : true;
			break;
	}
	return false;
}

function BBTool_checkForm(formID, inputs, msg) {

	var form = jQuery("#"+formID),
		formError = false,
		errorString = "",
		regExp = /\[([^\]]+)\]/g;

	inputs.each( function(i, el) {
	
		var input		= jQuery(this),
			layer		= input.parent(),
			inputError	= false,
			defaults	= {
							label:		"",
							required:	false,
							chkType:	"",
							msg:		"",
							msgTarget:	input,
							process:	false,
							dspErrMsg:	true,
							type:		input.attr("type")
						},
			params		= jQuery.extend({}, defaults, eval( '(' + input.attr("data-BBParams") + ')' ));

		if(params.process)
			input.val( eval( params.process.replace( regExp, "jQuery(':input[name=$1]').val()" ) ) );
		if(typeof(params.msgTarget)=="string") 
			layer = jQuery( params.msgTarget );

		var inputValue	= ( params.type=="checkbox" ) ? input.attr("checked") : input.val();
		
		if( params.required || ( !params.required && params.chkType!="" && inputValue != "" && inputValue != "NaN") || (inputValue != "" && params.chkType!="") && inputValue != "NaN" ) {
		
			jQuery.each( params.chkType.split(","), function( index, checkOp) {
				
				inputError |= BBTool_check(checkOp, inputValue),
				formError |= inputError;
			});
			
			if(inputError) {
			
				errorString += "<p>" + ((params.msg!=""&&!msg) ? params.msg : BBLabels.label_errorFieldValue.replace("{field}", params.label)) + "</p>";
				
				if(!msg&&input.data("checked")&&!layer.hasClass("error")) {
					layer.removeClass("valid").addClass("error");
					input.data("error", true);
					if(params.dspErrMsg) input.triggerHandler("tip.error");
				}
				if(params.dspErrMsg) input.triggerHandler("tip.hintHide");
				
			} else if (!inputError&&!msg&&input.data("checked")) {
				layer.removeClass("error").addClass("valid");
				input.data("error", false);
				input.triggerHandler("tip.hintHide");
				// Gestion des toottips pour les input hidden
				if(input.attr("type")=="hidden") {
					layer.triggerHandler("tip.hide");
					layer.unbind();
				} else {
					input.triggerHandler("tip.hide");
					input.unbind("tip");
				}
			}
			input.data("checked", true);
			
		} else if( !params.required && inputValue == "" ) {
			layer.removeClass("error");
			input.data("error", false);
			input.triggerHandler("tip.hintHide");
			if(input.attr("type")=="hidden") {
				layer.triggerHandler("tip.hide");
				layer.unbind();
			} else {
				input.triggerHandler("tip.hide");
				input.unbind("tip");
			}
		}

	});
	
	if(BBSettings.BBForms.checkFormMethod!="rt")
		form.trigger( (jQuery(".error", form).length>0) ? "error" : "valid" );
	else if(eval(form.data("inptNB"))<=jQuery(".valid", form).length&&jQuery(".error", form).length==0)
		form.triggerHandler("valid");
	else
		form.triggerHandler("error");// BBTrace(eval(form.data("inptNB")) + " "+jQuery(".valid", form).length);
	
	return ((msg)?errorString:formError);
	
}

function BBTool_formPost( formID ) {

	var form				= jQuery("#"+formID),
		params				= form.attr("data-BBParams")||{},
		defaults			= {
								action:			BBVars.pageURL,
								chkType:		"std",
								chkFunction:	"BBTool_checkForm",
								msg:			BBLabels.label_stdFormErrMsg,
								msgDsp:			false,
								extChk:			false,
								haltOnError:	false,
								ajaxPost:		false
							},
		inputs				= jQuery(":input[data-BBParams]",form),
		formError			= (jQuery(".error", form).length>0) ? true : false;
		params				= jQuery.extend({}, defaults, eval( '(' + form.attr("data-BBParams") + ')' ));
		
	formError |= BBTool_checkForm(formID, inputs);
	
	if(!formError) {
		if(params.ajaxPost) {
			jQuery.post(
				params.action,
				form.serialize(),
				function(data) {BBTool_openMsgBox(data, true)},
				"html"
			);
		} else form.submit();
	} else {
		if(params.msgDsp) alert(params.msg);
		form.trigger("error");
	}
}

function BBTool_initRTForms( target ) {

	var BBForms = ((target) ? jQuery(target) : jQuery("form.BBForms"));
	
	BBForms.each( function() {

		var currentForm		= jQuery(this),
			submitBtn		= jQuery("a.submit", currentForm),
			inputs			= jQuery(":input[data-BBParams]", currentForm),
			formParams		= eval( '(' + currentForm.attr("data-BBParams") + ')' ),
			requiredInputNB = 0,
			inputValueArray	= null,
			tipParams		= {
									hint: {
										xOffset: 		30,
							            yOffset: 		-40,
							            tooltipID: 		'BBTTipHint',
										tTipHeight:		"auto",
										tTipWidth:		"auto",
										tTipDspPos:		"left",
										pointer:		true,
										pointerPos:		"bottom,right",
										pointerOffset:	{x: -19, y: -2},
										classN:			"",
										events:			{
															init:	"tip.hint",
															show:	"tip.hint",
															hide:	"tip.hintHide"
														}
									}, error: {
										xOffset: 		30,
							            yOffset: 		-40,
							            tooltipID: 		'BBTTipError',
										tTipHeight:		"auto",
										tTipWidth:		"auto",
										tTipDspPos:		"left",
										pointer:		true,
										pointerPos:		"bottom,right",
										pointerOffset:	{x: -19, y: -2},
										classN:			"tTipError",
										events:			{
															init:	"tip.error",
															show:	"tip.error",
															hide:	"tip.valid tip.hide"
														}
									}, submitError: {
										xOffset: 		0,
							            yOffset: 		0,
							            tooltipID: 		'BBTTipError',
										tTipHeight:		"auto",
										tTipWidth:		"auto",
										tTipDspPos:		"top",
										pointer:		false,
										classN:			"tTipError",
										events:			{
															init:	"tip.error",
															show:	"tip.error",
															hide:	"tip.valid tip.hide"
														}
									}
								};
								
		inputs.each( function(i,el) {
			var input = jQuery(this),
				params = eval( '(' + input.attr("data-BBParams") + ')' );

			input.bind( BBSettings.BBForms.checkEvtList, function(e) {
				// Pour eviter le check sur le focus par tabulation
				if(jQuery(this).val()==""&&e.type=="keyup"&&!jQuery(this).parent().hasClass("valid")) return false;
				((input.attr("type")=="hidden")?jQuery( params.msgTarget ):input).tooltip( function(el) {
						tipMsg = (params.msg) ? params.msg : BBLabels.label_errorFieldValue.replace("{field}", params.label);
						return tipMsg + "<div>"+tipMsg+"</div>";
					}, tipParams.error);
					//Pour avoir plusieurs ttip
					//}, jQuery.extend(tipParams.error, {tooltipID: "iptTTip"+i}) );
				BBTool_checkForm( currentForm.attr("id"), input );
			}).bind(BBSettings.BBForms.hintEvtList.show, function(e) {
			
				if(input.data("hint")) return false;
			
				if(params.hint&&!input.parent().hasClass("valid")&&!input.parent().hasClass("error")) {
					((input.attr("type")=="hidden")?jQuery( params.msgTarget ):input).tooltip( function(el) {
							tipMsg = params.hint;
							return tipMsg + "<div>"+tipMsg+"</div>";
					}, tipParams.hint ).trigger("tip.hint").trigger("tip.hide");
					
					input.data("hint", true);
					
				} else if(params.hint&&input.parent().hasClass("error")) {
					((input.attr("type")=="hidden")?jQuery( params.msgTarget ):input).tooltip( function(el) {
							tipMsg = params.hint;
							return tipMsg + "<div>"+tipMsg+"</div>";
					}, jQuery.extend({}, tipParams.hint, {classN: "tTipError"}) ).trigger("tip.hide").trigger("tip.hint");
					
					input.data("hint", true);
					
				};
				// Rajout pour le desaffichage du message d erreur si la valeur de l input est comparee a celle d un autre
				if(typeof(params.link)!="undefined"&&jQuery(params.link).length>0)
					jQuery(params.link).trigger("tip.hide");
			}).bind(BBSettings.BBForms.hintEvtList.hide, function(e) {
				if(params.hint) ((input.attr("type")=="hidden")?jQuery( params.msgTarget ):input).trigger("tip.hintHide");
				input.data("hint", false);
			}).data("checked", false);
			if(input.val()!="") {
				BBTool_checkForm( currentForm.attr("id"), input );
			}
			if(params.required)requiredInputNB++;
			
			// Specifique Morgan
			input.parent().bind("click", function(e) { input.trigger("focus"); });
			
		}).bind("focus", function() {
			inputValueArray = [];
			inputs.each( function(i,el) {
				inputValueArray[i] = jQuery(this).val();
			});
		}).bind("blur", function(e) {
			var checkInput = [];
			inputs.each( function(i,el) {
				if(jQuery(this).val()!=inputValueArray[i]) checkInput = jQuery(checkInput).add(el);
			});
			if(checkInput.length>0) BBTool_checkForm( currentForm.attr("id"), checkInput );
		});

		submitBtn.tooltip( function(el) { 
					tipMsg = BBTool_checkForm(currentForm.attr("id"),inputs,true);
					return tipMsg + "<div>"+tipMsg+"</div>";
				}, tipParams.submitError )
			.bind("mouseenter", function(e) {
				if(currentForm.data("error")&&BBTool_checkForm(currentForm.attr("id"),inputs,true)!="") jQuery(this).trigger("tip.error");
			}).bind("mouseleave", function(e) {
				if(currentForm.data("error")) jQuery(this).trigger("tip.hide");
			});
		currentForm.data("inptNB", requiredInputNB);
		currentForm.bind("error", function(e) {
			jQuery(this).data("error", true);
			submitBtn.stop().animate({opacity: 0.5}, function() {
				jQuery(this).unbind("click");
			});
		}).bind("valid", function(e) {
			jQuery(this).data("error", false);
			submitBtn.stop().animate({opacity: 1}, function() {
				jQuery(this).unbind("click");
				jQuery(this).bind("click", function(evt) {
					evt.preventDefault();
					if( jQuery.isFunction(formParams.callback) )
						formParams.callback.call();
					BBTool_formPost(currentForm.attr("id"), ( (formParams.ajaxPost) ? true : false ));
				});
			});
		}).trigger( ((BBTool_checkForm(currentForm.attr("id"),inputs))?"error":"valid") );
		
	});

}
