
/* format for identity */
var regexp_name = /^[a-zA-Z\u00aa\u00c1\u00e1\u00c0\u00e0\u00c2\u00e2\u00c4\u00e4\u00c3\u00e3\u00c5\u00e5\u00e6\u00c6\u00c7\u00e7\u00d0\u00f0\u00c9\u00e9\u00c8\u00e8\u00ca\u00ea\u00cb\u00eb\u00cd\u00ed\u00cc\u00ec\u00ce\u00ee\u00ef\u00cf\u00d1\u00f1\u00d3\u00f3\u00d2\u00f2\u00d4\u00f4\u00d6\u00f6\u00d8\u00f8\u008c\u009c\u00df\u00de\u00fe\u00da\u00fa\u00d9\u00f9\u00db\u00fb\u00dc\u00fc\u00fd\u00dd\u009f\u00ff\u00b0\u00a3\-' ]+$/;  
var regexp_adress = /^[a-zA-Z0-9\u00aa\u00c1\u00e1\u00c0\u00e0\u00c2\u00e2\u00c4\u00e4\u00c3\u00e3\u00c5\u00e5\u00e6\u00c6\u00c7\u00e7\u00d0\u00f0\u00c9\u00e9\u00c8\u00e8\u00ca\u00ea\u00cb\u00eb\u00cd\u00ed\u00cc\u00ec\u00ce\u00ee\u00ef\u00cf\u00d1\u00f1\u00d3\u00f3\u00d2\u00f2\u00d4\u00f4\u00d6\u00f6\u00d8\u00f8\u008c\u009c\u00df\u00de\u00fe\u00da\u00fa\u00d9\u00f9\u00db\u00fb\u00dc\u00fc\u00fd\u00dd\u009f\u00ff\u00b0\u00a3\-'\/\\"\[\]\(\)\+\*\#\{\}\=\@Ã?Â£%&$\.\?\| \n\r  ]+$/;
var regexp_numeric = /^\d+$/;  
var regexp_alpha = /^[a-zA-Z]+$/;  
var regexp_alphanumeric = /^[a-zA-Z0-9]+$/;
var regexp_email = /^(\w[-._\w]*@\w[-._\w]*\w\.\w{2,6})$/;
var regexp_name_numeric = /^[a-zA-Z0-9\u00aa\u00c1\u00e1\u00c0\u00e0\u00c2\u00e2\u00c4\u00e4\u00c3\u00e3\u00c5\u00e5\u00e6\u00c6\u00c7\u00e7\u00d0\u00f0\u00c9\u00e9\u00c8\u00e8\u00ca\u00ea\u00cb\u00eb\u00cd\u00ed\u00cc\u00ec\u00ce\u00ee\u00ef\u00cf\u00d1\u00f1\u00d3\u00f3\u00d2\u00f2\u00d4\u00f4\u00d6\u00f6\u00d8\u00f8\u008c\u009c\u00df\u00de\u00fe\u00da\u00fa\u00d9\u00f9\u00db\u00fb\u00dc\u00fc\u00fd\u00dd\u009f\u00ff\u00b0\u00a3\-' ]+$/;  

/*required = mandatory: if null/empty =>error msg
optional = not mandatory: if null/empty => no error msg but min-max/format/custo can be checked
optionalWarning = optional BUT if null/empty =>display a warning popin*/
var AF_VALIDATION_FORMAT = /^\s*(required|optional|optionalWarning)?\s*(\[\d*\-\d*\])?\s*(\/[^/]+\/d?)?\s*(check:\S+)?\s*\s*(warning:\S+)?$/;  // example: "required [min-max] /regexp_name/ check:todo()" 
var AF_LENGTH_FORMAT = /\[(\d*)\-(\d*)\]/;  // example: [min-max]

var VALIDATION_MANDATORY = "mandatory";
var VALIDATION_LENGTH = "length";
var VALIDATION_FORMAT = "format";
var VALIDATION_CUSTOM = "custom";
var VALIDATION_WARNING = "warning";
var NRS = false;
var ImgON = "/FR/common/common/img/pictos/img-erreur_on.gif";
var ImgOFF = "/FR/common/common/img/pictos/img-erreur_off.gif";

var DEBUG = false;

  
var fieldsOnError = new Array();
var errorMessages = new Array();
var fieldsWarningOK = true;
var generalWarning = ""; 
var isWarningDisplayed = false;

var defaultErrorMessage = new Object();  /* must be filled in the page, depending on the language: Ex: defaultErrorMessage[VALIDATION_MANDATORY] = "<code cmsid='properties.xxx'></code>"; */

/**
* Initialization for NRS only
*/
function initializeNRS(){
	NRS = true;
	ImgON = "/FR/common/common/img/pictos/form-error.gif";
}

/**
* To display or not img
*/
function DstepRoll(ImgNam,Chemimg,Mylayon){
	var ns4=(document.layers)?true:false;
	var ie4=(document.all)?true:false;
	var ns6=(document.getElementById && !document.all)?true:false;
	var imgToRoll;
	if(Mylayon==0){
		if(document.images){imgToRoll=document.images[ImgNam];}
	} else {
		if (ns4){imgToRoll=document.layers[Mylayon].document.images[ImgNam];}
		if (ie4||ns6) {imgToRoll=document.images[ImgNam];}
	}
	
	if (imgToRoll) {
		imgToRoll.src=Chemimg;
	}
}

/**
 * Checks the format of all fields with af_validation attribute in the specified form.
 * Returns true if no error.
 */
function af_validation(formId, debug) {
	DEBUG = debug;
	
	// hide existing errors 
	clearErrors();

	var fieldsOK = true;
	fieldsWarningOK = true;
	
	var inputs = getAfValidationInputs(formId);
	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		
		// do not check disabled inputs
		if (!input.disabled) {		
			// remove useless blank characters
			if (input.type == "text") {
				input.value = input.value.strip();
			}
			
			// get the attribute af_validation 
			var validation = input.getAttribute("af_validation");
			if (AF_VALIDATION_FORMAT.test(validation)) {
				// the format is ok, extract values 
				var required = RegExp.$1;
				var minMax = RegExp.$2;
				var regexp = RegExp.$3;
				var custom = RegExp.$4;
				var warning = RegExp.$5;
				
				// do the checks 
				if (required != "") {
					if(required == "required"){
						fieldsOK = checkRequired(required, input) && fieldsOK;
					}
					else if (required == "optionalWarning"){
						fieldsOK = checkOptionalWarning(warning, input) && fieldsOK;
					}
				}
				if (minMax != "") {
					fieldsOK = checkMinMax(minMax, input) && fieldsOK;
				}
				if (regexp != "") {			
					fieldsOK = checkRegExp(regexp, input) && fieldsOK;
				}
				if (custom != "") {			
					fieldsOK = checkCustom(custom, input) && fieldsOK;
				}	
				
			} else {
				if (DEBUG) {
					alert("Bad af_validation format for the field '" + input.id + "'");
				}
			}
		}
	}

	showMessagesRecap();

	return fieldsOK;
}

function showMessagesRecap() {
	// update the top recap error block
	var errorList = $('errorList');
	if (errorList && errorMessages.length > 0) {
		var buffer  ="";
		for (var m=0; m < errorMessages.length; m++) {
			buffer += '<div>' + errorMessages[m] + '</div>';
		}
		errorList.innerHTML = buffer ;
		// show the top recap error block
		$('allErrorsContainer').style.display = 'block';
		location.href="#anchor_errors"
	}
}

/**
 * Checks if specified field matches mandatory
 * Returns true if no error.
 */
function checkRequired(required, input) {
	var fieldValue = $F(input);

	var isOnError = (required == "required") && (fieldValue == '' || fieldValue == null);
	if (isOnError) {
			showError(input, VALIDATION_MANDATORY);
			return false;
	}
	
	return true; // no error
}

/**
 * Checks if specified field matches warning condition.
 * Returns true if no error.
 */
function checkOptionalWarning( warning, input) {
	var fieldValue = $F(input);
	if (fieldValue == '' || fieldValue == null) {		
		fieldsWarningOK = false;
		//save the url of the warning popin to display
		generalWarning = warning;			
		return true; //no error but warning must be displayed
	}
	
	return true; // no error
}

/**
 * Checks if specified field matches length condition.
 * Returns true if no error.
 */
function checkMinMax(minMax, input) {
	// check length only if field is not empty (the field may be optional) 
	var fieldValue = $F(input);
	if (fieldValue != '') { 
		// extracts the min and max value; minMax looks like "[min-max]" 
		AF_LENGTH_FORMAT.test(minMax);
		
		var min = RegExp.$1;
		if (!min) {
			min = 0;
		}
		var max = RegExp.$2;
		if (!max) {
			max = 10000;
		}
		
		// checks length
		var isOnError = (fieldValue.length < min || fieldValue.length > max);
		if (isOnError) {
			showError(input, VALIDATION_LENGTH, new Array(min, max));
			return false;
		}
	}
	
	return true; // no error
}

/**
 * Checks if specified field matches its regular expression.
 * Returns true if no error.
 */
function checkRegExp(regexp, input) {
	// check regexp only if field is not empty (the field may be optional) 
	var fieldValue = $F(input);
	if (fieldValue != '') { 
		// extracts the regexp name; regexp looks like "/regexp_name/d" 		
		var regExpName = regexp.substring(1, regexp.lastIndexOf("/"));
		// find the regexp variable 
		var regExpVariable = eval(regExpName);
		// checks format 
		if (!regExpVariable.test(fieldValue)) {
			showError(input, VALIDATION_FORMAT);
			return false;
		}
	}
	return true; // no error
}

/**
 * Checks if specified field matches its regular expression.
 * Returns true if no error.
 */
function checkRegExpSansShowError(regexp, input) {
	// check regexp only if field is not empty (the field may be optional) 
	var fieldValue = $F(input);
	if (fieldValue != '') { 
		// extracts the regexp name; regexp looks like "/regexp_name/d" 		
		var regExpName = regexp.substring(1, regexp.lastIndexOf("/"));
		// find the regexp variable 
		var regExpVariable = eval(regExpName);
		// checks format 
		if (!regExpVariable.test(fieldValue)) {
			
			return false;
		}
	}
	return true; // no error
}
 
/**
 * Do the custon check
 * Returns true if no error.
 */
function checkCustom(custom, input) {
	var fieldValue = $F(input);
	// extracts the custom action (custom looks like "check:myMethod(a,b)") 
	var customMethode = custom.substring(6);
	// execute the check 
	var fieldOk = eval(customMethode);
	if (!fieldOk) {
		showError(input, VALIDATION_CUSTOM);
		return false;
	}
	
	return true; // no error
}

/**
 * Eval the warning method
 * return true if warning 
 */
 
 function displayWarning() {
 	//if fields are ok but some of warning fields are empty => display the warning
	if (generalWarning != "" && !fieldsWarningOK) {			
		// extracts the warning action (warning looks like "warning:url") 
		var urlWarning = generalWarning.substring(8);
		// execute the methode 
		GB_showResize("",urlWarning);
		isWarningDisplayed = true;
	}
	else{
		isWarningDisplayed = false;
	}
}

 
/**
 * Remove "onError" classname on all the fields
 */
function clearErrors() { 
	for (var i = 0; i < fieldsOnError.length; i++) {
		clearError(fieldsOnError[i]);
	}
	fieldsOnError.clear();
	
	errorMessages.clear();
	var errorList = $('errorList');
	if (errorList) { 		
		errorList.innerHTML = '';
		$('allErrorsContainer').style.display = 'none';
	}
}

/**
 * Return true if the field is already in error
 */
function isOnError(input) {
	for (var i = 0; i < fieldsOnError.length; i++) {
		if (fieldsOnError[i] == input) {
			return true;
		}
	}
	
	return false;
}
 
/**
 * Remove "onError" classname on the specified input, its associated error image and error message.
 */
function clearError(input) {

	input.removeClassName("onError");

	var img = getErrorImg(input);
	if (img) {
		img.removeClassName("onError");
		if(NRS){
			var img_name = getErrorImgName(input);
			DstepRoll(img_name,ImgOFF,0);
		}
	}
	
	var errMsg_mandatory = getErrorContainer(input, VALIDATION_MANDATORY);
	if (errMsg_mandatory) {
		errMsg_mandatory.removeClassName("onError");
	}
	var errMsg_length = getErrorContainer(input, VALIDATION_LENGTH);
	if (errMsg_length) {
		errMsg_length.removeClassName("onError");
	}
	var errMsg_format = getErrorContainer(input, VALIDATION_FORMAT);
	if (errMsg_format) {
		errMsg_format.removeClassName("onError");
	}
	var errMsg_custom = getErrorContainer(input, VALIDATION_CUSTOM);
	if (errMsg_custom) {
		errMsg_custom.removeClassName("onError");
	}
	
	var toDoOnClearError = input.getAttribute("af_onClearError");
	if (toDoOnClearError) {
		// remove "javascript:" if exists (it's an error)
		toDoOnClearError = toDoOnClearError.replace(/javascript:/i, '');
		eval(toDoOnClearError);
	}
	
}

/**
 * Add "onError" classname to the field, error image and error message.
 */
function showError(input, validation, msgParams) { 
	fieldsOnError.push(input);

	input.addClassName("onError");

	var img = getErrorImg(input);
	if (img) {
		img.addClassName("onError");
		if(NRS){
			var img_name = getErrorImgName(input);
			DstepRoll(img_name,ImgON,0);
		}
	} else if (DEBUG && NRS) {
		alert("Cannot find error image for '" + input.id + "'"); 
	}
	
	var errMsgContainer = getErrorContainer(input, validation);
	if (errMsgContainer) {
		errMsgContainer.addClassName("onError");
		updateErrorMessage(input, validation, errMsgContainer, msgParams);
		
		addMessageToList(errMsgContainer.innerHTML);
	} else if (DEBUG) {
		alert("Cannot find error message for '" + input.id + "' - " + validation);
	}
	
	var toDoOnShowError = input.getAttribute("af_onShowError");
	if (toDoOnShowError) {
		// remove "javascript:" if exists (it's an error)
		toDoOnShowError = toDoOnShowError.replace(/javascript:/i, '');
		eval(toDoOnShowError);
	}
}

/**
 * Add the message to the top list of error messages, and only if the message is not already in the list 
 */
function addMessageToList(message) {
	var isMessageFound = false;
	for (var i = 0; i < errorMessages.length; i++) {
		if (errorMessages[i] == message) {
			isMessageFound = true;
			break;
		}
	}
	if (!isMessageFound) {
		errorMessages.push(message);
	}
}

/**
 * Get the id to use for image, errorContainer, label, etc...
 */
function getErrorId(input) {
	var id = input.getAttribute("af_idError");
	if (!id) { /* no custom id defined for this input, use the id of the input */
		id = input.id;
	}
	return id;
}
/**
 * Gets the error image nameassociated to the specified input
 */ 
function getErrorImgName(input) {
	return "img_" + getErrorId(input);	
}

/**
 * Gets the error image associated to the specified input
 */ 
function getErrorImg(input) {
	return $("img_" + getErrorId(input));	
}
 	
/**
 * Gets the error message associated to the specified input and specified error type
 */ 
function getErrorContainer(input, validation) {
	return $('errmsg_' + validation + '_' + getErrorId(input));
}

/**
 * Gets the label asociated to the specified input
 */ 
function getLabel(input, validation) {
	return $('label_' + getErrorId(input));
}

/**
 * Update the content of the error message container :
 *     - use default error message if container is empty
 *     - replace {0} with the label of the field    
 */
function updateErrorMessage(input, validation, errMsgContainer, msgParams) {
	var msg = errMsgContainer.innerHTML;
	if (!msg && defaultErrorMessage[validation]) {
		  msg = defaultErrorMessage[validation];
	}
		 
	var label = getLabel(input);
	if (label) {
			msg = msg.replace('{0}', '<a href="#anchor_' + getErrorId(input) + '" tabindex="-1">' + label.innerHTML + '</a>');
			if (msgParams) {
				for (var p = 0; p < msgParams.length; p++) {
					msg = msg.replace('{'+(p+1)+'}', msgParams[p]);
				}
			}
	} else if (DEBUG && msg.indexOf('{0}') != -1) {
			alert("Cannot find label for '" + input.id + "'");
	}
	
	errMsgContainer.innerHTML = msg;
}


/**
 * Get all the inputs with attribute "af_validation" in the specified form (or of the page if formId is null)
 */
function getAfValidationInputs(formId) {
	var afValidationInputs = new Array();
	
	if (!formId) {	
		// for each form
		var forms = document.getElementsByTagName("form");
		for (var f = 0; f < forms.length; f++) {
			if (forms[f].id) {
				// get the inputs of the form
				var inputs = getAfValidationInputs(forms[f].id);
				// add them to the result
				for (var i = 0; i < inputs.length; i++) {
					afValidationInputs.push(inputs[i]);
				}
			} else if (DEBUG) {
				alert("Form needs an id");
			}
		}	
	} else {	
		// get all the inputs of the specified form 
		var allInputs = $(formId).getElements(); 
	
		for (var i = 0; i < allInputs.length; i++) {
			var input = allInputs[i];
			
			// search the attribute af_validation 
			var validation = input.getAttribute("af_validation");
			if (validation) {
				afValidationInputs.push(input);
			}	
		}
	}
	
	return afValidationInputs;
}

var dynamicRegExp = new Array();

/**
 * add validation of the field on the onkeypress event for dynamic format validation
 */
function addDynamicValidation() {

	var inputs = getAfValidationInputs();
	for (var i = 0; i < inputs.length; i++) {	
		var input = inputs[i];
		
		// get the attribute af_validation 
		var validation = input.getAttribute("af_validation");

		// check the format of af af_validation attribute 
		if (AF_VALIDATION_FORMAT.test(validation)) {
			// the format is ok, extract values 
			var regexp = RegExp.$3;
			
			// add the dynamic check
			if (regexp.charAt(regexp.length - 1) == "d") {
				dynamicRegExp[input.id] = regexp;
				input.onkeyup = function() { 
					if (checkRegExp(dynamicRegExp[this.id], this)) {
						clearError(this);
					}
				};
			}
		} else {
			if (DEBUG) {
				alert("Bad af_validation format for the field '" + input.id + "'");
			}
		}		
	}
}

/*
 * Change the min - max parameters of the the af_validation attribute
 */
function changeLengthAFValidation(idInput,minLength,maxLength){
  var newAfValidation = $(idInput).getAttribute("af_validation").replace(/\[\d*-\d*\]/,"["+minLength+"-"+maxLength+"]");
  $(idInput).setAttribute("af_validation",newAfValidation);
}

/*
 * Change the regular expression parameter of the the af_validation attribute
 */
function changeRegexpAFValidation(idInput,newRegexp){
  var newAfValidation = $(idInput).getAttribute("af_validation").replace(/\/[^/]+\//,"/"+newRegexp+"/");
  $(idInput).setAttribute("af_validation",newAfValidation);
}

/*
 * Change the required parameters of the the af_validation attribute
 */
function changeRequiredAFValidation(idInput,oldRequired,newRequired){
  var newAfValidation = $(idInput).getAttribute("af_validation").replace(oldRequired,newRequired);
  $(idInput).setAttribute("af_validation",newAfValidation);
}


addEvent(window, "load", addDynamicValidation);

