/**
* University of Nebraska Foundation
* Payment 2.0 - BBIS ADF
* Updated: Aug 13, 2021
* Version: 26.3.0
**/
(function ($) {
// Defaults for connecting to WordPress API to pull fund information
WPAPI = {
params: window.location.search,
wpURLs: [],
wpURLPrefix: 'https://nufoundation.org/wp-json/wp/v2/fund?',
wpURLSuffix: '&_fields=slug,title,priority,site_name,crm_guid,has_benefit'
};
var donationAppeal = "";
// Create an instance of the DonationService
var donationService = new BLACKBAUD.api.DonationService(
$('.BBDonationApiContainer').data('partid')
);
// Create an instance of the DonationService
var queryService = new BLACKBAUD.api.QueryService(
'https://ali.nufoundation.org/',
window.location.origin
);
// Create the donation object we'll send
var donation = {
Gift: {
PaymentMethod: 0,
Designations: []
},
PartId: $('.BBDonationApiContainer').data('partid'),
Origin: {
PageId: BLACKBAUD.api.pageInformation.pageId,
PageName: $(document).attr('title')
} // END Origin
};
/** Custom Methods **/
function addAppeal() {
var queryID = 'f34461b5-9f7d-4880-8901-9139d5af8d5c';
var queryFilter = new Array({ columnName: "Name", value: donationAppeal });
var appealSuccess = function (results) {
donation.Origin.AppealID = results.Rows[0].Values[1];
};
var appealFail = function (error) { displayErrors(error, 'appealFail'); };
queryService.getResults(queryID, appealSuccess, appealFail, queryFilter);
}; // END Appeal
function addCustomNotes() {
var commentContent = $('#comments').val();
var benefitInfo = "";
if ($('select option:selected').attr('has-benefit')) {
benefitInfo = "\r\n Once your donation has been processed a receipt will be mailed to the address provided.";
} else {
benefitInfo = "\r\n \r\n No goods or services were provided in exchange for this donation.";
}
donation.Gift.Comments = commentContent + benefitInfo;
}; // END addCustomNotes
// Add reccuring gift information to donatioObject
function addRecurringGift() {
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
// Required Reccurring Info
donation.Gift.Recurrence = {
Frequency: $('#frequency').val(),
StartDate: new Date(startDate.getUTCFullYear(), startDate.getUTCMonth(), startDate.getUTCDate()),
EndDate: new Date(endDate.getUTCFullYear(), endDate.getUTCMonth(), endDate.getUTCDate()),
DayOfMonth: $('#dayOfMonth').val(),
DayOfWeek: $('#dayOfWeek').val(),
Month: $('#month').val()
}; // Close Recurrence
switch (donation.Gift.Recurrence.Frequency) {
case '1':
case '7':
donation.Gift.Recurrence.DayOfMonth = null;
donation.Gift.Recurrence.Month = null;
break;
case '2':
case '3':
donation.Gift.Recurrence.Month = null;
donation.Gift.Recurrence.DayOfWeek = null;
break;
case '4':
donation.Gift.Recurrence.DayOfWeek = null;
break;
default:
null
}
if ($('#startDate').val() == "") {
var today = new Date();
donation.Gift.Recurrence.StartDate = new Date(getTodaysDate());
}
}; // END addRecurringGift
// Add tribute information to donatioObject
function addTributeInfo() {
// Required Info
donation.Gift.Tribute = {
TributeDefinition: {
FirstName: $('#tributeFirstName').val(),
LastName: $('#tributeLastName').val(),
Name: $('#tributeFirstName').val() + "" + $('#tributeLastName').val(),
Type: $('input[name="tributeType"]:checked').val()
},
Acknowledgee: {
FirstName: $('#acknowledgeeFirstName').val(),
LastName: $('#acknowledgeeLastName').val(),
AddressLines: $('#acknowledgeeStreetAddress').val(),
City: $('#acknowledgeeCity').val(),
State: $('#acknowledgeeState option:selected').attr('name'),
PostalCode: $('#acknowledgeePostalCode').val(),
Country: $('#acknowledgeeCountry option:selected').attr('name'),
}
}; // Close Tribute
// Optional Info
$('#acknowledgeePhone').val() ?
donation.Gift.Tribute.Acknowledgee.Phone = $('#acknowledgeePhone').val() : null;
// Optional Tribute Info
$('#acknowledgeeEmail').val() ?
donation.Gift.Tribute.Acknowledgee.Email = $('#acknowledgeeEmail').val().trim() : null;
// TributeDefinition.Description is required by the API
donation.Gift.Tribute.TributeDefinition.Description = $('#tributeComments').val() != "" ? $('#tributeComments').val() : 'New Tribute';
}; // END addTributeInfo
function capitalizeString(string) {
return string.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}; // END capitalizeString
function formatDate(date) {
var dateRegEx = new RegExp(/\d{4}\-\d{2}\-\d{2}/g);
if (dateRegEx.test(date)) {
return date;
} else if (date.length == 8) {
date = date.slice(0, 4) + '-' + date.slice(4, 6) + '-' + date.slice(6);
return date;
}
}; // END formateDate
// Collect input data from the form
function gatherUserInput() {
donation.Gift = {
Designations: [{
Amount: $('#giftAmount').val(),
DesignationId: $('#fund-id').val(),
FundName: $('#fund-id option:selected').text()
}],
PaymentMethod: 0
}; // END Gift
if ($('#addTribute').is(":checked") && !$('#donateRecurring').is(":checked")) {
addTributeInfo()
}
$('#donateRecurring').is(":checked") ?
addRecurringGift() : null;
$('#finderNumber').val() ?
donation.Gift.FinderNumber = $('#finderNumber').val() : null;
$('#giveAnonymously').is(":checked") ?
donation.Gift.IsAnonymous = true : null;
addCustomNotes();
}; // END gatherUserInput
function getTodaysDate() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
return now.getFullYear() + "-" + (month) + "-" + (day);
}; // END getTodaysDate()
function populateCountryState(countrySelector, stateSelector) {
// Populate the County and State fields using the CountryService
var selectCountry = $('#' + countrySelector),
selectState = $('#' + stateSelector);
var blackbaudCountryService = new BLACKBAUD.api.CountryService();
var donorCountry = BLACKBAUD.api.querystring.getQueryStringValue('country');
var donorState = BLACKBAUD.api.querystring.getQueryStringValue('state');
// Load Countries
blackbaudCountryService.getCountries(function (countries) {
for (var i = 0, j = countries.length; i < j; i++) {
selectCountry.append(
''
);
}
$('#' + countrySelector + ' option[name="united states"]').insertBefore($('#' + countrySelector + ' option:nth-child(2)'));
// If donorCountry is null default to US
donorCountry == "" ? $('#' + countrySelector + ' option[name="united states"]').prop('selected', 'selected') :
$('#' + countrySelector + ' option[name="' + donorCountry + '"]').prop('selected', 'selected');
$('#' + countrySelector).trigger('change');
}); // Close getCountries
// Watch Countries Change
selectCountry.on('change', function () {
// Load States
blackbaudCountryService.getStates($(this).val(), function (states) {
selectState.html('');
for (var i = 0, j = states.length; i < j; i++) {
selectState.append(
''
);
}
// If the country is the united states
if ($('#' + countrySelector + ' option:checked').attr('name') == 'united states') {
// If donorState is null default to Nebraska
donorState == "" ? $('#' + stateSelector + ' option[name="ne"]').prop('selected', 'selected') :
$('#' + stateSelector + ' option[name="' + donorState + '"]').prop('selected', 'selected');
} // End If
}); // Close getStates
}); // Close .on()
}; // END populateCountryState
// process all available query vals
function populateQueryVals() {
var apiWPFailed = function (error) {
displayErrors(error, 'apiWPFailed');
}; // END apiFailed
var apiWPSuccess = function (results) {
var resultNum = results.length;
var benefit;
var resultStop = Math.min(20, results.length);
// Populate with only priority funds
// Unless only 1 fund exists
for (var n = 0; n < resultStop; n++) {
$('#fund-id').append(
''
);
if (results[n].has_benefit) {
$('option#' + results[n].slug).attr('ereceipt', results[n].has_benefit);
}
if (WPAPI.fundid) {
$('option#' + WPAPI.fundid).attr('selected', 'selected');
}
} // End for
$('#loadOption').remove();
}; // END apiSuccess
WPAPI.sitename = BLACKBAUD.api.querystring.getQueryStringValue('sitename');
WPAPI.fundid = BLACKBAUD.api.querystring.getQueryStringValue('fundid');
WPAPI.recurring = {
isRecurring: BLACKBAUD.api.querystring.getQueryStringValue('is_recurring'),
frequency: BLACKBAUD.api.querystring.getQueryStringValue('recurring_frequency'),
weekday: BLACKBAUD.api.querystring.getQueryStringValue('recurring_weekday'),
month: BLACKBAUD.api.querystring.getQueryStringValue('recurring_month'),
monthday: BLACKBAUD.api.querystring.getQueryStringValue('recurring_monthday'),
startDate: formatDate(BLACKBAUD.api.querystring.getQueryStringValue('recurring_startdate')),
endDate: formatDate(BLACKBAUD.api.querystring.getQueryStringValue('recurring_enddate'))
}; // Close recurring
// Setup Tribute Section
WPAPI.tribute = BLACKBAUD.api.querystring.getQueryStringValue('tribute_type');
if (WPAPI.tribute != '') {
$('#addTribute').trigger('click');
if (WPAPI.tribute == 'honor') {
$('#inHonorOf').prop('checked', true);
} else if (WPAPI.tribute == 'memory') {
$('#inMemoryOf').prop('checked', true);
}
}
$('#giftAmount').val(BLACKBAUD.api.querystring.getQueryStringValue('amount'));
$('#comments').val(BLACKBAUD.api.querystring.getQueryStringValue('comments'));
if (WPAPI.recurring.isRecurring == 'yes') {
$('#donateRecurring').trigger('click');
}
if (!WPAPI.params.includes('fundid=') && !WPAPI.params.includes('sitename=')) {
// Just grab the priority funds
WPAPI.wpURLs.push(WPAPI.wpURLPrefix + '&filter[meta_key]=priority&filter[orderby]=priority&filter[order]=dsc' + WPAPI.sitename + WPAPI.wpURLSuffix);
} else {
if (WPAPI.fundid) {
WPAPI.wpURLs.push(WPAPI.wpURLPrefix + 'slug=' + WPAPI.fundid + WPAPI.wpURLSuffix);
} // End if (WPAPI.fundid))
if (WPAPI.sitename) {
WPAPI.wpURLs.push(WPAPI.wpURLPrefix + 'per_page=50&filter[meta_query][0][key]=priority&filter[meta_query][0][compare]=>&filter[meta_query][0][value]=0&filter[orderby]=priority&filter[meta_query][1][key]=site_name&filter[meta_query][1][compare]=LIKE&filter[meta_query][1][value]=' + WPAPI.sitename + WPAPI.wpURLSuffix);
} // End if ( WPAPI.sitename )
} // End else
// IFF appeal exists add it
donationAppeal = BLACKBAUD.api.querystring.getQueryStringValue('appeal');
donationAppeal != "" ? addAppeal() : null;
/**
* Grab Funds from WordPress
*/
async function getAllUrls(urls) {
try {
var data = await Promise.all(
urls.map(
url => fetch(url).then(
response => response.json()
).then(fund => {
apiWPSuccess(fund);
})
));
return data;
} catch (error) {
error => {
apiWPFailed(error);
};
throw error;
}
} // End async
var responses = getAllUrls(WPAPI.wpURLs);
}; // END populateQueryVals
// setup adf
function setupADF() {
// Hide Donation Confirmation Section
$('.adfDonationConfirmationContainer').hide();
// Hide optional areas if not checked
if ($('#donateRecurring').is(":checked")) {
$('#recurringInfo').show();
$('#addTributeDiv, #tributeInfo').hide();
} else {
$('#recurringInfo').hide();
$('#addTributeDiv').show();
}
$('#addTribute').is(":checked") ? $('#tributeInfo').show() : $('#tributeInfo').hide();
// Show/Hide sections if correlating box is checked
$('#addTribute').change(function () {
// Display tributeInfo if selected
if ($('#addTribute').is(":checked")) {
$('#addTribute, #tributeInfo').show();
// Pull Country/State Data for Acknowledgee
populateCountryState('acknowledgeeCountry', 'acknowledgeeState')
} else {
$('#addTribute, #tributeInfo').hide();
};
});
$('#donateRecurring').change(function () {
if ($('#donateRecurring').is(":checked")) {
$('#recurringInfo').show();
$('#frequency').trigger('change');
$('#addTributeDiv, #tributeInfo').hide();
$('#addTribute').prop("checked", false);
var today = new Date();
var todayDate = today.getDate();
var todayDay = today.getDay();
var todayMonth = today.getMonth() + 1;
// Populate Recurring info from URL
WPAPI.recurring.frequency ?
$('#frequency option[term=' + WPAPI.recurring.frequency + ']').prop('selected', 'selected') : $('#frequency option[term="monthly"]').prop('selected', 'selected');
WPAPI.recurring.weekday ?
$('#dayOfWeek option[value=' + WPAPI.recurring.weekday + ']').prop('selected', 'selected') : $('#dayOfWeek option[value=' + todayDay + ']').prop('selected', 'selected');
WPAPI.recurring.month ?
$('#month option[value=' + WPAPI.recurring.month + ']').prop('selected', 'selected') : $('#month option[value=' + todayMonth + ']').prop('selected', 'selected');
WPAPI.recurring.monthday ?
$('#dayOfMonth option[value=' + WPAPI.recurring.monthday + ']').prop('selected', 'selected') : $('#dayOfMonth option[value=' + todayDate + ']').prop('selected', 'selected');
$('#frequency').trigger('change');
if (WPAPI.params.enddate) {
$('#endDate').val(WPAPI.recurring.endDate);
}
if (WPAPI.params.startdate) {
// Default Starting date with Today's Date
$('#startDate').val(WPAPI.recurring.startDate);
} else {
$('#startDate').val(getTodaysDate());
}
} else {
$('#recurringInfo').hide();
$('#addTributeDiv').show();
}
});
$('#frequency').change(function () {
// Display the correct fields when a donation frequency is selected
var freqNum = this.value;
switch (freqNum) {
case '1':
case '7':
$('#dayOfWeekGroup').show();
$('#dayOfMonthGroup, #monthGroup').hide();
break;
case '2':
case '3':
$('#dayOfMonthGroup').show();
$('#dayOfWeekGroup, #monthGroup').hide();
break;
case '4':
$('#dayOfMonthGroup, #monthGroup').show();
$('#dayOfWeekGroup').hide();
break;
default:
$('#dayOfWeekGroup, #dayOfMonthGroup, #monthGroup').hide();
}
});
// Reset recurring gift to give accurate frequency options
$('#frequency').trigger('change');
populateQueryVals();
}; // END setupADF
// this function validate all required fields of donation page
function validateFormClientSide() {
$('input, div').removeClass('invalidField');
$(".validation").text("");
var errorCount = 0;
var validateName = function (contact) {
// First Name
if (!$("#" + contact + "FirstName").val()) {
errorCount++;
$("#" + contact + "FirstName").addClass('invalidField');
}
// Last Name
if (!$("#" + contact + "LastName").val()) {
$("#" + contact + "LastName").addClass('invalidField');
}
} // END validateName
var validateAddress = function (contact) {
//Street Address
if (!$("#" + contact + "StreetAddress").val()) {
errorCount++;
$("#" + contact + "StreetAddress").addClass('invalidField');
}
//City
if (!$("#" + contact + "City").val()) {
errorCount++;
$("#" + contact + "City").addClass('invalidField');
}
/*
//Postal Code
if (!validatePostalCode($("#" + contact + "PostalCode").val())) {
errorCount++;
$("#" + contact + "PostalCode").addClass('invalidField');
}
*/
//Email Address
if (!validateEmail($("#" + contact + "Email").val())) {
errorCount++;
$("#" + contact + "Email").addClass('invalidField');
}
//Phone
if (!validatePhone($("#" + contact + "phone").val())) {
errorCount++;
$("#" + contact + "phone").addClass('invalidField');
}
} // END validateAddress
var validateEmail = function (email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
} // END validateEmail
var validatePhone = function (phone) {
if (phone) {
var re = /^[0-9 \+\)\(\-]{6,20}\s?((([xX]|[eE][xX][tT])\.?\s*(\d+))*)$/;
return re.test(phone);
} else {
return true;
}
} // END validatePhone
var validateCountry = function (country, ctryData) {
if (country.toUpperCase() === ctryData.Id.toUpperCase() || country.toUpperCase() === ctryData.Abbreviation.toUpperCase() || country.toUpperCase() === ctryData.Description.toUpperCase()) {
return true;
}
return false;
} // END validateCountry
var validateStartDate = function (startDate) {
if (startDate) {
var pattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
return pattern.test(startDate);
} else {
return false;
}
} // END validateStartDate
//Amount
if ($('#giftAmount').val() <= 0 || !Number.isInteger(Number($('#giftAmount').val()))) {
errorCount++;
$('#giftAmount').parent().addClass('invalidField');
}
if ($('#addTribute').is(":checked")) {
validateName('acknowledgee');
validateName('tribute');
validateAddress('acknowledgee');
if (!$('input[name="tributeType"]:checked').val()) {
errorCount++;
$("#inHonorOf").closest('.col-sm-4').addClass('invalidField');
}
}
if (errorCount === 0) {
return true;
} else {
$(".validation").text("Please address the fields in red before continuing.").addClass('invalidField').css('padding', '10px');
return false;
}
}; // END validateFormClientSide
// Donation data is validated and ready for proccessing
function sendData() {
// Create our success handler
var createDonationSuccess = function (returnedDonation) {
var bbisError = setTimeout(function () { }, 0);
// Do nothing, page redirected to the shopping cart
};
// Create our error handler
var createDonationError = function (returnedErrors) {
clearTimeout(bbisError);
var msg = "An error has occured, please refresh the page and try again. ";
msg += "If need further assistance please contact us.";
$(".validation").html(msg).addClass('invalidField').css('padding', '10px');
console.log('Error creating donation: ', returnedErrors);
};
donationService.createDonation(donation, createDonationSuccess, createDonationError);
var errorMsg = "There seems to be an error, please refresh the page. If this issue persists, please contact us.";
var bbisError = setTimeout(function () { alert(errorMsg); }, 5000);
}; // END Send Data
/** Let's make sure the DOM is ready **/
$(function () {
// Prepare donation form
setupADF();
// User ready to submit donation
$('#btnSubmit').click(function (e) {
e.preventDefault();
// Validate User Input
if (validateFormClientSide()) {
$('#btnSubmit').text('Processing...');
gatherUserInput();
// Add donation to Cart
sendData();
}
});
});
}(jQuery));