// general purpose function to see if a suspected numeric input
// is a positive integer
function isPosInteger(inputVal)
{
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }
    return true
}

// general purpose function to see if a suspected numeric input
// is a positive or negative integer
function isInteger(inputVal)
{
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)
        if (i == 0 && oneChar == "-")
            {
            continue
            }
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }
    return true
}

// Determines whether a number is zero
function isZero(inputVal)
{
    return parseFloat(inputVal) == 0;
}

// general purpose function to see if a suspected numeric input
// is a positive or negative number
function isNumber(inputVal)
{
    oneDecimal = false
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)
            if (i == 0 && oneChar == "-")
            {
            continue
            }
        if (oneChar == "." && !oneDecimal)
            {
            oneDecimal = true
            continue
            }
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }

    return true
}

// another general purpose function to see if a suspected numeric input
// is a positive or negative number
function isNumber2(inputValue)
{
    if (isNaN(parseFloat(inputValue)))
        {
        alert("The value you entered is not a number.")
        return false
        }
    return true
}

// general purpose function to see if a suspected numeric input
// is a positive number
function isPosNumber(inputVal)
{
    oneDecimal = false
    inputStr = inputVal.toString()
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i)

        if (oneChar == "." && !oneDecimal)
            {
            oneDecimal = true
            continue
            }
        if (oneChar < "0" || oneChar > "9")
            {
            return false
            }
        }

    return true
}

// function to see if the decimal place is <= maximum decimal number
function isDecimal(inputVal, maxDecimal)
{
    inputStr = inputVal.toString()
    var rArray = inputStr.split(".");
    if (rArray.length > 2){return false;}
    if (rArray.length == 2)
    {
        if (rArray[1].length > maxDecimal)
           return false;
    }
    return true;
}

// function to see if the number exceeds the maximum length 
// in the database, including decimal number
// Note: this function DOES NOT count the decimal point
function isDBNumber(inputVal, maxLen, maxDecimal)
{
    inputStr = inputVal.toString()
    var rArray = inputStr.split(".");
    if (rArray.length > 2){return false;}
    if (rArray.length <= 2)
    {
    if (rArray[0].length > (maxLen-maxDecimal)){return false;}
    }
    return true;
}

// function to see if input is a valid Tax ID number.
function isTaxID(strInput)
{
    // Tax id should be nn-nnnnnnn.
    // Be sure there is a dash.
    var dash1 = strInput.indexOf("-")
    if (dash1 == -1)
        {return false}

    // Extract the two parts of the tax id.
    if (dash1 == 2)
        {
        var taxid1 = parseInt(strInput.substring(0, dash1), 10)
        var taxid2 = parseInt(strInput.substring(dash1+2, strInput.length), 10)
        if (isNaN(taxid1) || isNaN(taxid2))
            {
            // There is a non-numeric character in one of the component values.
            alert("NaN: The Tax ID entry is not in an acceptable format.\n\nYou should enter the Tax ID number as nn-nnnnnnn.")
            return false
            }

        }
    else
        {
            // There are no dashes or they are in the wrong places.
            alert("Bad Dash: The Tax ID entry is not in an acceptable format.\n\nYou should enter the Tax ID number as nn-nnnnnnn.")
            return false
         }
    return true;
}

// function to see if input is valid US Social Security Number
function isSSN(strInput)
{
    // SSN should be nnn-nn-nnnn

    // Be sure there are two dashes
    var dash1 = strInput.indexOf("-")
    var dash2 = strInput.lastIndexOf("-")
    if (dash1 == -1 || dash1 == dash2)
        {return false}

    // Extract the tree paqrts of the SSN
    if (dash1 == 3 && dash2 == 6)
        {
        var SSN1 = parseInt(strInput.substring(0, dash1), 10)
        var SSN2 = parseInt(strInput.substring(dash1+2, dash2), 10)
        var SSN3 = parseInt(strInput.substring(dash2+2, strInput.length), 10)
        if (isNaN(SSN1) || isNaN(SSN2) || isNaN(SSN3))
            {
            // there is a non-numeric character in one of the component values
            alert("NaN: The SSN entry is not in an acceptable format.\n\nYou should enter SSN as nnn-nn-nnnn.")
            return false
            }

        }
    else
        {
            // there are no dashes or they are in the wrong places
            alert("Bad Dash: The SSN entry is not in an acceptable format.\n\nYou should enter SSN as nnn-nn-nnnn.")
            return false
         }
    return true;
}

