/*
'---
'--- Validation.js - Fonctions de validation en JavaScript
'---
'--- Par Francois Cusson-Lafrenaye, ing.
'---     Seconde Vision [www.sv.qc.ca]
'---
'--- Ce fichier doit être inclus dans la section <HEAD>. Chacun des champs à valider peut
'--- être indiqué ainsi :
'---
'--- <SCRIPT>AjoutValidation("NomForm.NomChamp", VAL_NONVIDE + VAL_NOMBRE, "Vous devez indiquer de quoi de valides!");</SCRIPT>
'---
'--- REVISIONS
'--- 2008/09/30, JPB-	Adaptation
'---
*/

<!-- Fonctions de validation -->

var VAL_NONVIDE = 1;
var VAL_NOMBRE = 2;
var VAL_COMPARE_VALEUR_INT = 3;
var VAL_COMPARE_VALEUR_FLOAT = 4;
var VAL_COMPARE_VALEUR_DATE = 5;
var VAL_COMPARE_QUESTION_INT = 6;
var VAL_COMPARE_QUESTION_FLOAT = 7;
var VAL_COMPARE_QUESTION_DATE = 8;
var VAL_COMPARE_CONTROL_SUM = 9
var VAL_COMPARE_CONTROL_QUESTIONID = 10;
var VAL_COND_NONVIDE = 11;
var ALPHA_LENGTH = 12;
var ALPHA_WORD = 13;
var IFRAME_VALID = 14;
var VAL_NONVIDE_COND = 15;

var ArrayValidation = new Array();
var ArrayValidation_ComiteEthique = new Array();
var ArrayValidationQuestion_ComiteEthique = new Array();
var ArrayQuestionToggle = new Array();

function $N(el_name){ return $A(document.getElementsByName(el_name)).first(); }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * AjoutValidation() - Ajoute un item à valider
 */
