// reg.js
//
//  This file contains various JavaScript functions.
//
//  Usage:  <script language="javascript" SRC="includes/reg.js"></script>
//          then in the link use <a href="#" OnClick="functionName("string")>
//
//  Created by:  CDO 02/27/01
//
//  Modified Date:      By:     Describe Changes:
//  12/13/01            JDO     Added help buttons
//  01/21/02            CDO     Functions for detecting double submit and back button
//  03/11/02            CDO     Remove toLowerCase from capitalizeFirst function 
//  09/26/02            DOH     Added proccesspayment action for live credit card processing
//  01/23/03            CDO     Added image functions
//  02/10/03            CDO     Netscape CSS
//  01/10/05            DOH     Added hot keys for volunteer registration (see HotKeyCallVolunteer)

var nav4 = navigator.appName == 'Netscape';
var isMac = navigator.userAgent.indexOf("Mac") != -1;
if ( isMac ) {
  document.write("<link rel='stylesheet' type='text/css' href='images/regstyle_mac.css'>");
} else if ( nav4 ) {
  document.write("<link rel='stylesheet' type='text/css' href='images/regstyle_nav4.css'>");
} else {
  document.write("<link rel='stylesheet' type='text/css' href='images/regstyle.css'>");
}


function preloadnns(name, icon)
{
    if (document.images && document[name]) {
        if (! icon) icon = name;

        document[name + '_default'] = document[name].src;
        document[name + '_over'] = new Image();
        document[name + '_over'].src = 'images/BTN_' + icon + '_F.gif';
    }
}

function turnOver(name)
{
    if (document.images && document[name + '_over'])
        document[name].src = document[name + '_over'].src;
}

function turnOff(name)
{
    if (document.images && document[name + '_default'])
        document[name].src = document[name + '_default'];
}
function doSimpleSubmit() {
  document.edit.sAction.value = "edit";
  if (document.edit.bSubmitted) {
    if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
    else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  }
  document.edit.submit();
}

function doSimpleCancel() {
  document.edit.sAction.value = "cancel";
  document.edit.submit();
}

function doWebPageSave() {
  document.edit.sAction.value = "edit";
  if (document.edit.imageFile != "" && !document.edit.defaultImageFile.checked) {
    document.newWin = window.open('includes/upload_in_progress.htm','pagesave','top=30,left=30,width=300,height=200,scrollbars=yes');
    document.newWin.focus();
  }
  document.edit.submit();
}

function unloadfunction() {
  if (document.newWin) document.newWin.close();
}

function doRemove(id,namestr) {
  if (confirm('Delete registration for '+namestr+'?')) {
    document.edit.action="registration.cfm";
    document.edit.sAction.value="remove";
    document.edit.id.value=id;
    if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
    else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
    document.edit.submit();
  }
}

function doEditPay() {
  document.edit.action="registration.cfm";
  document.edit.sAction.value="pay";
  document.edit.id.value="1";
  if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
  else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  document.edit.submit();
}

function doRegister() {
  document.edit.action="registration.cfm";
  document.edit.sAction.value="processpayment";
  if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
  else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  document.edit.submit();
}

function doAddId() {
  document.edit.action="registration.cfm";
  document.edit.sAction.value="add";
  if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
  else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  document.edit.submit();
}

function doReview() {
  document.edit.sAction.value="review";
  if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
  else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  document.edit.submit();
}

function doEditID(id) {
  document.edit.action="registration.cfm";
  document.edit.sAction.value="update";
  document.edit.id.value=id;
  if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
  else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  document.edit.submit();
}

function doEditIDVol(id) {
  document.edit.action="volunteer_registration.cfm";
  document.edit.id.value=id;
  if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
  else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  document.edit.submit();
}

function doRemoveVol(id,namestr) {
  if (confirm('Delete volunteer registration for '+namestr+'?')) {
    document.edit.action="volunteer_registration.cfm";
    document.edit.sAction.value="remove";
    document.edit.id.value=id;
    if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
    else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
    document.edit.submit();
  }
}

