//FormUtilities.js
//Functions that take the drudgery out of writing forms validation

//verifies that a required field has not been left blank
function VerifyContent(FormField, FieldDescription)	
{	
	if (FormField.value == "")
	{
		alert("Please enter a value for " + FieldDescription);
		FormField.focus();
		return (false);
	}
	return (true);
}	  

 //verifies that a field does not have more than the maximum # of characters!
function VerifyCharacters(FormField, FieldDescription, MaxLength)	
{	
	if (FormField.value.length > MaxLength)
	{
	// Build alert box message showing how many characters entered
	mesg = "You have entered " + FormField.value.length + " character(s) for " + FieldDescription + "\n"
	mesg = mesg + "The maximum amount to enter is " + MaxLength + " characters.\n"
	mesg = mesg + "Please verify your input and submit again."
	alert(mesg);
	// Place the cursor on the field for revision
	FormField.focus();
	// return false to stop further processing
	return (false);
	 }
	return (true);
}


function VerifyEmail(FormField, FieldDescription)
{
  //var ValidEmail = new RegExp("^[a-zA-Z0-9_\.]+@[a-zA-Z0-9_\.]+$")
	//([a-zA-Z0-9\-]+\.)+)([a-zA-Z]{2,4})
	//if(!(ValidEmail.test(FormField.value)))
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(FormField.value))
	{
    return (true)
  }
	alert(FormField.value + " is not a valid email address. Please re-enter ");
	FormField.focus();
	return (false);
}
function VerifyEmailLite(FormField)
{
  //var ValidEmail = new RegExp("^[a-zA-Z0-9_\.]+@[a-zA-Z0-9_\.]+$")
	//([a-zA-Z0-9\-]+\.)+)([a-zA-Z]{2,4})
	//if(!(ValidEmail.test(FormField.value)))
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(FormField.value))
	{
    return (true)
  }
	return (false);
}
//verifies that a selection has been made from a selector box
//assumes that index 0 is not a valid selection 
function VerifySelChosen(FormField, FieldDescription)
{
  if (FormField.selectedIndex <= 0)
 	{
   	alert("Please make a selection for " + FieldDescription + ".");
   	FormField.focus();
   	return (false);
 	}
	return (true);
}
//verifies that a selection has been made from a selector box
//assumes that index 0 is a valid selection 
function VerifySelChosenBaseOne(FormField, FieldDescription)
{
  if (FormField.selectedIndex < 0)
 	{
   	alert("Please make a selection for " + FieldDescription + ".");
   	FormField.focus();
   	return (false);
 	}
	return (true);
}
//verifies that a selection has been made from a selector box with multiple selections allowed
//assumes that index 0 is a valid selection 
function VerifyMultiSelChosen(FormField, FieldDescription)
{
	var optionSelected = false;
	for (var i = 0; i < FormField.length; i++) {
		if (FormField.options[i].selected)
			optionSelected = true;
	}
  if (!optionSelected)
 	{
   	alert("Please make a selection for " + FieldDescription + ".");
   	FormField.focus();
   	return (false);
 	}
	return (true);
}

//verifies that one of a set of radio buttons has been chosen
function VerifyRadioChosen(FormField, FieldDescription)
{
  for (i = 0; i <= FormField.length - 1; i++)
  {
	 if (FormField[i].checked) return true
  }
  alert ('You must choose from' + FieldDescription)
	FormField[0].focus();
  return false
}
//verifies that one of a set of checkboxes has been checked
function VerifyBoxChecked(FormField, FieldDescription)
{
  for (i = 0; i <= FormField.length - 1; i++)
  {
	  if (FormField[i].checked) return true
  }
  alert ('You must choose ' + FieldDescription)
	FormField[0].focus();
  return false
}

//VerifyOtherSpecify(formName.selPet, formName.txtPet, 'other', 'Please specify your pet preference')
function VerifyOtherSpecify(SelectField, TextField, OtherValue, Message)
{
  if (GetSelectedOption(SelectField) == OtherValue)
	{
	  if (TextField.value == "")
		{
		  alert(Message);
			TextField.focus();
			return false;
		}
	}
	return true;
}

//validates for a five-digit all numeric zip code
function VerifyZip5(FormField)
{
	var ValidZip = new RegExp("^\[0-9\-]{5,}$")
   if (!(ValidZip.test(FormField.value)))
  {
	  alert('Please enter a Valid Zip Code.');
	  FormField.focus();
	  return (false);
  } 
	return (true);
}

