//Validation Related Functions
// globals
var clickcheck = 0; 			//increments in verify(), prevents multiple submit
var errors = "";
var errorsf = "";
var english = true;
var allOptional = false; 	//Allows user to decide whether all fields are required or not.
function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}
function oCROption(checked, value)
{
	this.checked = checked;
	this.value = value;
}
function oCR(e) 
{
	this.name = e.name;
	this.type = e.type;
	if(e.alt != null) this.alt = e.alt;
	if(e.optional != null) this.optional = e.optional;
	this.myOptions = new Array();
}
function getDisplay(e) {
	if ((e.alt != null) && (e.alt != "")) {
		display = e.alt;
	} else {
		display = e.name;
	}
	return display;
}
function verify(f, english, allOptional) 
{
	
	var myobj = "";
	var myid = "";
	var msg = "";
	var empty_fields = "";
	lastElement = "_NoElement";
	var myArray = new Array();
	
	//must create a new array of objects to loop through
	for(i=0;i<f.length;i++) {
		e = f.elements[i];
		if((e.type != "checkbox") && (e.type != "radio")) {
			myArray[myArray.length] = e;
		} else {
			chkObjExist = 0;
			for(j=0;j<myArray.length;j++){
				if(myArray[j].name == e.name){
					chkObjExist=j;
				}
			}
			if(!chkObjExist) {
				idx = myArray.length;
				myArray[idx] = new oCR(e);
				myArray[idx].myOptions[myArray[idx].myOptions.length] = new oCROption(e.checked, e.value);
			} else {
				myArray[chkObjExist].myOptions[myArray[chkObjExist].myOptions.length] = new oCROption(e.checked, e.value);
			}
		}
	}
	
	// now loop through the new array
	for(var i = 0; i < myArray.length; i++) {
		var e = myArray[i]; // collections refered to by name
		var removedNode = "";
		myobj = e;
		myid = 'advice-' + e.name;
		try {
			document.getElementById(myid).style.display = "none";
		} catch(err) {
			//nothing
		}
		
		if(e.validated != null && e.validated != undefined)e.validated=false;
		if(!e.validated && e.name != lastElement) {
			lastElement = e.name;
			e.validated=true;
			
			// uncomment for no required fields ..
			if (allOptional == true) {
				if(e.optional == null) e.optional = true;
			}
			
			// NOT OPTIONAL - Does blank check
			if (((e.type == "text") || (e.type == "textarea") || (e.type == "file") || (e.type == "password")) && !e.optional) {
				// first check if the field is empty
				if ((e.value == null) || (e.value == "") || isblank(e.value)) {
					empty_fields += "<br> " + getDisplay(e);
					var obj = e;
					var id = 'advice-' + e.name;
					var prop = '__advice'+e.name;
					if (!obj[prop]){
						var advice = document.createElement('span');
						var message = "Required Field";
						advice.appendChild(document.createElement('br'));
						advice.appendChild(document.createTextNode(message));
						advice.appendChild(document.createElement('br'));
						advice.className = 'validation-advice';
						advice.id = id;
						obj.parentNode.className = 'doublespace';
						obj.parentNode.insertBefore(advice, obj.nextSibling);
					}	
					continue;
				}
			}
	
			//Required Checkbox/radio button
			if(((e.type == "radio") || (e.type == "checkbox")) && !e.optional) {
				crcheck=false;
	
				//single objects have no length
				if(e.myOptions.length) {
					for(k=0;k<e.myOptions.length;k++) {
						if(e.myOptions[k].checked) {
							crcheck=true;
						}
					}
				} else { 
					if(e.checked) {
						crcheck=true; // why? By clicking here you verify that...
					}
				}
	
				if(!crcheck) {
					empty_fields += "<br> " + getDisplay(e);
					var obj = e;
					var id = 'advice-' + e;
					var prop = '__advice'+e;
					if (!obj[prop]){
						var advice = document.createElement('span');
						var message = "Required Field";
						advice.appendChild(document.createElement('br'));
						advice.appendChild(document.createTextNode(message));
						advice.appendChild(document.createElement('br'));
						advice.className = 'validation-advice';
						advice.id = id;
	//					if (obj[0]){
	//						obj[0].parentNode.insertBefore(advice, obj[0].previousSibling);
	//					} else {
	//						obj.parentNode.insertBefore(advice, obj.previousSibling);
	//					}
					}
				}
			}
			// String validation
			// minLen=x; minimum string length (password length > 6 for example)
			// maxLen=y; maximum string length (not necessary with the use of forms)
			// compare=oElement; compare the value of the current element with that of another element
			if ((e.type == "text") || (e.type == "textarea") || (e.type == "file") || (e.type == "password")) {
				if(e.value.length < e.minLen){
					errors += getDisplay(e);
					errors += " must be at least " + e.minLen + " characters in length.<br>";
					errorsf += getDisplay(e);
					errorsf += " doit être au moins " + e.minLen + " caractères en longueur.<br>";
					var obj = e;
					var id = 'advice-' + e;
					var prop = '__advice'+e;
					if (!obj[prop]){
						var advice = document.createElement('span');
						var message = "Must be at least " + e.minLen + " characters in length.";
						advice.appendChild(document.createElement('br'));
						advice.appendChild(document.createTextNode(message));
						advice.appendChild(document.createElement('br'));
						advice.className = 'validation-advice';
						advice.id = id;
						obj.parentNode.insertBefore(advice, obj.nextSibling);
					}		
				}
				if(e.value.length > e.maxLen){
					errors += getDisplay(e);
					errors += " must be less than " + e.maxLen + " characters in length.<br>";
					errorsf += getDisplay(e);
					errorsf += " doit être moins que " + e.maxLen + " caractères en longueur.<br>";
					var obj = e;
					var id = 'advice-' + e;
					var prop = '__advice'+e;
					if (!obj[prop]){
						var advice = document.createElement('span');
						var message = "Must be less than " + e.minLen + " characters in length.";
						advice.appendChild(document.createElement('br'));
						advice.appendChild(document.createTextNode(message));
						advice.appendChild(document.createElement('br'));
						advice.className = 'validation-advice';
						advice.id = id;
						obj.parentNode.insertBefore(advice, obj.nextSibling);
					}		
				}
				if(e.compare != null && (e.compare.value != e.value)){
					errors += getDisplay(e);
					errors += " must match " + getDisplay(e.compare) + ".<br>";
					errorsf += getDisplay(e);
					errorsf += " doit correspondre " + getDisplay(e.compare) + ".<br>";
					var obj = e;
					var id = 'advice-' + e;
					var prop = '__advice'+e;
					if (!obj[prop]){
						var advice = document.createElement('span');
						var message = "Must match " + getDisplay(e.compare) +".";
						advice.appendChild(document.createElement('br'));
						advice.appendChild(document.createTextNode(message));
						advice.appendChild(document.createElement('br'));
						advice.className = 'validation-advice';
						advice.id = id;
						obj.parentNode.insertBefore(advice, obj.nextSibling);
					}	
				}
			}			
			// CHECK NUMERIC FORMAT
			// provide one of the following:
			//	min=q; if the value is an ID, and you want it > q to be valid..
			//	max=r; if the value is an ID, and you want it < r to be valid..
			if ((e.type == "text" || e.type == "textarea") && (e.numeric || (e.min != null) || (e.max != null)) && !isblank(e.value)) { 
				var myValue = e.value
				var v2 = myValue.replace(/,/g, "");
				var v3 = v2.replace("$","");
				var v = parseFloat(v3);
				if ((isNaN(v)) || ((e.min != null) && (v < e.min)) || ((e.max != null) && (v > e.max))) {
					var message ="";
					errors += "The field " + getDisplay(e) + " must be a number";
					errorsf += "Le champ " + getDisplay(e) + " doit être un nombre";
					message += "Must be a number";
					if (e.min != null) {
						errors += " that is greater than " + e.min;
						errorsf += " c'est plus grand que " + e.min;
						message += " greater than " + e.min;
					}
					
					if (e.max != null && e.min != null) {
						errors += " and less than " + e.max;
						errorsf += " et moins que " + e.max;
						message += " and less than " + e.max;
					} else if (e.max != null) {
						errors += " that is less than " + e.max;
						errorsf += " c'est moins que " + e.max;
						message += " less than " + e.max;
					}
					errors += ".<br>";
					errorsf += ".<br>";
					message += "."
					
					var obj = e;
					var id = 'advice-' + e;
					var prop = '__advice'+e;
					if (!obj[prop]){
						var advice = document.createElement('span');
						advice.appendChild(document.createElement('br'));
						advice.appendChild(document.createTextNode(message));
						advice.appendChild(document.createElement('br'));
						advice.className = 'validation-advice';
						advice.id = id;
						obj.parentNode.insertBefore(advice, obj.nextSibling);
					}	
				}
			}
	
			// CHECK EMAIL FORMAT
			if (e.emailFormat && ((e.type == "text") || (e.type == "textarea"))) {
				if (isblank(e.value) == false) {
					var emailError = 0
					
					indAt = e.value.indexOf('@');
					indDot = e.value.lastIndexOf('.');
				
					if ( (indAt == -1) || (indDot == -1) || (indDot < indAt) || (indDot < (e.value.length - 5)) || ((indDot - indAt) <= 1) || (indAt == 0) ) {
						errors += "<br>The email address '" + e.value + "' appears to be in an invalid format.<br>Please confirm the email address.<br>";
						errorsf += "Le couriel '" + e.value + "' semble être dans un format invalide. Veuillez confirmer l'adresse électronique.<br>";
						var obj = e;
						var id = 'advice-' + e;
						var prop = '__advice'+e;
						if (!obj[prop]){
							var advice = document.createElement('span');
							var message = "Invalid format.";
						advice.appendChild(document.createElement('br'));
							advice.appendChild(document.createTextNode(message));
							advice.appendChild(document.createElement('br'));
							advice.className = 'validation-advice';
							advice.id = id;
							obj.parentNode.insertBefore(advice, obj.nextSibling);
						}
					}
				}
			}
	
			// CHECK DATE FORMAT
			// required format: mm|dd|yyyy where | is any ascii character
			if (e.dateFormat && ((e.type == "text") || (e.type == "textarea"))) {
				if (isblank(e.value) == false) {
					var maxDays = 31;
					var allNumeric = true;
					theMonth = e.value.substring(0,2);
					theDay = e.value.substring(3,5);
					theYear = e.value.substring(6,10);
	
					if (isNaN(theMonth) || isNaN(theDay) || isNaN(theYear)) {
						allNumeric = false;
					} else {
						if (theMonth == 2)	{
							if ((theYear % 4) == 0) {
								maxDays = 29
							} else {
								maxDays = 28;
							}
						} else if ((theMonth == 4) || (theMonth == 6) || (theMonth == 9) || (theMonth == 11)) {
							maxDays = 30;
						}
					}
					
					if (
						(allNumeric == false) ||
						(e.value.length != 10) || 
						((theMonth < 1) || (theMonth > 12)) || 
						((theDay < 1) || (theDay > maxDays)) || 
						((theYear < 1900) || (theYear > 9999))
						) {
						errors += "<br>The date '" + e.value + "' appears to be in an invalid format.  <br>Please re-enter the date as mm/dd/yyyy.<br>";
						errorsf += "- La date '" + e.value + "' semble être dans un format invalide. Entrez s'il vous plaît dans la date comme mm/jj/aaaa.<br>";
						var obj = e;
						var id = 'advice-' + e;
						var prop = '__advice'+e;
						if (!obj[prop]){
							var advice = document.createElement('span');
							var message = "Invalid format.";
						advice.appendChild(document.createElement('br'));
							advice.appendChild(document.createTextNode(message));
							advice.appendChild(document.createElement('br'));
							advice.className = 'validation-advice';
							advice.id = id;
							obj.parentNode.insertBefore(advice, obj.nextSibling);
						}
					}
				}
			}
			//Dropdowns - make sure the item selected is a valid item
			//not appropriate for multiple selects
			//Dropdowns sometimes include headers
			//provide one of the following:
			//	inList=[true|false]; selectedIndex Must/Must Not be in indexList
			//	indexList="1,2,3,4,5,..n";
			//	min=q; if the value is an ID, and you want it > q to be valid..
			//	max=r; if the value is an ID, and you want it < r to be valid..
			if(((e.type == "select") || (e.type == "select-one")) && !e.multiple) {
				dropcheck=true;
				if(e.selectedIndex == null)e.selectedIndex=0;
				if(e.inList == null)e.inList=false;
				
				if(e.indexList){
					indexArray = e.indexList.split(",");
					for(idx=0;idx<indexArray.length;idx++){
						check=indexArray[idx];
						if((!e.inList && check==e.selectedIndex)||(e.inList && check!=e.selectedIndex)){
							dropcheck=false;
						}
					}
				}
				
				if ((e.min != null) && (e[e.selectedIndex].value < e.min)) dropcheck=false;
				if ((e.max != null) && (e[e.selectedIndex].value > e.max)) dropcheck=false;
				
				if(!dropcheck){
					errors += "<br>An inappropriate selection has been made in " + getDisplay(e) + "<br>";
					errorsf += "Un choix inopportun a été fait dans " + getDisplay(e) + "<br>";
					var obj = e;
					var id = 'advice-' + e;
					var prop = '__advice'+e;
					if (!obj[prop]){
						var advice = document.createElement('span');
						var message = "Inappropriate selection.";
						advice.appendChild(document.createElement('br'));
						advice.appendChild(document.createTextNode(message));
						advice.appendChild(document.createElement('br'));
						advice.className = 'validation-advice';
						advice.id = id;
						obj.parentNode.insertBefore(advice, obj.nextSibling);
					}
				}
				
			} 
		} // end check validated
	} // end for
    if (!empty_fields && !errors) {
		//wait = "Please wait while your entries are updated.\n(This may take up to a minute.)";
		//waitf = "Attendez s'il vous plaît tandis que vos entrées sont mises à jour. (Cela peut prendre jusqu'à une minute.)";
		//if(english)alert(wait);
		//if(!english)alert(waitf);
		
		clickcheck++;
		return true;
	}
    msg = "<br><b>This record cannot be saved because of the following error(s).</b><br>";
    msg += "<b>Please correct these error(s) and re-submit.</b><br><br>";
    msgf  = "______________________________________________________\n\n"
    msgf += "Le formulaire n'a pas été soumis à cause d'une ou des erreurs suivantes.\n";
    msgf += "Corrigez s'il vous plaît cette ou ces erreurs et resoumettre.\n";
    msgf += "______________________________________________________\n\n"
    if (empty_fields) {
        msg += "<b>The following required field(s) are empty:</b><br>" + empty_fields + "<br>";
        msgf += "Le ou les champs exigés suivant sont vide:" + empty_fields + "\n";
    }
    msg += "\n" + errors;
    msgf += "\n" + errorsf;
	
    if(!english)alert(msgf);
    if(english) {
		document.getElementById("myPanelBody").innerHTML = msg;
		window.location = "#Home";		
		document.getElementById("myPanel").style.display = "";
		
	//	alert(msg);
		
	}
	errors = "";
	errorsf = "";
    return false;
}
