/*
	validate generic script thingie
	(c)2000 Ryan Vettese - Interface Developer (CE) - Organic
	        rvettese@organic.com - 416-874-7007
	---------------------------------------------------------
	Aug 30 00 - first version - very generic form checking
	          - code documentation added
	Sep 05 00 - multiple form handling added
	          - multi param functionality added
						- multiple multi param functionality added
	          - more 'generic' functions added
	Sep 06 00 - getFieldValue() to use netscape friendly 'selectedIndex'
	            for select boxes added
	          - checkbox/radio input value checking added
	Sep 06 01 - added ability to declare forms in seperate functions
	
	Things-to-Fix/Bugs/Issues/Problems/Work-Arounds:
	---------------------------------------------------------
	- CheckAlpha regular expression isn't correct.
	- flagError shouldn't write the remaining errors to the
	  errorText once an error has been written. (it gets too verbose).
	- \', \\ and similar have to be double escaped to make it through
	  to the generic function. i.e.: \' = \\\' and \\ = \\\\
	- how should we handle 'select-multiple's?  right now it will
	  only return the first select value.
	
	Setup:
	---------------------------------------------------------
	- set the 'check' param in an Array in the onSubmit param of the <form> tag.
	- array rules are pretty simple, you can have as many checks on a field as you want.

	- 'check' array setup goes:
			- position 0: nice name
			- position 1: default value for the field, i.e.: the field cannot equal this value
			- position 2...n: functions to run on field (*)

	- 'extraParams' array setup goes:
			- position 0: the matching function name
			- position 1...n: params to send to the function

	- (*) function notes:
			- each function assumes two parameters which are both
			  passed automatically by the function caller: arg_whichField and arg_niceName.
			- if a function requires more then the two basic params then the 'extraParams'
			  array needs to be added to the ogncUValParams() for that field.
			- checkLength and checkValidDate are examples of 'generic' functions that
			  require more than the two params.

*/

var err = 0;
var sendError = true;
var errorMessage = '';
var defaultFieldValue = '';
var formArray = new Array();

function submitForm(arg_which) {
	if(ogncUVal(arg_which)) eval(arg_which).submit();
}

function ogncUValAddForm(arg_which) {
	formArray[formArray.length+1] = arg_which;
}

function ogncUVal(arg_form) {
	//reset err counter and err text
	err=0;
	errorMessage='';

	//evaluate the argument back into an object
	validateForm=eval(arg_form);
	
	//set validate parameters
	for (a=0; a<formArray.length; a++) {
		if(formArray[a] && formArray[a].length>0) eval(formArray[a]+'()');
	}

	//loop through all the form elements
	for (x=0; x<validateForm.elements.length; x++)
	{
		formElement = validateForm.elements[x];
		fieldName = formElement.name;
		//check to see if the 'check' param has been set for the current form element
		if(formElement.check)
		{
			//set the nice name from the first param if the 'check' array.
			niceName = formElement.check[0];
			defaultValue = formElement.check[1];

			//loop through the rest of the 'check' array.
			for (yc=2; yc<formElement.check.length; yc++)
			{
				functionName = formElement.check[yc];
				//call the param as a function with two arguments.
				//arg 1 - the form field name in string format.
				//        note: we have to send the string and not the value because we
				//        may need reformat the field value with the clean functions.
				//arg 2 - the nice name for the error alert.
				functionCall = functionName+'(\''+arg_form+'.elements.'+fieldName+'\',\''+niceName+'\'';
				if(formElement.extraParams)
				{
					for(extraFuncs=0;extraFuncs<formElement.extraParams.length; extraFuncs++)
					{
						if(formElement.extraParams && formElement.extraParams[extraFuncs] && formElement.extraParams[extraFuncs][0]==functionName)
						{
							for(ze=1; ze<formElement.extraParams[extraFuncs].length; ze++)
							{ functionCall = functionCall + ',\''+formElement.extraParams[extraFuncs][ze]+'\''; }
						}
					}
				}
				functionCall = functionCall+')';
				eval(functionCall)
			}
		}
	}
	//if there's an error then alert the error text.
	if(err>0)
	{
		if(sendError==true) {
			errorMessage="Sorry, the form could not be submitted yet.\nPlease correct the following fields and re-enter.\n\n" + errorMessage;
			alert(errorMessage);
		}
		sendError=true;
		return false;
	}
	//otherwise, submit the form and have a nice day.
	else
	{ sendError=true; return true; }
	
}