//validates for a three-digit all numeric cvc code
function VerifyCVC3(FormField)
{
	var ValidCVC = new RegExp("^\[0-9\-]{3,}$")
   if (!(ValidCVC.test(FormField.value)))
  {
	  alert('Please enter a Valid Three Digit CVC Code.');
	  FormField.focus();
	  return (false);
  } 
	return (true);
}

//phone number validation
//allows for 10-15 characters, numeric, ()-
function VerifyPhoneNo(FormField, FieldDescription)
{
	if (FormField.value == "")
	 {
	   alert("Please enter a value for " + FieldDescription + ".");
	   FormField.focus();
	   return (false);
	 }
	 if (FormField.value.length < 10)
	 {
	   alert("Please enter at least 10 characters in " + FieldDescription + ".");
	   FormField.focus();
	   return (false);
	 }
	 if (FormField.value.length > 15)
	 {
	   alert("Please enter at most 15 characters in " + FieldDescription + ".");
	   FormField.focus();
	   return (false);
	 }
	 var checkOK = "0123456789--() \t\r\n\f";
	 var checkStr = FormField.value;
	 var allValid = true;
	 for (i = 0;  i < checkStr.length;  i++)
	 {
	   ch = checkStr.charAt(i);
	   for (j = 0;  j < checkOK.length;  j++)
	     if (ch == checkOK.charAt(j))
	       break;
	   if (j == checkOK.length)
	   {
	     allValid = false;
	     break;
	   }
	 }
	 if (!allValid)
	 {
	   alert("Please enter only digit, whitespace and \"-()\" characters in " + FieldDescription + ".");
	   FormField.focus();
	   return (false);
	 }
	 return (true);
}

//verifies a valid credit card expiration date 
//takes integers for month and year and checks to see if the date is before this month
function VerifyFutureDate(DayField, MonthField, YearField, FieldDescription)
{
		var Today = new Date();
		var thisDay = parseInt(Today.getDay()) + 1;
		var thisMonth = parseInt(Today.getMonth()) + 1;
		var thisYear = parseInt(Today.getFullYear());
		var selDay = parseInt(DayField.value);
		var selMonth = parseInt(MonthField.value);
		var selYear = parseInt(YearField.value);
		if (!(selYear > thisYear))
		{
		  if (!(selMonth > thisMonth))
			{
				if (selDay < thisDay)
				{
					alert("Please select a future date for " + FieldDescription + ".");
					DayField.focus();
					return (false);
				}
			}
		}
		return (true);
}

