
var validationRules=new Array();
var validationGroups=new Array();

var zip_country = 'US' ;

function setValidationCountry( country )
{
  zip_country = country ;
}

function validate(optionalValidateFunc) {

	//
	// validate - validates form1 on a given page
	//
	// returns true if all fields ok, false otherwise
	//
	//		optionalValidateFunc: optional - should be boolean.  Use for local validations.
	//
	
	/*function usage:
	
	Before this function is called, the validationRules[] array must be populated that specifies 
	 rules to be used for each field.
	 
	 Example:
	 
	 <input type="text" name="taxrate" onchange="makeDirty();">
	 <script>validationRules['taxrate']='required,percent,minvalue=10,maxvalue=25'; [/script]  (replace the [ with <)
	 
	 this will validate the field against the rules specified.
	
	*/
	
	
	var errorString=''; warningString='';
	var formOK=true;

	if (optionalValidateFunc!=null) {
		rv=eval(optionalValidateFunc);
		if (rv==null || rv=='') {
			formOK = true;
		} else {
			formOK = false;
			errorString+=rv;
		}
	}
	
	//loop through form1, and verify each field
	
	
	
	for (ind=0;ind<document.form1.elements.length;ind++) {
		//if there is an entry in the validationRules array corresponding to the name of the element,
		//begin checking that element's value
    var elmValidate = document.form1.elements[ind] ;
    var elmName = elmValidate.name ;
    
		if (validationRules[elmName]!=null) 
		{
			
      // alert ( "Validation rule for " + elmName + " is \"" + validationRules[elmName] + "\"" ) ;
			vRule=validationRules[elmName].split(',');
			fieldOK=true;
			
			//see if dispname attribute is present in validation string
			var dispName = elmName ;
			for (j=0;j<vRule.length;j++) {
				a=vRule[j].split('=');
				if (a[0]=='dispname') {
					dispName=a[1];
				}
			}
			
			
			//loop through validation rules, and check them
			for (j=0;j<vRule.length;j++) {
				setProperty(elmValidate,'backgroundColor','#F7F7EF');
				setProperty(elmValidate,'color','#000000');
				// alert('checking field ' + ind + ' with value ' + elmValidate.value + ' against rule ' + vRule[j]);
				valToCheck = elmValidate.value;
				
				if (elmValidate.tagName.toLowerCase()=='textarea') 
				{
					valToCheck = stripHTML(elmValidate.innerText);
					// alert('-' + valToCheck + '-');
					if (valToCheck=='<P>&nbsp;</P>') valToCheck = '';
				}
									
				checkResult=checkInput(valToCheck,vRule[j]);
				
				// alert(valToCheck + ',' + vRule[j] + '=' + checkResult);
				
				if (checkResult!='') 
				{
					if ((formOK)&&(elmValidate.type!='hidden')) {
						try {
							elmValidate.focus();
						} catch (e) {
						
						}
					}
					formOK=false;
					
					r=checkResult.split('|');
					
					if (r[0]=='error') 
					{
						setProperty(elmValidate,'backgroundColor','#43367B');
						setProperty(elmValidate,'color','#FFFFFF');
						errorString+=dispName + ' ' +r[1] + '\n';	
					} 
					else if (r[0]=='warning') 
					{
						setProperty(elmValidate,'backgroundColor','#43367B');
						warningString+=dispName + ' ' +r[1] + '\n';	
					}

					break;
				}
			}

		}
	}
	
	//alert(validationGroups['serviceTypes'])
	for (ind=0;ind<validationGroups.length;ind++) {
		checkResult=checkGroup(validationGroups[ind]);
		if (checkResult!='') {

			formOK=false;
					
			r=checkResult.split('|');
					
			if (r[0]=='error') {
				errorString+=dispName + ' ' +r[1] + '\n';	
			} else if (r[0]=='warning') {
				warningString+=dispName + ' ' +r[1] + '\n';	
			}

			break;
		}
	}
	
	if (!formOK) {
		msg='';
		if (errorString!='') {msg='Errors have occurred:\n' + errorString + '\n\n';}
		if (warningString!='') {msg+= 'Warnings:\n' + warningString + '\n\n';}
		if (errorString!='') {
			alert(msg);
			return false;
		}
		if (warningString!='') {
			return confirm(msg + 'Proceed?');
		}
	}
	
	return true;
} //end function validate