function doVolRegister() {
  document.edit.action="volunteer_register.cfm";
  document.edit.sAction.value="register";
  if (document.edit.bSubmitted.value == "1") document.edit.bSubmitted.value = "2";
  else if (document.edit.bSubmitted.value != "2") document.edit.bSubmitted.value = "1";
  document.edit.submit();
}

function showHelp(param) {
  var sDoc = "show_help.cfm"+param;
  hWin = window.open(sDoc,'showHelp','top=30,left=30,height=300,width=650,scrollbars=yes,resizable=no');
  hWin.focus();
}

function doForceSubmit()
{
  document.edit.sAction.value="edit";
  document.edit.sForce.value="FORCE";
  document.edit.submit();
}

function selectTeam(param) {
  var sDoc = "selectTeam.cfm"+param;
  hWin = window.open(sDoc,'selectTeam','top=30,left=30,height=350,width=670,scrollbars=yes,resizable=yes');
  hWin.focus();
}
function checkTeam(param,id) {
  if (id && id != "") {
    var sDoc = "checkTeam.cfm"+param+"&id="+id;
    hWin = window.open(sDoc,'checkTeam','top=30,left=30,height=10,width=10');
    hWin.focus();
  }
}
function pageTo(pg) {
    document.pageform['pgCmd'].value=pg
    document.pageform.submit();
}

