// Form Validation function by Digimage Designs
// www.digimagedesigns.com
// required args for each form element to validate:
// name, english name, type, required, variable
function validateForm() {

  var a = validateForm.arguments, i, j = 0, tf, f = new Array(), errorString = '', count = 0, cf = new Array(), fv, fn;
  
  if ( a.length < 2 ) return true;
    
  for ( i = 1 ; i < a.length ; i ++ ) {
    f[count++] = new Array(a[i], a[++i], a[++i], a[++i], a[++i]); //fields
  }
  
  tf = 'document.' + a[0] + '.'; //target form

  for ( i = 0 ; i < f.length ; i ++ ) {
    cf = f[i]; //current field
	
	//assign fv (field value)
	if ( cf[2] == 'checkbox' ) { //fv = value of 'OTHER' textbox.
	  while ( eval(tf + 'elements[j].name') != cf[0] + '_other' ) {
	    j++;
	  }
	  fn = eval(tf + 'elements[++j].name');
	  fv = eval(tf + fn + '.value');
	} else {
	  fv = eval(tf + cf[0] + '.value');
	}

	if ( cf[2] == 'checkbox' ) {
	//checkbox "Other" validation
	  if ( eval(tf + cf[0] + '_other') ) { //'other' checkbox exists
	    if ( eval(tf + cf[0] + '_other.checked') ) { //'other' checkbox is checked
		  if ( fv == '' ) {
		    errorString += '\n- \'' + cf[1] + '\': OTHER is checked but no text has been entered.';
		  }
		} else if ( !eval(tf + cf[0] + '_other.checked') && fv != '' ) { //'other' checkbox is NOT checked but text has been entered
		  errorString += '\n- \'' + cf[1] + '\': OTHER is not checked but text has been entered.\n   Please check this box if you mean to submit the text.';
		}
	  }
	} else if ( cf[2] == 'password' ) {
	//password validation
	  if ( fv != '' ) {
	    if ( fv.length < cf[3] ) {
	      errorString += '\n- \'' + cf[1] + '\' must be at least ' + cf[3] + ' characters.';
	    } else if ( eval(tf + cf[0] + '_verify') ) { //password re-entry field exists
	      var passwordVerify = eval(tf + cf[0] + '_verify');
	      if ( fv != passwordVerify.value ) {
	        errorString += '\n- \'' + cf[1] + '\': The Re-entry field does not match.';
	      }
	    }
	  }
	} else if ( fv.length < cf[3] ) {
	//required field (or minimum length of input)
	  if ( fv.length > 0 ) {
	    errorString += '\n- \'' + cf[1] + '\' must be at least ' + cf[3] + ' characters.';
	  } else {
	    errorString += '\n- \'' + cf[1] + '\' is empty.';
	  }
	} else if ( cf[2] == 'email' && fv.length > 0 && (fv.indexOf('@',2) < 0 || fv.indexOf('.',fv.indexOf('@',2)) < 0) ) {
	//email address validation
	  errorString += '\n- The email address entered in \'' + cf[1] + '\' is invalid.';
	}
  }
  
  if ( errorString != '' ) {
    alert('The form has not been sent.\n\nThere are the following errors:' + errorString);
	return false;
  } else {
    return true;
  }
}