function setProperty(obj,styleProperty,value) {
	if (MSIE) {  //global variable
		obj.style[styleProperty]=value;
	} else {
		eval('obj.' + styleProperty + '="' + value + '";');
		//alert('obj.' + styleProperty + '="' + value + '";');
	}	
}

function checkGroup(validationStr) {
	alert(validationStr);
	return '';
}

function checkInput(n, validationRule, x,y,z) {
	//
	// checkInput - checks a value against a rule
	// 
	// returns '' if value OK, otherwise returns error string to display.
	//
	// error string format: 'error|error text'
	//
	//n: value to be tested
	//validationRule: rule to be tested
	//x: optional...for additional parameters
	//y: optional...for additional parameters
	//z: optional...for additional parameters


	//----------begin pattern definitions------------
	var required_pat=/^[.\n]+$/;
	
	var login_pat=/^[a-zA-Z0-9À-ÿ @\\\.]*$/;
	var pwd_pat=/^[a-zA-Z0-9À-ÿ\.\,'&\+\-#!@\$\%\^\*\(\) ]*$/;
	
	var alpha_numeric_pat= /^[a-zA-Z0-9À-ÿ ]*$/;
	var alpha_only_pat= /^[a-zA-ZÀ-ÿ ]*$/;
	var alpha_punct_pat= /^[a-zA-ZÀ-ÿ\.\,'!@&\+\- ]*$/;
	
	var address_pat=/^[a-zA-Z0-9À-ÿ#]*[a-zA-Z0-9À-ÿ\,\/\.\-'# ]*$/;
	var alpha_numeric_punct_pat= /^[a-zA-Z0-9À-ÿ\.\,'&\+\-# ]*$/;
	var phone_pat= /^\(?[0-9]{3}[\)-\.]?[0-9]{3}[-\.]?[0-9]{4}$/;
	var alpha_only_1_pat =  /^.*[a-zA-ZÀ-ÿ].*$/; //At least One Char
	
	var numeric_0_pat=/^[0-9]*$/; 
	var numeric_1_pat=/^[0-9]+$/;
	var float_pat=/^[0-9]*\.?[0-9]*$/;
	var percent_pat=/^[0-9]{0,2}\.?[0-9]{0,3}$/;
	
	
	var money_pat = /^[0-9,]*\.?[0-9]{0,2}$/;

	var zip_pat = /^[0-9]{5}$/;
	var zip9_pat= /^[0-9]{5}-[0-9]{4}$/;
  var can_post_pat = /^[ABCEGHJKLMNPRSTVXY]\d[A-Z] ?\d[A-Z]\d$/
	
	var no_numeric_pat=/^.*[0-9].*$/;  // string contains numeric
	
	var email_pat=/^[\w\_\-\.\-]+@[\w\_\-]*\.[\w\.\_\-]+$/;
	
	var hours_pat=/^[0-9]{1,2}:[0-9]{2}[ ]?[aApP][mM]$/;
	
	var date_pat=/^[0-9]{1,2}[\-\/\.]?[0-9]{1,2}[\-\/\.]?[0-9]{4}$/;
	
	var forbidden_chars=/[\<\>"]/;
	//----------end pattern definitions------------
	
	//alert('testing "'+n+'" for "'+fmt+'"');
	
	// test for globally forbidden characters
	//if (forbidden_chars.test(n)) {return 'error|contains invalid characters';}
	if (validationRule==null) {alert('checking ' + n); return '';}
	
	// parse parametrized validation rules		
	a=validationRule.split('=');
	fmt=a[0];
	
	if (a.length>0) {
		param=a[1];
		param2=a[2];
	}
	//---------format conversion
	var nbr=new Number(n)
	
	
	//---------begin tests----------
	
	switch (fmt) {
		case 'required' :
			if (n=='') {return 'error|is required';} else {return '';}
		case 'login' :
			if (!login_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}
		case 'pwd' :
			if (!pwd_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}		
		case 'alpha_numeric' : 
			if (!alpha_numeric_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}
		case 'alpha_punct' : 
			if (!alpha_punct_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}
		case 'alpha_only' : 
			if (!alpha_only_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}
		case 'address' : 
			if (!address_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}
		case 'alpha_numeric_punct' : 
			if (!alpha_numeric_punct_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}
		case 'phone' : 
			if (!phone_pat.test(n) && n!='') {return 'error|is not in the form (111)555-1212';} else {return '';}
		case 'alpha_only_1' : 
			if (!alpha_only_1_pat.test(n)) {return 'error|contains invalid characters';} else {return '';}
		case 'numeric_0' : 
			if (!numeric_0_pat.test(n)) {return 'error|must be a number';} else {return '';}
		case 'numeric_1' : 
			if (!numeric_1_pat.test(n)) {return 'error|must be a number';} else {return '';}
		case 'float' :
			if (!float_pat.test(n)) {return 'error|must be numeric';} else {return '';}
		case 'money' : 
			if ((!money_pat.test(n))||(nbr<0)) {return 'error|must be a valid money value';} else {return '';}
		case 'no_numeric' : 
			if (!no_numeric_pat.test(n)) {return 'error|must not contain numbers';} else {return '';}
		case 'email' : 
			if (!email_pat.test(n) && n!='') {return 'error|is not a valid email';} else {return '';}		
		case 'zip' :
      if ( zip_country == "US" ) 
      {
			  if (n.length>5) 
			  {
				  if (!zip9_pat.test(n)) {return 'error|is not a valid US zip code';} else {return '';}
			  } 
			  else 
			  {
				  if(n !=''){
					  if (!zip_pat.test(n)) {return 'error|is not a valid US zip code';} else {return '';}
				  }else{
					  return '';
				  }	
			  }
      }
      else if ( zip_country == "Canada" ) 
      {
        if (!can_post_pat.test(n))
        {
          return ('error|is not a valad Canadian postal code');
        }
        else
        {
          return ('') ;
        }
      }
		case 'hours' :
			if (!hours_pat.test(n) && n!='') {return 'error|not in the form 6:00 pm';} else {return '';}																											
		case 'percent' :
			if ((!percent_pat.test(n))||(nbr>=100)||(nbr<0)) {return 'error|is not a valid percentage';} else {return '';}	
		case 'date':
			if (n!='') {
				//if (!date_pat.test(n)) {return 'error|is an invalid date';}
				
				if (!vbIsDate(n)) {return 'error|is an invalid date';}
				
				
				return '';
			}
			break;
		
		// ----------------- parametrized validations -------------------
		
		
		case 'maxvalue' :
			if (nbr>param) {return 'error|cannot be greater than ' + param;} else {return '';}
		case 'minvalue' :
			if (nbr<param) {return 'error|cannot be less than ' + param;} else {return '';}
		case 'minwarning' :
			if (nbr<param) {return 'warning|should not be less than ' + param;} else {return '';}			
		case 'maxwarning' :
			if (nbr>param) {return 'warning|should not be greater than ' + param;} else {return '';}	
		case 'maxlength' :
			if (n.length>param) {return 'error|length cannot be greater than ' + param;}	
		case 'conditionalRequirement' :
			/*usage: 
						conditionalRequirement=goalRating217=3;4;5
						will be required only if goalRating217 is 3, 4, or 5
			
			*/
			if (n=='') {
				conditionalObjID = param;
				conditionalValues = param2;
				if (document.all[conditionalObjID]!=null) {
					 v = document.all[conditionalObjID].value;
					 
					 if ((v==null || v=='') && document.all[conditionalObjID].tagName.toLowerCase()=='select')
						v=0;
					 cv = conditionalValues.split(';');  /// <--------important! split on ;'s
					 for (j=0;j<cv.length;j++)
						if (v == cv[j])
							return 'error|is required';
				}
			}
		default:
			
			return '';
	} //end switch

	return '';
}//function checkInput


if (navigator.userAgent.indexOf('MSIE',0)>0) {
	MSIE=true;
} else {
	MSIE=false;
}
