// check for IE3
var isIE3 = (navigator.appVersion.indexOf('MSIE 3') != -1);
var numberoftimes = 0;
 
/***************************************************************
** define and instantiate validation objects
** the validation object accepts the following parameters:
**
**   realName: name used in the alerts (same as label on the page)
**
**   formEltName: this must be the name of the corresponding
**       HTML form element; make it the same as the object name
**
**   eltType: element type (we have to create this since IE3
**       doesn't support the type property for for elements)
**     text
**     textarea
**     checkbox
**     radio
**     select
**
**   uptoSnuff: function call that's evaluated during validation check
**     isText(str)
**     isSelect(formObj)
**     isRadio(formObj)
**     isCheck(formObj, form, [index of first checkbox in group],
**         [number of checkboxes])
**     isEmail(str)
**     isState(str)
**     isZipCode(str)
**     isPhoneNum(str)
**     isDate(str)
**
**   format: text representation of required format;
**       pass 'null' if no required format;
**       used in alert as an aid to user
***************************************************************/

// object definition
function validation(realName, formEltName, eltType, upToSnuff, format) {
  this.realName = realName;
  this.formEltName = formEltName;
  this.eltType = eltType;
  this.upToSnuff = upToSnuff;
  this.format = format;
}

// create a new object for each form element you need to validate
var b_agreement          = new validation(' The terms and conditions', 'b_agreement', 'checkbox', 'isCheck(formObj, form, 91,1)', null);

var b_firstname          = new validation(' First Name', 'b_firstname', 'text', 'isText(str)', null);
var b_lastname           = new validation(' Last Name', 'b_lastname', 'text', 'isText(str)', null);
var b_address1           = new validation(' Street Address', 'b_address1', 'text', 'isText(str)', null);
var b_city               = new validation(' City', 'b_city', 'text', 'isText(str)', null);
var b_state              = new validation(' State', 'b_state', 'text', 'isState(str)', null);
var b_zip                = new validation(' Zip Code', 'b_zip', 'text', 'isText(str)', null);
var b_email              = new validation(' Email', 'b_email', 'text', 'isEmail(str)', null);
var b_occupation         = new validation(' Occupation', 'b_occupation', 'text', 'isText(str)', null);
var b_employer           = new validation(' Employer', 'b_employer', 'text', 'isText(str)', null);

var s_address1           = new validation(' Credit Card Billing Street Address', 's_address1', 'text', 'isText(str)', null);
var s_city               = new validation(' Credit Card Billing City', 's_city', 'text', 'isText(str)', null);
var s_state              = new validation(' Credit Card Billing State', 's_state', 'text', 'isState(str)', null);
var s_zip                = new validation(' Credit Card Billing Zip Code', 's_zip', 'text', 'isText(str)', null);

var b_donationamount     = new validation(' Donation Amount', 'b_donationamount', 'text', 'isText(str)', null);

var cctype               = new validation(' Credit Card Type', 'cctype', 'text', 'isSelect(formObj)', null);
var ccnum                = new validation(' Credit Card Number', 'ccnum', 'text', 'isText(str)', null);
var ccmo                 = new validation(' Expiration Month', 'ccmo', 'text', 'isSelect(formObj)', null);
var ccyr                 = new validation(' Expiration Year', 'ccyr', 'text', 'isSelect(formObj)', null);

/***************************************************************
** Define the elts array:
** Add a new item to the array for each object you create above
** Make sure the value of the array element is the same as
** the name of the object, and that the array elements are listed
** in the same order the corresponding objects appear in the form
** (it's more clear to the user that way)
***************************************************************/
// var elts = new Array(firstname,lastname,billing_address_1,billing_city,billing_zip,billing_email,billing_phone,order_shipping_name,order_shipping_address1,order_shipping_city,order_shipping_zip,order_shipping_phone);
/***************************************************************
** The main function keeps track of which fields the user missed
** or filled in incorrectly, and alerts the user so they can go
** back and fix what's wrong.
** Set allAtOnce to true if you want this &quot;validation help&quot; to
** alert the user to all mistakes at once; set it to false if
** you want it to show one mistake at a time
***************************************************************/
var allAtOnce = true;
/***************************************************************
** change text for alerts here
** unspecified field (text): &quot;Please include [field name].&quot;
** unspecified field (other): &quot;Please choose [field name].&quot;
** invalid text field entries: &quot;[field value] is an invalid [field name]!&quot;
** help with format: &quot;Use this format: &quot;
***************************************************************/
var beginRequestAlertForText = "Please include";
//var beginRequestAlertGeneric = "Please choose ";
var beginRequestAlertGeneric = "Please accept";
var endRequestAlert = ".";
var beginInvalidAlert = " is an invalid ";
var endInvalidAlert = ".";
var beginFormatAlert = "  Use this format: ";
/***************************************************************
** these functions validate the string or form object passed in,
** and return true or false based on whether the test succeeds or fails
**
** validate existence of input
**   isText(str): verifies text input or textarea is not empty
**   isSelect(formObj): verifies item from a select menu is chosen
**   isRadio(formObj): verifies one of a group of radio buttons is chosen
**   isCheck(formObj, form, [begin], [num]): verifies at least one
**       of a group of checkboxes is checked
**     for [begin], fill in the index number in the elements array
**       of the first checkbox (remember to start counting from zero)
**     for [num], fill in the number of checkboxes in the group
**
** validate text in text input or textarea matches pattern
**   isEmail(str): verifies email address (contains &quot;@&quot; and &quot;.&quot;)
**   isState(str): verifies U.S. State Code
**   isZipCode(str): verifies zip code of form xxxxx or xxxxx-xxxx
**   isPhoneNum(str): verifies phone number of form xxx-xxx-xxxx
**   isDate(str): verifies date of form mm/dd/yyyy
***************************************************************/