// NNS hotkeys stuff

  function PopulateNNSPage(currentEmail)
  {
    if(document.edit.genderID2)
      document.edit.genderID2.checked=true;
    if(document.edit.rg_DOB1)
      document.edit.rg_DOB1.value="01";
    if(document.edit.rg_DOB2)
      document.edit.rg_DOB2.value="01";
    if(document.edit.rg_DOB3)
      document.edit.rg_DOB3.value="1980";
    if(document.edit.rg_Age)
      document.edit.rg_Age.value="23";

    document.edit.rg_FirstName.value="Test";
    document.edit.rg_LastName.value="Test";
    document.edit.rg_Address1.value="3300 Mayette Ave.";
    document.edit.rg_City.value="Santa Rosa";
    document.edit.rg_State.value="105";
    if(document.edit.rg_Country)
      document.edit.rg_Country.value="322";

    document.edit.rg_Zip.value="95405";
    // email done per user
    document.edit.rg_WorkPhone1.value="800";
    document.edit.rg_WorkPhone2.value="698";
    document.edit.rg_WorkPhone3.value="8699";
    if(document.edit.regwaiver)
      document.edit.regwaiver.checked=true;
    if(document.edit.pm_NameOnCard)
      document.edit.pm_NameOnCard.value="test";
    if(document.edit.pm_BillInfoSame)
      document.edit.pm_BillInfoSame.checked=true;
    if(document.edit.pm_billaddress1)
      document.edit.pm_billaddress1.value="3300 Mayette Ave.";
    if(document.edit.pm_billcity)
      document.edit.pm_billcity.value="Santa Rosa";
    if(document.edit.pm_billState)
      document.edit.pm_billState.value="105";
    if(document.edit.pm_billzip)
      document.edit.pm_billzip.value="94954";
    if(document.edit.pm_billCountry)
      document.edit.pm_billCountry.value="322";

    document.edit.rg_Email.value=currentEmail;
    document.edit.rg_Email2.value=currentEmail;
  }
  function PopulateRaceCentralPage(currentEmail)
  {
    if(document.edit.genderID2)
      document.edit.genderID2.checked=true;
    if(document.edit.rg_DOB1)
      document.edit.rg_DOB1.value="01";
    if(document.edit.rg_DOB2)
      document.edit.rg_DOB2.value="01";
    if(document.edit.rg_DOB3)
      document.edit.rg_DOB3.value="1980";
    if(document.edit.rg_Age)
      document.edit.rg_Age.value="23";

    document.edit.rg_FirstName.value="Test";
    document.edit.rg_LastName.value="Test";
    document.edit.rg_Address1.value="229 S Olive Ave";
    document.edit.rg_City.value="Rialto";
    document.edit.rg_State.value="105";
    if(document.edit.rg_Country)
      document.edit.rg_Country.value="322";

    document.edit.rg_Zip.value="92376";
    // email done per user
    document.edit.rg_WorkPhone1.value="800";
    document.edit.rg_WorkPhone2.value="698";
    document.edit.rg_WorkPhone3.value="8699";
    if(document.edit.regwaiver)
      document.edit.regwaiver.checked=true;
    if(document.edit.pm_NameOnCard)
      document.edit.pm_NameOnCard.value="test";
    if(document.edit.pm_BillInfoSame)
      document.edit.pm_BillInfoSame.checked=true;
    if(document.edit.pm_billaddress1)
      document.edit.pm_billaddress1.value="229 S Olive Ave";
    if(document.edit.pm_billcity)
      document.edit.pm_billcity.value="Rialto";
    if(document.edit.pm_billState)
      document.edit.pm_billState.value="105";
    if(document.edit.pm_billzip)
      document.edit.pm_billzip.value="92376";
    if(document.edit.pm_billCountry)
      document.edit.pm_billCountry.value="322";

    document.edit.rg_Email.value=currentEmail;
    document.edit.rg_Email2.value=currentEmail;
  }
  function PopulateDavesPage(currentEmail)
  {
    document.edit.genderID2.checked=true;
    document.edit.rg_DOB1.value="07";
    document.edit.rg_DOB2.value="04";
    document.edit.rg_DOB3.value="1951";
    document.edit.rg_Age.value="53";
    document.edit.rg_FirstName.value="Dave";
    document.edit.rg_LastName.value="Test";
    document.edit.rg_Address1.value="5910 Longleaf Dr";
    document.edit.rg_City.value="Lawrence";
    document.edit.rg_State.value="119";
    document.edit.rg_Country.value="322";
    document.edit.rg_Zip.value="66049";
    // email done per user
    document.edit.rg_WorkPhone1.value="785";
    document.edit.rg_WorkPhone2.value="832";
    document.edit.rg_WorkPhone3.value="1645";
    document.edit.regwaiver.checked=true;
    document.edit.pm_NameOnCard.value="test";
    document.edit.pm_BillInfoSame.checked=true;
    document.edit.pm_billaddress1.value="5910 Longleaf Dr";
    document.edit.pm_billcity.value="Lawrence";
    document.edit.pm_billState.value="119";
    document.edit.pm_billzip.value="66049";
    document.edit.pm_billCountry.value="322";
    document.edit.rg_Email.value=currentEmail;
    document.edit.rg_Email2.value=currentEmail;
  }
  function PopulateNNSPageVolunteer(currentEmail)
  {
    document.edit.rg_DOB1.value="01";
    document.edit.rg_DOB2.value="01";
    document.edit.rg_DOB3.value="1980";
    document.edit.rg_FirstName.value="Test";
    document.edit.rg_LastName.value="Test";
    document.edit.rg_Address1.value="921 Transport Way ste 26";
    document.edit.rg_City.value="Petaluma";
    document.edit.rg_State.value="105";
    document.edit.rg_Country.value="322";
    document.edit.rg_Zip.value="94954";
    // email done per user
    document.edit.rg_WorkPhone1.value="800";
    document.edit.rg_WorkPhone2.value="698";
    document.edit.rg_WorkPhone3.value="8699";
    document.edit.rg_HomePhone1.value="800";
    document.edit.rg_HomePhone2.value="698";
    document.edit.rg_HomePhone3.value="8699";
    document.edit.regwaiver.checked=true;
    document.edit.rg_Email.value=currentEmail;
    document.edit.rg_Email2.value=currentEmail;
    document.edit.genderID2.checked=true;
  }
  function PopulateTeamRegistration(currentEmail)
  {
    document.edit.tm_LeaderFirstName.value="Test";
    document.edit.tm_LeaderLastName.value="Test";
    document.edit.tm_Name.value="My Cool New Team";
    document.edit.tm_Address1.value="229 S. Olive Ave.";
    document.edit.tm_City.value="Rialto";
    document.edit.tm_Zip.value="92376";
    document.edit.tm_WorkPhone1.value="909";
    document.edit.tm_WorkPhone2.value="874";
    document.edit.tm_WorkPhone3.value="5480";
    document.edit.tm_HomePhone1.value="909";
    document.edit.tm_HomePhone2.value="874";
    document.edit.tm_HomePhone3.value="5480";
    document.edit.isResidential1.checked=true;
    // email done per user
    document.edit.tm_Email.value=currentEmail;
    document.edit.tm_Email2.value=currentEmail;
    document.edit.tm_category.selectedIndex = 1;
    document.edit.sPassword.value='test'
    document.edit.sPassword_Confirm.value='test'
  }
  function PopulateDonationPage(currentEmail)
  {
    document.edit.dn_Amount.value = "5";
    document.edit.dn_FirstName.value = "Test";
    document.edit.dn_LastName.value = "Donation";
    if( document.edit.dn_cvv2 )
      document.edit.dn_cvv2.value = "111";
    document.edit.dn_Address1.value = "229 S. Olive. Ave.";
    document.edit.dn_City.value = "Rialto";
    document.edit.dn_Zip.value = "92376";
    document.edit.dn_Email.value = currentEmail;
  }
