/*
 Patrick L. Jarvis
 St. Paul, Minnesota USA
 March 22, 2008

 Copyright Patrick L. Jarvis 2008, All Rights Reserved

 This is the donation form Javascript.

 Adopted for use with donation page by Doug R
*/

// Store the HTML ids in global variables to make it easier to
// change if the HTML is changed.
 addressOfPerson = 'addressOfPerson';
 amountForPayPal = 'amountForPayPal';
 emailOfPerson = 'emailOfPerson';
  contributionAmount = 'contributionAmount';
  duesAmount = 'duesAmount';
 itemName = 'itemName';
 nameOfPerson = 'nameOfPerson';
 orderForm = 'orderForm';
 orderInformation = 'orderInformation';

 telephoneOfPerson = 'telephoneOfPerson';
 totalChargeAmount = 'totalChargeAmount';
 validateButton = 'validateButton';

// Initialize some other global variables.
 grandTotal = 0; // the amount to be charged.
 validateButtonText = null; // text from page will be used.


function formatAsMoney(value)
{
 // return the passed value as a string with two positions
 // to the right of the decimal point.
 var i;
 var result;

 value = value - 0;
 result = value.toString();

 // add decimal point, if necessary
 if(result.indexOf('.')<0) result = result + '.';

 // calculate how many zeros to add to the right of the decimal
 i = result.indexOf('.');
 i = 2-(result.length - i - 1);

 // concatenate zeros to right of the decimal point
 while(i>0)
 {
 result = result + '0';
 i=i-1;
 }

 return result;
}


function initialize()
{
 // Set the global variable to contain the text of the submit button.
 // This text will be used with the total begin charged and will be
 // displayed as the button's text.
 if(validateButtonText == null)
 validateButtonText = document.getElementById(validateButton).value;

 // Initialize values used by the page

 document.getElementById(contributionAmount).value = '0.00';
 document.getElementById(orderInformation).style.visibility = 'visible';
 updateTotals();
}

function trimWhiteSpace(data)
{
 // Return data with all leading and trailing whitespace removed.
 // If a null is passed to this function, a zero length string
 // is returned.
 var left;
 var right;
 var whitespace = ' \t\n\r'; // blank, tab, newline.return

 if(data == null || data.length == 0) return '';

 // Find the left-most non-whitespace character in data, if there is one
 for(left=0; left<data.length && whitespace.indexOf(data.substring(left,left+1))>=0; left++);

 // If no whitespace characters in data, then return data
 if(left >= data.length) return data;

 // left points to the leftmost non-white space character. right will point
 // to the rightmost non-white space character
 for(right=data.length-1; right>left && whitespace.indexOf(data.substring(right,right+1))>=0; right--);

 // now we have identified the left and right boundaries of the
 // non-whitespace characters, return just those characters
 return data.substring(left,right+1);
}

function updateTotals()
{
 
 //Update all the totals that are related to user entered data. Check the
 //value entered for the contribution amount. If it is invalid, put out an
 //error message and reset the contribution value to zero. This method sets
 //the global variable: grandTotal
 
 var contribution;
 var grandTotalFormatted;
 var dues;
 var i;
 var message;

 // Get the information from the form
 contribution = trimWhiteSpace(document.getElementById(contributionAmount).value);
 dues = trimWhiteSpace(document.getElementById(duesAmount).value);

 // The contribution is the only thing the user enters. Make sure
 // it is a money value and not less than zero.
 message = validateContributionAmount(contribution);
 if(message != null)
 {
 alert(message);
 contribution = 0; // reset the bad value to zero.
 dues = 0;
 }

 // The contribution amount is valid. If it is zero, rewrite
 // it in standard form in case they hosed with it. I subtract zero
 // from contribution to force it to be in its numeric rather than
 // string form.
 if(contribution-0 == 0) document.getElementById(contributionAmount).value = '0.00';
 if (dues-0 == 0) document.getElementById(duesAmount).value = '0.00';

 // The user entered stuff is OK, so now we can do our calculations
 // and update the values displayed on the page.

 // I need to subtract zero to force addition as opposed to concatentation
 // grandTotal is a global variable.
 grandTotal = (contribution - 0) + (dues - 0);
document.getElementById("total").innerHTML = "$" + formatAsMoney(grandTotal);

 // Format the contribution to have two digits to the right of the
 // decimal point and store this value back to the html page
 document.getElementById(contributionAmount).value = formatAsMoney(contribution);
 document.getElementById(duesAmount).value = formatAsMoney(dues);


 // Now make format the grand total to have two digits to the
 // right of the decimal point and store this value back to the html page
 grandTotalFormatted = formatAsMoney(grandTotal);
 //document.getElementById(totalChargeAmount).innerHTML = grandTotalFormatted;
 // Place the grand total in the submit button, too.
 //document.getElementById(validateButton).value = validateButtonText + ': $' + grandTotalFormatted;
}

