/*
 * validateForm.js - contains functions for validating form data to be submitted.
 *
 * Proper use is to call this function in the onSubmit of your form
 * e.g. onSubmit="return VerifyFields(this)"
 *
 *  function VerifyFields(f) {
 *    var a = [ [/^Name/,         "Name",                 "text",     true,      100],
 *              [/^Address/,      "Address",              "text",     true,      100],
 *              [/^City/,         "City",                 "text",     true,       50],
 *              [/^Zip$/,         "Zip Code",             "zip",     true,        50],
 *              [/^Email$/,       "Email Address",        "email",     true,      50],
 *              [/^Telephone$/,   "Telephone Number",     "text",     true,       50],
 *              [/^Company$/,     "Company",              "text",     true,      100] ];
 *  
 *		// if you have special validation rules for checkboxes, ddlbs, etc., put them here
 *    if(f.State.options[0].selected){
 *      alert("State is a required field.")
 *      return false;
 *    }
 *    
 *    if (!VerifyAllFields(f,a)) {
 *       return false; 
 *    }
 *  }
 *
 *
 *  The array values are:  the name of the field (regex), print name, type, required, maxlen.
 */ 

 

function vf_ltrim(argvalue) {

 while (1) {
	 if (argvalue.substring(0, 1) != " ")
		 break;
	 argvalue = argvalue.substring(1, argvalue.length);
 }

 return argvalue;
}


function vf_rtrim(argvalue) {

 while (1) {
	 if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
		 break;
	 argvalue = argvalue.substring(0, argvalue.length - 1);
 }

 return argvalue;
}


function vf_trim(argvalue) {
		var tmpstr = vf_ltrim(argvalue);
		return vf_rtrim(tmpstr);
		}


function vf_isNull( val ) {
	var isValid = false;

	if (val+"" == "null")
		isValid = true;

	return isValid;
}  // end vf_isNull


function vf_isUndef( val ) {
	var isValid = false;

	if (val+"" == "undefined")
		isValid = true;

	return isValid;
}  // end vf_isUndef


function vf_isAlpha( str ) {
	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str+"" == "null" || str+"" == "")	
		return false;

	var isValid = true;

	str += "";	// convert to a string for performing string comparisons.

	// Loop through string one character at time,  breaking out of for
	// loop when an non Alpha character is found.
		for (var i = 0; i < str.length; i++) {
		// Alpha must be between "A"-"Z", or "a"-"z"
		if ( !( ((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
						((str.charAt(i) >= "A") && (str.charAt(i) <= "Z")) ) ) {
								isValid = false;
								break;
						}
	 } // end for loop

	return isValid;
}  // end vf_isAlpha 


function vf_isEmpty( str ) {
	var isValid = false;

	if ( vf_isNull(str) || vf_isUndef(str) || (str+"" == "") )
		isValid = true;

	return isValid;
}  // end vf_isEmpty


function vf_isEmailValid( str ) {
	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str+"" == "null" || str+"" == "")	
		return false;

	var isValid = true;

	str += "";

	namestr = str.substring(0, str.indexOf("@"));  // everything before the '@'
	domainstr = str.substring(str.indexOf("@")+1, str.length); // everything after the '@'

	// Rules: namestr cannot be empty, or that would indicate no characters before the '@',
	// domainstr must contain a period that is not the first character (i.e. right after
	// the '@').  The last character must be an alpha.
		if (vf_isEmpty(str) || (namestr.length == 0) || 
			(domainstr.indexOf(".") <= 0) ||
			(domainstr.indexOf("@") != -1) ||
			!vf_isAlpha(str.charAt(str.length-1)))
		isValid = false;

		return isValid;
} // end isValidEmail


function vf_isTextAcceptable (s){
    var i = 0;
    var sLength = s.length;

// Check for CR and LF and allow them
// otherwise alert is '<' or '>' or any
// other non-printable character.

    while (i < sLength){
      c = s.charAt(i);
      if ((isNaN(c)== true)){
        if ((c == "<") || (c == ">") ||
            (c < " " ) || (c > "~")){
          i = sLength;
          return false;
        }
      }
      i++;
    }
    return true;
}


function vf_isCheckboxChecked( checkboxObject ) { 

	// Validate parameter value
	if (checkboxObject+"" == "undefined" || checkboxObject == null)
		return false;

	for (var i=0; i < checkboxObject.length; i++) { 
		if (checkboxObject[i].checked) { 
			return true;
		} 
	} // end for loop 
	return false;
}