function HotKeyCall()
  {
    var keyCharLocal;
    var altOnLocal;
    altOnLocal = window.event.altKey;
    altOnRemote = window.event.shiftKey;
    ctrlOnRemote = window.event.ctrlKey;
    keyCharLocal = String.fromCharCode(window.event.keyCode);
    if ( altOnLocal )
      if ( keyCharLocal == 'p' || keyCharLocal == 'P'  )
      {
        if ( ctrlOnRemote && altOnRemote )
        {
          PopulateNNSPage("dan@nnsllc.com");
        }
      }
      else if ( keyCharLocal == 'i' || keyCharLocal == 'I'  )
      {
        if ( ctrlOnRemote && altOnRemote )
        {
          PopulateRaceCentralPage("ivonne@rccal.com");
        }
      }
      else if ( keyCharLocal == 'd' || keyCharLocal == 'D'  )
      {
        if ( ctrlOnRemote && altOnRemote )
        {
          PopulateRaceCentralPage("racecentral@msn.com");
        }
      }
      else if ( keyCharLocal == 's' || keyCharLocal == 'S'  )
      {
        if ( ctrlOnRemote && altOnRemote )
        {
          PopulateDavesPage("dave@sportslistdata.com");
        }
      }
      else if ( keyCharLocal == 't' || keyCharLocal == 'T'  )
      {
        if ( ctrlOnRemote && altOnRemote )
        {
          PopulateTeamRegistration("dan@nnsllc.com");
        }
      }
      else if ( keyCharLocal == 'o' || keyCharLocal == 'O'  )
      {
        if ( ctrlOnRemote && altOnRemote )
        {
          PopulateDonationPage("dan@nnsllc.com");
        }
      }
  }
function HotKeyCallVolunteer()
  {
    var keyCharLocal;
    var altOnLocal;
    altOnLocal = window.event.altKey;
    altOnRemote = window.event.shiftKey;
    ctrlOnRemote = window.event.ctrlKey;
    keyCharLocal = String.fromCharCode(window.event.keyCode);
    if ( altOnLocal )
      if ( keyCharLocal == 'p' || keyCharLocal == 'P'  )
      {
        if ( ctrlOnRemote && altOnRemote )
        {
          PopulateNNSPageVolunteer("dan@nnsllc.com");
        }
      }
  }

/********************************** Image Methods ***************************************/
// adds the given object as a child of the parent object 
function addObject( childNode, parentNode )
{

  var type = ( typeof parentNode );
  
  // make sure we are adding to an object
  if( type != "object" )
    return;
    
 
  if( parentNode.appendChild )
    parentNode.appendChild( childNode );
      
  return childNode;
}

  function getElement( theDocument, elementName )
  {
    if( theDocument == null )
      return null;

    if( elementName == null )
      return null;

    var element = ( theDocument.all ) ? theDocument.all[ elementName ] : theDocument.getElementById( elementName );
    return element;
  }