function AjoutValidation(iChamp, iType, iMessageErreur)
{	
	ArrayValidation[ArrayValidation.length] = new Array(iChamp, iType, iMessageErreur);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * AjoutValidation_ComiteEthique() - Ajoute un item à valider pour les formulaires du Comité d'Éthique
 */
function AjoutValidation_ComiteEthique(iChamp, iType, iOperateur, iValeur, iMessageErreur, highlightID, errorID)
{	
	var error_id = (errorID == null ) ? 'error_type_' + iType + '_' + getOperatorText(iOperateur) : errorID;
	var nextId = ArrayValidationQuestion_ComiteEthique.length;
	ArrayValidationQuestion_ComiteEthique[nextId] = new Array();
	ArrayValidationQuestion_ComiteEthique[nextId]['champ'] = iChamp;
	ArrayValidationQuestion_ComiteEthique[nextId]['type'] = iType;
	ArrayValidationQuestion_ComiteEthique[nextId]['operateur'] = iOperateur;
	ArrayValidationQuestion_ComiteEthique[nextId]['valeur'] =  iValeur;
	ArrayValidationQuestion_ComiteEthique[nextId]['erreur'] = iMessageErreur;
	ArrayValidationQuestion_ComiteEthique[nextId]['highlightID'] = highlightID;
	ArrayValidationQuestion_ComiteEthique[nextId]['errorID'] = error_id;
	ArrayValidationQuestion_ComiteEthique[nextId]['conditionnalID'] = null;
}

function AjoutValidationConditionnel_ComiteEthique(iCondID, iChamp, iType, iOperateur, iValeur, iMessageErreur, highlightID, errorID)
{
	var error_id = (errorID == null ) ? 'error_type_' + iType + '_' + getOperatorText(iOperateur) : errorID;
	var nextId = ArrayValidationQuestion_ComiteEthique.length;
	ArrayValidationQuestion_ComiteEthique[nextId] = new Array();
	ArrayValidationQuestion_ComiteEthique[nextId]['champ'] = iChamp;
	ArrayValidationQuestion_ComiteEthique[nextId]['type'] = iType;
	ArrayValidationQuestion_ComiteEthique[nextId]['operateur'] = iOperateur;
	ArrayValidationQuestion_ComiteEthique[nextId]['valeur'] =  iValeur;
	ArrayValidationQuestion_ComiteEthique[nextId]['erreur'] = iMessageErreur;
	ArrayValidationQuestion_ComiteEthique[nextId]['highlightID'] = highlightID;
	ArrayValidationQuestion_ComiteEthique[nextId]['errorID'] = error_id;
	ArrayValidationQuestion_ComiteEthique[nextId]['conditionnalID'] = iCondID;
}

function AddQuestionToggle(elemID, switchID)
{
	var nextId = ArrayQuestionToggle.length;
	ArrayQuestionToggle[nextId] = new Array();
	ArrayQuestionToggle[nextId]['elemID'] = elemID;
	ArrayQuestionToggle[nextId]['switchID'] = switchID;
}

function toggleQuestionsVisibility()
{
	ArrayQuestionToggle.each(function(obj){
		var switches = obj['switchID'].split(',');
		var switchOn = false;
		switches.each(function(el){
			if(!switchOn)
			{
				var choix = $('ReponseChoix_' + el);
				
				if(choix)
				{
					if( isControlChecked(choix) ){
						switchOn = true;
					}
				}
			}
		});
		var tr_el = $(obj['elemID']);
		tr_el.style.display = switchOn ? 'block' : 'none';
		
		var iframes = tr_el.select('iframe');
		iframes.each(function(iframe){
			if(document.frames){
				document.frames[iframe.id].window.location.reload();
			}
			else{
				iframe.contentWindow.location.reload();
			}				  
		});
	});
	
	if( ArrayQuestionToggle.length > 0 )
		Ajust_Image(ImgLeftPaddingTop_value, ImgLeftPaddingLeft_value, ImgRightPaddingTop_value, ImgRightPaddingLeft_value);
}

function AjoutAlphaValidation_ComiteEthique(elem, type, minCount, maxCount)
{
	var el = $(elem);
	
	// Create stats panel if it doesn't exist already
	createStatsPanel(elem);
	
	switch(type)
	{
		case 'CHAR_STATS':
			new CharCountValidator(el.id, minCount, maxCount);
			break;
			
		case 'WORD_STATS':
			new WordCountValidator(el.id, minCount, maxCount);
			break;
	}
}

function getStatsPanelID(elem){ return elem + '_stats_panel'; }

function getCharCountPanelID(elem){ return elem + '_charCount';	}

function getWordCountPanelID(elem){	return elem + '_wordCount';	}

function createStatsPanel(elem)
{
	var el = $(elem);
	var parent = el.up();
	var panel = null;
	
	if(parent.hasClassName('TD_Reponse'))
	{
		panel = parent.select('#' + elem + '_stats_panel');
		
		if(panel.size() == 0)
		{
			parent.insert('<div id="' + elem + '_stats_panel"><div id="' + elem + '_charCount"></div><div id="' + elem + '_wordCount"></div></div>');
		}
		
	}
}

var CharCountValidator = Class.create({
	initialize: function(fieldid, minChar, maxChar){
		this.currentCount = 0;
		this.fieldid = fieldid;
		this.minChar = minChar;
		this.maxChar = maxChar;
		$(fieldid).observe('keydown', this.updateCountOnKeyPress.bind(this));
		$(fieldid).observe('blur', this.updateCountOnKeyPress.bind(this));
		$(fieldid).observe('change', this.updateCountOnKeyPress.bind(this));
	},
	updateCountOnKeyPress: function(event) {
		this.currentCount = $(this.fieldid).getValue().length;
			
		refreshCharCount(this.fieldid, this.currentCount, checkMinCount(this.minChar, this.currentCount), checkMaxCount(this.maxChar, this.currentCount), this.minChar, this.maxChar);
	}
});

var WordCountValidator = Class.create({
	initialize: function(fieldid, minWord, maxWord){
		this.currentCount = 0;
		this.fieldid = fieldid;
		this.minWord = minWord;
		this.maxWord = maxWord;
		$(fieldid).observe('keydown', this.updateCountOnKeyPress.bind(this));
		$(fieldid).observe('blur', this.updateCountOnKeyPress.bind(this));
		$(fieldid).observe('change', this.updateCountOnKeyPress.bind(this));
	},
	updateCountOnKeyPress:function(event) {
		this.currentCount = $(this.fieldid).getValue().length == 0 ? 0 : $(this.fieldid).getValue().split(' ').length;
		
		refreshWordCount(this.fieldid, this.currentCount, checkMinCount(this.minWord, this.currentCount), checkMaxCount(this.maxWord, this.currentCount), this.minWord, this.maxWord);
	}
});

function refreshWordCount(el_id, count, isMinError, isMaxError, minValue, maxValue)
{
	var panel = $(getWordCountPanelID(el_id));
	var message = 'Nombre de mot(s): ' + count;
	
	if(isMinError && isMaxError && minValue != 0 && maxValue != 0)
		message += ' <span style="color: #ff0000; font-weight: bold;">Vous devez avoir entre ' + minValue + ' et ' + maxValue + ' mots</span>';
	else if(isMinError && minValue != 0)
		message += ' <span style="color: #ff0000; font-weight: bold;">Vous devez avoir un minimum de ' + minValue + ' mots</span>';
	else if(isMaxError&& maxValue != 0)
		message += ' <span style="color: #ff0000; font-weight: bold;">Vous devez avoir un maximum de ' + maxValue + ' mots</span>';
	
	
	panel.update(message);
	
	Ajust_Image(ImgLeftPaddingTop_value, ImgLeftPaddingLeft_value, ImgRightPaddingTop_value, ImgRightPaddingLeft_value);
}

function refreshCharCount(el_id, count, isMinError, isMaxError, minValue, maxValue)
{
	var panel = $(getCharCountPanelID(el_id));
	var message = 'Nombre de caractère(s): ' + count;
	
	if(isMinError && isMaxError && minValue != 0 && maxValue != 0)
		message += ' <span style="color: #ff0000; font-weight: bold;">Vous devez avoir entre ' + minValue + ' et ' + maxValue + ' caractères</span>';
	else if(isMinError && minValue != 0)
		message += ' <span style="color: #ff0000; font-weight: bold;">Vous devez avoir un minimum de ' + minValue + ' caractères</span>';
	else if(isMaxError && minValue != 0)
		message += ' <span style="color: #ff0000; font-weight: bold;">Vous devez avoir un maximum de ' + maxValue + ' caractères</span>';
	
	panel.update(message);
	
	Ajust_Image(ImgLeftPaddingTop_value, ImgLeftPaddingLeft_value, ImgRightPaddingTop_value, ImgRightPaddingLeft_value);
}

function checkMinCount(minCount, value)
{	
	return value < minCount;
}

function checkMaxCount(maxCount, value)
{	
	return value > maxCount;
}

function resetValidation(formID)
{
	var form = $(formID);
	
	var erreurs = form.select(".erreur");
	var has_error = erreurs.size() > 0;
	
	if(has_error)
	{
		erreurs.each(function(_err){
			_err.remove();
		});
	}
}

function add_error(elem, errorID, message)
{
	var el = $(elem);
	el.insert('<div id="' + errorID + '" class="erreur">' + message  + '</div>');
}

function remove_errors(elem)
{
	var el = $(elem);
	var erreurs = el.select('.erreur');
	
	erreurs.each(function(_err){
		_err.remove();
	});
	
	if(el.id == 'TitreEtape')
		el.style.display = 'block';
}

function isControlEmpty(ctl)
{
	var el = $(ctl);
	var empty = false;
	//alert(el.type);
	if(el == null)
	{
		// Try to see if its a radio or checkbox group
		elems = $A(document.getElementsByName(ctl));
		
		var howManyChecked = 0;
		
		elems.each(function(elem){
			if(elem.checked) howManyChecked++;
		});
		
		empty = howManyChecked == 0;
	} else {
	
		if(el.type == 'textarea')
		{
			empty = el.getValue() == "";
		}
		else if(el.type == 'text')
		{
			empty = el.getValue() == "";	
		}
		else if(el.type == 'checkbox')
		{
			var elems = $A(document.getElementsByName(el.name));
			var howManyChecked = 0;
			
			elems.each(function(elem){
				if(elem.checked) howManyChecked++;
			});
			
			empty = howManyChecked == 0;
			
		}else if(el.type == 'radio'){
			
			var elems = $A(document.getElementsByName(el.name));
			var howManyChecked = 0;
			
			elems.each(function(elem){
				if(elem.checked) howManyChecked++;
			});
			
			empty = howManyChecked == 0;
		}else if(el.type == 'file'){
			empty = el.getValue() == '' && $('Hidden' + el.id).getValue() == '';
		}
		else if(el.type == 'select-one')
		{
			empty = el.getValue() == "";	
		}
	}
	
	return empty;
}

function compareValues(ctl, compareType, dataType, value)
{
	var el = $(ctl);

	var el_value = 0;
	var result = false;

	if(dataType == 'date' && el == null)
	{
		var idReg=new RegExp("(DateReponse_)", "g");
		var currentID = ctl.replace(idReg,"");
		
		var objYear = $N('FirstSelectYear_' + currentID);
		var year = objYear.value != '' ? objYear.value : objYear['options'][objYear['selectedIndex']].text ;
		
		var objMonth = $N('FirstSelectMonth_' + currentID);
		var month = objMonth.value != '' ? parseInt(objMonth.selectedIndex) + 1 : objMonth['selectedIndex'] + 1 ;
		
		var objDay = $N('FirstSelectDay_' + currentID);
		var day = objDay.value != '' ? objDay.value : objDay['options'][objDay['selectedIndex']].text ;
		
		
		var paddedMonth = ((month) < 10) ? '0' + month : month ;
		var paddedDay = (day < 10) ? '0' + day : day ;
		
		el_value = parseInt(year +  paddedMonth + paddedDay);
		
		dataType = 'dateCombo';
	}
	
	switch(dataType)
	{
		case 'int':
			el_value = el.getValue() == "" ? 0 : parseInt(el.getValue());	
			value = parseInt(value);
			break;
			
		case 'float':
			el_value = el.getValue() == "" ? 0 : parseFloat(el.getValue());	
			value = parseFloat(value);	
			break;
			
		case 'date':
			var reg=new RegExp("(-)", "g");
			el_value = el.getValue() == "" ? 0 : parseInt(el.getValue().replace(reg,""));	
			value = parseInt(value.replace(reg,""));
			break;
			
		case 'dateCombo':
			var reg=new RegExp("(-)", "g");
			//el_value already set
			value = parseInt(value.replace(reg,""));
			break;
	}
	
	switch(compareType)
	{
		case '=':
			result = (el_value == value);
		break;
		case '>':
			result = (el_value > value);
		break;
		case '>=':
			result = (el_value >= value);
		break;
		case '<':
			result = (el_value < value);
		break;
		case '<=':
			result = (el_value <= value);
		break;
		case '<>':
			result = (el_value != value);
		break;
	}
	
	return result;
}

function compareControlValues(ctl, compareType, dataType, compareTo)
{
	switch(dataType)
	{
		case 'date':
			compareTo = 'DateReponse_' + compareTo;
		break;
		default:
			compareTo = 'ReponseQuestion_' + compareTo;
	}
	
	var el = $(ctl);
	var compare_el = $(compareTo);

	var el_value = null;
	var compare_value = null;
	var result = false;
	var dateReg = new RegExp("(-)", "g");
	
	// If ctl is a date combo box selector, retrieve the 3 selectors
	if(dataType == 'date' && el == null)
	{
		var idReg=new RegExp("(DateReponse_)", "g");
		var currentID = ctl.replace(idReg,"");
		
		var objYear = $N('FirstSelectYear_' + currentID);
		var year = objYear.value != '' ? objYear.value : objYear['options'][objYear['selectedIndex']].text ;
		
		var objMonth = $N('FirstSelectMonth_' + currentID);
		var month = objMonth.value != '' ? parseInt(objMonth.selectedIndex) + 1 : objMonth['selectedIndex'] + 1 ;
		
		var objDay = $N('FirstSelectDay_' + currentID);
		var day = objDay.value != '' ? objDay.value : objDay['options'][objDay['selectedIndex']].text ;
		
		var paddedMonth = ((month) < 10) ? '0' + month : month ;
		var paddedDay = (day < 10) ? '0' + day : day ;
		
		el_value = parseInt(year +  paddedMonth + paddedDay);
	}
	else if(dataType == 'date' && el != null)
	{
		el_value = (el.getValue() == "") ? 0 : parseInt(el.getValue().replace(dateReg,""));
	}
	
	// If compareTo is a date combo box selector, retrieve the 3 selectors
	if(dataType == 'date' && compare_el == null)
	{
		var idReg=new RegExp("(DateReponse_)", "g");
		var currentID = compareTo.replace(idReg,"");
		
		var objYear = $N('FirstSelectYear_' + currentID);
		var year = objYear.value != '' ? objYear.value : objYear['options'][objYear['selectedIndex']].text ;
		
		var objMonth = $N('FirstSelectMonth_' + currentID);
		var month = objMonth.value != '' ? parseInt(objMonth.selectedIndex) + 1 : objMonth['selectedIndex'] + 1 ;
		
		var objDay = $N('FirstSelectDay_' + currentID);
		var day = objDay.value != '' ? objDay.value : objDay['options'][objDay['selectedIndex']].text ;
		
		
		var paddedMonth = ((month) < 10) ? '0' + month : month ;
		var paddedDay = (day < 10) ? '0' + day : day ;
		
		compare_value = parseInt(year +  paddedMonth + paddedDay);
	}
	else if(dataType == 'date' && compare_el != null)
	{
		compare_value = (compare_el.getValue() == "") ? 0 : parseInt(compare_el.getValue().replace(dateReg,""));	
	}
	
	switch(dataType)
	{
		case 'int':
			el_value = el.getValue() == "" ? 0 : parseInt(el.getValue());
			compare_value = compare_el.getValue() == "" ? 0 : parseInt(compare_el.getValue());
			break;
			
		case 'float':
			el_value = el.getValue() == "" ? 0 : parseFloat(el.getValue());	
			compare_value = compare_el.getValue() == "" ? 0 : parseFloat(compare_el.getValue());	
			break;
	}
	
	switch(compareType)
	{
		case '=':
			result = (el_value == compare_value);
		break;
		case '>':
			result = (el_value > compare_value);
		break;
		case '>=':
			result = (el_value >= compare_value);
		break;
		case '<':
			result = (el_value < compare_value);
		break;
		case '<=':
			result = (el_value <= compare_value);
		break;
		case '<>':
			result = (el_value != compare_value);
		break;
	}
	
	if(dataType == 'date')
	{
		compare_value = compare_value + '';
		compare_value = compare_value.substring(0,4) + '-' + compare_value.substring(4,6) + '-' + compare_value.substring(6,8);
	}
	var ret_val = Array();
	ret_val['valid'] = result;
	ret_val['value'] = compare_value;
	
	return ret_val;
}

function getOperatorText(type)
{
	switch(type)
	{
		case '=':
			result = 'equal';
		break;
		case '>':
			result = 'greater';
		break;
		case '>=':
			result = 'greaterThanEqual';
		break;
		case '<':
			result = 'lessThan';
		break;
		case '<=':
			result = 'lessThanEqual';
		break;
		case '<>':
			result = 'differentThan';
		break;
		default:
			result = 'notNull';
	}
	
	return result;
}

function valueGreaterEqualThan(ctl, value)
{
	return compareValues(ctl,'>=', value);
}

function valueGreaterThan(ctl, value)
{
	return compareValues(ctl,'>', value);
}

function valueIsEqualTo(ctl, value)
{
	return compareValues(ctl,'=', value);
}

function valueLessThan(ctl, value)
{
	return compareValues(ctl,'<', value);
}

function valueLessEqualThan(ctl, value)
{
	return compareValues(ctl,'<=', value);
}

function valueDifferentThan(ctl, value)
{
	return compareValues(ctl,'<>', value);
}

function isControlChecked(ctl)
{
	var el = $(ctl);
	
	if(el)
		return el.checked;
	else
		return false;
}

function areControlsChecked(ctls)
{
	var elems = ctls.split(',');
	var valid = false;
	
	elems.each(function(id){
		valid = isControlChecked('ReponseChoix_' + id);
	});
	
	return valid;
}

function checkAlphaValidation(ctl, type, operateur, value)
{
	var el = $(ctl);
	var ctl_value = (type == 'length') ? el.getValue().length : el.getValue().split(' ').length;
	
	var keepIDReg = new RegExp("(ReponseQuestion_)", "g");
	var question_header = $('TRHidden_' + ctl.replace(keepIDReg, ''));
	
	if(question_header.style.display == "none")
	{
		// Bypass validation if control is hidden
		return true;	
	} else {
		switch(operateur)
		{
			case '<':
				result = ctl_value < value;
			break;
			
			case '>':
				result = ctl_value > value;
			break;
			
			case '<=':
				result = ctl_value <= value;
			break;
			
			case '>=':
				result = ctl_value >= value;
			break;	
		}
	}

	return result;
}

function compareControlSum(ctls, value)
{
	var elems = ctls.split(",");
	var sum = 0;
	var valid = false;
	
	elems.each(function(el){
		
		var current_el = $('ReponseQuestion_' + el);
		
		if(current_el != null)
		{
			current_el.removeClassName('highlight');
			if($('TRHidden_' + el).style.display == 'none'){
				current_el.clear();	
			}else{
				var current_value = current_el.getValue();
				if(current_value != '')
				sum += parseInt(current_value);
			}
		}
	});
	
	valid = sum == value;
	
	if(!valid)
	{
		elems.each(function(el){
			$('ReponseQuestion_' + el).addClassName('highlight');
		});
	}
	
	return valid;	
}

function getControlValue(elem)
{
	var el = $('ReponseQuestion_' + elem);
	
	if(el && el.type == "text")
	{
		return el.getValue();
	}
	
	return 0;
}


function isIFrameValid(ctl, id)
{
	var el = $(ctl);
	var header = $('TRHidden_' + id);
	
	var valid = false;
	
	if(header == null)
		return true;
		
	if(header.style.display == 'none')
		return true;
	
	if(el == null)
		return false;
	
	if(document.frames)
		valid = eval("document.frames." + ctl + ".document.getElementById('HiddenQuestionValide').value");
	else
		valid = $(ctl).contentDocument.getElementById('HiddenQuestionValide').value;
	
	return valid == 'true' ? true : false ;
}

/* Deprecated 
function highlight_error(elem, errorID, message, valid)
{
	var el = $(elem);
	var erreurs = el.select("#" + errorID);
	var has_error = erreurs.size() > 0;
	
	// Si la question est valide et qu'elle contient des erreurs, les enlever
	if(valid && has_error)
	{
		erreurs.each(function(_err){
			_err.remove();
		});
	}else if(!valid && !has_error){
		el.insert('<div id="' + errorID + '" class="erreur">' + message  + '</div>');
	}
}
*/

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DoValidation_Formulaire() - Valide chacun des items enregistrés dans ArrayValidation
*/
function DoValidation_Formulaire_Question_A_Valider()
{
	/*var i = 0;
	var Champ;
	*/
	formValid = true;
	var errors = Array();
	
	ArrayValidationQuestion_ComiteEthique.each(function(valid){
		var questionValid = false;
		var error_message = null;
		var compReg = new RegExp("(%VALUE%)", "g");
		
		switch(valid['type'])
		{
			case VAL_NONVIDE:
				questionValid = !isControlEmpty(valid['champ']);
				break;
			
			case VAL_COMPARE_VALEUR_INT:
				questionValid = compareValues(valid['champ'], valid['operateur'], 'int', valid['valeur']);
				break;
				
			case VAL_COMPARE_VALEUR_FLOAT:
				questionValid = compareValues(valid['champ'], valid['operateur'], 'float', valid['valeur']);
				break;
			
			case VAL_COMPARE_VALEUR_DATE:
				questionValid = compareValues(valid['champ'], valid['operateur'], 'date', valid['valeur'] );
				break;
			
			case VAL_COMPARE_CONTROL_SUM:
				questionValid = compareControlSum(valid['champ'], valid['valeur']);
				break;
			
			case VAL_COMPARE_CONTROL_QUESTIONID:
				ret_val = getControlValue(valid['valeur']);
				questionValid = compareControlSum(valid['champ'], ret_val);
				error_message = valid['erreur'].replace(compReg, ret_val);
				break;
				
			case VAL_COND_NONVIDE:
				questionValid = isControlChecked(valid['conditionnalID']) ? !isControlEmpty(valid['champ']) : true;
				break;
				
			case VAL_COMPARE_QUESTION_INT:
				ret_val = compareControlValues(valid['champ'], valid['operateur'], 'int', valid['valeur']);
				questionValid = ret_val['valid'];
				compared_value = ret_val['value'];
				error_message = valid['erreur'].replace(compReg, compared_value);
				break;
				
			case VAL_COMPARE_QUESTION_FLOAT:
				ret_val = compareControlValues(valid['champ'], valid['operateur'], 'float', valid['valeur']);
				questionValid = ret_val['valid'];
				compared_value = ret_val['value'];
				error_message = valid['erreur'].replace(compReg, compared_value);
				break;
				
			case VAL_COMPARE_QUESTION_DATE:
				ret_val = compareControlValues(valid['champ'], valid['operateur'], 'date', valid['valeur']);
				questionValid = ret_val['valid'];
				compared_value = ret_val['value'];
				error_message = valid['erreur'].replace(compReg, compared_value);
				break;
				
			case ALPHA_LENGTH:
				questionValid = checkAlphaValidation(valid['champ'], 'length', valid['operateur'], valid['valeur'])
				break;
				
			case ALPHA_WORD:
				questionValid = checkAlphaValidation(valid['champ'], 'word', valid['operateur'], valid['valeur'])
				break;
				
			case IFRAME_VALID:
				questionValid = isIFrameValid(valid['champ'], valid['valeur']);
				break;
				
			case VAL_NONVIDE_COND:
				needsAdditionalValidation = areControlsChecked(valid['valeur']);
				questionValid = needsAdditionalValidation ? !isControlEmpty(valid['champ']) : true;
		}
		
		remove_errors(valid['highlightID']);
		
		if(!questionValid){
			formValid = false;
			var error = Array();
			error['id'] = valid['highlightID'];
			error['errorID'] = valid['errorID'];
			error['message'] = error_message == null ? valid['erreur'] : error_message ;
				
			errors.push(error)
		}

	});
	
	var my_errors = $A(errors);
	my_errors.each(function(err){
		add_error(err['id'], err['errorID'], err['message']);
	});
	
	Ajust_Image(ImgLeftPaddingTop_value, ImgLeftPaddingLeft_value, ImgRightPaddingTop_value, ImgRightPaddingLeft_value);
	
	return formValid;
}

/* FIN FONCTION DE VALIDATION USERFRIENDLY (sans alert()) */

function EnleverValidation(iChamp, iType, iMessageErreur, WhichTextbox_)
{
	var valeurRechercher = iChamp + "," + iType + "," + iMessageErreur;
	var indexTrouver = -1;

	for(i=0; i<ArrayValidation.length; i++)
	{
		if(ArrayValidation[i] == valeurRechercher)
		{
			indexTrouver = i;
		}
	}

	if(indexTrouver != -1)
	{
		ArrayValidation.splice(indexTrouver, 1);
		//$(WhichTextbox_).value = "";
	}
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * DoValidation() - Valide chacun des items enregistrés dans ArrayValidation
 */
function DoValidation()
{
	var i = 0;
	var Champ;

	for ( ; i < ArrayValidation.length; i++)
	{
		// Accès à l'objet Champ avec gestion des [] dans les noms en PHP
		if (ArrayValidation[i][0].indexOf("[]") < 0)
		{
			Champ = eval("document." + ArrayValidation[i][0]);
		}
		else
		{
			// On utilise la forme NomForm.elements['NomChamp[]']
			var NomChamp = ArrayValidation[i][0].replace(".", ".elements['") + "']";
			Champ = eval("document." + NomChamp);
		}
		
		// Si le champ est valide...
		if (typeof(Champ) != "undefined")
		{
            // Sinon, si le champ est une liste (select)...
            if (typeof(Champ.options) != "undefined")
            {
				// Non-vide?
				if (ArrayValidation[i][1] & VAL_NONVIDE)
				{
					// On s'assure que la valeur sélectionnée a une valeur non-vide
					var Selection = Champ.selectedIndex;
					var Valeur = "" + Champ.options[Selection].value;
					
					if (Valeur == "")
					{
						alert(ArrayValidation[i][2]);

						if (Champ.type != "hidden") Champ.focus();

						return false;
					}
                }
            }

			// Sinon, si le champ est un array...
			else if (typeof(Champ.length) != "undefined")
			{
				// Non-vide?
				if (ArrayValidation[i][1] & VAL_NONVIDE)
				{
					// On s'assure qu'on a au moins une valeur de choisie (attention si TEXT !)
					var Okay = false;
					var j = 0;

					for ( ; j < Champ.length; j++)
					{
						Okay |= Champ[j].checked;
					}

					if (!Okay)
					{
						alert(ArrayValidation[i][2]);

						if (Champ.type != "hidden") Champ[0].focus();

						return false;
					}
				}

				// Nombre?
				if (ArrayValidation[i][1] & VAL_NOMBRE)
				{
					// On regarde chaque champ et, s'il contient une valeur, elle doit etre numérique
					var j = 0;

					for ( ; j < Champ.length; j++)
					{
                        if (Champ[j].value != "")
					    {
                            // Protection contre les virgules et les espaces
						    if (Champ[j].value.indexOf(",") > -1 || Champ[j].value.indexOf(" ") > -1)
						    {
                                alert(ArrayValidation[i][2]);

							     if (Champ[j].type != "hidden") Champ[j].focus();

							     return false;
						    }
						    else if (isNaN(parseFloat(Champ[j].value)))
						    {
							     alert(ArrayValidation[i][2]);

							     if (Champ[j].type != "hidden") Champ[j].focus();

							     return false;
						    }
						    else
						    {
							     Champ.value = parseFloat(Champ.value);
						    }
						}
					}
				}
			}

			// Sinon, si le champ est un champ "ordinaire"...
			else if (typeof(Champ.length) == "undefined")
			{
				// Non-vide?
				if (ArrayValidation[i][1] & VAL_NONVIDE)
				{
					if (Champ.value == "" || Champ.value == " " || Champ.value == "  ")
					{
						alert(ArrayValidation[i][2]);

						if (Champ.type != "hidden") Champ.focus();

						return false;
					}
				}

				// Nombre?
				if (ArrayValidation[i][1] & VAL_NOMBRE)
				{
					if (Champ.value != "")
					{
						// Protection contre les virgules et les espaces
						if (Champ.value.indexOf(",") > -1 || Champ.value.indexOf(" ") > -1)
						{
							alert(ArrayValidation[i][2]);

							if (Champ.type != "hidden") Champ.focus();

							return false;
						}
						else if (isNaN(parseFloat(Champ.value)))
						{
							alert(ArrayValidation[i][2]);

							if (Champ.type != "hidden") Champ.focus();

							return false;
						}
						else
						{
							Champ.value = parseFloat(Champ.value);
						}
					}
				}
			}
			
			// Sinon, on a un probleme avec la validation!
			else 
			{
                alert("Le champ " + ArrayValidation[i][0] + " ne peut pas être validé.");
            }
		}
	}

	return true;
}


function ValideCourriel(iCourriel) 
{ 
    var re=/^[a-z\d]+((\.|-|_)[a-z\d]+)*@((?![-\d])[a-z\d-]{0,62}[a-z\d]\.){1,4}[a-z]{2,6}$/gi;
    return (iCourriel.match(re)==iCourriel)&&(iCourriel.substr(iCourriel.lastIndexOf("@")).length<=256);   
}

function VerificationDomaine(iCourriel)
{
    // Liste des domaines possibles
    var re=/^(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|aero|arpa|biz|com|coop|edu|eu|gov|info|int|mil|museum|name|net|org|pro|jobs|travel)$/gi;
    
    return iCourriel.substr(iCourriel.lastIndexOf(".") + 1).match(re)!=null;
}



/* DÉBUT FONCTION DE VALIDATION USERFRIENDLY (sans alert()) */
function ValiderFormulaireInscriptionEvenement()
{
	var Erreur = 0;
	
	// Reset les classes d'erreurs des champs Dates si c'est le cas
	$("TD_Date1").className = "TD_Label"
	$("TD_Date2").className = "TD_Label"
	$("TD_Date3").className = "TD_Label"
	$("TD_Date4").className = "TD_Label"
	$("TD_Date5").className = "TD_Label"
	$("TD_Date6").className = "TD_Label"
	
	// Valide Prenom
	if($("Prenom").value == "")
	{
		Erreur = 1;
		$("TD_MessageErreur").innerHTML = "<span>Votre prénom est obligatoire.</span>"
		$("TD_Prenom").className = "TD_LabelErreur"
		$('Prenom').focus();
		return false;
	}
	else
	{
		Erreur = 0;
		$("TD_MessageErreur").innerHTML = "&nbsp;"
		$("TD_Prenom").className = "TD_Label"
	}
	
	// Valide Nom
	if($("Nom").value == "")
	{
		Erreur = 1;
		$("TD_MessageErreur").innerHTML = "<span>Votre nom est obligatoire.</span>"
		$("TD_Nom").className = "TD_LabelErreur"
		$('Nom').focus();
		return false;
	}
	else
	{
		Erreur = 0;
		$("TD_MessageErreur").innerHTML = "&nbsp;"
		$("TD_Nom").className = "TD_Label"
	}
	
	// Valide Courriel
	if($('Courriel').value == "" || $("Courriel").value.indexOf("@") == -1 || $("Courriel").value.indexOf(".") == -1)
	{
		Erreur = 1;
		$("TD_MessageErreur").innerHTML = "<span>Votre courriel est obligatoire.</span>"
		$("TD_Courriel").className = "TD_LabelErreur"
		$('Courriel').focus();
		return false;
	}
	else
	{
		Erreur = 0;
		$("TD_MessageErreur").innerHTML = "&nbsp;"
		$("TD_Courriel").className = "TD_Label"
	}
	
	
	if(Erreur == 0)
		return true;
	else
		return false;
}



function ValiderFormulaireInscriptionSondage()
{
	var Erreur = 0;
	
	
	// Valide Courriel
	if($('Courriel').value == "" || $("Courriel").value.indexOf("@") == -1 || $("Courriel").value.indexOf(".") == -1)
	{
		Erreur = 1;
		$("TD_MessageErreur").innerHTML = "<span>Votre courriel est obligatoire.</span>"
		$("TD_Courriel").className = "TD_LabelErreur"
		$('Courriel').focus();
		return false;
	}
	else
	{
		Erreur = 0;
		$("TD_MessageErreur").innerHTML = "&nbsp;"
		$("TD_Courriel").className = "TD_Label"
	}
	
	
	if(Erreur == 0)
		return true;
	else
		return false;
}


function Clear_ToutesErreurValidationFormulaireInscriptionEvenement()
{
	$("TD_MessageErreur").innerHTML = "&nbsp;"
	$("TD_Prenom").className = "TD_Label"
	$("TD_Nom").className = "TD_Label"
	$("TD_Courriel").className = "TD_Label"
	
	$("TD_Date1").className = "TD_Label"
	$("TD_Date2").className = "TD_Label"
	$("TD_Date3").className = "TD_Label"
	$("TD_Date4").className = "TD_Label"
	$("TD_Date5").className = "TD_Label"
	$("TD_Date6").className = "TD_Label"
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DoValidation_Formulaire() - Valide chacun des items enregistrés dans ArrayValidation
*/
function DoValidation_Formulaire()
{
	var i = 0;
	var Champ;
	
	for ( ; i < ArrayValidation_ComiteEthique.length; i++)
	{
		// Accès à l'objet Champ avec gestion des [] dans les noms en PHP
		if (ArrayValidation_ComiteEthique[i][0].indexOf("[]") < 0)
		{
			Champ = eval("document." + ArrayValidation_ComiteEthique[i][0]);
		}
		else
		{
			// On utilise la forme NomForm.elements['NomChamp[]']
			var NomChamp = ArrayValidation_ComiteEthique[i][0].replace(".", ".elements['") + "']";
			Champ = eval("document." + NomChamp);
		}
		
		// Si le champ est valide...
		if (typeof(Champ) != "undefined")
		{
            // Sinon, si le champ est une liste (select)...
            if (typeof(Champ.options) != "undefined")
            {
				// Non-vide?
				if (ArrayValidation_ComiteEthique[i][1] & VAL_NONVIDE)
				{
					// On s'assure que la valeur sélectionnée a une valeur non-vide
					var Selection = Champ.selectedIndex;
					var Valeur = "" + Champ.options[Selection].value;
					
					if (Valeur == "")
					{
						//alert(ArrayValidation_ComiteEthique[i][2]);
						$("TD_MessageErreur").innerHTML = "<span>" + ArrayValidation_ComiteEthique[i][2] + "</span>";
						$("TD_Question_" + ArrayValidation_ComiteEthique[i][3]).className = "TD_QuestionErreur";

						if (Champ.type != "hidden") Champ.focus();

						return false;
					}
					else
					{
						$("TD_MessageErreur").innerHTML = "&nbsp;";
						$("TD_Question_" + ArrayValidation_ComiteEthique[i][3]).className = "TD_Question";
					}
                }
            }

			// Sinon, si le champ est un array...
			else if (typeof(Champ.length) != "undefined")
			{
				// Non-vide?
				if (ArrayValidation_ComiteEthique[i][1] & VAL_NONVIDE)
				{
					// On s'assure qu'on a au moins une valeur de choisie (attention si TEXT !)
					var Okay = false;
					var j = 0;

					for ( ; j < Champ.length; j++)
					{
						Okay |= Champ[j].checked;
					}

					if (!Okay)
					{
						//alert(ArrayValidation_ComiteEthique[i][2]);
						$("TD_MessageErreur").innerHTML = "<span>" + ArrayValidation_ComiteEthique[i][2] + "</span>";
						$("TD_Question_" + ArrayValidation_ComiteEthique[i][3]).className = "TD_QuestionErreur";

						if (Champ.type != "hidden") Champ[0].focus();

						return false;
					}
					else
					{
						$("TD_MessageErreur").innerHTML = "&nbsp;";
						$("TD_Question_" + ArrayValidation_ComiteEthique[i][3]).className = "TD_Question";
					}
				}

				// Nombre?
				if (ArrayValidation_ComiteEthique[i][1] & VAL_NOMBRE)
				{
					// On regarde chaque champ et, s'il contient une valeur, elle doit etre numérique
					var j = 0;

					for ( ; j < Champ.length; j++)
					{
                        if (Champ[j].value != "")
					    {
                            // Protection contre les virgules et les espaces
						    if (Champ[j].value.indexOf(",") > -1 || Champ[j].value.indexOf(" ") > -1)
						    {
                                alert(ArrayValidation_ComiteEthique[i][2]);

							     if (Champ[j].type != "hidden") Champ[j].focus();

							     return false;
						    }
						    else if (isNaN(parseFloat(Champ[j].value)))
						    {
							     alert(ArrayValidation_ComiteEthique[i][2]);

							     if (Champ[j].type != "hidden") Champ[j].focus();

							     return false;
						    }
						    else
						    {
							     Champ.value = parseFloat(Champ.value);
						    }
						}
					}
				}
			}

			// Sinon, si le champ est un champ "ordinaire"...
			else if (typeof(Champ.length) == "undefined")
			{
				// Non-vide?
				if (ArrayValidation_ComiteEthique[i][1] & VAL_NONVIDE)
				{
					if (Champ.value == "" || Champ.value == " " || Champ.value == "  ")
					{
						//alert(ArrayValidation_ComiteEthique[i][2]);
						$("TD_MessageErreur").innerHTML = "<span>" + ArrayValidation_ComiteEthique[i][2] + "</span>";
						$("TD_Question_" + ArrayValidation_ComiteEthique[i][3]).className = "TD_QuestionErreur";

						if (Champ.type != "hidden") Champ.focus();

						return false;
					}
					else
					{
						$("TD_MessageErreur").innerHTML = "&nbsp;";
						$("TD_Question_" + ArrayValidation_ComiteEthique[i][3]).className = "TD_Question";
					}
				}

				// Nombre?
				if (ArrayValidation_ComiteEthique[i][1] & VAL_NOMBRE)
				{
					if (Champ.value != "")
					{
						// Protection contre les virgules et les espaces
						if (Champ.value.indexOf(",") > -1 || Champ.value.indexOf(" ") > -1)
						{
							alert(ArrayValidation_ComiteEthique[i][2]);

							if (Champ.type != "hidden") Champ.focus();

							return false;
						}
						else if (isNaN(parseFloat(Champ.value)))
						{
							alert(ArrayValidation_ComiteEthique[i][2]);

							if (Champ.type != "hidden") Champ.focus();

							return false;
						}
						else
						{
							Champ.value = parseFloat(Champ.value);
						}
					}
				}
			}
			
			// Sinon, on a un probleme avec la validation!
			else 
			{
                alert("Le champ " + ArrayValidation_ComiteEthique[i][0] + " ne peut pas être validé.");
            }
		}
	}
	
	if(ArrayValidationQuestion_ComiteEthique.length > 0)
	{
		return DoValidation_Formulaire_Question_A_Valider();
	}
	else
		return true;
}
/* FIN FONCTION DE VALIDATION USERFRIENDLY (sans alert()) */



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * AjoutValidationQuestion_A_Valider_ComiteEthique() - Ajoute un item à valider pour les formulaires du Comité d'Éthique
 */
function AjoutValidationQuestion_A_Valider_ComiteEthique(iChamp, iType, iValidationOperateur, iValidationValeur, iMessageErreur, highlightID)
{	
	var nextId = ArrayValidationQuestion_ComiteEthique.length;
	ArrayValidationQuestion_ComiteEthique[nextId] = new Array();
	ArrayValidationQuestion_ComiteEthique[nextId]['champ'] = iChamp;
	ArrayValidationQuestion_ComiteEthique[nextId]['type'] = iType;
	ArrayValidationQuestion_ComiteEthique[nextId]['operateur'] = iValidationOperateur;
	ArrayValidationQuestion_ComiteEthique[nextId]['valeur'] = iValidationValeur;
	ArrayValidationQuestion_ComiteEthique[nextId]['erreur'] = iMessageErreur;
	ArrayValidationQuestion_ComiteEthique[nextId]['highlightID'] = highlightID;
}

//function getErrorID(id)

function EnableDisableChampsAutre_Checkbox(iObject, iCounterTextbox)
{
	var other = $("ReponseQuestionChampsAutreCheckbox_" + iCounterTextbox);
	
	if(other)
	{
		if(iObject)
		{
			if(iObject.checked == true)
			{
				other.disabled = "";
				other.focus();
			}
			else
			{
				other.value = "";
				other.disabled = "disabled";			
			}
		}
	}
}


function EnableDisableChampsAutre_RadioButton(iObject, iCounterTextbox, iNbChoix)
{
	for(Counter = 0; Counter < iNbChoix; Counter++)
	{
		var disablingField = $("ReponseQuestionChampsAutreRadioButton_" + Counter);
		if(disablingField)
		{
			disablingField.value = "";
			disablingField.disabled = "disabled";
		}
	}
	
	var otherFields = $("ReponseQuestionChampsAutreRadioButton_" + iCounterTextbox);
	if(otherFields)
	{
		otherFields.disabled = "";
		otherFields.focus();
	}
}

function AfficherCacherTRConditionnelle_Checkbox(iCheckbox, iTRHidden, iStringAutreCheckbox)
{
	if($("TRHidden_" + iTRHidden))
   	{
		if(iCheckbox.checked == true)
			$("TRHidden_" + iTRHidden).style.display = "";
		else
		{
			$("TRHidden_" + iTRHidden).style.display = "none";
			
			ArrayAutreCheckbox = iStringAutreCheckbox.split(",");
			if(ArrayAutreCheckbox.length > 0)
			{
				for(Counter = 0; Counter < ArrayAutreCheckbox.length; Counter++)
				{
					if(ArrayAutreCheckbox[Counter] != "")
						$("ReponseChoix_" + ArrayAutreCheckbox[Counter]).checked = false;
				}
			}
		}
		
		Ajust_Image(ImgLeftPaddingTop_value, ImgLeftPaddingLeft_value, ImgRightPaddingTop_value, ImgRightPaddingLeft_value);
   	}
}

function AfficherCacherTRConditionnelle_RadioButton(iRadioButton, iTRHidden)
{
	var hiddenIDs = $A(iTRHidden.split(','));
	
	hiddenIDs.each(function(hidden){
		var tr = $('TRHidden_' + hidden);
		tr.style.display = iRadioButton.checked ? '' : 'none' ;
	});
	
	Ajust_Image(ImgLeftPaddingTop_value, ImgLeftPaddingLeft_value, ImgRightPaddingTop_value, ImgRightPaddingLeft_value);
	/*
	if($("TRHidden_" + iTRHidden))
   	{
		if(iRadioButton.checked == true)
		{
			$("TRHidden_" + iTRHidden).style.display = "";
		}
		else
			$("TRHidden_" + iTRHidden).style.display = "none";			
		
		
   	}
	*/
}


function CacherTRConditionnelle_RadioButton(iRadioButton, iTRHidden)
{
	$("TRHidden_" + iTRHidden).style.display = "none";	
}