//verifies a valid credit card expiration date 
//takes integers for month and year and checks to see if the date is before this month
function VerifyCCExpire(expMonth, expYear, MonthField)
{
		var Today = new Date();
		var thisMonth = parseInt(Today.getMonth()) + 1;
		var thisYear = parseInt(Today.getFullYear());
		var selMonth = parseInt(expMonth);
		var selYear = parseInt(expYear);
		if (!(selYear > thisYear))
		{
		  if (selMonth < thisMonth)
			{
				alert("Credit Card Expiration Date is invalid");
				MonthField.focus();
				return (false);
			}
		}
		return (true);
}
//validate credit card number and type
function VerifyCreditCard(Type,FormField)
{
	var ccNo = trim(FormField.value);
	if (!validCardNo(ccNo,FormField)) 
	{
		alert( "Credit Card Number is invalid. Please check or re-enter." );
		FormField.focus();
		return false;
	}
	var ceMessage = validCCType(Type, FormField);
	if ( ceMessage.length != 0 ) 
	{
		alert( ceMessage );
		return false;
	}
	return (true);	
}
//the next five functions are used by VerifyCreditCard
function CanonicCCNumber(CC) 
{
  var i;
  var ret = "";

  for ( i = 0 ; i < CC.length ; ++i ) 
	{
    var c = CC.charAt(i);
    if ( "0123456789".indexOf(c) >= 0 )
      ret += c;
  }
  return ret;
}
function validCCType(Type, FormField) 
{
  var CC = trim(FormField.value);
  var ccard = Type
  switch (ccard) {
    case "VI":
      if ( (CC.length == 13 || CC.length == 16) && CC.charAt(0) == "4" ) {
      } else {
        return "This credit card number is not a Visa card number. " +
          "Please correct the Credit Card Number or Type.";
      }
      break;

    case "MC":
      if ( (CC.length == 16 || CC.length == 19) && (CC.substr(0,2) >= "51" && CC.substr(0,2) <= "55") ) {
      } else {
        return "This credit card number is not a MasterCard card number. " +
          "Please correct the Credit Card Number or Type.";
      }
      break;

    case "AX":
      if ( (CC.length == 15 || CC.length == 18) && (CC.substr(0,2) >= "34" && CC.substr(0,2) <= "37") ) {
      } else {
        return "This credit card number is not an American Express card number. " +
          "Please correct the Credit Card Number or Type.";
      }
      break;

    default:
      return "Please select the Credit Card Type.";
  }

  return "";
}
function validCardNo(str,FormField) 
{
  strS = CanonicCCNumber(str);
  FormField.value = strS;
  return chkCardNo(strS);
}
function trim(str)
{
  re = /^\s*((\S+(\s+))*(\S+))\s*$/;
  if ( re.exec(str) != null )
    return RegExp.$1;
  else
    return "";
}
function chkCardNo(CardNumber) 
{
  var no_digit = CardNumber.length;
  var oddoeven = no_digit & 1;
  var sum = 0;

  for (var count = 0; count < no_digit; count++) {
    var digit = parseInt(CardNumber.charAt(count));
    if (!((count & 1) ^ oddoeven)) {
      digit *= 2;
      if (digit > 9)
        digit -= 9;
    }
    sum += digit;
  }
  if (sum % 10 == 0)
    return true;
  else
    return false;
}
//verifies all numeric field of given number of digits
function VerifyDigitNumber(FormField, theNumber)
{
  var ValidNumber = new RegExp("^\[0-9]{" + theNumber + "}$")
	var NumberIn = FormField.value
	if (!(ValidNumber.test(NumberIn)))
	{
	  alert('Please enter a valid ' + theNumber + ' digit Number.');
    FormField.focus();
    return (false);
	}
	return true
}
//verifies nine digit duns number that passes mod 10+5 test
function VerifyDuns(FormField)
{
//boolean function returns true for 9 digit all numeric duns passing mod 10 + 5 test
var ValidDuns = new RegExp("^\[0-9]{9}$")
var DunsIn = FormField.value
//check against regular expression to be sure its nine-digit all numeric
if (!(ValidDuns.test(DunsIn)))
  {
  alert('Please enter a NINE-DIGIT, ALL NUMERIC DUNS Number.');
  FormField.focus();
  return (false);
  }
else
  {
  // get last digit to compare against check digit
  var lastdigit = DunsIn.substr(8,1)
  var digit
  var checktotal = 0
  // parse the first eight digits
  for (i = 0; i <= 7; i++)
    {
	// if the position of the digit is even, then double the value
	if (i%2 != 0) 
	  {
	  digit = (DunsIn.substr(i,1)) * 2
	  // if the doubled value is more than ten, then break it into its digits and add them
	  // accomplished by modulus by ten then adding one as the number will never be higher than 18
	  if (digit > 9)
	    {
		digit = (digit % 10) + 1 
		}
	  }
	else
	  {
	  // digit position is odd, so do not double it
	  digit = (DunsIn.substr(i,1))
	  }  
	// add it to the total  
	checktotal = checktotal + parseInt(digit)
	//alert (checktotal + '--' + digit)
    }
  //get what should be the check digit
    digit = 10 - (checktotal % 10)
	if (digit > 9)
	  {
	  digit = 0
	  }
  //alert(digit)
  // compare it to the last digit
  if (digit != lastdigit)
    {
	//if its not right, then add 5
	digit = digit + 5
	// if its greater than 9 then subtract 10
	if (digit > 9)
	  {
	  digit = digit - 10
	  } 
	// compare again  
	if (digit != lastdigit)
	  {
	  // if it doesnt match, its not a duns
	  alert(DunsIn + ' is not a valid DUNS Number');
    FormField.focus();
	  return (false);
	  }
	}
  }
  return (true);
}

//returns the value of the option selected from a selector box
function GetSelectedOption(opt)
{
	var c = null;
	var ret = null;
	for(c=0; c < opt.options.length; c++)
	{
		if(opt.options[c].selected)
		{
			ret = (opt.options[c].value == null || opt.options[c].value.length == 0)
								? opt.options[c].text : opt.options[c].value;
			break;					
		}	
	}
	return ret;
}

function SetControl (objControl, Value)
{
	var strValue = "";
	var c = 0;
	if (Value < 10)
		strValue = "0" + Value;
	else
		strValue = "" + Value;
	SetSelectControl (objControl, strValue);
}

function SetSelectControl (objControl, Value)
{
	var c = 0;
	for(c=0; c < objControl.options.length; c++)
	{
		if(objControl.options[c].value == Value)
		{
			objControl.options[c].selected = true;
			break;					
		}	
	}
}