function validateContributionAmount(contribution)
{
 // Make sure the user entered data for the contribution is valid.
 // Return an error message if it is not valid. Return null if it
 // is valid.

 var errorMessage;
 var i;
 var messageStem;

 errorMessage = null;
 messageStem ='The contribution you entered (' + contribution + ') ';

 // Javascript will perform conversions on strings that include
 // x or e so I have to do character by character analysis here.
 for(i=0; i<contribution.length && errorMessage == null; i++)
 {
 if('01234567890.'.indexOf(contribution.substring(i,i+1)) < 0)
 errorMessage = messageStem + 'is not a number.';
 } // for

 if(errorMessage == null)
 if(isNaN(contribution - 0)) // must be a number
 {
 errorMessage = messageStem + 'is not a number.';
 } else
 if((contribution-0) < 0) // must be at least zero
 {
 errorMessage = messageStem + 'is less than zero.';
 }else
 {
 // Check to see if it has too many decimal places. First add a
 // decimal point if necessary.
 if(contribution.indexOf('.') < 0) contribution = contribution + '.';

 // Now make sure there are at least 3 zero digits at the right end
 contribution = contribution + '000';

 // Substring off the stuff to the right of the decimal
 contribution = contribution.substring(contribution.indexOf('.')+3,contribution.length-1);
 // Now test it
 if(contribution-0>0)
 errorMessage = messageStem + ' has more than two digits to the right of the decimal point.';
 }

 return errorMessage;
}

function validateFormAndSubmitToPaypal()
{
 // The user has pressed the Submit button to make the charge to PayPal.
 // The non-personal information is validated as it is entered, so it is OK
 // at this point. Check the personal information the user needs to enter.
 // If it is OK, then cause the PayPal charge to proceed. If it is not OK,
 // then give them an error message.

 var errorMessage;

 errorMessage = validatePersonalInformation();
 if(errorMessage != null) { alert(errorMessage); return; }

 // Everything appears OK, so cause the form's Submit button to be clicked
 // which will start the PayPal transaction. But only do this if the amount
 // to be charged is greater than zero. This amount is in the global
 // variable grandTotal which is set each time the updateTotals method
 // is called.
 if(grandTotal > 0)
 {
  var donationAmt = document.getElementById(contributionAmount).value;
  var duesAmt = document.getElementById(duesAmount).value;
  
  
 document.getElementById("itemName").value = "Donation - $" + donationAmt + "; Dues - $" + duesAmt;
 document.getElementById(amountForPayPal).value=grandTotal;
 document.getElementById(contributionAmount).value;
 document.getElementById(orderForm).submit();
 }
 else {
 	alert('Please enter a donation amount greater than 0.'); return;
 }

}

function validatePersonalInformation()
{
 // Make sure that some, and maybe reasonable, information has been entered
 // for each of the personal information fields. Return null if they are all
 // OK. Return an error message otherwise.

 // The error checking done here is completely inadequate but they have not
 // indicated to me how the data is to be used or how it should be error
 // checked.
 var ch;
 var digitCount;
 var field;
 var i;


 field = trimWhiteSpace(document.getElementById(nameOfPerson).value);
 if(field.length < 1) return 'Please enter your name.';

 field = trimWhiteSpace(document.getElementById(addressOfPerson).value);
 if(field.length < 1) return 'Please enter your mailing address.';

 // Check the telephone number.
 field = trimWhiteSpace(document.getElementById(telephoneOfPerson).value);
 if(field.length < 1) return 'Please enter your telephone number.';

 // The telephone number is not empty. It should contain only digits,
 // space, hyphen, and possibly parenthesis. This is only a very coarse
 // validation check.
 digitCount = 0;
 for(i=0; i<field.length; i++)
 {
 ch = field.substring(i,i+1);
 if('0123456789'.indexOf(ch) >= 0) digitCount = digitCount + 1;
 else
 if('() -'.indexOf(ch) < 0) return 'Telephone number contains invalid characters.';
 } //for

 if(digitCount != 7 && digitCount != 10) return 'Telephone number is invalid.';



 // Check the email address
 field = trimWhiteSpace(document.getElementById(emailOfPerson).value);
 if(field.length < 1) return 'Please enter your email address.';

 // The email address is not empty. Do some verification on its contents.
 i = field.indexOf('@');
 if(i < 0) return 'Email address does not contain the @ character.';

 if(i == 0) return 'Email address is missing account name.';
 if(i == field.length-1) return 'Email address is missing computer name.';
 if(field.indexOf('@',i+1)>i) return 'Email address contains more than one @ character.';
 i = field.indexOf('.',i+1);
 if(i<0 || i == field.length-1) return 'Email address is incorrectly formatted';


 return null;
}
