/*
'+---------------------------------------------------------------+
'| Copyright 2001 MachroTech, LLC                                |
'| http://www.machrotech.com                                     |
'|                                                               |
'| This software contains confidential information which is the  |
'| property of Machrotech, LLC. This entire software package is  |
'| protected by the copyright laws of the United States and      |
'| elsewhere. All rights are reserved. No part of this software  |
'| may be copied, transcribed or used without express written    |
'| permission of MachroTech. This includes but is not limited to |
'| the source code, designs, concepts, interfaces and            |
'| documentation that are associated with this software and its  |
'| development.                                                  |
'+---------------------------------------------------------------+
*/

/***************************** 
* Validate Email
******************************/

function validateEmail (emailStr) {

var emailPat=/^(.+)@(.+)$/

var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

var validChars="\[^\\s" + specialChars + "\]"

var firstChars=validChars

var quotedUser="(\"[^\"]*\")"

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

var atom="(" + firstChars + validChars + "*" + ")"

var word="(" + atom + "|" + quotedUser + ")"

var userPat=new RegExp("^" + word + "(\\." + word + ")*$")

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {  
	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    // user is not valid
    alert("The name part of the email address seems to be invalid.")
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {    
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("The IP part of the email address is invalid!")
		return false
	    }
    }
    return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name of the email address doesn't seem to be valid.")
    return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("The email address must end in a three-letter domain, or two letter country.")
   return false
}

if (domArr[domArr.length-1].length==3 && len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}
// If we've gotten this far, everything's valid!
return true;
}

	
/**********************************
* Check a text field for a maximum length
* and trims it if necessary
***********************************/
function check_len(field, max)
{
	if(field.value.length > max)
	{
		field.value = field.value.substring(0, max - 1)
		alert("The length of this field cannot exceed " + max + " characters.\nIt has been truncated to this size.")
	}
}

	
	
/**********************************
* Trim Leading and Trailing Spaces
***********************************/
function trim(trimString)
{
	//trims the trimString and returns true if the resulting value is nullstring
	//or true otherwise

	if(trimString.length == 0)
		return false;

	//Triom leading spaces
	while(''+trimString.charAt(0)==' ')
		trimString=trimString.substring(1,trimString.length);

	if(trimString.length == 0)
	{
		return false;
	}

	//Trim trailing spaces
	while(trimString.charAt(trimString.length-1)==' ')
		trimString=trimString.substring(0,trimString.length-1);

	if(trimString.length == 0)
	{
		return false;
	}

	return true;
}


/**********************************
* Validate ZIP code
***********************************/

function validateZIP(field)
{
	var valid = "0123456789-";
	var hyphencount = 0;

	if (field.length != 5 && field.length != 10)
	{
		alert("Please enter your 5-digit numeric zip code.");
		return false;
	}
	for (var i=0; i < field.length; i++)
	{
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1")
		{
			alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-"))
		{
			alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
			return false;
		}
	}
	return true;
}



/**********************************
* Validate phone number
***********************************/

// Removes all characters which appear in string bag from string s.
function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function handlespace(theField)
{
//**********************************************************************\
//the following is to remove " " and "-" in the phone number string
var Delimiters = " "
var Delimiters2 = "-"	
	
    var normalizedCCN = stripCharsInBag(theField, Delimiters)
    normalizedCCN = stripCharsInBag(normalizedCCN, Delimiters2)
    theField.value = normalizedCCN
    return true    
}

function CheckPhoneNumber(TheNumber) {
	var valid = true
	var GoodChars = "0123456789()-+ "
	var i = 0
	//var bool=handlespace(TheNumber)
	if (TheNumber=="") {
		// Return false if number is empty
		//alert("Please enter a valid phone number.")
		valid = false
	}
	for (i =0; i <= TheNumber.length -1; i++) {
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {

		 //alert("Please enter a valid phone number.")
			valid = false
		} // End if statement
	} // End for loop
	return valid
}



/*  ================================================================
    FUNCTION:  isCreditCard(st)
 
    INPUT:     st - a string representing a credit card number

    RETURNS:  true, if the credit card number passes the Luhn Mod-10
		    test.
	      false, otherwise
    ================================================================ */

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19 || st.length < 15)
    return (false);

	if (Left(st,1) == 6)
	return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
// Uncomment the following line to help create credit card numbers
// 1. Create a dummy number with a 0 as the last digit
// 2. Examine the sum written out
// 3. Replace the last digit with the difference between the sum and
//    the next multiple of 10.

//  document.writeln("<BR>Sum      = ",sum,"<BR>");
//  alert("Sum      = " + sum);

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()

function Left(str, n)
        /***
                IN: str - the string we are LEFTing
                    n - the number of characters we want to return

                RETVAL: n characters from the left side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                        return "";
                else if (n > String(str).length)   // Invalid bound, return
                        return str;                // entire string
                else // Valid bound, return appropriate substring
                        return String(str).substring(0,n);
        }