function checkEmpty(arg_whichField,arg_niceName) {
	checkField=eval(arg_whichField);
	if(checkField.check) defaultFieldValue = checkField.check[1];
	errorText = 'The '+arg_niceName+' field cannot be empty';
	fieldValue = getFieldValue(arg_whichField);
	if(checkField.length==0 || fieldValue=='' || fieldValue==false || (fieldValue==defaultFieldValue && defaultFieldValue!=''))
		{ flagError(errorText); }
}

function checkNumeric(arg_whichField,arg_niceName) {
	checkField=eval(arg_whichField);
	if(checkField.check) defaultFieldValue = checkField.check[1];
	errorText = 'The '+arg_niceName+' field must be a number';
	fieldValue = getFieldValue(arg_whichField);
	if(checkField.value.length>0 && isNaN(checkField.value) && (fieldValue!=defaultFieldValue || defaultFieldValue==''))
		{ flagError(errorText); }
}

function checkMinimum(arg_whichField,arg_niceName,arg_minval) {
	checkField=eval(arg_whichField);
	if(checkField.check) defaultFieldValue = checkField.check[1];
	errorText = 'You must enter a minimum value of at least $'+ arg_minval +' for the '+arg_niceName+' field';
	if(checkField.value<eval(arg_minval) && (fieldValue!=defaultFieldValue || defaultFieldValue==''))
		{ flagError(errorText); }
}

function checkDecimal(arg_whichField,arg_niceName) {
	checkField=eval(arg_whichField);
	if(checkField.check) defaultFieldValue = checkField.check[1];
	errorText = 'The '+arg_niceName+' field cannot contain any decimals';
	if(checkField.value.indexOf('.') != -1 && (fieldValue!=defaultFieldValue || defaultFieldValue==''))
		{ flagError(errorText); }
}

function checkAlpha(arg_whichField,arg_niceName) {
	checkField=eval(arg_whichField);
	errorText = 'The '+arg_niceName+' field must contain only alpha characters (a-Z)';
	regEx = /(\d+)|(^\s+)/;
	if((checkField.value.length>0) && (regEx.test(checkField.value)))
		{ flagError(errorText); }
}

function checkAlphaNumeric(arg_whichField,arg_niceName) {
	checkField=eval(arg_whichField);
	errorText = 'The '+arg_niceName+' field must contain only alpha or number characters';
	regEx = /\W+/;
	if((checkField.value.length>0) && (regEx.test(checkField.value)))
		{ flagError(errorText); }
}

function checkLength(arg_whichField,arg_niceName,arg_length) {
	checkField=eval(arg_whichField);
	if(checkField.check) defaultFieldValue = checkField.check[1];
	errorText = 'The '+arg_niceName+' field must be '+ arg_length +' characters long';
	if(checkField.value.length>0 && checkField.value.length!=eval(arg_length) && (fieldValue!=defaultFieldValue || defaultFieldValue==''))
		{ flagError(errorText); }
}

function checkValidDate(arg_whichField,arg_niceName,arg_otherNiceName,valuesSent,arg_form,arg_month,arg_day,arg_year) {
	dErr=0;
	
	if(valuesSent=='true')
	{
		varMonth=arg_month;
		varDay=arg_day;
		varYear=arg_year;
	}
	else
	{
		varMonth=getFieldValue(arg_form+'.elements.'+arg_month);
		varDay=getFieldValue(arg_form+'.elements.'+arg_day);
		varYear=getFieldValue(arg_form+'.elements.'+arg_year);
	}
	if(varMonth>=0 && varDay>=0 && varYear>=0)
	{
		errorText = 'The '+arg_otherNiceName+' is not a proper date';
		
		if(isNaN(varYear) || isNaN(varMonth) || isNaN(varDay)) dErr=1;
		if(varYear<1900 || varYear>2051) dErr=1;
		if(varMonth<1 || varMonth>12) dErr=1;
		if(varDay<1 || varDay>31) dErr=1;
					
		if(varMonth==4 || varMonth==6 || varMonth==9 || varMonth==11)
		{	if (varDay==31) dErr=1; }
					
		if(varMonth==2)
		{
			var g=parseInt(varYear/4);
			if(isNaN(g)) dErr=1;
			if(varDay>29) dErr=1;
			if(varDay==29 && ((varYear/4)!=parseInt(varYear/4))) dErr=1;
		}
		if(dErr==1) flagError(errorText);
	}
}

