// validation v2.3.0
// Last modified: Monday, February 11, 2002
/*
	Syntax: verify([form], [true|false], [true|false]);
	
	Example: verify([form], [true = english|false = french], [true = all fields optional|false = all fields required]);
	
	Attributes for different types
	------------------------------
	
	text, textarea, file, password
		numeric=[true|false];
		min=x;
		max=y;
		emailFormat=[true|false];
		urlFormat=[true|false];
		dateFormat=[true|false];
		minLen=x;
		maxLen=y;
		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
		allowChar=string; a string on chars, that are allowed (ie "1234567890()-." for a phone number)
	
	select-one, select(non-multiple)
		inList=[true|false];
		indexList="1,2,3,4,5,..n";
		min=x;
		max=y;
	
	radio, checkbox
		Example: f.element[0].alt = "Title";
	
	generic
		optional=[true|false];
		compare=formFieldObject;
		
	Warnings
		 a radio button/checkbox cannot be the first form element in a form.
		 
	Features that need to be added (or do we bother?)
		mask='mm/dd/yyyy';
		requiredBy=formFieldObject; not implemented - if value != '', e.optional=false;
		mask - Adding a a condition that if you encounter some special characters...  adding special character to the numeric option .... like () - or .  (telephone number)
*/

// 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 allowedChar(strValidCharacterSet, strToBeChecked) {
   var i;

   if (!strToBeChecked.length) { return false; }

   for (i=0; i<strToBeChecked.length; i++) {
	if (strValidCharacterSet.indexOf(strToBeChecked.charAt(i)) == -1) {
      return false;
    }
   }

   return true;
}