function isText(str) {
  return (str != "");
}

function isSelect(formObj) {
  return (formObj.selectedIndex != 0);
}

function isRadio(formObj) {
  for (j=0; j<formObj.length; j++) {
    if (formObj[j].checked) {
      return true;
    }
  }
  return false;
}

function isCheck(formObj, form, begin, num) {
  for (j=begin; j<begin+num; j++) {
	  //alert(formObj.name + " " + j + " " + form.elements[j].name);
    if (form.elements[j].checked) {
      return true;
    }
  }
  return false;
}

function isEmail(str) {
  return ((str != "") && (str.indexOf(".") != -1) && (str.indexOf(".") != -1));
}

function isState(str) {
  str = str.toUpperCase();
  return ( (str == "IT") || (str == "AK") || (str == "AL") || (str == "AR") || (str == "AZ") || (str == "CA") || (str == "CO") || (str == "CT") || (str == "DC") || (str == "DE") || (str == "FL") || (str == "GA") || (str == "HI") || (str == "IA") || (str == "ID") || (str == "IL") || (str == "IN") || (str == "KS") || (str == "KY") || (str == "LA") || (str == "MA") || (str == "MD") || (str == "ME") || (str == "MI") || (str == "MN") || (str == "MO") || (str == "MS") || (str == "MT") || (str == "NE") || (str == "NC") || (str == "ND") || (str =="NH") || (str == "NJ") || (str == "NM") || (str == "NV") || (str == "NY") || (str == "OH") || (str == "OK") || (str == "OR") || (str == "PA") || (str == "RI") || (str == "SC") || (str == "SD") || (str == "TN") || (str == "TX") || (str == "UT") || (str == "VA") || (str == "VT") || (str == "WA") || (str == "WI") || (str == "WV") || (str =="WY") || (str == "AA") || (str == "AE") || (str == "AP") || (str == "54") || (str == "55") || (str == "56") || (str == "57") || (str == "58") || (str == "59") || (str == "60") || (str == "61") || (str == "62") || (str == "63") || (str == "64") || (str == "65") || (str == "GU") || (str == "PR") || (str == "VI") || (str == "AA") || (str == "AE") || (str == "AP"));
}

function isZipCode(str) {
  var l = str.length;
  if ((l != 5) && (l != 10)) { return false }
  for (j=0; j<l; j++) {
    if ((l == 10) && (j == 5)) {
      if (str.charAt(j) != "-") { return false }
    } else {
      if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
    }
  }
  return true;
}

function isPhoneNum(str) {
  if (str.length != 13) { return false }
  for (j=0; j<str.length; j++) {
    if ((j == 3) || (j == 8)) {
      if (str.charAt(j) != "-") { return false }
    } else {
      if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
    }
  }
  return true;
}

function isSSN(str) {
  if (str.length != 11) { return false }
  for (j=0; j<str.length; j++) {
    if ((j == 3) || (j == 6)) {
      if (str.charAt(j) != "-") { return false }
    } else {
      if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
    }
  }
  return true;
}

function isDate(str) {
  if (str.length != 10) { return false }
  for (j=0; j<str.length; j++) {
    if ((j == 2) || (j == 5)) {
      if (str.charAt(j) != "/") { return false }
    } else {
      if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
    }
  }

  var month = str.charAt(0) == "0" ? parseInt(str.substring(1,2)) : parseInt(str.substring(0,2));
  var day = str.charAt(3) == "0" ? parseInt(str.substring(4,5)) : parseInt(str.substring(3,5));
  var begin = str.charAt(6) == "0" ? (str.charAt(7) == "0" ? (str.charAt(8) == "0" ? 9 : 8) : 7) : 6;
  var year = parseInt(str.substring(begin, 10));

  if (day == 0) { return false }
  if (month == 0 || month > 12) { return false }
  if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
    if (day > 31) { return false }
  } else {
    if (month == 4 || month == 6 || month == 9 || month == 11) {
      if (day > 30) { return false }
    } else {
      if (year%4 != 0) {
        if (day > 28) { return false }
      } else {
        if (day > 29) { return false }
      }
    }
  }
  return true;
}