// set the size of the given image
function setImageSize( theImage, width, height )
{
    theImage.width = width;
    theImage.height = height;
    
    return theImage;
}
// resize the given image to be with the given width and height maximum
function fitImage( theImage, maxWidth, maxHeight )
{
    var newWidth  = theImage.width;
    var newHeight = theImage.height;
    var height = theImage.height;
    var width = theImage.width;
    
    // determine the correct height/width ratio based on the image size and the maximum available space
    
    // maxWidth and maxHeight are the maximum allowed dimensions for the picture to take up
    if( ( height > maxHeight ) && ( width > maxWidth ) ) 
    {

      var dw = width - maxWidth;
      var dh = height - maxHeight;
      
      var rw = dw / maxWidth;
      var rh = dh / maxHeight;
                  
      // if the image is square, then size the image to be the smaller of the maxWidth and maxHeight
      if ( height == width ) 
      {
        newWidth = Math.min( maxWidth, maxHeight );
        newHeight = newWidth;
      } 
      // if the height is greater than the width, then scale the image width down
      else if ( rh > rw ) 
      {
        newHeight = maxHeight;
        newWidth = width * ( maxHeight / height );
      } 
      // if the width is greater, scale the height of the image
      else 
      {
        newWidth = maxWidth;
        newHeight = height * ( maxWidth / width);
      }
         
    } 
    else if ( width > maxWidth ) 
    {

      var r = maxWidth / width;
      newHeight = height * r;
      if ( newHeight < 10 ) 
        newHeight = maxHeight;
        
      newWidth = maxWidth;
    } 
    else if ( height > maxHeight ) 
    {

      var r = maxHeight / height;
      newWidth = width * r;
      if ( newWidth < 10) 
        newWidth = maxWidth;
        
      newHeight = maxHeight;
    } 
    
    setImageSize( theImage, newWidth, newHeight );
    return theImage;
}

// write an image with the given attributes onto the given document
function createImage( source, border, altTxt, name, onloadFunction )
{
    var img = document.createElement( "IMG" );
    img.src = source;
    img.border = border;
    img.alt = altTxt;
    img.name = name;
    img.id = name;
    
    if( ( createImage.arguments.length > 4 )  )
     img.onload = createImage.arguments[ 4 ];
      
    return img;
}
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

// autoTab use: onKeyUp="return autoTab(this, 3, event);"
function autoTab(input,len, e) {

  var keyCode = (isNN) ? e.which : e.keyCode; 
  var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
  
  if(input.value.length >= len && !containsElement(filter,keyCode)) {
    input.value = input.value.slice(0, len);
    input.form[(getIndex(input)+1) % input.form.length].focus();
  }

function containsElement(arr, ele) {
  var found = false, index = 0;
    while(!found && index < arr.length)
      if(arr[index] == ele)
        found = true;
      else
        index++;
      return found;
}

function getIndex(input) {
  
  var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
      if (input.form[i] == input)index = i;
        else i++;
      return index;
  }
    return true;
}
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var whitespace = " \t\n\r";
var decimalPointDelimiter = "."
var phoneNumberDelimiters = "()-.x";
var validUSPhoneChars = digits + phoneNumberDelimiters;
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";
var digitsInUSPhoneNumber = 10;
var ZIPCodeDelimiters = "-";
var ZIPCodeDelimeter = "-"
var validZIPCodeChars = digits + ZIPCodeDelimiters
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9
var creditCardDelimiters = " "
var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."
var sUSLastName = "Last Name"
var sUSFirstName = "First Name"
var sWorldLastName = "Family Name"
var sWorldFirstName = "Given Name"
var sTitle = "Title"
var sCompanyName = "Company Name"
var sUSAddress = "Street Address"
var sWorldAddress = "Address"
var sCity = "City"
var sCountry = "Country"
var sZIPCode = "ZIP Code"
var sWorldPostalCode = "Postal Code"
var sPhone = "Phone Number"
var sFax = "Fax Number"
var sDateOfBirth = "Date of Birth"
var sExpirationDate = "Expiration Date"
var sEmail = "Email"
var sCreditCardNumber = "Credit Card Number"
var sOtherInfo = "Other Information"
var iZIPCode = "This field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please reenter it now."
var iUSPhone = "This field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now."
var iWorldPhone = "This field must be a valid international phone number. Please reenter it now."
var iEmail = "This field must be a valid email address (like foo@bar.com). Please reenter it now."
var iCreditCardPrefix = "This is not a valid "
var iCreditCardSuffix = " credit card number. (Click the link on this form to see a list of sample numbers.) Please reenter it now."
var iDay = "This field must be a day number between 1 and 31.  Please reenter it now."
var iMonth = "This field must be a month number between 1 and 12.  Please reenter it now."
var iYear = "This field must be a 2 or 4 digit year number.  Please reenter it now."
var iDatePrefix = "The Day, Month, and Year for "
var iDateSuffix = " do not form a valid date.  Please reenter them now."
var defaultEmptyOK = false
var daysInMonth = new Array(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s)