function checkCanadianPostal(arg_whichField,arg_niceName) {
	checkField=eval(arg_whichField);
	errorText = 'The '+arg_niceName+' field does not appear to be in the correct format';
	regEx = /[a-zA-Z][0-9][a-zA-Z][0-9][a-zA-Z][0-9]/;
	if((checkField.value.length>0) && (!(regEx.test(checkField.value))))
		{ flagError(errorText); }
}

function cleanJustAlpha(arg_whichField,arg_niceName) {
	//code to strip alpha chars from field
	checkField=eval(arg_whichField).value;
	validChars="1234567890./";
	for(x=0; x<checkField.length; x++)
	{
		curChar = checkField.charAt(x);
		if(validChars.indexOf(curChar) != -1 && ((curChar != "0") && (isNumeric(curChar)))) {
			outString=outString + curChar;
		}
	}
	checkField = outString;
}

function cleanJustNum(arg_whichField,arg_niceName) {
	//code to strip non-alpha chars from field
}

function checkEmail(arg_whichField,arg_niceName) {
	checkField=eval(arg_whichField);
	errorText = 'The '+arg_niceName+' field is not a valid email address';
	regEx1 = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	if((checkField.value.length>0) && (!regEx1.test(checkField.value)))
		{ flagError(errorText); }
}

function checkPassword(arg_whichField,arg_niceName,arg_form,arg_checkAgainst,arg_minLength) {
	checkField=eval(arg_whichField);
	checkAgainstField=eval(arg_form+'.elements.'+arg_checkAgainst);
	if(checkField.value!=checkAgainstField.value)
	{
		flagError('The Password fields do not match');
		return;
	}
	if(checkField.value.length<arg_minLength || checkAgainstField.value.length<arg_minLength)
	{
		flagError('Your password must be greater than '+ arg_minLength +' characters');
	}
}

function beforeXDate(XDate, XMonth, XYear, arg_Date, arg_Month, arg_Year) {
	currentFullDate= new Date(XYear, XMonth, XDate);
	dateToValidate = new Date(arg_Year, arg_Month, arg_Date);
	if (dateToValidate.getTime() < currentFullDate.getTime()) { return true; }
	else { return false; }
}

function flagError(arg_errorText)
{
	errorMessage=errorMessage+'   '+arg_errorText+'\n';
	err++;
}

function clearDefault(arg_whichField, arg_defaultValue)
{
	if (arg_whichField.value == arg_defaultValue) { arg_whichField.value=""; }
}

function getFieldValue(arg_whichField)
{
	fieldObj = eval(arg_whichField);
	//select boxes - a multiple box will only return the first value now
	if(fieldObj.type=='select-one' || fieldObj.type=='select-multiple')
	{	return(fieldObj.options[fieldObj.selectedIndex].value);	}
	//check box
	else if(fieldObj.type=='checkbox')
	{
		if(fieldObj.checked) return true;
		else return false;
	}
	//a group of radio buttons
	else if(fieldObj[0] && fieldObj[0].type=='radio')
	{
		for(var i=0;i<fieldObj.length;i++)
		{
			if(fieldObj[i].checked)
			{
				i=-1;
				return true;
				break;
			}
		}
		if(i!=-1) return false;
	}
	//a single radio button - would this ever happen?
	else if(fieldObj.type=='radio')
	{
		if(fieldObj.checked) return true;
		else return false;
	}
	//all other types of inputs - text/password/hidden
	else
	{ return(fieldObj.value); }
}