/***************************************************************
** The validateForm() function validates the form elements
** previously defined as validation objects and as members of
** the elts array. We loop through the elts array, testing each
** element in turn, and alerting the user when they've missed
** a required field
***************************************************************/
function validateForm(form) {
  var formEltName = "";
  var formObj = "";
  var str = "";
  var realName = "";
  var alertText = "";
  var firstMissingElt = null;
  var hardReturn = "\r\n";
  
	//for (j=0; j<form.length; j++) {
	//	alert(form.name + " " + j + " " + form.elements[j].name);
	//}
		
  //
  // Modified by Karim Soufi so that this script can validate
  // different form elements based on billing and shiiping conditions.
  // It checks to see if the Billing address is the same as the
  // Shipping address then adjust the required fields accordingly.
  //  
  
  if (form.ship_to_bill.checked == false)
  {
      var elts = new Array(b_firstname,b_lastname,b_address1,b_city,b_state,b_zip,b_occupation,b_employer,b_email,b_donationamount,b_agreement,s_address1,s_city,s_state,s_zip,cctype,ccnum,ccmo,ccyr);
  }
  else
  {
      var elts = new Array(b_firstname,b_lastname,b_address1,b_city,b_state,b_zip,b_occupation,b_employer,b_email,b_donationamount,b_agreement,cctype,ccnum,ccmo,ccyr);
  }

  for (i=0; i<elts.length; i++) {
    formEltName = elts[i].formEltName;
    formObj = eval("form." + formEltName);
    realName = elts[i].realName;

    if (elts[i].eltType == "text") {
      str = formObj.value;

      if (eval(elts[i].upToSnuff)) continue;

      if (str == "") {
        if (allAtOnce) {
          alertText += beginRequestAlertForText + realName + endRequestAlert + hardReturn;
          if (firstMissingElt == null) {firstMissingElt = formObj};
        } else {
          alertText = beginRequestAlertForText + realName + endRequestAlert + hardReturn;
          alert(alertText);
        }
      } else {
        if (allAtOnce) {
          alertText += str + beginInvalidAlert + realName + endInvalidAlert + hardReturn;
        } else {
          alertText = str + beginInvalidAlert + realName + endInvalidAlert + hardReturn;
        }
        if (elts[i].format != null) {
          alertText += beginFormatAlert + elts[i].format + hardReturn;
        }
        if (allAtOnce) {
          if (firstMissingElt == null) {firstMissingElt = formObj};
        } else {
          alert(alertText);
        }
      }
    } else {
      if (eval(elts[i].upToSnuff)) continue;
      if (allAtOnce) {
        alertText += beginRequestAlertGeneric + realName + endRequestAlert + hardReturn;
        if (firstMissingElt == null) {firstMissingElt = formObj};
      } else {
        alertText = beginRequestAlertGeneric + realName + endRequestAlert + hardReturn;
        alert(alertText);
      }
    }
    if (!isIE3) {
      var goToObj = (allAtOnce) ? firstMissingElt : formObj;
      if (goToObj.select) goToObj.select();
      if (goToObj.focus) goToObj.focus();
    }
    if (!allAtOnce) {return false};
  }
  if (allAtOnce) {
    if (alertText != "") {
      alert(alertText);
      numberoftimes = 0;
      return false;
    }
  }
	    // alert("I am valid!"); //remove this when you use the code   
    return true; //change this to return true
}

function onlyonce()
{
  numberoftimes += 1;
  if (numberoftimes > 1)
  { 
    var themessage = "Please be patient. You have already submitted this form. Pressing submit multiple times will result in your account being billed multiple times. You will receive a response momentarily.";
    if (numberoftimes == 3)
    {
      themessage = "DO NOT PRESS SUBMIT MULTIPLE TIMES!!! YOUR ACCOUNT WILL BE BILLED EACH TIME YOU PRESS SUBMIT!!! Processing may take up to one minute.";
    }
    alert(themessage);
    return false; 
  } 
  else
  {
    return true;
  }    
}

function updateDonationAmount(otherAmount) {
	if(otherAmount!=''){
		for (i=0;i<document.donation.amount.length;i++) {
			if (document.donation.amount[i].checked)
				document.donation.amount[i].checked = false;
		}
		if((!isInt(otherAmount))||(otherAmount > 5000)){
			alert('Donation amount must be a NUMBER less than or equals to 5000 (no decimals!)');
			document.donation.amountother.value='';
			document.donation.b_donationamount.value='';
		}
		else{
			document.donation.b_donationamount.value=otherAmount;
		}
	}
}