function vf_isRadioChecked( radioObject ) { 

	// Validate parameter value
	if (radioObject+"" == "undefined" || radioObject == null)
		return false;

	for (var i=0; i < radioObject.length; i++) { 
		if (radioObject[i].checked) { 
			return true;
		} 
	} // end for loop 
	return false;
}


function vf_isSelected( selectObject ) { 

	// Validate parameter value
	if (selectObject+"" == "undefined" || selectObject == null)
		return false;
		
    // ignore first item
	for (var i=1; i < selectObject.length; i++) { 
		if (selectObject.options[i].selected) { 
			return true;
		} 
	} // end for loop 
	return false;
}

function vf_isTextAcceptable (s){
    var i = 0;
    var sLength = s.length;

    while (i < sLength){
      c = s.charAt(i);
      if ((isNaN(c)== true)){
        if ((c == "<") || (c == ">") ||
            (c < " " ) || (c > "~")){
          i = sLength;
          return false;
        }
      }
      i++;
    }
    return true;
}

function vf_isUSZip(s) {
    var pattern = /^\d{5}(-\d{4})?$/;
    return s.match(pattern);
}
function vf_isCanadaZip(s) {
    var pattern = /^[A-Z]\d[A-Z][ ]?\d[A-Z]\d$/;
    return s.match(pattern);
}
function vf_isZip(s) {
    return vf_isUSZip(s) || vf_isCanadaZip(s);
}

function vf_isInteger(s) {
    var pattern = /^(0|[+-]?[1-9][0-9]*)$/;
    return s.match(pattern);
}

function vf_isFloat(s) {
    var pattern = /^[+-]?([1-9]\d*|([1-9]\d*|0)?\.\d*)$/;
    return s.match(pattern);
}

function vf_isHtmlSafe(s) {
   // exclude angle brackets
   var pattern = /^[^<>]*$/;
   return s.match(pattern);
}

function vf_isText(s, max) {
    return (s.length <= max);
}

// checks for single or multiple ";" seperated addresses.
function vf_isEmail(s) {
  var isValid = true
  var badpattern = /\;{2,}/
  if(s.match(badpattern)){ // check for multiple ";" with no text between them.
    return (isValid=false)
  }
  var pattern = /^\w[\w\.\-]*@(\w[\w\-]*\.)+(\w[\w\-]*)*[a-zA-Z]$/
  if (s.indexOf(";") >=0 ) { // multiple addresses
    s=s.split(";")
    for(var j=0;j<s.length;j++){
      if(s[j].length > 0){
        if (!s[j].match(pattern)){
          isValid = false
        }
      }      
    }
    return isValid
  }else{// only one address
    return s.match(pattern);
  } 
}



function vf_isDate(s) {
    var pattern = /^\d{1,2}\/\d{1,2}\/(\d{2}|\d{4})$/
    return s.match(pattern);
}

function vf_isOrderItem(s) {
    var pattern = /^\d+(-\d+)?$/
    return s.match(pattern);
}

function vf_VerifyTextField(field, name, type, required, max) {

   if (vf_trim(field.value) == "") {
      if (required)
         return (name + ": Required\n");
      return "";
   }
   if (type == "text" && !vf_isText(field.value,max))
      return (name + ": Exceeds " + max + " character limit (" + field.value.length + " chars) \n");
   else if (type == "nonhtml" && !vf_isHtmlSafe(field.value))
      return (name + ": Angle brackets are not allowed\n");
   else if (type == "nonhtml" && !vf_isText(field.value,max))
      return (name + ": Exceeds " + max + " character limit (" + field.value.length + " chars) \n");
   else if (type == "integer" && !vf_isInteger(field.value))
      return (name + ": Not a number\n");
   else if (type == "float" && !vf_isFloat(field.value))
      return (name + ": Not a floating point number\n");
   else if (type == "email" && !vf_isEmail(field.value))
      return (name + ": Not a valid email address\n");
   else if (type == "date" && !vf_isDate(field.value))
      return (name + ": Not a valid date\n");
   else if (type == "zip" && !vf_isZip(field.value))
      return (name + ": Not a valid zip code\n");
   return "";
}

function VerifyAllFields(f,a) {

    m = "";
    for (var i=0; i<f.elements.length; i++)
        for (var j=0; j<a.length; j++)
           if (f.elements[i].name.match(a[j][0])) {
               m = m + vf_VerifyTextField(f.elements[i], a[j][1], a[j][2], a[j][3], a[j][4]);
               break;
           }

    if (m != "") {
        alert("Please correct the values in the following fields:\n\n" + m);
        return false;
    }

    return true;
}