// formLib.js
// Common functions used with forms
// Source: CGI Programming with Perl - O'Reilly - pp171-174


// We use this as a hash to track those elements validated on a per element 
// basis that have formatting problems
validate  = new Object();

// Takes a value, checks if it's an integer, and returns true or false
function IsInteger( Value ) {
	return ( Value == parseInt( Value ) );
}

// Takes a value and a range, checks if the value is in the range, and
// returns true or false
function inRange (value, low, high) {
	return (!(value < low) && value <= high );
}

// Checks values against format such as '#####' or '###-######-##'
function checkFormat (value, format){
	var formatOkay= true;
	if (value.length != format.length){
		return false;
	}
	for (var i = 0; i< format.length; i++ ){
		if (format.charAt(i) == '#' && ! isInteger( value.charAt(i) ) ){
			return false;
		}
		else if (format.charAt(i) != '#' &&
				 format.charAt(i) != value.charAt(i) ){
			return flase;
		}
	}
	return true;
}

// Takes a form and an array of element names; verifies that each has a value
function requireValues( form, requiredValues ) {
	for ( var i = 0; i < requiredValues.length; i++ ) {
		element = requiredText[i];
	    if ( form[element].value == "" ) {
	       alert ( "Veuillez compléter le champ " + element + ".");
	       return false;
	    }
	}
	return true;
}

// Takes a form and an array of element names; verifies that each has an
// option selected (other than the first; assumes that the first option in
// each select menu contains instructions)
function requireSelects (form, requiredSelect){
	for (var i = 0; i < requiredSelect.length; i++ ){
		element = requiredSelect[i];
		if (form[element].selectedIndex <= 0){
			alert ("Veuillez choisir une option pour le champ " + element + ".");
			return false;
		}
	}
	return true;
}


// Takes a form and an array of element names; verifies that each has a
// value checked
function requireRadios ( form, requiredRadio){
	for (var i= 0; i < requiredRadio.length; i++){
		element = requiredRadio[i];
		isChecked = false;
		for ( j = 0; j < form[element].length; j++ ) {
			if (form[element][j].checked) {
				isChecked = true;
			}
		}
		if ( ! isChecked ){
			alert ("Veuillez choisir une option pour le champ " + form[element][0].name + "." );
			return false;
		}
	}
	return true;
}

// Verify there are no uncorrected formatting problems with elements
// validated on a per element basis
function checkProblems (){
	for ( element in validate ){
		if ( ! validate[element] ) {
			alert ("Veuillez corriger le libellé du champ " + element + ".");
			return false;
		}
	}
	return true;
}

// Verifies if a value is positive
function isPositive( value ) {
	return ( value > 0 );
}