{   var i;

    if (isEmpty(s)) return true;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}



// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var 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 stripCharsNotInBag (s, bag)

{   var i;
    var 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 stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

function isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}

function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a positive, not negative, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 0) ) );
}

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}

function isNegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNegativeInteger.arguments.length > 1)
        secondArg = isNegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a negative, not positive, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) < 0) ) );
}

function isNonpositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonpositiveInteger.arguments.length > 1)
        secondArg = isNonpositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number <= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) <= 0) ) );
}

function isFloat (s)

{   var i;
    var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    if (s == decimalPointDelimiter) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

function isSignedFloat (s)

{   if (isEmpty(s)) 
       if (isSignedFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedFloat.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedFloat.arguments.length > 1)
            secondArg = isSignedFloat.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}

function isAlphabetic (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}

function isAlphanumeric (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphanumeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    // All characters are numbers or letters.
    return true;
}

function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}

function isInternationalPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isInternationalPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isInternationalPhoneNumber.arguments[1] == true);
    return (isPositiveInteger(s))
}

function isZIPCode (s)
{  if (isEmpty(s)) 
       if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) && 
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // 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 sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}

function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}

function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

// Display prompt string s in status bar.

function prompt (s)
{   window.status = s
}

// Display data entry prompt string s in status bar.

function promptEntry (s)
{   window.status = pEntryPrompt + s
}

function checkString (theField, s, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) 
       return false;
    else return true;
}

function capitalize(s) 
{
  var resultstring = "";
  bWS = true;
  for (i = 0; i < s.length; i++)
  {   
    var c = s.charAt(i);     
    if (isWhitespace(c))
    {
      bWS = true;
      resultstring += c;
    }
    else if (isLetter(c) && bWS == true)
    {
      resultstring += c.toUpperCase();
      bWS = false;
    } else resultstring += c;
  }
  return resultstring;
}
  
  

// checkCapitalizeFirst
function checkCapitalizeFirst (theField, emptyOK)
{
  var resultstring = "";
  if (checkCapitalizeFirst.arguments.length == 1) emptyOK = defaultEmptyOK;
  theField.value = stripInitialWhitespace(theField.value);
  if ((emptyOK == false) && isEmpty(theField.value)) return false;
  else 
  {
    theField.value = capitalize(theField.value);
    return true;
  }
}

function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}

function checkZIPCode (theField, emptyOK)
{   if (checkZIPCode.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    { var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters)
      if (!isZIPCode(normalizedZIP, false)) 
         return false;
      else 
      {  // if you don't want to insert a hyphen, comment next line out
         theField.value = reformatZIPCode(normalizedZIP)
         return true;
      }
    }
}

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}

function checkUSPhone (theField, emptyOK)
{   if (checkUSPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)
       if (!isUSPhoneNumber(normalizedPhone, false)) 
          return false;
       else 
       {  // if you don't want to reformat as (123) 456-789, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          return true;
       }
    }
}

function checkInternationalPhone (theField, emptyOK)
{   if (checkInternationalPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  if (!isInternationalPhoneNumber(theField.value, false)) 
          return false;
       else return true;
    }
}

function checkEmail (theField, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) 
       return false;
    else return true;
}