function setGatewayInfo()
{
	var theForm = document.donation;

	//Set Donation Amount
	if (theForm.amountother.value != "") {
		if (isInt(theForm.amountother.value))
		  theForm.b_donationamount.value = theForm.amountother.value;
		else {
			alert("Other donation amount must be a number");
			theForm.b_donationamount.value = "";
			theForm.amountother.value = "";
		}
	}
	else {
		for (i=0;i<theForm.amount.length;i++) {
			if (theForm.amount[i].checked)
				theForm.b_donationamount.value = theForm.amount[i].value;
		}
	}
	
	if (!isInt(theForm.b_donationamount.value)) {
	  theForm.b_donationamount.value = "";
	}
	
	if (theForm.b_agreement.checked)
		theForm.agreement.value = "YES";
	else
		theForm.agreement.value = "NO";
	
	var costObj = document.getElementById("theCost");
  costObj.value = theForm.b_donationamount.value;
	
  theForm.first_name.value      = theForm.b_firstname.value;
	theForm.last_name.value       = theForm.b_lastname.value;
  theForm.address.value         = theForm.b_address1.value;
	theForm.address2.value        = theForm.b_address2.value;
  theForm.city.value            = theForm.b_city.value;
  theForm.state.value           = theForm.b_state.value;
  theForm.zip.value             = theForm.b_zip.value;
  theForm.country.value         = theForm.b_country.value;
  theForm.occupation.value      = theForm.b_occupation.value;
	theForm.employer.value        = theForm.b_employer.value;
  theForm.phone.value           = theForm.b_phone1.value;
	theForm.workphone.value       = theForm.b_phone2.value;
  theForm.email.value           = theForm.b_email.value;
  theForm.saddr1.value          = theForm.s_address1.value;
	theForm.saddr2.value          = theForm.s_address2.value;
  theForm.scity.value           = theForm.s_city.value;
  theForm.sstate.value          = theForm.s_state.value;
  theForm.szip.value            = theForm.s_zip.value;
  theForm.sctry.value           = theForm.s_country.value;
	
	if (theForm.ship_to_bill.checked == true)
		theForm.ship_same_as_bill.value = "Yes";
	else
		theForm.ship_same_as_bill.value = "No";
    
  onlyonce();
}

function copybillingintoshipping(theForm)
{
    // When user checks the ship to bill box, copy billing address into shipping address
    // When user un-checks the ship to bill box, clear shipping address
    
    copy = theForm.ship_to_bill
    if (copy.checked == true)
    {
        theForm.s_address1.value       = theForm.b_address1.value;
        theForm.s_address2.value       = theForm.b_address2.value;
        theForm.s_city.value           = theForm.b_city.value;
        theForm.s_state.value          = theForm.b_state.value;
        theForm.s_zip.value            = theForm.b_zip.value;
        theForm.s_country.value        = theForm.b_country.value;
    } 
    else
    {
        theForm.s_address1.value       = "";
        theForm.s_address2.value       = "";
        theForm.s_city.value           = "";
        theForm.s_state.value          = "";
        theForm.s_zip.value            = "";
        theForm.s_country.value        = "";
    }
}

function updatebillingintoshipping(theForm)
{
    // If ship to bill is checked and user update the billing
    // address, update the shipping address accordingly
    
    copy = theForm.ship_to_bill
    if (copy.checked == true)
    {
        theForm.s_address1.value       = theForm.b_address1.value;
        theForm.s_address2.value       = theForm.b_address2.value;
        theForm.s_city.value           = theForm.b_city.value;
        theForm.s_state.value          = theForm.b_state.value;
        theForm.s_zip.value            = theForm.b_zip.value;
        theForm.s_country.value        = theForm.b_country.value;
    }
}

function cancellink() {
    return false;
}

function format_currency(amt) {
	// convert the form field value to a Number then multiply it by the float variable
	var amt=(amt-0)*1.00;
	// round the result to 2 decimal places 
	amt=((Math.floor(amt*100))/100); 
	// if we try to display the Number value, no trailing zeroes will be displayed, so we convert to a string; the string is what we'll actually display 
	var amtString=amt+"";
	// split the string using the decimal point as a delimiter 
	var amtStringParts=amtString.split(".");
	// if the resulting array is of length 1, then there's no decimal point, so concatenate ".00" to the end of amtString displaying it 
	if(amtStringParts.length==1) 
	  amtString+=".00" 
	// otherwise, if the substring following the decimal is of length 1, pad amtString with a single zero 
	else 
	  if(amtStringParts[1].length==1) 
	    amtString+="0"; 
	return amtString;
}

function isInt (str)
{
	var i = parseInt (str);

	if (isNaN (i)) {
		return false;
	}

	i = i . toString ();
	if (i != str){
		return false;
	}

	return true;
}