// function to see if input is valid SIC Number
function isSIC(strInput)
{
    // SIC should be nnnn-nn

    // Be sure there is a dashe
    var dash1 = strInput.indexOf("-")
    if (dash1 == -1)
       {return false}

    // Extract the parts of the SIC
    if (dash1 == 4)
        {
        var SIC1 = parseInt(strInput.substring(0, dash1), 10)
        var SIC2 = parseInt(strInput.substring(dash1+2, strInput.length), 10)
        if (isNaN(SIC1) || isNaN(SIC2))
            {
            // there is a non-numeric character in one of the component values
            alert("The SIC Code entry is not in an acceptable format.\n\nYou should enter SIC Code as NNNN-NN.")
            return false
            }

        }
    else
        {
            // there are no dashes or they are in the wrong places
            alert("The SIC Code entry is not in an acceptable format.\n\nYou should enter SIC Code as NNNN-NN.")
            return false
         }
    return true;
}

// Replaces the first occurrance of chFind with chReplacement in strInput
// and returns the result.
//
// Used in isDate() and isPhone()
function replaceString(strInput, chFind, chReplacement)
{
    var i = strInput.indexOf(chFind)
    var str = strInput.substring(0, i) + chReplacement + strInput.substring(i + 1, strInput.length)

    return str;
}

// date field validation
function isDate(inputValue)
{
    var inputStr = inputValue.toString()

    if (isNaN(Date.parse(inputStr)))   {
       return(false);
    }
    var datInput = new Date(Date.parse(inputStr))

    // CMK - 22 MAY 2000 - Added check to disallow 5 or more digit years.
  // JWR - 23 AUG 2001 - Added check to ensure 4-digit year at least.
  var year = datInput.getFullYear();
    if ( (year > 9999) || (year < 1000) ) {
       return(false);
    }

    //cwbutler - 6/5/2000 - Added to handle "9/31/2000", etc
    //first thing - zap all leading zeros
    var sFixDate = inputStr;
    sFixDate = sFixDate.replace(/^0/,'');
    sFixDate = sFixDate.replace(/\/0+/,'/');
    sFixDate = sFixDate.replace(/\/0+/,'/');
    
    //second thing, get the date JavaScript THINKS it has
    // use getFullYear() instead of getYear() for Netscape and IE. modified 9/8/00 STang
    var sCompDate = (datInput.getMonth() + 1) + "/" + datInput.getDate() + "/" + datInput.getFullYear();

    //finally, make sure they're the same
    if (sCompDate != sFixDate)
    {
        //cuz if they're not, it's an error
        return(false);
    }

    return(true);
}

// Function to see  if input is valid US phone number
function isPhone(strInput) {
   //CMK - 20 Apr 2000 - Rewrote function to accept following formats:
   // (111) 111-1111 Parenthesis with dash
   // 111-111-1111 Dashes
   // 111 111 1111 Spaces
   // 1111111111 No separation characters
   // 111.111.1111 Dots
   // 111-111-1111, X1111 Extension

   var inputStr = strInput.toString();
   var strFormatMsg = "The phone entry is not in an acceptable format.\n\nPlease enter phone numbers in the following format ###-###-####.";

   //This RegExp removes all dashes, parens, spaces, and dots from the string.
   inputStr = inputStr.replace(/[\-\)\(\.\ ]/g, '');

   if (inputStr.length < 10) {return false;}

   var AreaCode = parseInt(inputStr.substr(0, 3), 10)
   var CO = parseInt(inputStr.substr(3, 3), 10)
   var Number = parseInt(inputStr.substr(6, 4), 10)

   if (isNaN(AreaCode) || isNaN(CO) || isNaN(Number)) {return false;}
   if (AreaCode < 100 || AreaCode > 999)  {return false;}
   if (CO < 100 || CO > 999)  {return false;}
   if (Number < 0 || Number > 9999) {return false;}

   return true;
}

// Check whether string s is empty.