function verify(f, english, allOptional) 
{

	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
		
		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 += "\n " + getDisplay(e);
					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 += "\n " + getDisplay(e);
				}
			}

			// 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"))  && !isblank(e.value)) {
				if(e.value.length < e.minLen){
					errors += getDisplay(e);
					errors += " must be at least " + e.minLen + " characters in length.\n";
					errorsf += getDisplay(e);
					errorsf += " doit être au moins " + e.minLen + " caractères en longueur.\n";
				}
				if(e.value.length > e.maxLen){
					errors += getDisplay(e);
					errors += " must be less than " + e.maxLen + " characters in length.\n";
					errorsf += getDisplay(e);
					errorsf += " doit être moins que " + e.maxLen + " caractères en longueur.\n";
				}
				if(e.compare != null && (e.compare.value != e.value)){
					errors += getDisplay(e);
					errors += " must match " + getDisplay(e.compare) + ".\n";
					errorsf += getDisplay(e);
					errorsf += " doit correspondre " + getDisplay(e.compare) + ".\n";
				}
				if(e.value.length &&(e.allowChar != null) && (allowedChar(e.allowChar, e.value) == false)) {
					errors += getDisplay(e);
					errors += " contains invalid characters.\n";
					errorsf += getDisplay(e);
					errorsf += " contient des charactères invalides.\n";
				}
				
			}			

			// 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 v = parseFloat(e.value);
				var v2 = e.value.replace(/,/, "");

				if ((isNaN(v)) || (isNaN(v2)) || ((e.min != null) && (v < e.min)) || ((e.max != null) && (v > e.max))) {
					errors += "- The field " + getDisplay(e) + " must be a number";
					errorsf += "- Le champ " + getDisplay(e) + " doit être un nombre";

					if (e.min != null) {
						errors += " that is greater than " + e.min;
						errorsf += " c'est plus grand que " + e.min;
					}
					
					if (e.max != null && e.min != null) {
						errors += " and less than " + e.max;
						errorsf += " et moins que " + e.max;
					} else if (e.max != null) {
						errors += " that is less than " + e.max;
						errorsf += " c'est moins que " + e.max;
					}

					errors += ".\n";
					errorsf += ".\n";
				}

			}

	
			// 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 += "- The email address '" + e.value + "' appears to be in an invalid format.  Please confirm the email address.\n";
						errorsf += "- Le couriel '" + e.value + "' semble être dans un format invalide. Veuillez confirmer l'adresse électronique.\n";
					}
				}
			}

			// CHECK CANADA POSTAL CODE FORMAT
			if (e.canPostFormat && ((e.type == "text") || (e.type == "textarea"))) {
				if (isblank(e.value) == false) {
					e.value = e.value.toUpperCase();
					var canPostError = 0;
					
					if (e.value.length == 6) {					
						for (x=0;x<e.value.length;x++) {
							if ((x == 0 || x == 2 || x == 4) && !(allowedChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ", e.value.charAt(x)))) {
								canPostError = 1;
								break;
							} else if ((x == 1 || x == 3 || x == 5) && !(allowedChar("0123456789", e.value.charAt(x)))) {
								canPostError = 1;
								break;
							}
						}
					} else if (e.value.length == 7) {
						for (x=0;x<e.value.length;x++) {
							if ((x == 0 || x == 2 || x == 5) && !(allowedChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ", e.value.charAt(x)))) {
								canPostError = 1;
								break;
							} else if ((x == 1 || x == 4 || x == 6) && !(allowedChar("0123456789", e.value.charAt(x)))) {
								canPostError = 1;
								break;
							} else if ((x == 3) && !(allowedChar(" -", e.value.charAt(x)))) {
								canPostError = 1;
								break;
							}
						}
					} else {
						canPostError = 1;
					}
				
					if (canPostError) {		
						errors += "The postal code '" + e.value + "' appears to be in an invalid format.  Please confirm the postal code.\n";
						errorsf += "Le code postal '" + e.value + "' semble être d'un format invalide. S.V.P. confirmez le code postal.\n";
					}
				}
			}

			// CHECK US POSTAL CODE FORMAT
			if (e.usPostFormat && ((e.type == "text") || (e.type == "textarea"))) {
				if (isblank(e.value) == false) {
					var usPostError = 0;
					if (e.value.length == 5) {
						for (x=0;x<e.value.length;x++) {
							if ( allowedChar( "0123456789", e.value.charAt(x) ) == false)  {
								usPostError = 1;
								break;
							}
						}
					} else if (e.value.length == 10) {
						for (x=0;x<e.value.length;x++) {
							if (x != 5) {							
								if ( allowedChar( "0123456789", e.value.charAt(x) ) == false)  {
									usPostError = 1;
									break;
								}
							} else if (allowedChar("-", e.value.charAt(x)) == false) {
									usPostError = 1;
									break;
							}
						}
					} else {
						usPostError = 1;
					}
					if (usPostError) {		
						errors += "The zip code '" + e.value + "' appears to be in an invalid format.  Please confirm the zip code.\n";
						errorsf += "Le code postal '" + e.value + "' semble être d'un format invalide. S.V.P. confirmez le code postal.\n";
					}
				}
			}
			
			// CHECK URL FORMAT
			if (e.urlFormat && ((e.type == "text") || (e.type == "textarea"))) {
				if (isblank(e.value) == false) {
					var urlError = 0
					tmpURL = e.value.toLowerCase();
					
					indHttp = tmpURL.indexOf('http://');
					indHttps = tmpURL.indexOf('https://');
					indMailto = tmpURL.indexOf('mailto:');
					
					if ((indHttp == -1 && indHttps == -1 && indMailto == -1) || (indHttps != -1 && tmpURL.length <= 8) || (indHttp != -1 && tmpURL.length <= 7) || (indMailto != -1 && tmpURL.length <= 7) || !(allowedChar("a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,.,/,:,&,?,=,_,-,+,@", tmpURL))) {
						errors += "- The URL '" + e.value + "' appears to be in an invalid format.  Please confirm the URL.\n";
						errorsf += "- L'URL '" + e.value + "' semble être dans un format invalide. Veuillez confirmer l'URL.\n";
					}
				}
			}
			
			// CHECK DATE FORMAT
			// required format: m[m]|d[d]|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;
					var monthOneChar = false;
					var dayOneChar = false;
					
					theMonth = e.value.substring(0,2);
					if (isNaN(theMonth)) {
						theMonth = e.value.substring(0,1);
						monthOneChar = true;
					}
					
					if (monthOneChar) {
						theDay = e.value.substring(2,4);
						if (isNaN(theDay)) {
							theDay = e.value.substring(2,3);
							dayOneChar = true;
						}
					} else {
						theDay = e.value.substring(3,5);
						if (isNaN(theDay)) {
							theDay = e.value.substring(3,4);
							dayOneChar = true;
						}
					}
					
					if (monthOneChar && dayOneChar) {
						theYear = e.value.substring(4,8);
					} else if (monthOneChar || dayOneChar) {
						theYear = e.value.substring(5,9);
					} else {
						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) ||
						(e.value.length < 8) || 
						((theMonth < 1) || (theMonth > 12)) || 
						((theDay < 1) || (theDay > maxDays)) || 
						((theYear < 1900) || (theYear > 9999))
						) {
						errors += "- The date '" + e.value + "' appears to be in an invalid format.  Please re-enter the date as mm/dd/yyyy.\n";
						errorsf += "- La date '" + e.value + "' semble être dans un format invalide. Entrez s'il vous plaît dans la date comme mm/jj/aaaa.\n";
					}
				}
			}
	
			//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 && ((e[e.selectedIndex].value == "") && !e.optional)) {
					empty_fields += "\n " + getDisplay(e);
				} else if (!dropcheck && e[e.selectedIndex].value != "") {
					errors += "An inappropriate selection has been made in " + getDisplay(e) + "\n";
					errorsf += "Un choix inopportun a été fait dans " + getDisplay(e) + "\n";
				}
			} else if (((e.type == "select") || (e.type == "select-multiple")) && e.multiple) {
				cntSelected = 0;
				cntOkay = 0;
				
				for (curIdx=0;curIdx<e.options.length;curIdx++) {
					optionCheck = false;
					if (e.options[curIdx].selected) {
						cntSelected++;
						optionCheck = true;
						
						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==curIdx)||(e.inList && check!=curIdx)){
									optionCheck=false;
								}
							}
						}
						
						if ((e.min != null) && (e.options[curIdx].value < e.min)) optionCheck=false;
						if ((e.max != null) && (e.options[curIdx].value > e.max)) optionCheck=false;
					}
					if (optionCheck) {
						cntOkay++;
					}
				}
				
				if (cntSelected == 0 && !e.optional) {
					empty_fields += "\n " + getDisplay(e);
				} else if (cntSelected != cntOkay) {
					errors += "An inappropriate selection has been made in " + getDisplay(e) + "\n";
					errorsf += "Un choix inopportun a été fait dans " + getDisplay(e) + "\n";
				}
			} 

		} // 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  = "______________________________________________________\n\n"
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "______________________________________________________\n\n"

    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 += "- The following required field(s) are empty:" + empty_fields + "\n";
        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)alert(msg);

	errors = "";
	errorsf = "";

    return false;
}