function checkYear (theField, emptyOK)
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false)) 
       return false;
    else return true;
}

function checkMonth (theField, emptyOK)
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false)) 
       return false;
    else return true;
}

function checkDay (theField, emptyOK)
{   if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isDay(theField.value, false)) 
       return false;
    else return true;
}

function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    if (!isYear(yearField.value)) return false;
    if (!isMonth(monthField.value)) return false;
    if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
    else if (!isDay(dayField.value)) 
       return false;
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}



// Get checked value from radio button.

function getRadioButtonValue (radio)
{   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    return radio[i].value
}




// Validate credit card info.

function checkCreditCard (radio, theField)
{   var cardType = getRadioButtonValue (radio)
    var normalizedCCN = stripCharsInBag(theField.value, creditCardDelimiters)
    if (!isCardMatch(cardType, normalizedCCN)) 
       return false;
    else 
    {  theField.value = normalizedCCN
       return true
    }
}

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    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--;
  }

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} 

function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}  // END FUNCTION isVisa()

function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;

} 

function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isAmericanExpress()

function isDinersClub(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}

function isCarteBlanche(cc)
{
  return isDinersClub(cc);
}

function isDiscover(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) && (first4digs == "6011"))
    return isCreditCard(cc);
  return false;

} 

function isEnRoute(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 15) &&
      ((first4digs == "2014") ||
       (first4digs == "2149")))
    return isCreditCard(cc);
  return false;
}

function isJCB(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) &&
      ((first4digs == "3088") ||
       (first4digs == "3096") ||
       (first4digs == "3112") ||
       (first4digs == "3158") ||
       (first4digs == "3337") ||
       (first4digs == "3528")))
    return isCreditCard(cc);
  return false;

} 

function isAnyCard(cc)
{
  if (!isCreditCard(cc))
    return false;
  if (!isMasterCard(cc) && !isVisa(cc) && !isAmericanExpress(cc) && !isDinersClub(cc) &&
      !isDiscover(cc) && !isEnRoute(cc) && !isJCB(cc)) {
    return false;
  }
  return true;

} 

function isCardMatch (cardType, cardNumber)
{

  cardType = cardType.toUpperCase();
  var doesMatch = true;

  if ((cardType == "VISA") && (!isVisa(cardNumber)))
    doesMatch = false;
  if ((cardType == "MASTERCARD") && (!isMasterCard(cardNumber)))
    doesMatch = false;
  if ( ( (cardType == "AMERICANEXPRESS") || (cardType == "AMEX") )
                && (!isAmericanExpress(cardNumber))) doesMatch = false;
  if ((cardType == "DISCOVER") && (!isDiscover(cardNumber)))
    doesMatch = false;
  if ((cardType == "JCB") && (!isJCB(cardNumber)))
    doesMatch = false;
  if ((cardType == "DINERS") && (!isDinersClub(cardNumber)))
    doesMatch = false;
  if ((cardType == "CARTEBLANCHE") && (!isCarteBlanche(cardNumber)))
    doesMatch = false;
  if ((cardType == "ENROUTE") && (!isEnRoute(cardNumber)))
    doesMatch = false;
  return doesMatch;

}

function calcAge(month,day,year,asof,age)
{
  var dInput = new Date(year,month-1,day);
  
  if (asof)
  {
    var dAsOf = new Date(asof);
  }
  else
  {
    var dAsOf = new Date();
  }
  
  inputyear = dInput.getYear();
  
  if (inputyear < 1900) inputyear += 1900;

  if (navigator.appName == "Netscape")
  {
    var browserYear = dAsOf.getYear() + 1900;
  }
  else
  {
    var browserYear = dAsOf.getYear();
  }
  
  var iYear = browserYear - inputyear;

  if (dAsOf.getMonth() < dInput.getMonth())
  {
    iYear = iYear - 1;
  }
  else if (dAsOf.getMonth() == dInput.getMonth())
  {
    if (dAsOf.getDate() < dInput.getDate())
    {
      iYear = iYear - 1;
    }
  }
  age.value = iYear;
}