function isEmpty(s)
{
   return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or
// whitespace characters only.

function isWhitespace (s)
{
    var i;

   // whitespace characters
   var whitespace = " \t\n\r";

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

// function to see if input is valid for US 
// function strips out certain chars and then validates the zip code
// for either 5 or 9 digits
function isPostalCode(s)
{
  var sPart1
  var sPart2
  var zipStr = s.toString();

  // Strip out characters that might be in zip code field 
  // Strip out dash, space, period, comma, slash, backslash, pound
  zipStr = zipStr.replace(/[\-\ \.\,\\\/\#]/g, '');
 
  if (zipStr.length == 5 && isPosInteger(zipStr)) {return true;}

  if (zipStr.length == 9) {

       // Is it an extended zip code
       sPart1 = zipStr.substring(0,5);
       sPart2 = zipStr.substring(5,9);

       if (isPosInteger(sPart1) == true && isPosInteger(sPart2) == true)
            {return true;
            }
       else
       {return false;}
  }

  // Otherwise its not OK!
  return false;
}

// Return true/false if given value is a valid 5-digit or 9-digit U.S. postal code;
//    allows partial values to enable querying; valid inputs are:
//    9????,   where ? == an optional numeric character
//    99999-9??? where ? == an optional numeric character
// All other combinations are not valid. Assumes input value contains no characters.
function isQueryPostalCode (val)
{ 
  // Don't let the string end in a Dash
  if (val.charAt(val.length-1) == '-')
  { return false;
  }
  
  // Tokenize around the 'dash' for a 9-digit #####-#### pc
  var pcParts = val.split (/[\-]/);
  
  if (pcParts.length == 2)
  {
    // First part MUST be 5 in length
    if (pcParts[0].length == 5 && isPosInteger (pcParts[0]))
    { // Second part may be 1-4 numeric characters
      if (pcParts[1].length > 0 && pcParts[1].length <= 4 && isPosInteger (pcParts[1]))
      { return true;
      }
      else
      { return false;
      }
    }
    else
    { return false;
    }
  }
  else if (pcParts.length == 1)
  { // There is no second part - first part may be 5 chars or less
    if (pcParts[0].length > 0 && pcParts[0].length <= 5 && isPosInteger (pcParts[0]))
    { return true;
    } 
    else
    { return false;
    }
  }
  else
  { // We're not sure what user entered but it wasn't what we expected
    return false;
  }
}

function isURL(s)
{
  // Is it empty?
  if (isWhitespace(s))
    return false;

  var Http = s.indexOf('http');
  var Ftp = s.indexOf('ftp');
  var Colon = s.indexOf(':');
  var Slashes = s.indexOf('//');
  var Space = s.indexOf(' ');

  if ( ((Http == 0) || (Ftp == 0)) &&
       (Colon != -1) &&
     (Slashes != -1) &&
       (Colon < Slashes) &&
       (Space == -1) )
    return true;
  else
    return false;
}

//
function isEmail (s)
{
    // is s whitespace?
    if (isWhitespace(s)) return false;

    // there must be >= 1 character before @, so we
    // start looking at character position 1
    // (i.e. second character)
    var i = 1;
    var nLength = s.length;

    // look for @
    while ((i < nLength) && (s.charAt(i) != "@"))
    { i++
    }
   // The must be something after the @
    if ((i >= nLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < nLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= nLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

//
// Function isTime()
// Returns true if the given string contains a valid 12 hour time.
//
function isTime(s)
{
   // HH:MM
   // HH = 1 - 12, MM = 0 - 59

   // Find colon and space -- be sure they're in the right places
    var iColon = s.indexOf(":")

   // h:mm am or hh:mm am
   if (iColon != 2 && iColon != 1) {return false;}

   // Get the hours, minutes and am/pm
    var hh = s.substring(0, iColon);
    var mm = s.substring(iColon + 1);
    
    if ((!isInteger(hh)) || (!isInteger(mm)))
        {
        // there is a non-numeric character in one of the component values
        return false
        }

   // Be sure values are in range
   if (hh < 1 || hh > 12) { return false; }
    if (mm < 0 || mm > 59) { return false; }

   return true;
}

function isCurrency(s)
{
   // Allow "$", ",", "_" -- ignore it
   for (i=0; i<s.length; i++){
      if((i == 0) && (s.charAt(i) == "-")){}
    else if((i == 1) && (s.charAt(i - 1) == "-") && (s.charAt(i) == "$")){}
    else if((i == 1) && (s.charAt(i - 1) == "$") && (s.charAt(i) == "-")){}
      else if ((i > 1) && (s.charAt(i) == "$"))
         return false;
      else if ((i > 1) && (s.charAt(i) == "-"))
       return false;
   }
   var cu = replaceString(s, "$", "");
   if (cu == ""){return false;}
   var nu = cu.replace(/,/g, "");
   if (!isNumber(nu)){return false;}
   if (!isDecimal(nu, 2)){return false;}
   return true;
}

function addComma(num){
   var str = num.toString();
   strArray = new Array();
   for (i=0; i<str.length; i++){
      strArray[i] = str.charAt(i);
   }
   for (j=(strArray.length-3); j>0; j--){
       strArray[j-1] = strArray[j-1]+"@";
       j=j-2;
   }
   return (strArray.toString().replace(/,/g, "").replace(/@/g, ","));
}

function addDollar(str){
   return ("$".concat(str));
}

function makeTwoDecimal(str){
   if (str.length == 1)
      return (str+"0");
   else
      return str;
}
//*****************************************************************************
//  User interface functions (ValidXXX())
//*****************************************************************************

function ValidText(Field, bRequired, sMessage)
{
	if (bRequired && isWhitespace(Field.value))
	{
		alert(sMessage);
		Field.focus();
		return false;
	}
	return true;
}

function ValidSelect(Field, sMessage){
    if (isWhitespace(Field.options[Field.selectedIndex].value) || Field.options[Field.selectedIndex].value == "") {
      alert(sMessage);
          Field.focus();
          return false;
    }
    return true;
}


function ValidMultiSelect(Field, sMessage){
	var opt, bSelected, i;
	bSelected = false;
	for (i=0; i<Field.length; i++){
		if (Field[i].selected == true){
			bSelected = true;
      }
   }	
	if (!bSelected)
	{
		alert(sMessage);
         	Field.focus();
         	return false;
	} 
   return true;
}

function ValidRadio(Field, sAnchor, sMessage){
	var bSelected = false;	
	if (Field.length > 1){
		for (var i=0; i<Field.length; i++) {
			if (Field[i].checked) {
				bSelected = true;
			}
		}
	} else {
		if (Field.checked) {
			bSelected = true;
		}
	}
	if (bSelected != true)
	{
      	alert(sMessage);
		document.location = "#" + sAnchor;
		return false;
    }
    return true;
}

function ValidCheckbox(Field, sAnchor, sMessage){
	var bSelected = false;	
	if (Field.length > 1){
		for (var i=0; i<Field.length; i++) {
			if (Field[i].checked) {
				bSelected = true;
			}
		}
	} else {
		if (Field.checked) {
			bSelected = true;
		}
	}
	if (bSelected != true)
	{
      	alert(sMessage);
		document.location = "#" + sAnchor;
		return false;
    }
    return true;
}

function ValidTextArea(Field, bRequired, sMessage)
{  
	if (bRequired && isWhitespace(Field.value))
	{
		alert(sMessage);
		Field.focus();
		return false;
	}
	return true;
}

function ValidPhoneNumber(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isPhone(Field.value))
            {
            //CMK - 13 Apr 2000 - changed error message to use more common dash format.
            alert("Invalid Format. Use: '555-555-5555'.");  //CMK - 13 Apr 2000
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidEmail(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isEmail(Field.value))
            {
            alert("Invalid Format. Use: '<user>@<organization>.<domain>'.");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidDate(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
      {
      if (!isDate(Field.value))
         {
         alert("Invalid Format. Use: 'MM/DD/YYYY'.");
         Field.focus();
         Field.select();
         return false;
         }
      }
   return true;
}

function ValidTime(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isTime(Field.value))
            {
            alert("Invalid Format. Use: 'HH:MM'.");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidPostalCode(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }
   if (Field.value != "")
         {
         if (!isPostalCode(Field.value))
            {
            alert("Invalid Format. Use: '99999' or '99999-9999'" + ".");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidSSN(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
		 
         if (!isSSN(formatSSN(Field)))
            {
            alert("Invalid Format. Use: '555-55-5555'.");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidCurrency(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
   {
      if (!isCurrency(Field.value))
         {
         alert("Invalid Format. Use: '$99.99'.");
         Field.focus();
         Field.select();
         return false;
         }
    }  
   return true;
}

function ValidInteger(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
         {
         if (!isInteger(Field.value))
            {
            alert("Invalid Number.");
            Field.focus();
            Field.select();
            return false;
            }
         }
   return true;
}

function ValidPercentage(Field, bRequired, sMessage)
{
   if (bRequired && isWhitespace(Field.value))
      {
      alert(sMessage);
      Field.focus();
      return false;
      }

   if (Field.value != "")
   {
      var num = Field.value.replace(/%/g, "");
      if (!isPosNumber(num))
         {
         alert("Invalid Percentage.");
         Field.focus();
         Field.select();
         return false;
         }
    }  
   return true;
}
// End of DynamicFormValidation.js