function checkFilename(fileField, fieldLabel, validExt) {
	var fileNameOk = true;
	var fileExtOk = false;
	var errorCause = "";
	var fileExtension = "";
	var arrValidExt = validExt.split(',');
	
	if (fileField.value.length <= 0) {
		fileNameOk = false;
		errorCause += "  - No file selected\n";
	}
	
	if (fileNameOk) {
		fileExtension = fileField.value.substring(fileField.value.length - 4, fileField.value.length);
		if (validExt && validExt.length) {
			for (idx=0;idx<arrValidExt.length;idx++) {
				if (eval('.' + arrValidExt[idx]) == fileExtension) {
					fileExtOk = true;
					break;
				}
			}
		} else {
			fileExtOk = true;
		}
		
		if ((fileField.value.indexOf('.') == -1 || fileField.value.indexOf('.', fileField.value.length - 4) != fileField.value.length - 4) || !fileExtOk) {
			errorCause += "  - Invalid or Non-existant File Extension\n";
		}
	}
	
	if (!(fileNameOk) || !(fileExtOk)) {
		alert("The file selected in the field '" + fieldLabel + "' apprears to have the following errors:\n\n" + errorCause);
		return false;
	}
	
	return true;
}

function copyname(form, from, to, checkUp) {
	var strTmp = from.value;
	var strLength = strTmp.length; 
	var fileNameOk = true;
	var errorCause = "";
	var fileName = "";
	
	var counter = 0;
	for( var i=0; i<strLength; i++ ) {
		if( ( strTmp.substring( i, i+1 ) == "\\" ) || ( strTmp.substring( i, i+1 ) == "/" ) || ( strTmp.substring( i, i+1 ) == ":" ) ) {
			counter = i;
		}
	}
	
	fileName = strTmp.substring((counter + 1), strLength);
	to.value = fileName
	checkUp.value = 1;
}
