Advanced Donation Form

The Advanced Donation Form Part and accompanying REST APIs were released in version 3.0 of BBIS. They allow completely custom interfaces to be created for the donation experience, relaying the necessary information to the backend via the REST API or JavaScript SDK. For a complete list of possible options, be sure to visit the technical reference for more information.

All the examples below expect a page with a configured instance of the Advanced Donation Form Part on it. It's also important the examples below are meant to be as simple and straight-forward as possible. In a real-world scenario, we highly suggestion following standard web practices for form design, including labels for accessibility, and client-side data validation.

For all the Advanced Donation Form examples, I've split the grouped the content by language - HTML, CSS, or JS; however, when using the code in the Advanced Donation Form Part, the code is combined into a single textarea. Please be certain to wrap the content with appropriate <script> or <style> tag.

Barebones Example

In our first example, we'll create a very barebones example of a donation form, supplying only the required fields. For this example we've included no styling or error handling, other than displaying a message in the console. I've also hard-coded the designation and amount fields.

Important The DonationService constructor requires the Advanced Donation Form Part ID. In the examples below, we dynamically find this ID. You could hard-code this value if you prefer. The technique below assumes there's only one Advanced Donation Form Part per page.

<dl>
  <dt>First Name</dt>
  <dd><input type="text" id="first-name" /></dd>

  <dt>Last Name</dt>
  <dd><input type="text" id="last-name" /></dd>

  <dt>Email</dt>
  <dd><input type="text" id="email" /></dd>

  <dt>Address</dt>
  <dd><textarea id="address"></textarea></dd>

  <dt>City</dt>
  <dd><input type="text" id="city" /></dd>

  <dt>State</dt>
  <dd><input type="text" id="state" /></dd>

  <dt>Zip</dt>
  <dd><input type="text" id="zip" /></dd>

  <dt>Country</dt>
  <dd><input type="text" id="country" /></dd>
</dl>

<p><button class="btn-donate">Donate</button></p>
// Let's be good developers and not pollute the global namespace
(function($) {

  // Let's make sure the DOM is ready
  $(function() {

    // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );

    // Create the donation object we'll send
    // In order to simplify our examples, some of this information is hard-coded.
    var donation = {
      MerchantAccountId: '00000000-0000-0000-0000-000000000000',
      Gift: {
        PaymentMethod: 0,
        Designations: [
          {
            Amount: 5.00,
            DesignationId: '00000000-0000-0000-0000-000000000000'
          }
        ]
      }
    };

    // Create our success handler
    var success = function(returnedDonation) {
      console.log(returnedDonation);
    };

    // Create our error handler
    var error = function(returnedErrors) {
      console.log('Error!');
    };

    // Attach our event listener to the donate button
    $('.btn-donate').click(function(e) {

      // Stop the button from submitting the form
      e.preventDefault(); 

      // Add the information our user has typed
      donation.Donor = {
        FirstName: $('#first-name').val(),
        LastName: $('#last-name').val(),
        Address: {
          StreetAddress: $('#address').val(),
          City: $('#city').val(),
          State: $('#state').val(),
          PostalCode: $('#zip').val(),
          Country: $('#country').val()
        }
      };

      // Submit our donation
      ds.createDonation(donation, success, error);
    });

  });
}(jQuery));

Using the Payment 2.0 Part

When using the Payment 2.0 Part, the information required is reduced. For example, Donor information is should no longer be provided. Again, we're not including any styling or error handling, but I have introduced the ability to select a donation amount and designation.

<dl>
  <dt>Amount</dt>
  <dd>
    <select id="amount">
      <option value="5">5</option>
      <option value="10">10</option>
      <option value="20">20</option>
    </select>
  </dd>

  <dt>Designation</dt>
  <dd>
    <select id="designation">
      <option value="00000000-0000-0000-0000-000000000000">Example Designation 1</option>
      <option value="00000000-0000-0000-0000-000000000000">Example Designation 2</option>
    </select>
  </dd>
</dl>
      
<p><button class="btn-donate">Donate</button></p>
// Let's be good developers and not pollute the global namespace
(function($) {
  
  // Let's make sure the DOM is ready
  $(function() {
    
    // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );
    
    // Create the donation object we'll send
    // In order to simplify our examples, some of this information is hard-coded.
    var donation = {
      Gift: {
        PaymentMethod: 0,
        Designations: []
      }
    };
    
    // Create our success handler
    var success = function(returnedDonation) {
      console.log(returnedDonation);
    };
    
    // Create our error handler
    var error = function(returnedErrors) {
      console.log('Error!');
    };
    
    // Attach our event listener to the donate button
    $('.btn-donate').click(function(e) {
      
      // Stop the button from submitting the form
      e.preventDefault(); 
      
      // Add the information our user has typed
      donation.Gift.Designations.push({
        Amount: $('#amount').val(),
        DesignationId: $('#designation').val()
      });
      
      // Submit our donation
      ds.createDonation(donation, success, error);
    });
    
  });
}(jQuery));

Note The DonationService attempts to redirect to the BBSPCheckoutUri or PaymentPageUri if either of them exist (in that order) after a successful callback from the createDonation method.



Blackbaud Checkout Example (New)

This example will take advantage of the transaction workflow optimization code included in our Service Pack 25 release.

This feature can be used to configure the payment checkout pop up on ADF by using the payment's Checkout endpoints. This functionality is wrapped under Checkout Service, as shown in the example. This will enhance the end user experience and provide better troubleshooting around the missing transactions.

<!-- This div is for showing the layover after the payment completion and before the confirmation page(use when payment checkout pop up is configured)-->
(function ($) {


 // Create an instance of the DonationService
  var ds = new BLACKBAUD.api.DonationService(
  $('.BBDonationApiContainer').data('partid')),
         CheckoutModel=JSON.parse(checkoutData),
         serverMonth = $(".BBDonationApiContainer").attr("serverMonth") - 1,
         serverDay = $(".BBDonationApiContainer").attr("serverDay"),
         serverYear = $(".BBDonationApiContainer").attr("serverYear"),
         ServerDate = new Date(serverYear, serverMonth, serverDay);
		 
		 InitializeBBCheckout();
  var donationAmount = getDonationAmount();
        var numberOfInstallments = $("#number-of-installments").val();
        var installmentAmount = ds.getRecurringGiftInstallmentAmount(donationAmount, numberOfInstallments);
        var installmentAmt = installmentAmount;

  //Create the donation object we'll send
  //In order to simplify our examples, some of this information is hard-coded.
  var donation = {
  MerchantAccountId: '00000000-0000-0000-0000-000000000000',
  BBSPReturnUri: window.location.href,
  BBSPTemplateSitePageId: 000,
  PartId: $('.BBDonationApiContainer').data('partid'),
  Gift: {
        PaymentMethod: 0,
        Designations: []
      }
  };

  // Create our success handler
  var success = function (returnedDonation) {
  console.log(returnedDonation);
  };   

  // Create our error handler
  var error = function (returnedErrors) {
  console.log('Error!');
  };
 
//Checkout Payment popup is loaded in this form.
    if ($('form[data-formtype="bbCheckout"]').length <= 0) {
        var form = '<form method=\'get\' id=\"paymentForm\" data-formtype=\'bbCheckout\' data-disable-submit=\'false\' novalidate><\/form>';
        $('body').append(form);
    }


    $("#paymentForm").submit(function paymentComplete(e) {
        // prevent form from refreshing and show the transaction token
        e.preventDefault();
    });

	
	 var  SrtDt, donationData, ServerDate,
        checkoutGenericError = "There was an error while performing the operation.The page will be refreshed";
		
	//return the donation amount	
	function getDonationAmount() {
    if ($("#amtOther").prop("checked")) {
         return $("#txtAmount").val();
    } else {
         return $("[name='radioAmount']:checked").val();
        }
    }
	
	 

    //#region CCCheckoutPayment

	//return which payment method is selected on the page
    function GetPaymentType() {
        paymentMethod = $("[name='paymentMethod']:checked").val();
        return paymentMethod;
    }

	
    function getUrlVars(url) {
        var vars = [], hash;
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

	//this is the function that calls the payment api to open the checkout pop up with all the parameters
    this.makePayment = function () {
        var donor = data.Donor;
		var selectedCountry=$("#country :selected").attr("iso");
		var selectedState=$("#state :selected").attr("iso");
		
		if(selectedCountry && selectedCountry.toLowerCase() == "gb")
		{
			selectedCountry="UK";
		}
        
		bbcheckout.Configuration.Data.Amount = ($("#recMonthly").prop("checked")) ? installmentAmt : getDonationAmount();            
		bbcheckout.Configuration.Data.BillingAddressCity = donor.Address.City;
		bbcheckout.Configuration.Data.BillingAddressCountry = selectedCountry;
		bbcheckout.Configuration.Data.BillingAddressLine = donor.Address.StreetAddress;
		bbcheckout.Configuration.Data.BillingAddressPostCode = donor.Address.PostalCode;
		bbcheckout.Configuration.Data.BillingAddressState = selectedState;
		bbcheckout.Configuration.Data.BillingAddressEmail = donor.EmailAddress;
		bbcheckout.Configuration.Data.BillingAddressFirstName = donor.FirstName + " " + (donor.MiddleName ? donor.MiddleName:"");
		bbcheckout.Configuration.Data.BillingAddressLastName = donor.LastName;
		bbcheckout.Configuration.Data.Cardholder = donor.FirstName + " " + donor.LastName;
		bbcheckout.Configuration.Data.UseVisaCheckout = (data.Gift && !data.Gift.Recurrence);
		bbcheckout.Configuration.Data.UseMasterpass = (data.Gift && !data.Gift.Recurrence);
		bbcheckout.Configuration.Data.UseApplePay = (data.Gift && !data.Gift.Recurrence);
        bbcheckout.Configuration.TransactionType = bbcheckout.TransactionType.Card_Not_Present;
        bbcheckout.Configuration.Data.CardToken = null;
		
        if (data.Gift && data.Gift.Recurrence && !data.Gift.Recurrence.ProcessNow) {
            bbcheckout.Configuration.Data.CardToken = CheckoutModel.DataKey;
            bbcheckout.Configuration.TransactionType = bbcheckout.TransactionType.Store_Card; //Store card transactions
        } 
		else if (data.Gift && data.Gift.Recurrence ) {      //Set CardToken value only in case of recurring gifts.
            bbcheckout.Configuration.Data.CardToken = CheckoutModel.DataKey;
        }

        //Set Donor Info so that it will be passed to finish the transaction at the end.
		data.DonationSource = bbcheckout.Configuration.DonationSource.ADF;
		data.Type=bbcheckout.Configuration.TranType.Donation;
        bbcheckout.DonorInfo = data;
        bbcheckout.openCheckout();
    }

  function InitializeBBCheckout() 
   {
	   
	   bbcheckout = new BBCheckoutProcessor(checkoutFunctions(),CheckoutModel.APIControllerName,CheckoutModel.TokenId,'[class*="donationForm"]');
	   bbcheckout.Configuration.Data.Key = CheckoutModel.PublicKey;
       bbcheckout.Configuration.TransactionType = CheckoutModel.TransactionType;
       bbcheckout.Configuration.Data.ClientAppName = CheckoutModel.ClientAppName;        
       bbcheckout.Configuration.Data.MerchantAccountId = CheckoutModel.MerchantAccountId;
       bbcheckout.Configuration.Data.IsEmailRequired = CheckoutModel.IsEmailRequired;
       bbcheckout.Configuration.Data.IsNameVisible = CheckoutModel.IsNameVisible;
       bbcheckout.Configuration.Data.PrimaryColor = CheckoutModel.PrimaryColor;
       bbcheckout.Configuration.Data.SecondaryColor = CheckoutModel.SecondaryColor;
       bbcheckout.Configuration.Data.FontFamily = CheckoutModel.FontFamily;
       bbcheckout.Configuration.Data.UseCaptcha = CheckoutModel.UseCaptcha;
       bbcheckout.Configuration.WorkflowType = CheckoutModel.WorkFlowType;
       bbcheckout.Configuration.HandleBrowserClosing = (CheckoutModel.HandleBrowserClosing === true ? "True" : "False");
       bbcheckout.Configuration.APITokenID = CheckoutModel.TokenId;
	   // You can add your own message to display on screen, after checkout pop-up close
       bbcheckout.Configuration.TempConfirmationHtml = "Thank you for your contribution, please wait while we process your transaction.";
       bbcheckout.intializeCheckout();
   }

function checkoutFunctions()
   {
    //  If you don't have anything to do then you don't add any events from below mentioned checkoutEvents 
	checkoutEvents={
	checkoutComplete : function (e) {
        //Place any code if you want to do anything on checkout complete.

        bbcheckout.postCheckoutFinish();
    },

    checkoutError : function (data) {
        //Place any code if you want to do anything on error.
    },

    checkoutExpired : function () {
        //Place any code if you want to do anything on Checkout expired.
    },

    checkoutReady : function () {
        //Place any code if you want to do anything on Checkout Ready.
    },

    browserClose : function () {
        //Place any code if you want to do anything on Checkout Browser closing.

    },

    checkoutCancel : function () {
        //Place any code if you want to do anything on Checkout cancel.
    },

    checkoutLoaded : function () {
        //Place any code if you want to do anything on Checkout loaded.
    }

		  
	}
    return checkoutEvents;	  
   }



	//to check for recurring gift that is to be processed today or not (this is check for call stored card payment api)
    function isProcessNow() {
        var recStartDate = $("#start-date").val()
        var frequency = $("#frequency").val();
        var dayOfMonth = $('#day-of-month').val();
        var dayOfWeek = $("#day-of-week").val();
        var month = $('#month').val();

        var startDateIsTodayDate = false;

        var recurrrentStartDate = new Date(recStartDate);

        var isProcessedNow = false;

        var serverDate = new Date(ServerDate);


        if (
            recurrrentStartDate.getFullYear() === serverDate.getFullYear() &&
            recurrrentStartDate.getMonth() === serverDate.getMonth() &&
            recurrrentStartDate.getDate() === serverDate.getDate()
        ) {
            startDateIsTodayDate = true;
        }
        else {

            return false;
        }

        //Weekly Frequency
        if (frequency == 1) {
            isProcessedNow = startDateIsTodayDate && dayOfWeek == serverDate.getDay();
        }
        //Mothly and Quarterly frequency
        else if (frequency == 2 || frequency == 3) {
            isProcessedNow = startDateIsTodayDate && dayOfMonth == serverDate.getDate();
        }
        //Annually frequency
        else if (frequency == 4) {

            isProcessedNow =
                startDateIsTodayDate
                && dayOfMonth == serverDate.getDate()
                && month == serverDate.getMonth() + 1;
        }
        //Every 4 weeks
        else if (frequency == 7) {
            isProcessedNow = startDateIsTodayDate;
        }
        else {
            isProcessedNow = false;
        }

        return isProcessedNow;


    };

	//this function call when we click on donate button
	function sendData() {
        if (CheckoutModel && CheckoutModel.MACheckoutSupported && GetPaymentType() == 0) {
            ProcessCCPayment();
        }
    }
	
	 //use this method for credit card payment through popup
    function ProcessCCPayment() {
        
        data = donation;

            onValidationSuccess = function (result) {
			
			makePayment();
            return false;
        };
        onValidationFailed = function (error) {
            console.log(error);
        };

        ds.validateDonationRequest(data, onValidationSuccess, onValidationFailed);

    }
		
		
	// Attach our event listener to the donate button
    $('.btn-donate').click(function(e) {
      
      // Stop the button from submitting the form
      e.preventDefault(); 
	  sendData();
	  });
		
}(jQuery));
/* css other than bootstrap */


Blackbaud Checkout Example (Legacy)

This example will continue to work with Service Pack 25 release, however, it will not utilize the transaction workflow optimization code included as part of that release. Please refer to Example - Blackbaud Checkout (New) for updated sample that incorporates the optimized Blackbaud Checkout Code.

This feature can be used to configure the payment checkout pop up on ADF by using the payment's Checkout endpoints. This functionality is wrapped under Checkout Service, as shown in the example. This will enhance the end user experience and provide better troubleshooting around the missing transactions.

<!-- This div is for showing the layover after the payment completion and before the confirmation page(use when payment checkout pop up is configured)-->
<div id="bbspLoadingOverlay" class="bbspLoadingOverlay">
</div>
(function ($) {


 // Create an instance of the DonationService
  var ds = new BLACKBAUD.api.DonationService(
  $('.BBDonationApiContainer').data('partid')),
         serverMonth = $(".BBDonationApiContainer").attr("serverMonth") - 1,
         serverDay = $(".BBDonationApiContainer").attr("serverDay"),
         serverYear = $(".BBDonationApiContainer").attr("serverYear"),
         ServerDate = new Date(serverYear, serverMonth, serverDay);
		 
  var donationAmount = getDonationAmount();
        var numberOfInstallments = $("#number-of-installments").val();
        var installmentAmount = ds.getRecurringGiftInstallmentAmount(donationAmount, numberOfInstallments);
        var installmentAmt = installmentAmount;

  //Create the donation object we'll send
  //In order to simplify our examples, some of this information is hard-coded.
  var donation = {
  MerchantAccountId: '00000000-0000-0000-0000-000000000000',
  BBSPReturnUri: window.location.href,
  BBSPTemplateSitePageId: 000,
  PartId: $('.BBDonationApiContainer').data('partid'),
  Gift: {
        PaymentMethod: 0,
        Designations: []
      }
  };

  // Create our success handler
  var success = function (returnedDonation) {
  console.log(returnedDonation);
  };   

  // Create our error handler
  var error = function (returnedErrors) {
  console.log('Error!');
  };
 
//Checkout Payment popup is loaded in this form.
    if ($('form[data-formtype="bbCheckout"]').length <= 0) {
        var form = '<form method=\'get\' id=\"paymentForm\" data-formtype=\'bbCheckout\' data-disable-submit=\'false\' novalidate><\/form>';
        $('body').append(form);
    }


    $("#paymentForm").submit(function paymentComplete(e) {
        // prevent form from refreshing and show the transaction token
        e.preventDefault();
    });

	
	 var  SrtDt, publicKey, donationData, EditorContent, ServerDate,
        checkoutGenericError = "There was an error while performing the operation.The page will be refreshed";
		
	//return the donation amount	
	function getDonationAmount() {
    if ($("#amtOther").prop("checked")) {
         return $("#txtAmount").val();
    } else {
         return $("[name='radioAmount']:checked").val();
        }
    }
	
	 //Handle Generic error 
    function handleError(errorMessage) {
        $("#bbspLoadingOverlay").hide();
        alert(checkoutGenericError);
        location.reload(true);
    }

    //#region CCCheckoutPayment

	//return which payment method is selected on the page
    function GetPaymentType() {
        paymentMethod = $("[name='paymentMethod']:checked").val();
        return paymentMethod;
    }

	//set the public key by using public key service that is used to open the checkout pop up
    function GetPublicKey() {
     
    onPublicKeySuccess = function (reply) {
        publicKey = JSON.parse(reply.Data).PublicKey;
    };
    
	onPublicKeyFailure = function (d) {
    };
    
	ds.getCheckoutPublicKey(onPublicKeySuccess, onPublicKeyFailure);

    }


	//get all the information that is configured on the editor used to open the checkout pop up
    function GetEditorInformation(partId) {

        onEditorContentSuccess = function onSuccess(content) {
            donation.MerchantAccountId = content.MerchantAccountID;
            EditorContent = content;
        };

        onEditorContentFailure = function onFail(error) {
        };

        ds.getADFEditorContentInformation(partId, onEditorContentSuccess, onEditorContentFailure);

    }


    function getUrlVars(url) {
        var vars = [], hash;
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

	//this is the function that calls the payment api to open the checkout pop up with all the parameters
    this.makePayment = function () {
        opened = false;

        var checkout = new SecureCheckout(handleCheckoutComplete, handleCheckoutError, handleCheckoutCancelled, handleCheckoutLoaded);
        var donor = data.Donor;
		var selectedCountry=$("#country :selected").attr("iso");
		var selectedState=$("#state :selected").attr("iso");
		
		if(selectedCountry && selectedCountry=="GB")
		{
			selectedCountry="UK";
		}
        donationData = {
            "key": publicKey,
            'Amount': ($("#recMonthly").prop("checked")) ? installmentAmt : getDonationAmount(),
            'UseCaptcha': EditorContent.RecaptchRequired,
            'BillingAddressCity': donor.Address.City,
            'BillingAddressCountry': selectedCountry,
            'BillingAddressLine': donor.Address.StreetAddress,
            'BillingAddressPostCode': donor.Address.PostalCode,
            'BillingAddressState': selectedState,
            'BillingAddressEmail': donor.EmailAddress,
            'BillingAddressFirstName': donor.FirstName + " " +donor.MiddleName,
            'BillingAddressLastName': donor.LastName,
            'Cardholder': donor.FirstName + " " + donor.LastName,
            'ClientAppName': 'BBIS',
            'MerchantAccountId': EditorContent.MerchantAccountID,
            'IsEmailRequired': true,
            'PrimaryColor': EditorContent.PrimaryFontColor,
            'SecondaryColor': EditorContent.SecondaryFontColor,
            'FontFamily': EditorContent.FontType,
            'IsNameVisible': true,
          'UseVisaCheckout': EditorContent.UseVisaPass && (data.Gift && !data.Gift.Recurrence),
          'UseMasterpass': EditorContent.UseMasterPass && (data.Gift && !data.Gift.Recurrence),
          'UseApplePay': EditorContent.UseApplePay && (data.Gift && !data.Gift.Recurrence)
        };
       if (data.Gift && data.Gift.Recurrence )
		{
			donationData.CardToken = EditorContent.DataKey;
		}

        //check server date and start date here -- if same then make transaction today
        if (data.Gift && data.Gift.Recurrence && !data.Gift.Recurrence.ProcessNow) {
            return checkout.processStoredCard(donationData);
        }
        else {

            return checkout.processCardNotPresent(donationData);
        }
    }

	//to check for recurring gift that is to be processed today or not (this is check for call stored card payment api)
    function isProcessNow() {
        var recStartDate = $("#start-date").val()
        var frequency = $("#frequency").val();
        var dayOfMonth = $('#day-of-month').val();
        var dayOfWeek = $("#day-of-week").val();
        var month = $('#month').val();

        var startDateIsTodayDate = false;

        var recurrrentStartDate = new Date(recStartDate);

        var isProcessedNow = false;

        var serverDate = new Date(ServerDate);


        if (
            recurrrentStartDate.getFullYear() === serverDate.getFullYear() &&
            recurrrentStartDate.getMonth() === serverDate.getMonth() &&
            recurrrentStartDate.getDate() === serverDate.getDate()
        ) {
            startDateIsTodayDate = true;
        }
        else {

            return false;
        }

        //Weekly Frequency
        if (frequency == 1) {
            isProcessedNow = startDateIsTodayDate && dayOfWeek == serverDate.getDay();
        }
        //Mothly and Quarterly frequency
        else if (frequency == 2 || frequency == 3) {
            isProcessedNow = startDateIsTodayDate && dayOfMonth == serverDate.getDate();
        }
        //Annually frequency
        else if (frequency == 4) {

            isProcessedNow =
                startDateIsTodayDate
                && dayOfMonth == serverDate.getDate()
                && month == serverDate.getMonth() + 1;
        }
        //Every 4 weeks
        else if (frequency == 7) {
            isProcessedNow = startDateIsTodayDate;
        }
        else {
            isProcessedNow = false;
        }

        return isProcessedNow;


    };

	//when checkout popup is successfully loaded
    handleDonationCreated = function (data) {
        var orderID = JSON.parse(data.Data).OrderId;
    }

	//when checkout popup is fail to load
    this.handleDonationCreateFailed = function (error) {
        handleError(error);
    }

	//when the payment is successfully completed and we have to show the confirnmation screen
    this.handlePaymentComplete = function (data) {
        $("#bbspLoadingOverlay").hide();
        //confirmation message show here
		//donationform
        $(".form").hide();
		//confirmation div
        $(".confirmation").show();

       $(".confirmation").html(JSON.parse(data.Data).confirmationHTML);
    }

	//this function called when the checkout popup is loaded on a page
    function handleCheckoutLoaded() {

        if (!opened) {

            opened = true;
            var url = $("#bbCheckoutPaymentIframe").prop('src');
            var tid = getUrlVars(url)["t"];

            //save transaction id in global variable. Will be used throughout the transaction
            this.transactionIDl = tid;

            if (tid) {
                data.TokenId = tid;
                ds.checkoutDonationCreate(data, handleDonationCreated, handleDonationCreateFailed);
                return false;
            }
        }

        return false;
    }

	//when we cancel the payment pop up then unbind all the binded events on checkout popup
    function UnBindPaymentCheckoutEvents() {
        $(document).unbind("checkoutComplete");
        $(document).unbind("checkoutLoaded");
        $(document).unbind("checkoutError");
        $(document).unbind("checkoutCancel");
    }

	//this is called when the payment is completed
    function handleCheckoutComplete(event, tranToken) {
        $("#bbspLoadingOverlay").show();

		var Id=tranToken ? tranToken :(event?(event.detail?(event.detail.transactionToken?event.detail.transactionToken:null):null):null);
		
        if (Id) {
            data.TokenId = Id;
            ds.checkoutDonationComplete(data, handlePaymentComplete, handleDonationCreateFailed);
        }
        else {
            handleError();
        }
		UnBindPaymentCheckoutEvents();
        return false;
    }

	//call when there is any error while doing the payment on checkout pop up
    handleCheckoutError = function (event, errorMsg, errorCode) {
        handleError(errorMsg);
    }

    //Cancel Donation if user close checkout popup
    function handleCheckoutCancelled() {
        try {
            ds.checkoutDonationCancel(data, onSuccess, onFail);
        }
        catch (e) {
            //do not store this error. Already stored from server side
        }
        UnBindPaymentCheckoutEvents();
    }

	//this function call when we click on donate button
	function sendData() {
        if (EditorContent && EditorContent.MACheckoutSupported && GetPaymentType() == 0) {
            ProcessCCPayment();
        }
    }
	
	 //use this method for credit card payment through popup
    function ProcessCCPayment() {
        
        data = donation;

            onValidationSuccess = function (result) {
            makePayment();
            return false;
        };
        onValidationFailed = function (error) {
            console.log(error);
        };

        ds.validateDonationRequest(data, onValidationSuccess, onValidationFailed);

    }
	
	//Call some functions       
        GetEditorInformation($('.BBDonationApiContainer').data('partid'));
        GetPublicKey();
		
		
	// Attach our event listener to the donate button
    $('.btn-donate').click(function(e) {
      
      // Stop the button from submitting the form
      e.preventDefault(); 
	  sendData();
	  });
		
}(jQuery));
/* css other than bootstrap */
.bbspLoadingOverlay {
width: 100%;
height: 100%;
left: 0;
top: 0;
position: fixed;
z-index: 9999999;
background-color: grey;
opacity: 0.8;
display: none;
}

Pledge Installments Example

Pledge installments are the payment donor makes for a pledge according to a defiend time schedule. The example includes the HTML required to display input fields to capture required parameters for pledge installment endpoints.

<fieldset class="donationInformation">
	<legend>
		<span class="BBListingHeading DonationListingHeading">Gift Information</span>
	</legend>
	<div>
		<input type="checkbox" id="isPaymentTwo"/> Check this box if you are using a Payment 2.0 part with this ADF
		<div class="giftAmount">
			<label class="required">Select Gift Amount:</label>
			<ul>
				<li>
					<input id="amt1000" type="radio" name="radioAmount" value="1000" />
					<label for="amt1000">
						<span class="term">Platinum</span>
						<span class="value">$1,000</span>
					</label>
				</li>
				<li>
					<input id="amt500" type="radio" name="radioAmount" value="500" />
					<label for="amt500">
						<span class="term">Gold</span>
						<span class="value">$500</span>
					</label>
				</li>
				<li>
					<input id="amt100" type="radio" name="radioAmount" value="100" />
					<label for="amt100">
						<span class="term">Silver</span>
						<span class="value">$100</span>
					</label>
				</li>
				<li>
					<input id="amt25" type="radio" name="radioAmount" value="25" />
					<label for="amt25">
						<span class="term">Bronze</span>
						<span class="value">$25</span>
					</label>
				</li>
				<li class="other">
					<input id="amtOther" type="radio" name="radioAmount" value="-1" checked="checked" />
					<label for="amtOther">
						<span class="term">Enter an amount</span>
					</label>
					<input id="txtAmount" type="text" placeholder="$" class="BBFormTextbox">
				</li>
			</ul>
		</div>
	</div>
</fieldset>
        
<!-- PLEDGE INSTALLMENT START-->
<div class="pledgeInstallments">
	<label class="required">Pledge Installment:</label>
	<ul>
		<li class="other">
			<label for="numberOfInstallments">
				Number of Installments:
			</label>
			<input id="numberOfInstallments" type="text" placeholder="$" class="BBFormTextbox">
		</li>
		<li class="other">
			Installment Amount:
			<label id="installmentAmount"/>
		</li>
		<li class="other">
			Installment End Date:
			<label id="installmentEndDate" />
		</li>
	</ul>
</div>
	<!-- PLEDGE INSTALLMENT END-->
// Let's be good developers and not pollute the global namespace
(function($) {
  
  // Let's make sure the DOM is ready
  $(function() {
    
    // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );
    
    // Create the donation object we'll send
    // In order to simplify our examples, some of this information is hard-coded.
    var donation = {
      MerchantAccountId: '00000000-0000-0000-0000-000000000000',
      Gift: {
        PaymentMethod: 0,
        Designations: [
          {
		  //Amount has been hardcoded to 500. Replace the value with a value entered by user.
            Amount: 500.00,
            DesignationId: '00000000-0000-0000-0000-000000000000'
          }
        ]
      }
    };
    
    // Create our success handler
    var success = function(returnedDonation) {
      console.log(returnedDonation);
    };
    
    // Create our error handler
    var error = function(returnedErrors) {
      console.log('Error!');
    };
    
    // Attach our event listener to the donate button
    $('.btn-donate').click(function(e) {
      
      // Stop the button from submitting the form
      e.preventDefault();
	  
      //if payment 2.0 is checked, No need to capture the donor information
       if(!isPaymentTwo){
		  donation.Donor = {
			Title: $("#title").val(),
			FirstName: $("#firstName").val(),
			LastName: $("#lastName").val(),
			EmailAddress: $("#emailAddress").val(),
			Phone: $("#phone").val(),
			Address: {
			  Country: $("#country").val(),
			  State: $("#state").val(),
			  City: $("#city").val(),
			  StreetAddress: $("#streetAddress").val(),
			  PostalCode: $("#postalCode").val()
			},
			OrganizationName: organizationName
		  };
	  }
	  
	   // PLEDGE INSTALLMENT BEGIN ********************************************************************************************************************************************************************************************************************************************************
	  var numberOfInstallments = $('#numberOfInstallments').val();
	  if (numberOfInstallments) {
	      //Amount has been hardcoded to 500. Replace the value with a value entered by user.
		  var installmentAmount = ds.getRecurringGiftInstallmentAmount(500, numberOfInstallments);
		  donation.Gift.PledgeInstallment = {
			  NumberOfInstallments: numberOfInstallments,
			  InstallmentAmount: installmentAmount
		  }
	  }
      // PLEDGE INSTALLMENT END ********************************************************************************************************************************************************************************************************************************************************
        
      // Submit our donation
      ds.createDonation(donation, success, error);
    });
    
  });
}(jQuery));

Displaying Available Countries and States

Using the Country and State endpoints, you can quickly populate the available countries and their corresponding states. The first example uses jQuery to make an AJAX request. We also wrap this functionality in the Country and State JavaScript Service, which is shown in the second example.

<dl>
  <dt>Country</dt>
  <dd><select id="country"></select></dd>
  
  <dt>State</dt>
  <dd><select id="state"></select></dd>
</dl>
// Let's be good developers and not pollute the global namespace
(function($) {

// Let's make sure the DOM is ready
$(function() {

  var selectCountry = $('#country');
  var selectState = $('#state');
  
  // Load Countries
  $.get(BLACKBAUD.api.pageInformation.rootPath + '/webapi/country', function(countries) {
    for (var i = 0, j = countries.length; i < j; i++) {
      selectCountry.append('<option value="' + countries[i].Id + '" iso="'+countries[i].ISO+'">' + countries[i].Description + '</option>');
    }
  });
  
  // Watch Country Change
  $('#country').on('change', function() {
  
    // Load States
    $.get(BLACKBAUD.api.pageInformation.rootPath + '/webapi/country/' + $(this).val() + '/state', function(states) {
      selectState.html('');
      for (var i = 0, j = states.length; i < j; i++) {
        selectState.append('<option value="' + states[i].Id + '" iso="'+states[i].ISO+'">' + states[i].Description + '</option>');
      }
    });
  });

});
}(jQuery));

The following example uses the Country and State JavaScript Service instead of making an AJAX call directly to the endpoints.

<dl>
  <dt>Country</dt>
  <dd><select id="country"></select></dd>
  
  <dt>State</dt>
  <dd><select id="state"></select></dd>
</dl>
// Let's be good developers and not pollute the global namespace
(function($) {

// Let's make sure the DOM is ready
$(function() {

  var selectCountry = $('#country');
  var selectState = $('#state');
  var service = new BLACKBAUD.api.CountryService();
  
  // Load Countries
  service.getCountries(function(countries) {
    for (var i = 0, j = countries.length; i < j; i++) {
      selectCountry.append('<option value="' + countries[i].Id + '" iso="'+countries[i].ISO+'">' + countries[i].Description + '</option>');
    }
  });
  
  // Watch Countries Change
  $('.countries').on('change', function() {
  
    // Load States
    service.getStates($(this).val(), function(states) {
      selectState.html('');
      for (var i = 0, j = states.length; i < j; i++) {
        selectState.append('<option value="' + states[i].Id + '" iso="'+states[i].ISO+'">' + states[i].Description + '</option>');
      }
    });
  });

});
}(jQuery));

Displaying Available Designation(s)

Using this example, you can display multiple designations on your ADF form. Create a Designation Type Ad-Hoc query With Enable query for CMS REST API in CRM and provide its ID in the ADF JS. Resultant Designations would be available for selection in the form of a dropdown on your ADF.

<dl>
  <dt>Designation</dt>
  <dd><select id="designation"></select></dd>
</dl>
// Let's be good developers and not pollute the global namespace
(function($) {

// Let's make sure the DOM is ready
$(function() {

  var designationQueryId = "00000000-0000-0000-0000-000000000000";  /* Ad-hoc Query of Designation Type With Enable query for CMS REST API */
  var service = new BLACKBAUD.api.QueryService();
  
  // Load Designation(s)
  service.getResults(designationQueryId, function (d) {
		var rows = d.Rows;
		$.each(rows, function () {
			var values = this['Values'];
			$("#designation").append($("<option></option>").val(values[0]).text(values[1]));
		});
	}, null, [statusFilter]);   
  });

});
}(jQuery));

Recurrence Example

In this example, we're back to "proceeding directly to payment," as opposed to using the Payment 2.0 Part. This means we'll need to collect the donor information.

Using recurrence with the Advanced Donation Form can be a little tricky, in that the fields which are required, differs depending on the frequency of the recurrence. For example, the Month field is only valid and required if the Frequency field is set to Annually (4).

<h3>Donor Information</h3>
<dl>
  <dt>First Name</dt>
  <dd><input type="text" id="first-name" /></dd>
  
  <dt>Last Name</dt>
  <dd><input type="text" id="last-name" /></dd>
  
  <dt>Email</dt>
  <dd><input type="text" id="email" /></dd>
  
  <dt>Address</dt>
  <dd><textarea id="address"></textarea></dd>
  
  <dt>City</dt>
  <dd><input type="text" id="city" /></dd>
  
  <dt>State</dt>
  <dd><input type="text" id="state" /></dd>
  
  <dt>Zip</dt>
  <dd><input type="text" id="zip" /></dd>
  
  <dt>Country</dt>
  <dd><input type="text" id="country" /></dd>
</dl>

<h2>Recurrence</h2>
<dl>
  <dt>Frequency</dt>
  <dd>
    <select id="frequency">
      <option value="1">Weekly</option>
      <option value="2">Monthly</option>
      <option value="3">Quarterly</option>
      <option value="4">Annually</option>
	  <option value="7">Every 4 weeks</option>
    </select>
  </dd>
  
  <dt>Start Date</dt>
  <dd><input type="text" id="start-date" /></dd>
  
  <dt>Day of Week</dt>
  <dd>
    <select id="day-of-week">
      <option value="0">Sunday</option>
      <option value="1">Monday</option>
      <option value="2">Tuesday</option>
      <option value="3">Wednesday</option>
      <option value="4">Thursday</option>
      <option value="5">Friday</option>
      <option value="6">Saturday</option>
    </select>
  </dd>
  
  <dt>Day of Month</dt>
  <dd>
    <select id="day-of-month">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
      <option>7</option>
      <option>8</option>
      <option>9</option>
      <option>10</option>
      <option>11</option>
      <option>12</option>
      <option>13</option>
      <option>14</option>
      <option>15</option>
      <option>16</option>
      <option>17</option>
      <option>18</option>
      <option>19</option>
      <option>20</option>
      <option>21</option>
      <option>22</option>
      <option>23</option>
      <option>24</option>
      <option>25</option>
      <option>26</option>
      <option>27</option>
      <option>28</option>
      <option>29</option>
      <option>30</option>
      <option>31</option>
    </select>
  </dd>
</dl>

<p><button class="btn-donate">Donate</button></p>
// Let's be good developers and not pollute the global namespace
(function($) {
  
  // Let's make sure the DOM is ready
  $(function() {
    
    // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );
    
    // Create the donation object we'll send
    // In order to simplify our examples, some of this information is hard-coded.
    var donation = {
      MerchantAccountId: '00000000-0000-0000-0000-000000000000',
      Gift: {
        PaymentMethod: 0,
        Designations: [
          {
            Amount: 5.00,
            DesignationId: '00000000-0000-0000-0000-000000000000'
          }
        ]
      }
    };
    
    // Create our success handler
    var success = function(returnedDonation) {
      console.log(returnedDonation);
    };
    
    // Create our error handler
    var error = function(returnedErrors) {
      console.log('Error!');
    };
    
    // Attach our event listener to the donate button
    $('.btn-donate').click(function(e) {
      
      // Stop the button from submitting the form
      e.preventDefault(); 
      
      // Add the information our user has typed
      donation.Donor = {
        FirstName: $('#first-name').val(),
        LastName: $('#last-name').val(),
        Address: {
          StreetAddress: $('#address').val(),
          City: $('#city').val(),
          State: $('#state').val(),
          PostalCode: $('#zip').val(),
          Country: $('#country').val()
        }
      };
      
      // The following fields are always required
      donation.Gift.Recurrence = {
        Frequency: $('#frequency').val(),
        StartDate: $('#start-date').val()
      };
      
      // The remaining required values are different depending on what frequency the user selects
      var frequency = $('#frequency').val();
      switch (frequency) {
        case 1:
          donation.Gift.Recurrence.DayOfWeek = $('#day-of-week').val();
        break;
        case 2:
        case 3:
          donation.Gift.Recurrence.DayOfMonth = $('#day-of-month').val();
          // Purposefully letting selection fall through (no "break")
        case 4:
          donation.Gift.Recurrence.Month = $('#month').val();
        break;
		case 7:
		 donation.Gift.Recurrence.DayOfMonth=0;
		 donation.Gift.Recurrence.Month=0;
		 //Purposefully assigning DayOfWeek is -1 beacuse 0 is defined for Sunday.
		 donation.Gift.Recurrence.DayOfWeek =-1;
		break;
      };
        
      // Submit our donation
      ds.createDonation(donation, success, error);
    });
    
  });
}(jQuery));

Tribute Example

In this example, we're back to "proceeding directly to payment," as opposed to using the Payment 2.0 Part. This means we'll need to collect the donor information. I've also introduced the ability to add a tribute.

<h3>Donor Information</h3>
<dl>
  <dt>First Name</dt>
  <dd><input type="text" id="first-name" /></dd>
  
  <dt>Last Name</dt>
  <dd><input type="text" id="last-name" /></dd>
  
  <dt>Email</dt>
  <dd><input type="text" id="email" /></dd>
  
  <dt>Address</dt>
  <dd><textarea id="address"></textarea></dd>
  
  <dt>City</dt>
  <dd><input type="text" id="city" /></dd>
  
  <dt>State</dt>
  <dd><input type="text" id="state" /></dd>
  
  <dt>Zip</dt>
  <dd><input type="text" id="zip" /></dd>
  
  <dt>Country</dt>
  <dd><input type="text" id="country" /></dd>
</dl>

<h3>Tribute Information</h3>
<dl>
  <dt>First Name</dt>
  <dd><input type="text" id="tribute-first-name" /></dd>
  
  <dt>Last Name</dt>
  <dd><input type="text" id="tribute-last-name" /></dd>
  
  <dt>Description</dt>
  <dd><textarea id="tribute-description"></textarea></dd>
</dl>
      
<h3>Acknowledgee Information</h3>
<dl>
  <dt>First Name</dt>
  <dd><input type="text" id="acknowledgee-first-name" /></dd>
  
  <dt>Last Name</dt>
  <dd><input type="text" id="acknowledgee-last-name" /></dd>
  
  <dt>Email</dt>
  <dd><input type="text" id="acknowledgee-email" /></dd>
  
  <dt>Address</dt>
  <dd><textarea id="acknowledgee-address"></textarea></dd>
  
  <dt>City</dt>
  <dd><input type="text" id="acknowledgee-city" /></dd>
  
  <dt>State</dt>
  <dd><input type="text" id="acknowledgee-state" /></dd>
  
  <dt>Zip</dt>
  <dd><input type="text" id="acknowledgee-zip" /></dd>
  
  <dt>Country</dt>
  <dd><input type="text" id="acknowledgee-country" /></dd>
</dl>
      
<p><button class="btn-donate">Donate</button></p>
// Let's be good developers and not pollute the global namespace
(function($) {
  
  // Let's make sure the DOM is ready
  $(function() {
    
    // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );
    
    // Create the donation object we'll send
    // In order to simplify our examples, some of this information is hard-coded.
    var donation = {
      MerchantAccountId: '00000000-0000-0000-0000-000000000000',
      Tribute: {},
      Gift: {
        PaymentMethod: 0,
        Designations: [
          {
            Amount: 5.00,
            DesignationId: '00000000-0000-0000-0000-000000000000'
          }
        ]
      }
    };
    
    // Create our success handler
    var success = function(returnedDonation) {
      console.log(returnedDonation);
    };
    
    // Create our error handler
    var error = function(returnedErrors) {
      console.log('Error!');
    };
    
    // Attach our event listener to the donate button
    $('.btn-donate').click(function(e) {
      
      // Stop the button from submitting the form
      e.preventDefault(); 
      
      // Add the information our user has typed
      donation.Donor = {
        FirstName: $('#first-name').val(),
        LastName: $('#last-name').val(),
        Address: {
          StreetAddress: $('#address').val(),
          City: $('#city').val(),
          State: $('#state').val(),
          PostalCode: $('#zip').val(),
          Country: $('#country').val()
        }
      };

      // Add our tribute information
      // See REST api tech reference for more information on the Type field
      donation.Tribute.TributeDefintion = {
         Type: 'Tribute',
        Name: $('#tribute-first-name') + " " + $('#tribute-last-name'),     
        FirstName: $('#tribute-first-name'),
        LastName: $('#tribute-last-name'),
        Description: $('tribute-description')
      };
      
      // Add our acknowledgee information
      donation.Tribute.Acknowledgee = {
        FirstName: $('#acknowledgee-first-name').val(),
        LastName: $('#acknowledgee-last-name').val(),
        Address: {
          StreetAddress: $('#acknowledgee-address').val(),
          City: $('#acknowledgee-city').val(),
          State: $('#acknowledgee-state').val(),
          PostalCode: $('#acknowledgee-zip').val(),
          Country: $('#acknowledgee-country').val()
        }
      };
      
      // Submit our donation
      ds.createDonation(donation, success, error);
    });
    
  });
}(jQuery));


Using the Consent endpoints, you can quickly populate the available consents. This example uses jQuery to make an AJAX request. We also wrap this functionality in the Consent JavaScript Service, which is shown in this example.



Direct Debit Example

This feature can be used to configured the direct debit on ADF by using the payment's using the Donation endpoints.

Organizations have many donors (especially in international markets) that prefer to give gifts with Direct Debit (also known as ACH). To build parity with our current Advance Donation Form (ADF), we need to allow organizations to accept donations via direct debit on ADF. This functionality is wrapped under DirectDebit Service, as shown in the example.

<!--This div is use to show the direct debit section on a page-->
<div id="directDebitSection">
        <div class="formrow" id="tr_DDPDFInstructions">
            <div colspan="3">
                <span><i>In order to set up a Direct Debit instruction
                    online, you must be the account holder of a personal bank or building society account.
                    If you are not the only required signatory on your account or you would rather send
                    us a paper version please
                    <a ID="lnkDDPDF" title="Direct Debit PDF" href="DirectDebit.ddpdf"
                        Target="_blank" rel="noopener noreferrer">click here</a></i>
	            </span>
            </div>
        </div>
        <div class="formrow">
                <label ID="lblFinancialLBL">Financial Institution:</label>
                <input type="text" ID="txtFinancialInstitution" MaxLength="100"/>
        </div>
        <div class="formrow">
                <label ID="lblBranchName">Branch Name:</label>
                <input type="text" ID="txtBranchName" MaxLength="100"/>
        </div>
        <div class="formrow" id="tr_BankingSystemType">
                <label ID="lblBankingSystemType">Banking System Type:</label>
                <select ID="ddlBankingSystemType"></select>
        </div>
        <div class="formrow">
                <label ID="lblRoutNumLBL">Routing Number:</label>
                <input type="text" ID="txtRoutingNumber" MaxLength="9" />
               <!-- <asp:CustomValidator ID="cvRoutingNumber"  ClientValidationFunction="RoutingNumberClientValidation"  />   --> 
  
                <a ID="lnk_BankHelp" title="Display help details in another window" style="cursor:pointer;">
	<img src="images/help-32_1.gif" alt="help" title="Help" style="height:32px;width:36px;vertical-align:bottom; border:0;" />
                </a>
        </div>
        <div class="formrow" id="tr_CanadaTransitNum">
                <label ID="lblCanadaTransitNum">Transit Number:</label>
                <input type="text" ID="txtCanTransitNumber" MaxLength="5"/>
        </div>
        <div class="formrow">
                <label ID="lblAccountNumber">Account Number:</label>
                <span id="spn_AccountNo">
                    <input type="text" ID="txtAccountNumber" MaxLength="20"/>
                </span>
                <span id="spn_AccountNoNZ">
                    <input type="text" ID="txtAccountNumberNZ" Width="30" MaxLength="7"/>
					<span>-</span>
                    <input type="text" ID="txtSuffixNZ" Width="20" MaxLength="3" />
                    <label ID="lblSuffixNZ" Visible="false"></label>
                </span>
                    </div>
        <div class="formrow" id="tr_AccountType">
                <label ID="lblAccountType">Account Type:</label>
                <select ID="ddlAccountType"></select>
        
        </div>
        <div class="formrow">
                <label ID="lblAccountHolderName">Account Holder's Name:</label>
                <input type="text" ID="txtAccountHolder" MaxLength="50"/>
        </div>
        <div class="formrow" id="tr_CurrentDate" >
                <label ID="lblDebitDate">Date:</label>
                <label ID="lbl_CurrentDate"></label>
        </div>
        <div class="formrow" id="tr_OrigNumber">
                <label ID="lblOriginatorID">Service user's ID number:</label>
                <label ID="lbl_OrigNumber"></label>
        </div>
        <div id="tr_DDBankInstructions">
            <span colspan="3">
                <p>
                    <label><b>Instruction to your Bank or Building Society</b></label>
                </p>
                                   <label ID="lbl_DDBankInstructions">
<i>Please pay %1 Direct Debits from the account detailed in this Instruction subject to the safeguards assured by the Direct Debit Guarantee. I understand that this Instruction may remain with %1 and, if so, details will be passed electronically to my Bank/Building Society.</i>
					</label>						
                                
                    <label>
<i>Banks and Building Societies may not accept Direct Debit Instructions for some types of account.</i>
                    </label>
                
            </span>
        </div>
        <div id="tr_DDInstructions">
            <span colspan="3">
                <img src="images\dlogo.gif" alt="Direct Debit" title="Direct Debit" style="text-align: center;" />
                <a ID="lnk_DDGuarantee" title="Display the Direct Debit Guarantee in another window" style="cursor:pointer;color:blue;text-decoration:underline;">The Direct Debit Guarantee</a>
			</span>
        </div>
        <div id="tr_DDPDFInstructions2">
            <span colspan="2">
                <p>
                    <label>
<i>By clicking 'Donate Now' you are confirming that you are the account holder and that you are the only person required to authorise debits from this account.</i>
		</label>
                </p>
            </span>
        </div>
   </div>
// Let's be good developers and not pollute the global namespace
(function ($) {

 // Let's make sure the DOM is ready
$(function () {

  // Create an instance of the DonationService
  var ds = new BLACKBAUD.api.DonationService(
  $('.BBDonationApiContainer').data('partid'));
     
 
   //Create the donation object we'll send
  //In order to simplify our examples, some of this information is hard-coded.
  var donation = {
  MerchantAccountId: '00000000-0000-0000-0000-000000000000',
  BBSPReturnUri: window.location.href,
  BBSPTemplateSitePageId: 000,
  Gift: {
        PaymentMethod: 2,
        Designations: []
      }
  };

  // Create our success handler
  var success = function (returnedDonation) {
  console.log(returnedDonation);
  if (returnedDonation.Donation.Gift.PaymentMethod === 2) {
      window.location.href = window.location.href + "?t=" + d.Donation.Id;
  }
  };   

  // Create our error handler
  var error = function (returnedErrors) {
  console.log('Error!');
  };
  
	//Show and Hide directdebit div on the page
 function showHideDirectDebitDiv() {
   if ($("#paymentDirectDebit").prop("checked")) {
      $("#directDebitInformation").show();
      hideAndVisible_BankingTypeField();
      addCountryHandler();
     }
     else {
       $("#directDebitInformation").hide();
        }
    }

	//Call the function when we have to hide and visible the banking type field
    function hideAndVisible_BankingTypeField() {
        if ($('[id="ddlBankingSystemType"] option').length == 1) {
            $('#tr_BankingSystemType').css('display', 'none');
        } else {
            $('#tr_BankingSystemType').css('display', '');
        }
    }

	//Use to bind the banking types that is configured in CRM
    function bindDirectDebitData() {
        donationService.getBankingTypeData(function (d) {
            $.each(d, function () {
                $("#ddlBankingSystemType").append($("<option></option>").val(this["Abbreviation"]).text(this["Description"]));
            });
        });

        donationService.getAccountTypeData(function (d) {
            $.each(d, function () {
                $("#ddlAccountType").append($("<option></option>").val(this["Id"]).text(this["Description"]));
            });
        });

        donationService.getOriginIdAndTime(function (d) {
            $("#lbl_CurrentDate").text(d["Time"]);
            $("#lbl_OrigNumber").text(d["OriginId"]);
        });
    }

	//this function is used to select the banking type on the basis of country dropdown change
    function addCountryHandler() {
        var bankingSystemType = $('[id="ddlBankingSystemType"]'), addrCtl = $("[id='country'] :selected"), selectBankingOption, exists = false, bankingOptions;
        if (bankingSystemType && bankingSystemType.length > 0) {
            bankingOptions = $('[id="ddlBankingSystemType"] option');
            if (bankingOptions.length > 0) {
                if (!(bankingOptions.length === 1)) {
                    if (countryData && (validateCountry(addrCtl.val(), countryData.NZ) || validateCountry(addrCtl.val(), countryData.AUS))) {
                        selectBankingOption = "Aus_NZ";
                    }
                    else if (countryData && validateCountry(addrCtl.val(), countryData.UK)) {
                        selectBankingOption = "UK";
                    }
                    else if (countryData && validateCountry(addrCtl.val(), countryData.CAD) || validateCountry(addrCtl.val(), countryData.USA)) {
                        selectBankingOption = "USA";
                    }

                    exists = 0 !== bankingSystemType.find('option[value="' + selectBankingOption + '"]').length;
                    if (exists && exists === true) {
                        bankingSystemType.val(selectBankingOption);
                    } else {
                        bankingSystemType.val("Please Select");
                    }
                }
            }
            hideAndVisible_DirectDebitFields();
        }
    }

	//Hide and Visible direct debit fields on the basis of country dropdown and banking type dropdown change
    function hideAndVisible_DirectDebitFields() {
        var bankingType = "Please Select", htmlElement = "", routingNumberTextBoxLabel = "", selectedCountry = "", routingNumberTextBox = "", transitNumberBox = "",
            routingNumber = $('[id="txtRoutingNumber"]'),
            transitNumber = $('[id="txtCanTransitNumber"]'),
            routingNumberLabel = $('[id="lblRoutNumLBL"]'),
            addressCTL = $("[id='country'] :selected"),
            bankingSystemLabel = $('[id="lblBankingSystemType"]'),
            bankingSystemType = $('[id="ddlBankingSystemType"] :selected'),
            accountType = $('[id="tr_AccountType"],[id*="DC_AccountType"]'),
            accountNo = $('[id="spn_AccountNo"]'),
            accountNoNZ = $('[id="spn_AccountNoNZ"]'),
            financialInstitution = $('[id="lblFinancialLBL"]'),
            accountNoLabel = $('[id="lblAccountNumber"]'),
            routingNumberHelpSymbol = $('[id="lnk_BankHelp"]'),
            requiredFieldAccountType = $('[id="RequiredFieldAccountType"]'),
            ukFields = $('[id="tr_DDInstructions"], [id="tr_OrigNumber"], [id="tr_CurrentDate"], [id="tr_DDBankInstructions"], [id="tr_DDPDFInstructions"], [id="tr_DDPDFInstructions2"],[id="DC_DDInstructions"],[id="DC_OrigNumber"],[id="DC_CurrentDate"],[id="DC_DDBankInstructions"],[id="DC_DDPDFInstructions"],[id="DC_DDPDFInstructions2"]');

        if (!routingNumber || routingNumber.length <= 0) {
            return;
        }

        if (bankingSystemType && bankingSystemType.length > 0) {
            bankingType = bankingSystemType.attr("Value");
        }

        if (routingNumber && routingNumber.length > 0) {
            routingNumberTextBox = routingNumber;
        }

        if (addressCTL && addressCTL.length > 0) {
            selectedCountry = addressCTL.val();
        }

        if (routingNumberLabel && routingNumberLabel.length > 0) {
            routingNumberTextBoxLabel = routingNumberLabel;
        }

        if (transitNumber && transitNumber.length > 0) {
            transitNumberBox = transitNumber;
            $('[id="tr_CanadaTransitNum"]').css("display", "none");
        }
        accountNo.css("display", "");
        accountNoNZ.css("display", "");
        accountNoLabel.html("Account Number:");
        routingNumberHelpSymbol.css("display", "");
        if (ukFields && ukFields.length > 0) {

            ukFields.css('display', 'none');
        }

        if (countryData && validateCountry(selectedCountry, countryData.CAD) && transitNumberBox && transitNumberBox.length > 0 && bankingType === "USA") {
            routingNumberTextBoxLabel.html("Institution ID:");
            routingNumberTextBox.attr("maxlength", "4");
            routingNumberTextBox.val('');
            accountType.css("display", "none");
            accountNoNZ.css("display", "none");
            $('[id="tr_CanadaTransitNum"]').css("display", "");

        } else {
            if (bankingType !== "Please Select") {
                if (bankingType === "USA") {
                    routingNumberTextBoxLabel.html("Routing Number:");
                    routingNumberTextBox.attr("maxlength", "9");
                    routingNumberTextBox.val('');
                    accountType.css("display", "");
                    accountNoNZ.css("display", "none");
                }
                else if (bankingType === "UK") {
                    routingNumberTextBoxLabel.html("Sort Code:");
                    routingNumberTextBox.attr("maxlength", "6");
                    routingNumberTextBox.val('');
                    accountType.css("display", "none");
                    accountNoNZ.css("display", "none");
                    if (ukFields) {
                        ukFields.css('display', '');
                    }

                }
                else if (bankingType === "Europe") {
                    routingNumberTextBoxLabel.html("BIC:");
                    routingNumberTextBox.attr("maxlength", "11");
                    routingNumberTextBox.val('');
                    accountType.css("display", "");
                    accountNoNZ.css("display", "none");
                    routingNumberHelpSymbol.css("display", "none");
                }
                else if (bankingType === "Aus_NZ") {
                    routingNumberTextBoxLabel.html("BSB Number:");
                    routingNumberTextBox.attr("maxlength", "6");
                    routingNumberTextBox.val('');
                    accountType.css("display", "none");
                    accountNoNZ.css("display", "none");
                    if (countryData && validateCountry(selectedCountry, countryData.NZ)) {
                        accountNo.css("display", "none");
                        accountNoNZ.css("display", "");
                        routingNumberTextBoxLabel.html("Bank/Branch No.:");
                        accountNoLabel.html("Account No./Suffix:");
                        routingNumberTextBox.attr("maxlength", "7");
                        routingNumberTextBox.val('');
                    }
                }
                else if (bankingType === "Other") {
                    routingNumberTextBoxLabel.html("Bank Code:");
                    routingNumberTextBox.attr("maxlength", "25");
                    routingNumberTextBox.val('');
                    accountType.css("display", "");
                    accountNoNZ.css("display", "none");
                    routingNumberHelpSymbol.css("display", "none");
                }

                else {
                    routingNumberTextBoxLabel.html("Routing Number:");
                    routingNumberTextBox.attr("maxlength", "9");
                    routingNumberTextBox.val('');
                    accountType.css("display", "");
                    accountNoNZ.css("display", "none");

                }

            }
            else {
                routingNumberTextBoxLabel.html("Routing Number:");
                routingNumberTextBox.attr("maxlength", "9");
                accountType.css("display", "");
                accountNoNZ.css("display", "none");
            }
        }
    }

//this function is called when we click on help image of reoting number textbox(and it changes on the basis of banking type dropdown change)
    function donationBankHelp() {
        var sFeatures = 'WIDTH=392px,HEIGHT=400px,RESIZABLE=YES,SCROLLBARS=NO,TOOLBAR=NO,LEFT=5,TOP=20,location=No;status=No', oPopUp,
            bankingType = $('[id="ddlBankingSystemType"] :selected'), addressCTL = $("[id='country'] :selected"), selectedValue = "", selectedCountry = "", qParam = "";

        if (bankingType && bankingType.length > 0) {
            selectedValue = bankingType.attr("Value");;
        }
        if (addressCTL && addressCTL.length > 0) {
            selectedCountry = addressCTL.val();
        }


        if (countryData && validateCountry(selectedCountry, countryData.AUS) && selectedValue === 'Aus_NZ') {
            qParam = 'AUS';
        } else if (countryData && validateCountry(selectedCountry, countryData.NZ) && selectedValue === 'Aus_NZ') {
            qParam = 'NZ';
        } else if (countryData && validateCountry(selectedCountry, countryData.CAD) && selectedValue === 'USA' && $('[id="tr_CanadaTransitNum"]') && $('[id="tr_CanadaTransitNum"]').length > 0) {
            qParam = 'CAD';
        } else {
            switch (selectedValue) {
                case 'USA':
                    qParam = "USA";
                    break;
                case "Aus_NZ":
                    qParam = "AUS";
                    break;
                case "UK":
                    qParam = "UK";
                    break;
                default:
                    qParam = "USA";
                    break;
            }
        }

        oPopUp = new PopUpDialogBB('~/Admin/DonationHelp.ascx', '_blank', sFeatures, '&mode=2&displayfor=' + qParam);
        oPopUp.Show();
    }


    function dDGuarantee() {
        var sFeatures = 'WIDTH=650px,HEIGHT=415px,RESIZABLE=YES,SCROLLBARS=NO,TOOLBAR=NO,LEFT=5,TOP=20,location=No;status=No',
            oPopUp = new PopUpDialogBB('~/Admin/DonationHelp.ascx', '_blank', sFeatures, '&mode=3');
        oPopUp.Show();
    }

	//this is used to set country object with all possible value of the countries(like Abbreviation, Country Name, and Guid)
    function getCountryMappings() {

        //this is use for direct debit validations
        countryData = {};
        countryService.getCountries(function (d) {
            $.each(d, function () {
                var tmpData = {};
                tmpData.Id = this["Id"];
                tmpData.Abbreviation = this["Abbreviation"];
                tmpData.Description = this["Description"];
                switch (this["Id"].toUpperCase()) {
                    case 'D81CEF85-7569-4B2E-8F2E-F7CF998A3342':
                        countryData.USA = tmpData;
                        break;
                    case 'A2ECC209-3D20-4DDA-BC4C-7585C8E2E701':
                        countryData.UK = tmpData;
                        break;
                    case 'D9EE54CD-2183-490C-A3AD-11152B271335':
                        countryData.CAD = tmpData;
                        break;
                    case 'F189F24C-2538-46A1-8458-1E3F3967B843':
                        countryData.AUS = tmpData;
                        break;
                    case 'DA42443E-AB81-40EE-A239-91ED699C0801':
                        countryData.NZ = tmpData;
                        break;
                }

            });
        });
    }

	//for validate the country thatused to select the banking type on the basis of country dropdown change 
    function validateCountry(country, ctryData) {
        if (country.toUpperCase() === ctryData.Id.toUpperCase() || country.toUpperCase() === ctryData.Abbreviation.toUpperCase() || country.toUpperCase() === ctryData.Description.toUpperCase()) {
            return true;
        }
        return false;

    }
 
	 //Bind Direct Debit
	 
	    getCountryMappings();
        bindDirectDebitData();
		
		//Attach Listeners
		$("#recMonthly").click(function () {
        $("#directDebit").css("display", "");
        });
        $("#recOneTime").click(function () {
        $("#directDebit").css("display", "none");
        });
        $("#paymentDirectDebit").click(function () { showHideDirectDebitDiv(); })
        $("#ddlBankingSystemType").change(function () { hideAndVisible_DirectDebitFields(); })
$("#lnk_BankHelp").click(function () { donationBankHelp(); });
        $("#lnk_DDGuarantee").click(function () { dDGuarantee(); });

//Attach event listener on country change
$("#country").change(function () { addCountryHandler(); })
		
     // Attach our event listener to the donate button
   $('.btn-donate').click(function(e) {
      
      // Stop the button from submitting the form
      e.preventDefault(); 
	  
      //Payment Method(2) means direct debit and set all the properties of direct debit
        if (paymentMethod === "2" && $("#paymentDirectDebit").prop("checked")) {
            donation.Gift.DirectDebitInformation = {};
            var selectedCountry = $("#country :selected").val(), bankingType = $("#ddlBankingSystemType :selected").val();
            donation.Gift.DirectDebitInformation.FinancialInstitution = $("#txtFinancialInstitution").val();
            donation.Gift.DirectDebitInformation.BranchName = $("#txtBranchName").val();
            donation.Gift.DirectDebitInformation.AccountHolderName = $("#txtAccountHolder").val();
            donation.Gift.DirectDebitInformation.BankingType = bankingType;


            if (countryData && validateCountry(selectedCountry, countryData.CAD) && bankingType === "USA") {
                donation.Gift.DirectDebitInformation.RoutingNumber = $("#txtRoutingNumber").val();
                donation.Gift.DirectDebitInformation.TransitNumber = $("#txtCanTransitNumber").val();
            }
            else {
                donation.Gift.DirectDebitInformation.RoutingNumber = $("#txtRoutingNumber").val();
            }

            if (countryData && validateCountry(selectedCountry, countryData.NZ) && bankingType === "Aus_NZ") {
                donation.Gift.DirectDebitInformation.AccountNumber = $("#txtAccountNumberNZ").val();
                donation.Gift.DirectDebitInformation.SuffixNo = $("#txtSuffixNZ").val();
            }
            else {
                donation.Gift.DirectDebitInformation.AccountNumber = $("#txtAccountNumber").val();
            }

            if (bankingType === "Europe" || bankingType === "Other" || countryData && (!validateCountry(selectedCountry, countryData.CAD) && bankingType === "USA")) {
                donation.Gift.DirectDebitInformation.AccountType = $("#ddlAccountType :selected").val();
            }
            else {
                donation.Gift.DirectDebitInformation.AccountType = "";
            }

        }

     // Submitting the donation
     ds.createDonation(donation, success, error);
     }); 

  });
 }(jQuery));

Using Blackbaud Secure Payments

Integration with the Blackbaud Secure Payments service has been updated in the Advanced Donation Form.

<dl>
  <dt>First Name</dt>
  <dd><input type="text" id="first-name" /></dd>

  <dt>Last Name</dt>
  <dd><input type="text" id="last-name" /></dd>

  <dt>Email</dt>
  <dd><input type="text" id="email" /></dd>

  <dt>Address</dt>
  <dd><textarea id="address"></textarea></dd>

  <dt>City</dt>
  <dd><input type="text" id="city" /></dd>

  <dt>State</dt>
  <dd><input type="text" id="state" /></dd>

  <dt>Zip</dt>
  <dd><input type="text" id="zip" /></dd>

  <dt>Country</dt>
  <dd><input type="text" id="country" /></dd>
</dl>

<p><button class="btn-donate">Donate</button></p>
// Let's be good developers and not pollute the global namespace
(function($) {

// Let's make sure the DOM is ready
$(function() {

  // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );

  // Create the donation object we'll send
  // In order to simplify our examples, some of this information is hard-coded.
  var donation = {
    MerchantAccountId: '00000000-0000-0000-0000-000000000000',
    BBSPReturnUri: window.location.href,
    BBSPTemplateSitePageId: 000,
    Gift: {
      PaymentMethod: 0,
      Designations: [
        {
          Amount: 5.00,
          DesignationId: '00000000-0000-0000-0000-000000000000'
        }
      ]
    }
  };

  // Create our success handler
  var success = function(returnedDonation) {
    console.log(returnedDonation);
  };

  // Create our error handler
  var error = function(returnedErrors) {
    console.log('Error!');
  };

  // Attach our event listener to the donate button
  $('.btn-donate').click(function(e) {

    // Stop the button from submitting the form
    e.preventDefault(); 

    // Add the information our user has typed
    donation.Donor = {
      FirstName: $('#first-name').val(),
      LastName: $('#last-name').val(),
      Address: {
        StreetAddress: $('#address').val(),
        City: $('#city').val(),
        State: $('#state').val(),
        PostalCode: $('#zip').val(),
        Country: $('#country').val()
      }
    };

    // Submit our donation
    ds.createDonation(donation, success, error);
  });

});
}(jQuery));
// Let's be good developers and not pollute the global namespace
(function($) {

// Let's make sure the DOM is ready
$(function() {

  // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );

  // Create the donation object we'll send
  // In order to simplify our examples, some of this information is hard-coded.
  var donation = {
    MerchantAccountId: '00000000-0000-0000-0000-000000000000',
    BBSPReturnUri: window.location.href,
    BBSPTemplateSitePageId: 000,
    Gift: {
      PaymentMethod: 0,
      Designations: [
        {
          Amount: 5.00,
          DesignationId: '00000000-0000-0000-0000-000000000000'
        }
      ]
    }
  };

  // Create our success handler
  var success = function(returnedDonation) {
    console.log(returnedDonation);
  };

  // Create our error handler
  var error = function(returnedErrors) {
    console.log('Error!');
  };
  
  
  
  //set the public key by using public key service that is used to open the checkout pop up
    function GetPublicKey() {
    
    onPublicKeySuccess = function (reply) {
        publicKey = JSON.parse(reply.Data).PublicKey;
    };
   
	ds.getCheckoutPublicKey(onPublicKeySuccess, error);
	return publicKey;
    }
  
  
    //this is the function that calls the payment api to open the checkout pop up with all the parameters
    this.makePayment = function () {
        var donor = donation.Donor;
        bbcheckout.Configuration.Data.Amount = "5.00";
        bbcheckout.Configuration.Data.BillingAddressCity = donor.Address.City;
        bbcheckout.Configuration.Data.BillingAddressCountry = donor.Address.Country;
        bbcheckout.Configuration.Data.BillingAddressLine = donor.Address.StreetAddress;
        bbcheckout.Configuration.Data.BillingAddressPostCode = donor.Address.PostalCode;
        bbcheckout.Configuration.Data.BillingAddressState = donor.Address.State;
        bbcheckout.Configuration.Data.BillingAddressEmail = donor.EmailAddress;
        bbcheckout.Configuration.Data.BillingAddressFirstName = donor.FirstName + " " + (donor.MiddleName ? donor.MiddleName:"");
        bbcheckout.Configuration.Data.BillingAddressLastName = donor.LastName;
        bbcheckout.Configuration.Data.Cardholder = donor.FirstName + " " + donor.LastName;
        bbcheckout.Configuration.Data.UseVisaCheckout = (data.Gift && !data.Gift.Recurrence);
        bbcheckout.Configuration.Data.UseMasterpass = (data.Gift && !data.Gift.Recurrence);
        bbcheckout.Configuration.Data.UseApplePay = (data.Gift && !data.Gift.Recurrence);
		bbcheckout.Configuration.TransactionType = bbcheckout.TransactionType.Card_Not_Present;
        bbcheckout.Configuration.Data.CardToken = null;
		
        if (data.Gift && data.Gift.Recurrence && !data.Gift.Recurrence.ProcessNow) {
            bbcheckout.Configuration.Data.CardToken = CheckoutModel.DataKey;
            bbcheckout.Configuration.TransactionType = bbcheckout.TransactionType.Store_Card; //Store card transactions
        }
		else if (data.Gift && data.Gift.Recurrence ) {      //Set CardToken value only in case of recurring gifts.
            bbcheckout.Configuration.Data.CardToken = CheckoutModel.DataKey;
        }

        //Set Donor Info so that it will be passed to finish the transaction at the end.
		data.DonationSource = bbcheckout.Configuration.DonationSource.ADF;
		data.Type=bbcheckout.Configuration.TranType.Donation;
        bbcheckout.DonorInfo = data;
        bbcheckout.openCheckout();
        }
  
  function InitializeBBCheckout() 
   {
	   
	   bbcheckout = new BBCheckoutProcessor(checkoutFunctions(),CheckoutModel.APIControllerName,CheckoutModel.TokenId,'[class*="donationForm"]');
	   bbcheckout.Configuration.Data.Key = CheckoutModel.PublicKey;
       bbcheckout.Configuration.TransactionType = CheckoutModel.TransactionType;
       bbcheckout.Configuration.Data.ClientAppName = CheckoutModel.ClientAppName;        
       bbcheckout.Configuration.Data.MerchantAccountId = CheckoutModel.MerchantAccountId;
       bbcheckout.Configuration.Data.IsEmailRequired = CheckoutModel.IsEmailRequired;
       bbcheckout.Configuration.Data.IsNameVisible = CheckoutModel.IsNameVisible;
       bbcheckout.Configuration.Data.PrimaryColor = CheckoutModel.PrimaryColor;
       bbcheckout.Configuration.Data.SecondaryColor = CheckoutModel.SecondaryColor;
       bbcheckout.Configuration.Data.FontFamily = CheckoutModel.FontFamily;
       bbcheckout.Configuration.Data.UseCaptcha = CheckoutModel.UseCaptcha;
       bbcheckout.Configuration.WorkflowType = CheckoutModel.WorkFlowType;
       bbcheckout.Configuration.HandleBrowserClosing = (CheckoutModel.HandleBrowserClosing === true ? "True" : "False");
       bbcheckout.Configuration.APITokenID = CheckoutModel.TokenId;
	   // You can add your own message to display on screen, after checkout pop-up close
       bbcheckout.Configuration.TempConfirmationHtml = "Thank you for your contribution, please wait while we process your transaction.";
       bbcheckout.intializeCheckout();
   }

function checkoutFunctions()
   {
	//  If you don't have anything to do then you don't add any events from below mentioned checkoutEvents 
	checkoutEvents={
	checkoutComplete : function (e) {
        //Place any code if you want to do anything on checkout complete.
       

        bbcheckout.postCheckoutFinish();
    },

    checkoutError : function (data) {
        //Place any code if you want to do anything on error.
    },

    checkoutExpired : function () {
        //Place any code if you want to do anything on Checkout expired.
    },

    checkoutReady : function () {
        //Place any code if you want to do anything on Checkout Ready.
    },

    browserClose : function () {
        //Place any code if you want to do anything on Checkout Browser closing.

    },

    checkoutCancel : function () {
        //Place any code if you want to do anything on Checkout cancel.
    },

    checkoutLoaded : function () {
        //Place any code if you want to do anything on Checkout loaded.
    }

		  
	  }

return checkoutEvents;	  
   }

	function getUrlVars(url) {
      var vars = [], hash;
      var hashes = url.slice(url.indexOf('?') + 1).split('&');
      for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
        return vars;
    }
  
    
	 //use this method for credit card payment through popup
    function ProcessCCPayment() {
        
            onValidationSuccess = function (result) {
           
			makePayment();
            return false;
        };
        onValidationFailed = function (error) {
            console.log(error);
        };

        ds.validateDonationRequest(donation, onValidationSuccess, onValidationFailed);

    }

  // Attach our event listener to the donate button
  $('.btn-donate').click(function(e) {

    // Stop the button from submitting the form
    e.preventDefault(); 

    // Add the information our user has typed
    donation.Donor = {
      FirstName: $('#first-name').val(),
      LastName: $('#last-name').val(),
      Address: {
        StreetAddress: $('#address').val(),
        City: $('#city').val(),
        State: $('#state').val(),
        PostalCode: $('#zip').val(),
        Country: $('#country').val()
      }
    };

    // Send the donation
	ProcessCCPayment()
  });

});
}(jQuery));
// This example will continue to work with Service Pack 25 release, however, it will not utilize the transaction workflow optimization code included as part of that release. Please refer to Checkout JS(New) for updated sample that incorporates the optimized Blackbaud Checkout Code.
  
// Let's be good developers and not pollute the global namespace
(function($) {

// Let's make sure the DOM is ready
$(function() {

  // Create an instance of the DonationService
    var ds = new BLACKBAUD.api.DonationService(
      $('.BBDonationApiContainer').data('partid')
    );

  // Create the donation object we'll send
  // In order to simplify our examples, some of this information is hard-coded.
  var donation = {
    MerchantAccountId: '00000000-0000-0000-0000-000000000000',
    BBSPReturnUri: window.location.href,
    BBSPTemplateSitePageId: 000,
    Gift: {
      PaymentMethod: 0,
      Designations: [
        {
          Amount: 5.00,
          DesignationId: '00000000-0000-0000-0000-000000000000'
        }
      ]
    }
  };

  // Create our success handler
  var success = function(returnedDonation) {
    console.log(returnedDonation);
  };

  // Create our error handler
  var error = function(returnedErrors) {
    console.log('Error!');
  };
  
  
  
  //set the public key by using public key service that is used to open the checkout pop up
    function GetPublicKey() {
    
    onPublicKeySuccess = function (reply) {
        publicKey = JSON.parse(reply.Data).PublicKey;
    };
   
	ds.getCheckoutPublicKey(onPublicKeySuccess, error);
	return publicKey;
    }
  
  
  //this is the function that calls the payment api to open the checkout pop up with all the parameters
    this.makePayment = function () {
        opened = false;
        var donor=donation.Donor;
        var checkout = new SecureCheckout(handleCheckoutComplete, handleCheckoutError, handleCheckoutCancelled, handleCheckoutLoaded);
        donationData = {
            "key": GetPublicKey(),
            'Amount': "5.00",
            'UseCaptcha': true,
            'BillingAddressCity': donor.Address.City,
            'BillingAddressCountry': donor.Address.Country,
            'BillingAddressLine': donor.Address.StreetAddress,
            'BillingAddressPostCode': donor.Address.PostalCode,
            'BillingAddressState': donor.Address.State,
            'BillingAddressEmail': donor.EmailAddress,
            'BillingAddressFirstName': donor.FirstName,
            'BillingAddressLastName': donor.LastName,
            'Cardholder': donor.FirstName + " " + donor.LastName,
            'ClientAppName': 'BBIS',
            'MerchantAccountId': donation.MerchantAccountId,
            'IsEmailRequired': true,
            'PrimaryColor': true,
            'SecondaryColor': true,
            'FontFamily': true,
            'IsNameVisible': true,
          'UseVisaCheckout':true,
          'UseMasterpass': true,
          'UseApplePay': true
        };

            return checkout.processCardNotPresent(donationData);
        }
  
  //when checkout popup is successfully loaded
    handleDonationCreated = function (data) {
        var orderID = JSON.parse(data.Data).OrderId;
    }


	function getUrlVars(url) {
      var vars = [], hash;
      var hashes = url.slice(url.indexOf('?') + 1).split('&');
      for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
        return vars;
    }
  
  //this function called when the checkout popup is loaded on a page
    function handleCheckoutLoaded() {

        if (!opened) {

            opened = true;
            var url = $("#bbCheckoutPaymentIframe").prop('src');
            var tid = getUrlVars(url)["t"];

            //save transaction id in global variable. Will be used throughout the transaction
            this.transactionIDl = tid;

            if (tid) {
                donation.TokenId = tid;
                ds.checkoutDonationCreate(donation, handleDonationCreated, error);
                return false;
            }
        }

        return false;
    }

	//when we cancel the payment pop up then unbind all the binded events on checkout popup
    function UnBindPaymentCheckoutEvents() {
        $(document).unbind("checkoutComplete");
        $(document).unbind("checkoutLoaded");
        $(document).unbind("checkoutError");
        $(document).unbind("checkoutCancel");
    }

	//this is called when the payment is completed
    function handleCheckoutComplete(event, tranToken) {
        var Id=tranToken ? tranToken :(event?(event.detail?(event.detail.transactionToken?event.detail.transactionToken:null):null):null);
		
        if (Id) { 
            donation.TokenId = Id;
            ds.checkoutDonationComplete(donation, success, error);
        }
        else {
           console.log(error);
        }
		UnBindPaymentCheckoutEvents();
        return false;
    }

	//call when there is any error while doing the payment on checkout pop up
    handleCheckoutError = function (event, errorMsg, errorCode) {
        console.log(error);
    }

    //Cancel Donation if user close checkout popup
    function handleCheckoutCancelled() {
        try {
            ds.checkoutDonationCancel(donation, success, error);
        }
        catch (e) {
            //do not store this error. Already stored from server side
        }
        UnBindPaymentCheckoutEvents();
    }
  
  
	 //use this method for credit card payment through popup
    function ProcessCCPayment() {
        
            onValidationSuccess = function (result) {
            makePayment();
            return false;
        };
        onValidationFailed = function (error) {
            console.log(error);
        };

        ds.validateDonationRequest(donation, onValidationSuccess, onValidationFailed);

    }

  // Attach our event listener to the donate button
  $('.btn-donate').click(function(e) {

    // Stop the button from submitting the form
    e.preventDefault(); 

    // Add the information our user has typed
    donation.Donor = {
      FirstName: $('#first-name').val(),
      LastName: $('#last-name').val(),
      Address: {
        StreetAddress: $('#address').val(),
        City: $('#city').val(),
        State: $('#state').val(),
        PostalCode: $('#zip').val(),
        Country: $('#country').val()
      }
    };

    // Send the donation
	ProcessCCPayment()
  });

});
}(jQuery));


ADF - Complete Example(New)

This example takes advantage of the transaction workflow optimization code included with our Service Pack 25 release.

All our other examples available on the Developer Site are designed to be inserted into an Advanced Donation Form Part; however the following example is designed as a complete standalone solution – applicable even on a different server than the one serving your BBIS website.

Please note you will need to update the references in the example below to your BBIS installation.

  1. The following ADF JS is only valid for BBSP, Checkout pop-up and IATS. This is not applicable for Payment 2.0.
  2. If you change the ID of any HTML control, then you will need to update/change all instances of that ID in both HTML and JS.
  3. Ensure you are using all the validations and If conditions and pass all the values in the same format as mentioned in the sample.
  4. Changing the visual appearance of page : Modify the default CSS Class written under the CSS tab as per your own requirements.
  5. Configuring Designation : Change the value of variable - designationQueryId="" :
    1. Use of this variable to display All Available Designation(s) on UI.
    2. In the PART CONFIGURATION SECTION, Change the value of the variable - designationQueryId="". This value can be found using SQL against your application Database by executing query (Select * from ADHOCQUERY Where NAME = '{your respective CRM application Ad-hoc Query Name of Designation Record Type}') on table. In this table you can copy the ID column value.
  6. Add/Remove Feature Section : In this example we have two types of feature section. The first being the HTML tab, used for Controls available on Page UI. Secondly, the JAVASCRIPT tab, used for handling functionality of these HTML Controls.
    1. For adding Recurring Gift capability, add the HTML content between "RECURRING GIFT - SECTION START AND RECURRING GIFT - SECTION END" under HTML tab. Also add JAVASCRIPT between "RECURRENCE FUNCTIONS - SECTION START AND RECURRENCE FUNCTIONS - SECTION END" under JAVASCRIPT tab.
    2. For adding Gift Amount, choose HTML DESIGN between "GIFT AMOUNT - SECTION START AND GIFT AMOUNT - SECTION END" under HTML tab. Also add JAVASCRIPT between "RECURRENCE FUNCTIONS - SECTION START AND RECURRENCE FUNCTIONS - SECTION END" under JAVASCRIPT tab.
    3. For adding Consent capability, choose HTML DESIGN between "CONSENT - SECTION START AND CONSENT - SECTION END" under HTML tab. Also add JAVASCRIPT between "CONSENT VALIDATION FUNCTIONS - SECTION START AND CONSENT VALIDATION FUNCTIONS - SECTION END" under JAVASCRIPT tab.
<!DOCTYPE html>
<html lang="en">
<head>
  
  <title>ADF - Complete Example(New)</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    
  <script type="text/javascript">

        /*------------------------------------------- PART CONFIGURATION - SECTION START -------------------------------------------*/

        var designationQueryId = "8d9fccdf-dea8-4590-8ec2-355a4c59df04";  /* Ad-hoc Query of Designation Type With Enable query for CMS REST API */

        var consentPartId = parseInt($('.BBDonationApiContainer').attr('partid'), 10);

        var cnstType = ($('.BBDonationApiContainer').attr('cnsttype') == "True");

        /*------------------------------------------- PART CONFIGURATION - SECTION END -------------------------------------------*/

  </script>
	
</head>
<body>
  <div class="donationForm container">
        <div class="alert" style="background-color:#b6cbe5;">
            <h3>Advanced Donation Form <small>Complete Example(New)</small></h3>
        </div>
        <div class="validation"></div>
        <div class="consentValidation" id="inline" style="display:none"></div>
        <div class="form">
            <fieldset class="donationInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Gift Information</span></div>
                </div>
                <div class="row">
                    <!-- *********************************************** GIFT AMOUNT - SECTION START *********************************************** -->
                    <div class="col-sm-5">
                        <div class="giftAmount">
                            <label class="required">Select Gift Amount:</label>
                            <ul class="list-group">
                                <li>
                                    <input id="amt1000" type="radio" name="radioAmount" value="1000" />
                                    <label for="amt1000">
                                        <span class="term">Platinum</span>
                                        <span class="value">$1,000</span>
                                    </label>
                                </li>
                                <li>
                                    <input id="amt500" type="radio" name="radioAmount" value="500" />
                                    <label for="amt500">
                                        <span class="term">Gold</span>
                                        <span class="value">$500</span>
                                    </label>
                                </li>
                                <li>
                                    <input id="amt100" type="radio" name="radioAmount" value="100" />
                                    <label for="amt100">
                                        <span class="term">Silver</span>
                                        <span class="value">$100</span>
                                    </label>
                                </li>
                                <li>
                                    <input id="amt25" type="radio" name="radioAmount" value="25" />
                                    <label for="amt25">
                                        <span class="term">Bronze</span>
                                        <span class="value">$25</span>
                                    </label>
                                </li>
                                <li class="other">
                                    <input id="amtOther" type="radio" name="radioAmount" value="-1" checked="checked" />
                                    <label for="amtOther">
                                        <span class="term">Enter an amount</span>
                                    </label>
                                    <input id="txtAmount" type="text" placeholder="$">
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!-- *********************************************** GIFT AMOUNT - SECTION END *********************************************** -->
                    <div class="col-sm-7">
                        <div class="recurrence">
                            <label class="required">Recurrence:</label>
                            <ul class="list-group">
                                <li>
                                    <input id="recOneTime" type="radio" name="radioRecurrence" value="0" checked="checked" />
                                    <label for="recOneTime">
                                        Make a one time gift.
                                    </label>
                                </li>
                                <li>
                                    <input id="recMonthly" type="radio" name="radioRecurrence" value="1" />
                                    <label for="recMonthly">
                                        Recurring Gift.
                                    </label>
                                </li>
                            </ul>
                        </div>

                        <!-- *********************************************** RECURRING GIFT - SECTION START *********************************************** -->

                        <div id="divRecurringGift" style="display:none;">
                            <h5>What's good?</h5>
                            <div class="row">
                                <div class="col-sm-9">
                                    I want to pledge above amount to the Avengers Initiative in
                                </div>
                                <div class="col-sm-2">
                                    <input id="number-of-installments" type="text" class="form-control" />
                                </div>
                                <div class="col-sm-1">
                                    installments.
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    I pledge to pay
                                </div>
                                <div class="col-sm-4">
                                    <label id="installment-amount">$0.00</label> every
                                </div>
                                <div id="divFrequency" class="col-sm-5">
                                    <div class="row">
                                        <div class="col-sm-6">
                                            <select id="frequency" class="form-control">
                                                <option value="">Select Frequency</option>
                                                <option value="1">Weekly</option>
                                                <option value="2">Monthly</option>
                                                <option value="3">Quarterly</option>
                                                <option value="4">Annually</option>
                                                <option value="7">Every4Weeks</option>
                                            </select>
                                        </div>
                                        <div id="divDayOfWeek" class="col-sm-6" style="display:none;">
                                            <select id="day-of-week" class="form-control">
                                                <option value="">Select Day-of-Week</option>
                                                <option value="0">Sunday</option>
                                                <option value="1">Monday</option>
                                                <option value="2">Tuesday</option>
                                                <option value="3">Wednesday</option>
                                                <option value="4">Thursday</option>
                                                <option value="5">Friday</option>
                                                <option value="6">Saturday</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-2">
                                    on the
                                </div>
                                <div id="divDayOfMonth" class="col-sm-4">
                                    <select id="day-of-month" class="form-control">
                                        <option value="">Select Day-Of-Month</option>
                                        <option>1</option>
                                        <option>2</option>
                                        <option>3</option>
                                        <option>4</option>
                                        <option>5</option>
                                        <option>6</option>
                                        <option>7</option>
                                        <option>8</option>
                                        <option>9</option>
                                        <option>10</option>
                                        <option>11</option>
                                        <option>12</option>
                                        <option>13</option>
                                        <option>14</option>
                                        <option>15</option>
                                        <option>16</option>
                                        <option>17</option>
                                        <option>18</option>
                                        <option>19</option>
                                        <option>20</option>
                                        <option>21</option>
                                        <option>22</option>
                                        <option>23</option>
                                        <option>24</option>
                                        <option>25</option>
                                        <option>26</option>
                                        <option>27</option>
                                        <option>28</option>
                                        <option>29</option>
                                        <option>30</option>
                                        <option>31</option>
                                    </select>
                                </div>
                                <div class="col-sm-1">
                                    of
                                </div>
                                <div id="divMonth" class="col-sm-5">
                                    <select id="month" class="form-control">
                                        <option value="">Month</option>
                                        <option value="1">January</option>
                                        <option value="2">February</option>
                                        <option value="3">March</option>
                                        <option value="4">April</option>
                                        <option value="5">May</option>
                                        <option value="6">June</option>
                                        <option value="7">July</option>
                                        <option value="8">August</option>
                                        <option value="9">September</option>
                                        <option value="10">October</option>
                                        <option value="11">November</option>
                                        <option value="12">December</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-2">
                                    starting on
                                </div>
                                <div class="col-sm-3">
                                    <input type="text" id="start-date" class="form-control" placeholder="mm/dd/yyyy" />
                                </div>
                                <div class="col-sm-7">
                                    . My final payment will be made on <label id="end-date" class="col-form-label" />
                                </div>
                            </div>

                            <!-- *********************************************** RECURRING GIFT - SECTION END *********************************************** -->
                        </div>
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Additional Information</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <input type="checkbox" id="isAnonymous">
                        <label for="isAnonymous" class="col-form-label">
                            Make this gift anonymously
                        </label>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <input type="checkbox" id="createGiftAidDeclaration">
                        <label for="createGiftAidDeclaration" class="col-form-label checkbox-inline">
                            Create gift aid declaration
                        </label>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-4">
                        <label for="Comments" class="col-form-label">
                            Comments:
                        </label>
                        <input type="text" class="form-control" placeholder="comments" id="comments" maxlength="400">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="appealId" class="col-form-label">
                            Appeal ID:
                        </label>
                        <input type="text" class="form-control" id="appealId" maxlength="60" placeholder="enter an appeal GUID">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="designation" class="col-form-label">
                            Designation:
                        </label>
                        <select class="form-control" id="designation" name=" "></select>
                    </div>
                </div>
            </fieldset>
            <!-- *********************************************** CONSENT - SECTION START *********************************************** -->

            <div>
                <div id="myModal" class="modal-content" style="display:none">
                    <div class="consentValidation" id="overlay" style="display:none;padding: 7px 0px 8px 7px"></div>
                    <fieldset style="border:none;">
                        <legend>
                            <span id="consentTitle">Consent Start</span><br />
                            <hr />
                            <label id="consentStatement" style="text-align:center;"></label><br />
                        </legend>
                        <input type="hidden" value="" id="hdnCRMConsentSolicitCode" />
                        <input type="hidden" value="" id="hdnCRMSolicitCode" />
                        <table id="consentOption" class="table">
                            <tr>
                                <th style="border:1px solid black;border-color:#efefef;">Communication Type</th>
                                <th style="border:1px solid black;border-color:#efefef;">Opt-in</th>
                                <th style="border:1px solid black;border-color:#efefef;">Opt-out</th>
                            </tr>
                        </table>
                        <legend>
                            <a id="privacylink">View Privacy Policy</a><br /><br />
                            <button style="display:none" class="btn btn-primary" type="button">Submit</button>
                        </legend>
                    </fieldset>
                </div>
            </div>

            <!-- *********************************************** CONSENT - SECTION END *********************************************** -->
            <!-- *********************************************** BILLING/DONOR INFORMATION - SECTION START *********************************************** -->

            <fieldset class="billingInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Finder Number</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="finderNumber" class="col-form-label">
                            Finder number:
                        </label>
                        <input type="text" class="form-control" id="finderNumber" maxlength="60" placeholder="enter a finder number">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Billing Information</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="title" class="col-form-label">
                            Title:
                        </label>
                        <select class="form-control" id="title" name=" ">
                            <option value="" selected="selected">select a value</option>
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="firstName" class="col-form-label">
                            First name:
                        </label>
                        <input type="text" class="form-control" id="firstName" maxlength="30" placeholder="enter your first name">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="middleName" class="col-form-label">
                            Middle name:
                        </label>
                        <input type="text" class="form-control" id="middleName" maxlength="30" placeholder="enter your middle name">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="lastName" class="required col-form-label">
                            Last name:
                        </label>
                        <input type="text" class="form-control" id="lastName" maxlength="60" placeholder="enter your last name">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="country" class="col-form-label required">
                            Country:
                        </label>
                        <select class="form-control" id="country"></select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="streetAddress" class="col-form-label required" id="streetAddressLabel">
                            Address:
                        </label>
                        <textarea class="form-control" id="streetAddress" cols="20" rows="1"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="city" class="col-form-label required" id="cityLabel">
                            City:
                        </label>
                        <input type="text" class="form-control" id="city" maxlength="50" placeholder="enter a city">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="state" class="col-form-label required" id="stateLabel">
                            State/Province:
                        </label>
                        <select class="form-control" id="state"></select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="postalCode" class="col-form-label required" id="postalCodeLabel">
                            ZIP/Postal code:
                        </label>
                        <input type="text" class="form-control" id="postalCode" maxlength="10" placeholder="enter a zip code">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="emailAddress" class="col-form-label required">
                            Email:
                        </label>
                        <input type="email" class="form-control" id="emailAddress" maxlength="120" placeholder="enter an email">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="phone" class="col-form-label">
                            Phone:
                        </label>
                        <input type="text" class="form-control" id="phone" placeholder="enter a phone">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Payment Information</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="formrow required">
                            <ul class="list-group">
                                <li id="creditCard">
                                    <input id="paymentCreditCard" type="radio" name="paymentMethod" value="0" checked="checked" />
                                    <label for="paymentCreditCard">
                                        Credit Card
                                    </label>
                                </li>
                                <li id="billMeLater">
                                    <input id="paymentBillMeLater" type="radio" name="paymentMethod" value="1" />
                                    <label for="paymentBillMeLater">
                                        Bill Me Later
                                    </label>
                                </li>
                                <li id="directDebit" style="display:none;">
                                    <input id="paymentDirectDebit" type="radio" name="paymentMethod" value="2" />
                                    <label for="paymentDirectDebit">
                                        DirectDebit
                                    </label>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Matching Gifts</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <input type="checkbox" id="isCorporate">
                        <label for="isCorporate" class="col-form-label">
                            This donation if on behalf of a company
                        </label>
                    </div>
                </div>
                <div class="row required invisible" id="organizationNameDiv">
                    <div class="col-sm-4">
                        <label for="organizationName" class="col-form-label">
                            Company name:
                        </label>
                        <input type="text" id="organizationName" maxLength="60" placeholder="enter your company name" class="form-control">
                    </div>
                </div>
            </fieldset>

            <!-- *********************************************** BILLING/DONOR INFORMATION - SECTION END *********************************************** -->
            <!-- *********************************************** TRIBUTE - SECTION START *********************************************** -->

            <fieldset class="tribueInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Tribute /Acknowledgee Information</span></div>
                </div>
                <div>
                    <div class="row">
                        <div row="col-sm-12">
                            &nbsp;&nbsp;
                            <input type="checkbox" id="includeTribue">
                            <label for="includeTribue" class="col-form-label">
                                Include tribute:
                            </label>
                        </div>
                    </div>
                    <div class="invisible" id="tribute">
                        <div class="row">
                            <div class="col-sm-6">
                                <label class="required">What kind of tribute:</label>
                                <ul class="pagination">
                                    <li>
                                        <input id="kindSpecific" type="radio" name="radioTribute" value="1" checked="checked" />
                                        <label for="kindSpecific">
                                            <span class="term">Specific</span>
                                        </label>
                                    </li>
                                    <li>
                                        &nbsp;&nbsp;&nbsp;
                                        <input id="kindGeneral" type="radio" name="radioTribute" value="2" />
                                        <label for="kindGeneral">
                                            <span class="term">General</span>
                                        </label>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="row">
                            <div id="specificTribute" class="col-sm-6">
                                <div class="formrow">
                                    <label for="tributeID" class="col-form-label">
                                        Tribute ID:
                                    </label>
                                    <input type="text" class="form-control" id="tributeID" maxlength="60" placeholder="enter a tribute GUID">
                                </div>
                            </div>
                        </div>
                        <div class="invisible" id="generalTribute">
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="tributeFirstName" class="col-form-label">
                                        First name:
                                    </label>
                                    <input type="text" class="form-control" id="tributeFirstName" placeholder="enter a first name">
                                </div>
                                <div class="col-sm-3">
                                    <label for="tributeLastName" class="col-form-label">
                                        Last name:
                                    </label>
                                    <input type="text" class="form-control" id="tributeLastName" placeholder="enter a last name">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="tributeType" class="col-form-label">
                                        Type:
                                    </label>
                                    <input type="text" class="form-control" id="tributeType" placeholder="enter a tribute type">
                                </div>
                                <div class="col-sm-3">
                                    <label for="tributeDescription" class="col-form-label">
                                        Description:
                                    </label>
                                    <input type="text" class="form-control" id="tributeDescription" placeholder="enter a description">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12">
                                <input type="checkbox" id="includeAcknowledgee">
                                <label for="includeAcknowledgee" class="col-form-label">
                                    Include acknowledgee:
                                </label>
                            </div>
                        </div>
                        <div class="invisible" id="acknowledgee">
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="acknowledgeeFirstName" class="col-form-label">
                                        First name:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeFirstName" placeholder="enter a first name">
                                </div>
                                <div class="col-sm-3">
                                    <label for="acknowledgeeLastName" class="col-form-label">
                                        Last name:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeLastName" placeholder="enter a last name">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="acknowledgeeCountry" class="col-form-label">
                                        Country:
                                    </label>
                                    <select class="adfSelect form-control required" id="acknowledgeeCountry"></select>
                                </div>
                                <div class="col-sm-3">
                                    <label for="acknowledgeeAddressLines" id="streetAddressLabelAcknowledgee" class="col-form-label">
                                        Address lines:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeAddressLines" placeholder="enter address lines">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-2">
                                    <label for="acknowledgeeCity" id="cityLabelAcknowledgee" class="col-form-label">
                                        City:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeCity" placeholder="enter city">
                                </div>
                                <div class="col-sm-2">
                                    <label for="acknowledgeeState" id="stateLabelAcknowledgee" class="col-form-label">
                                        State:
                                    </label>
                                    <select class="adfSelect form-control required" placeholder="State" id="acknowledgeeState"></select>
                                </div>
                                <div class="col-sm-2">
                                    <label for="acknowledgeePostalCode" id="postalCodeLabelAcknowledgee" class="col-form-label">
                                        Postal code:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeePostalCode" placeholder="enter postal code">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="acknowledgeeEmail" class="col-form-label">
                                        Email:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeEmail" placeholder="enter email">
                                </div>
                                <div class="col-sm-3">
                                    <label for="acknowledgeePhone" class="col-form-label">
                                        Phone:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeePhone" placeholder="enter phone">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>

            <!-- *********************************************** TRIBUTE - SECTION END *********************************************** -->
            <!-- *********************************************** ATTRIBUTE INFORMATION - SECTION START *********************************************** -->

            <fieldset class="attributeInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Attributes</span></div>
                </div>
                <div>
                    <div class="row">
                        <div class="col-sm-12">
                            <input type="checkbox" id="includeAttribute1">
                            <label for="includeAttribute1" class="col-form-label">
                                Include attribute 1:
                            </label>
                        </div>
                    </div>
                    <div class="invisible" id="attribute1">
                        <div class="row">
                            <div class="col-sm-3">
                                <label for="attribute1ID" class="col-form-label">
                                    Attribute ID:
                                </label>
                                <input type="text" class="form-control" id="attribute1ID" placeholder="enter attribute GUID">
                            </div>
                            <div class="col-sm-3">
                                <label for="attribute1Value" class="col-form-label">
                                    Value:
                                </label>
                                <input type="text" class="form-control" id="attribute1Value" placeholder="enter value">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <input type="checkbox" id="includeAttribute2">
                            <label for="includeAttribute2" class="col-form-label">
                                Include attribute 2:
                            </label>
                        </div>
                    </div>
                    <div class="invisible" id="attribute2">
                        <div class="row">
                            <div class="col-sm-3">
                                <label for="attribute2ID" class="col-form-label">
                                    Attribute ID:
                                </label>
                                <input type="text" class="form-control" id="attribute2ID" placeholder="enter attribute GUID">
                            </div>
                            <div class="col-sm-3">
                                <label for="attribute2Value" class="col-form-label">
                                    Value:
                                </label>
                                <input type="text" class="form-control" id="attribute2Value" placeholder="enter value">
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>

            <!-- *********************************************** ATTRIBUTE INFORMATION - SECTION END *********************************************** -->
            <!-- *********************************************** DIRECT DEBIT - SECTION START *********************************************** -->

            <fieldset id="directDebitInformation" style="display:none;">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Direct Debit</span></div>
                </div>
                <div id="directDebitSection">
                    <div class="row" id="tr_DDPDFInstructions">
                        <div class="col-sm-12 text-justify">
                            <span>
                                <i>
                                    In order to set up a Direct Debit instruction online, you must be the account holder of
                                    a personal bank or building society account. If you are not the only required signatory
                                    on your account or you would rather send us a paper version please
                                    <a ID="lnkDDPDF" title="Direct Debit PDF" href="#"
                                       Target="_blank" rel="noopener noreferrer">click here</a>
                                </i>
                            </span>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-3">
                            <label ID="lblFinancialLBL" class="col-form-label">Financial Institution:</label>
                            <input type="text" ID="txtFinancialInstitution" MaxLength="100" class="form-control" />
                        </div>
                        <div class="col-sm-3">
                            <label ID="lblBranchName" class="col-form-label">Branch Name:</label>
                            <input type="text" ID="txtBranchName" MaxLength="100" class="form-control" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-2" id="tr_BankingSystemType">
                            <label ID="lblBankingSystemType" class="col-form-label">Banking System Type:</label>
                            <select ID="ddlBankingSystemType" class="form-control"></select>
                        </div>
                        <div class="col-sm-2">
                            <label ID="lblRoutNumLBL" class="col-form-label">Routing Number:</label>
                            <input type="text" ID="txtRoutingNumber" MaxLength="9" class="form-control" />
                            <a ID="lnk_BankHelp" title="Display help details in another window" style="cursor:pointer;">
                                <img alt="help" title="Help" style="height:32px;width:36px;vertical-align:bottom; border:0;" />
                            </a>
                        </div>
                        <div class="col-sm-2">
                            <label ID="lblAccountNumber" class="col-form-label">Account Number:</label>
                            <span id="spn_AccountNo">
                                <input type="text" ID="txtAccountNumber" MaxLength="20" class="form-control" />
                            </span>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="row">
                                <div class="col-sm-4" id="tr_CanadaTransitNum">
                                    <label ID="lblCanadaTransitNum" class="col-form-label">Transit Number:</label>
                                    <input type="text" ID="txtCanTransitNumber" MaxLength="5" class="form-control" />
                                </div>
                                <div class="col-sm-8" id="spn_AccountNoNZ">
                                    <br />
                                    <table>
                                        <tr>
                                            <td>
                                                <input type="text" ID="txtAccountNumberNZ" MaxLength="7" class="form-control" />
                                            </td>
                                            <td>
                                                <span>-</span>
                                            </td>
                                            <td>
                                                <input type="text" ID="txtSuffixNZ" MaxLength="3" class="form-control" />
                                            </td>
                                            <td>
                                                <label ID="lblSuffixNZ" Visible="false" class="col-form-label"></label>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-3" id="tr_AccountType">
                        <label ID="lblAccountType" class="col-form-label">Account Type:</label>
                        <select ID="ddlAccountType" class="form-control"></select>
                    </div>
                    <div class="col-sm-3">
                        <label ID="lblAccountHolderName" class="col-form-label">Account Holder's Name:</label>
                        <input type="text" ID="txtAccountHolder" MaxLength="50" class="form-control" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-3" id="tr_CurrentDate">
                        <label ID="lblDebitDate" class="col-form-label">Date :</label>
                        <label ID="lbl_CurrentDate" class="col-form-label"></label>
                    </div>
                    <div class="col-sm-3" id="tr_OrigNumber">
                        <label ID="lblOriginatorID" class="col-form-label">Service user's ID number :</label>
                        <label ID="lbl_OrigNumber" class="col-form-label"></label>
                    </div>
                </div>
                <div id="tr_DDBankInstructions" class="text-justify">
                    <span colspan="3">
                        <label><b>Instruction to your Bank or Building Society</b></label>
                        <label ID="lbl_DDBankInstructions" class="col-form-label">
                            <i>
                                Please pay %1 Direct Debits from the account detailed in this Instruction subject to the safeguards assured by
                                the Direct Debit Guarantee. I understand that this Instruction may remain with %1 and, if so, details will be passed
                                electronically to my Bank/Building Society.
                            </i>
                        </label>
                        <label>
                            <i>Banks and Building Societies may not accept Direct Debit Instructions for some types of account.</i>
                        </label>
                    </span>
                </div>
                <div id="tr_DDInstructions">
                    <span colspan="3">
                        <img alt="Direct Debit" title="Direct Debit" style="text-align: center;" />
                        <a ID="lnk_DDGuarantee" title="Display the Direct Debit Guarantee in another window" href="#"
                           style="cursor:pointer;color:blue;text-decoration:underline;">The Direct Debit Guarantee</a>
                    </span>
                </div>
                <div id="tr_DDPDFInstructions2" class="text-justify">
                    <span colspan="2">
                        <label>
                            <i>By clicking 'Donate Now' you are confirming that you are the account holder and that you are the only person required to authorize debits from this account.</i>
                        </label>
                    </span>
                </div>
            </fieldset>

            <!-- *********************************************** DIRECT DEBIT - SECTION END *********************************************** -->
            <br />
            <!-- This is the final 'Donate' button, when Donor fill the all required field of page after that press this button for Submit Donation. -->
            <div class="row">
                <div class="col-sm-6">
                    <input id="donate" class="submit btn btn-success form-control" type="button" value="Donate" />
                </div>
                <div class="col-sm-6">
                    <input class="btn btn-danger form-control" type="reset" value="Reset" />
                </div>
            </div>

        </div>

        <!-- Its a compulsory div, it display the Confirmation screen with Donor details after successful donation. -->
        <div class="confirmation container"></div>
    </div>
</body>
</html>
(function () {
		
		/*------------------------------------------- VARIABLE DECLARATION - SECTION START -------------------------------------------*/

        var blocked,
            donationService,
            part,
            partInstanceId,
            addressLinesCaption,
            cityCaption,
            stateCaption,
            postCodeCaption,
            installmentAmt,
            SrtDt,
            merchantAccountId,
            donationData,
            ServerDate,
            ClientSitesID,
            checkoutGenericError = "There was an error while performing the operation. The page will be refreshed.";

        /*------------------------------------------- VARIABLE DECLARATION - SECTION END -------------------------------------------*/

            this.transactionID = null;

            //Checkout Payment pop-up is loaded in this form
            if ($('form[data-formtype="bbCheckout"]').length <= 0) {
                var form = '<form method=\'get\' id=\"paymentForm\" data-formtype=\'bbCheckout\' data-disable-submit=\'false\' novalidate><\/form>';
                $('body').append(form);
            }

            $("#paymentForm").submit(function paymentComplete(e) {
                // prevent form from refreshing and show the transaction token
                e.preventDefault();
            });

            /*------------------------------------------- JAVASCRIPT - VALIDATION FUNCTIONS - SECTION START -------------------------------------------*/

            function validateEmail(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);
            }

            function validatePhone(phone) {
                if (phone) {
                    var re = /^[0-9 \+\)\(\-]{6,20}\s?((([xX]|[eE][xX][tT])\.?\s*(\d+))*)$/;
                    return re.test(phone);

                } else {

                    return true;
                }

            }

            function validateCountry(country, ctryData) {
                if (country.toUpperCase() === ctryData.Id.toUpperCase() || country.toUpperCase() === ctryData.Abbreviation.toUpperCase() || country.toUpperCase() === ctryData.Description.toUpperCase()) {
                    return true;
                }
                return false;
            }

            function validateStartDate(startDate) {
                if (startDate) {
                    var pattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
                    return pattern.test(startDate);
                } else {
                    return false;
                }
            }

            function ValidateDonationRequest(data) {
                return new Promise(function (resolve, reject) {
                    onSuccess = function (result) {
                        resolve();
                    };
                    onFail = function (error) {
                        setValidationMessage(convertErrorsToHtml(error));
                    };
                    donationService.validateDonationRequest(data, onSuccess, onFail)
                });
            }

            // this function validate all required fields of donation page
            function validateFormClientSide() {

                $(".validation").html("");
                var errs = "";
                //Amount
                if (getDonationAmount() <= 0) {
                    errs += "Gift amount is not valid.<br/>";
                }
                //Last Name
                if (!part.find("#lastName").val()) {
                    errs += "Last name is required.<br/>";
                }
                //Email Address
                if (!validateEmail(part.find("#emailAddress").val())) {
                    errs += "Email is not valid.<br/>";
                }
                //Street Address
                if (!part.find("#streetAddress").val()) {
                    errs += addressLinesCaption + " is required.<br/>";
                }
                //City
                if (!part.find("#city").val()) {
                    errs += cityCaption + " is required.<br/>";
                }
                //Postal Code
                if (!part.find("#postalCode").val()) {
                    errs += postCodeCaption + " is required.<br/>";
                }
                //Phone
                if (!validatePhone(part.find("#phone").val())) {
                    errs += "Phone is not valid.<br/>";
                }
                // Organization name
                if (part.find("#isCorporate").prop("checked") && !part.find("#organizationName").val()) {
                    errs += "Company name is required if this donation is on behalf of a company";
                }
                // No Of Installation
                if (part.find("#recMonthly").prop("checked") && part.find("#number-of-installments").val() < 2) {
                    errs += "Number Of installments should be greater than 1 in case of recurring gift.";
                }
                //Payment Method
                if (part.find("#recMonthly").prop("checked")) {
                    if (!part.find("#paymentCreditCard").prop("checked") && !part.find("#paymentDirectDebit").prop("checked")) {
                        errs += "Select Payment Method"
                    }
                }
                if (part.find("#recOneTime").prop("checked")) {
                    if (!part.find("#paymentCreditCard").prop("checked") && !part.find("#paymentBillMeLater").prop("checked")) {
                        errs += "Select Payment Method"
                    }
                }

                if (errs === "") {
                    return true;
                } else {
                    setValidationMessage(errs);
                    return false;
                }
            }

            function setValidationMessage(html) {
                part.find(".validation").html(html);
            }

            /*************************************** CONSENT VALIDATION FUNCTIONS - SECTION START ***************************************/

            function consentValidation() {
                $(".consentValidation").html("");
                var errs = "";
                // Consent info
                var solicitCodeCount = $("table[id='consentOption'] tr[isRequired]").length
                if (solicitCodeCount > 0) {
                    for (var i = 1; i <= solicitCodeCount; i++) {
                        if ($($("#consentOption tr[isRequired]")[i - 1]).attr("isrequired") == "true" && $($("#consentOption tr[isRequired]")[i - 1]).find(':checked').val() === undefined) {
                            errs += $($("#consentOption tr[isRequired]")[i - 1]).find("label")[0].innerHTML + " is required.<br/>"
                        }
                    }
                }
                if (errs === "") {
                    return true;
                } else {
                    setConsentValidationMessage(errs);
                    return false;
                }
            }

            function setConsentValidationMessage(html) {
                $(".consentValidation").html(html);
            }

            /*************************************** CONSENT VALIDATION FUNCTIONS - SECTION END ***************************************/

            /*------------------------------------------- JAVASCRIPT - VALIDATION FUNCTIONS - SECTION END -------------------------------------------*/

            /*------------------------------------------- JAVASCRIPT FUNCTIONS - SECTION START -------------------------------------------*/

            function convertErrorToString(error) {
                if (error) {
                    if (error.Message) return error.Message;
                    switch (error.ErrorCode) {
                        case 101:
                            return error.Field + " is required.";
                        case 105:
                            return error.Field + " is not valid.";
                        case 106:
                            return "Record for " + error.Field + " was not found.";
                        case 203:
                            return "Donation not completed on BBSP.";
                        case 107:
                            return "Max length for " + error.Field + " exceeded.";
                        default:
                            return "Error code " + error.ErrorCode + ".";
                    }
                }
            }

            function convertErrorsToHtml(errors) {
                var i, message = "Unknown error.<br/>";
                if (errors) {
                    message = "";
                    for (i = 0; i < errors.length; i++) {
                        message = message + convertErrorToString(errors[i]) + "<br/>";
                    }
                }
                return message;
            }

            // Extract the data entered by the user and fill the result object for transaction processing.
            function extractDataFromForm() {
                var paymentMethod,
                    result,
                    organizationName = "",
                    consentOptions,
                    solicitCodeCount;

                if (part.find("#isCorporate").prop("checked")) {
                    organizationName = part.find("#organizationName").val();
                }
                paymentMethod = part.find("[name='paymentMethod']:checked").val();
                result = {};
                // Donor information
                result.Donor = {
                    Title: part.find("#title").val(),
                    FirstName: part.find("#firstName").val(),
                    MiddleName: part.find("#middleName").val(),
                    LastName: part.find("#lastName").val(),
                    EmailAddress: part.find("#emailAddress").val(),
                    Phone: part.find("#phone").val(),
                    Address: {
                        Country: part.find("#country").val(),
                        State: part.find("#state").val(),
                        City: part.find("#city").val(),
                        StreetAddress: part.find("#streetAddress").val(),
                        PostalCode: part.find("#postalCode").val()
                    },
                    OrganizationName: organizationName
                };
                // Consent Information
                consentOptions = [];
                solicitCodeCount = $("table[id='consentOption'] tr[isRequired]").length;
                if (solicitCodeCount > 0) {
                    for (var i = 1; i <= solicitCodeCount; i++) {
                        consentOptions.push({
                            SolicitCodeID: $("table[id='consentOption'] tr[isRequired]")[i - 1].id,
                            IsRequired: $("table[id='consentOption'] tr[isRequired]")[i - 1].isrequired,
                            ConsentPreferenceCode: $($("table[id='consentOption'] tr[isRequired]")[i - 1]).find(':checked').val()
                        });
                    }
                }
                result.ContactConsents = { ConsentPartId: consentPartId, SolicitCodes: consentOptions };
                result.Gift = {
                    PaymentMethod: paymentMethod,
                    Designations: [{
                        Amount: (part.find("#recMonthly").prop("checked")) ? installmentAmt : getDonationAmount(),
                        DesignationId: part.find("#designation").val()
                    }],
                    FinderNumber: part.find("#finderNumber").val(),
					Comments: part.find("#comments").val(),
                    CreateGiftAidDeclaration: part.find("#createGiftAidDeclaration").prop("checked"),
                    IsAnonymous: part.find("#isAnonymous").prop("checked"),
                    IsCorporate: part.find("#isCorporate").prop("checked")
                };
                // Recurring Gift Information
                if (part.find("#recMonthly").prop("checked")) {
                    result.Gift.Recurrence = {
                        DayOfMonth: part.find('#day-of-month').val(),
                        Month: (part.find("#frequency").val() == "2" || part.find("#frequency").val() == "3") ? "" : part.find('#month').val(),
                        Frequency: part.find("#frequency").val(),
                        StartDate: part.find("#start-date").val(),
                        EndDate: part.find("#end-date").text(),
                        DayOfWeek: part.find("#day-of-week").val(),
                        ProcessNow: isProcessNow()
                    };
                }
                // Tribute Information
                if (part.find("#includeTribue").prop("checked")) {
                    var kind = part.find("[name='radioTribute']:checked").val();
                    if (kind === "1") {
                        result.Gift.Tribute = {
                            TributeId: part.find("#tributeID").val()
                        };
                    } else {
                        result.Gift.Tribute = {
                            TributeDefinition: {
                                Name: part.find("#tributeFirstName").val() + " " + part.find("#tributeLastName").val(),
                                FirstName: part.find("#tributeFirstName").val(),
                                LastName: part.find("#tributeLastName").val(),
                                Type: part.find("#tributeType").val(),
                                Description: part.find("#tributeDescription").val()
                            }
                        };
                    }
                    if (part.find("#includeAcknowledgee").prop("checked")) {
                        result.Gift.Tribute.Acknowledgee = {
                            FirstName: part.find("#acknowledgeeFirstName").val(),
                            LastName: part.find("#acknowledgeeLastName").val(),
                            Country: part.find("#acknowledgeeCountry").val(),
                            AddressLines: part.find("#acknowledgeeAddressLines").val(),
                            City: part.find("#acknowledgeeCity").val(),
                            State: part.find("#acknowledgeeState").val(),
                            PostalCode: part.find("#acknowledgeePostalCode").val(),
                            Phone: part.find("#acknowledgeePhone").val(),
                            Email: part.find("#acknowledgeeEmail").val()
                        };
                    }
                }
                // Attribute Information
                if (part.find("#includeAttribute1").prop("checked") || part.find("#includeAttribute2").prop("checked")) {
                    result.Gift.Attributes = [];
                    var index = 0;
                    if (part.find("#includeAttribute1").prop("checked")) {
                        result.Gift.Attributes[index] = {
                            AttributeId: part.find("#attribute1ID").val(),
                            Value: part.find("#attribute1Value").val()
                        };
                        index += 1;
                    }
                    if (part.find("#includeAttribute2").prop("checked")) {
                        result.Gift.Attributes[index] = {
                            AttributeId: part.find("#attribute2ID").val(),
                            Value: part.find("#attribute2Value").val()
                        };
                        index += 1;
                    }
                }
                // Fetching Direct Debit related information
                if (paymentMethod === "2" && part.find("#paymentDirectDebit").prop("checked")) {
                    result.Gift.DirectDebitInformation = {};
                    var selectedCountry = part.find("#country :selected").val(), bankingType = part.find("#ddlBankingSystemType :selected").val();
                    result.Gift.DirectDebitInformation.FinancialInstitution = part.find("#txtFinancialInstitution").val();
                    result.Gift.DirectDebitInformation.BranchName = part.find("#txtBranchName").val();
                    result.Gift.DirectDebitInformation.AccountHolderName = part.find("#txtAccountHolder").val();
                    result.Gift.DirectDebitInformation.BankingType = bankingType;
                    if (countryData && validateCountry(selectedCountry, countryData.CAD) && bankingType === "USA") {
                        result.Gift.DirectDebitInformation.RoutingNumber = part.find("#txtRoutingNumber").val();
                        result.Gift.DirectDebitInformation.TransitNumber = part.find("#txtCanTransitNumber").val();
                    }
                    else {
                        result.Gift.DirectDebitInformation.RoutingNumber = part.find("#txtRoutingNumber").val();
                    }
                    if (countryData && validateCountry(selectedCountry, countryData.NZ) && bankingType === "Aus_NZ") {
                        result.Gift.DirectDebitInformation.AccountNumber = part.find("#txtAccountNumberNZ").val();
                        result.Gift.DirectDebitInformation.SuffixNo = part.find("#txtSuffixNZ").val();
                    }
                    else {
                        result.Gift.DirectDebitInformation.AccountNumber = part.find("#txtAccountNumber").val();
                    }
                    if (bankingType === "Europe" || bankingType === "Other" || countryData && (!validateCountry(selectedCountry, countryData.CAD) && bankingType === "USA")) {
                        result.Gift.DirectDebitInformation.AccountType = part.find("#ddlAccountType :selected").val();
                    }
                    else {
                        result.Gift.DirectDebitInformation.AccountType = "";
                    }
                }
                result.Origin = {
                    PageId: BLACKBAUD.api.pageInformation.pageId,
                    AppealId: part.find("#appealId").val(),
                    PartId: partInstanceId,
                    ClientSitesID: ClientSitesID
                };
                result.BBSPTemplateSitePageId = BLACKBAUD.api.pageInformation.pageId;
                if (paymentMethod == 0) {
                    result.BBSPReturnUri = window.location.href;
                }
                result.MerchantAccountId = CheckoutModel.MerchantAccountId;
                result.PartId = partInstanceId;
                return result;
            }

            // this function submit Donation using CreateDonation() of donationService
            function submitDonationToServer(data) {
                onSuccess = function (d) {
                    // For Pledge, go ahead and show the confirmation.  For credit card, you will be redirected to BBSP already.
                    if (d.Donation.TransactionStatus === 1) {
                        part.find(".form").hide();
                        part.find(".confirmation").show();
                        getConfirmationHtml(d.Donation.Id);
                    }
                    if (d.Donation.Gift.PaymentMethod === 2) {
                        window.location.href = window.location.href + "?t=" + d.Donation.Id;
                    }
                };
                onFail = function (d) {
                    setValidationMessage(convertErrorsToHtml(d));
                };
                if (data && data.Donor && data.Donor.Address) {
                    data.Donor.Address.State = part.find("#state :selected").attr("iso");
                }
                donationService.createDonation(data, onSuccess, onFail);

            }

            // Success Callback from Secure Payment Page
            function completeBBSPPayment(id) {
                onSuccess = function (d) {
                    '<%Session["' + d.Id + '"] = "' + true + '"; %>';
                    getConfirmationHtml(d.Id);
                };
                onFail = function (d) {
                    setValidationMessage(convertErrorsToHtml(d));
                };
                donationService.completeBBSPDonation(id, onSuccess, onFail);
            }

            // Display the Final Confirmation screen after Successful Doantion
            function getConfirmationHtml(id) {
                onSuccess = function (d) {
                    part.find(".confirmation").html(d);
                };
                onFail = function (d) {
                    setValidationMessage(convertErrorsToHtml(d));
                };
                donationService.getDonationConfirmationHtml(id, onSuccess, onFail);
            }

            // bind the Designation
            function bindDesignationDropdown() {
                queryService = new BLACKBAUD.api.QueryService();
                statusFilter = { columnName: 'Is active', value: 'True' };
                queryService.getResults(designationQueryId, function (d) {
                    var rows = d.Rows;
                    $.each(rows, function () {
                        var values = this['Values'];
                        $("#designation").append($("<option></option>").val(values[0]).text(values[1]));
                    });
                }, null, [statusFilter]);
            }

            // populate the Title Dropdown with available list of Title
            function bindTitleDropdown() {
                codeTableService = new BLACKBAUD.api.CodeTableService();
                codeTableService.getTitles('456FFD4C-0FBF-49DB-A503-0726F86E2A39', function (d) {
                    $.each(d, function () {
                        $("#title").append($("<option></option>").val(this["Description"]).text(this["Description"]));
                    });
                });
            }

            // bind the Linked user Details to the HTML Controls of Page, when we logged in with Linked User
            function bindUserData() {
                userService = new BLACKBAUD.api.UserService();
                userService.getProfile(function (d) {
                    part.find("#firstName").val(d["FirstName"]);
                    part.find("#lastName").val(d["LastName"]);
                    part.find("#phone").val(d["Phone"]);
                    // only bind the Primary Address of Linked user
                    if (d.Addresses && d.Addresses.length > 0) {
                        var ads = d.Addresses.find(function (x) {
                            return x.IsPrimary === true;
                        });
                        if (ads) {
                            part.find("#country").val(ads["Country"]);
                            bindStateDropdown(undefined, ads["State"]);
                            part.find("#city").val(ads["City"]);
                            part.find("#streetAddress").val(ads["StreetAddress"]);
                            part.find("#postalCode").val(ads["PostalCode"]);
                        }
                    }
                    // only bind the Primary Email Address of Linked user
                    if (d.EmailAddresses && d.EmailAddresses.length > 0) {
                        var email = d.EmailAddresses.find(function (x) {
                            return x.IsPrimary === true;
                        });

                        if (email) {
                            part.find("#emailAddress").val(email["EmailAddress"]);
                        }

                    }
                });
            }

            // change the Address related Label of Page, when change the Country from Country dropdown
            function updateAddressLabels() {
                var countryId = $("#country").find(":selected").attr("id");
                countryService = new BLACKBAUD.api.CountryService();
                countryService.getAddressCaptions(countryId, function (d) {
                    if (!!d) {
                        addressLinesCaption = d["AddressLines"];
                        cityCaption = d["City"];
                        stateCaption = d["State"];
                        postCodeCaption = d["PostCode"];
                    }
                    else {
                        addressLinesCaption = "Address lines";
                        cityCaption = "City";
                        stateCaption = "State/Providence";
                        postCodeCaption = "Zip/Postal code";
                    }
                    $("#streetAddressLabel").text(addressLinesCaption + ":");
                    $("#cityLabel").text(cityCaption + ":");
                    $("#stateLabel").text(stateCaption + ":");
                    $("#postalCodeLabel").text(postCodeCaption + ":");
                }, function () {
                });
            }

            // change the Tribute Acknowledge Address related Label of Page, when change the Tribute Acknowledge Country from Country dropdown
            function updateAcknowledgeeAddressLabels() {
                var countryId = $("#acknowledgeeCountry").find(":selected").attr("id");
                countryService = new BLACKBAUD.api.CountryService();
                countryService.getAddressCaptions(countryId, function (d) {
                    if (!!d) {
                        addressLinesCaption = d["AddressLines"];
                        cityCaption = d["City"];
                        stateCaption = d["State"];
                        postCodeCaption = d["PostCode"];
                    }
                    else {
                        addressLinesCaption = "Address lines";
                        cityCaption = "City";
                        stateCaption = "State/Providence";
                        postCodeCaption = "Zip/Postal code";
                    }
                    $("#streetAddressLabelAcknowledgee").text(addressLinesCaption + ":");
                    $("#cityLabelAcknowledgee").text(cityCaption + ":");
                    $("#stateLabelAcknowledgee").text(stateCaption + ":");
                    $("#postalCodeLabelAcknowledgee").text(postCodeCaption + ":");
                }, function () {
                });
            }


            /*************************************** RECURRENCE FUNCTIONS - SECTION START ***************************************/

            function showHideRecurrenceDiv() {
                if (part.find("#recMonthly").prop("checked")) {
                    part.find("#divRecurringGift").show();
                }
                else {
                    part.find("#divRecurringGift").hide();
                }
                part.find("#directDebitInformation").hide();
            }

            function updateEverythingPossible() {
                var donationAmount = getDonationAmount();
                var numberOfInstallments = part.find("#number-of-installments").val();
                var installmentAmount = donationService.getRecurringGiftInstallmentAmount(donationAmount, numberOfInstallments);
                var startDate = part.find("#start-date").val();
                var frequency = part.find("#frequency").val();
                var dayOfMonth = part.find('#day-of-month').val();
                var dayOfWeek = part.find("#day-of-week").val();
                var month = part.find('#month').val();
                if (numberOfInstallments < 2) {
                    setValidationMessage("Number Of installments should be greater than 1 in case of recurring gift.");
                    return false;
                }
                else {
                    setValidationMessage("");
                    if (frequency == 1) {//Weekly
                        part.find("#divDayOfWeek").show();
                        part.find("#divMonth").hide();
                        part.find("#annual-options").hide();
                        part.find("#divDayOfMonth").hide();
                    } else if (frequency == 2 || frequency == 3) {//Monthly| Quarterly
                        part.find("#divMonth").hide();
                        part.find("#divDayOfMonth").show();
                        part.find("#divDayOfWeek").hide();
                    } else if (frequency == 4) {//Annually
                        part.find("#divMonth").show();
                        part.find("#divDayOfMonth").show();
                        part.find("#divDayOfWeek").hide();
                        if (frequency == 4) {
                            part.find("#annual-options").css("display", "inline");
                        }
                        else {
                            part.find("#annual-options").hide();
                        }
                    } else if (frequency == 7) {    //Every4Weeks
                        part.find("#divDayOfWeek").hide();
                        part.find("#divMonth").hide();
                        part.find("#annual-options").hide();
                        part.find("#divDayOfMonth").hide();
                    } else {
                        part.find("#divDayOfWeek").hide();
                        part.find("#divMonth").show();
                        part.find("#divDayOfMonth").show();
                        part.find("#annual-options").hide();
                    }
                    if (validateStartDate(startDate)) {
                        if (frequency == 1) {
                            var StartDate1 = new Date(startDate);
                            var dayOfStartDate = StartDate1.getDay();
                            if (dayOfStartDate != dayOfWeek && !isNaN(parseInt(dayOfWeek, 10))) {
                                var startDateCopy = new Date(StartDate1);
                                var firstDayOfCurrentWeek = new Date(startDate);
                                firstDayOfCurrentWeek.setHours(0, 0, 0, 0);
                                // if start date's day of week is not monday then calculate the first day(i.e. monday) of the week of start date
                                //{0-Sunday,1-Monday,2-Tuesday,3-Wednesday,4-Thursday,5-Friday,6-Saturday}
                                if (dayOfStartDate != 1) {
                                    firstDayOfCurrentWeek.setDate(StartDate1.getDate() - dayOfStartDate + (dayOfStartDate == 0 ? -6 : 1));
                                }
                                // if the installment's day of week is not same as start date's day of week , then adjust the start date.
                                while (firstDayOfCurrentWeek < startDateCopy ||
                                    firstDayOfCurrentWeek.getDay() != parseInt(dayOfWeek, 10)) {
                                    firstDayOfCurrentWeek.setDate(firstDayOfCurrentWeek.getDate() + 1);
                                }
                                // set the start date's to the expected day of week
                                StartDate1 = firstDayOfCurrentWeek;
                            }
                            var endDate = new Date(StartDate1);
                            endDate.setDate(StartDate1.getDate() + (7 * (numberOfInstallments - 1)));
                            var endDateFormatted;
                            if (endDate) {
                                var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                                endDateFormatted = monthNames[endDate.getMonth()] + " " + endDate.getDate() + ", " + endDate.getFullYear();
                            }
                        }
                        else {
                            var endDate = donationService.getRecurringGiftLastPaymentDate(numberOfInstallments, frequency, startDate, month, dayOfMonth, dayOfWeek);
                            var endDateFormatted;
                            if (endDate) {
                                var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                                endDateFormatted = monthNames[endDate.getMonth()] + " " + endDate.getDate() + ", " + endDate.getFullYear();
                            }
                        }
                    }
                    part.find("#installment-amount").text("$" + installmentAmount);
                    part.find("#end-date").text(endDateFormatted);
                    installmentAmt = installmentAmount;
                }
            }

            //to check for recurring gift that is to be processed today or not (this is check for call stored card payment api)
            function isProcessNow() {
                var recStartDate = part.find("#start-date").val(),
                    frequency = part.find("#frequency").val(),
                    dayOfMonth = part.find('#day-of-month').val(),
                    dayOfWeek = part.find("#day-of-week").val(),
                    month = part.find('#month').val(),
                    startDateIsTodayDate = false,
                    recurrrentStartDate = new Date(recStartDate),
                    isProcessedNow = false,
                    serverDate = new Date(ServerDate);
                if (
                    recurrrentStartDate.getFullYear() === serverDate.getFullYear() &&
                    recurrrentStartDate.getMonth() === serverDate.getMonth() &&
                    recurrrentStartDate.getDate() === serverDate.getDate()
                ) {
                    startDateIsTodayDate = true;
                }
                else {
                    return false;
                }
                //Weekly Frequency
                if (frequency == 1) {
                    isProcessedNow = startDateIsTodayDate && dayOfWeek == serverDate.getDay();
                }
                //Mothly and Quarterly frequency
                else if (frequency == 2 || frequency == 3) {
                    isProcessedNow = startDateIsTodayDate && dayOfMonth == serverDate.getDate();
                }
                //Annually frequency
                else if (frequency == 4) {
                    isProcessedNow =
                        startDateIsTodayDate
                        && dayOfMonth == serverDate.getDate()
                        && month == serverDate.getMonth() + 1;
                }
                //Every 4 weeks
                else if (frequency == 7) {
                    isProcessedNow = startDateIsTodayDate;
                }
                else {
                    isProcessedNow = false;
                }
                return isProcessedNow;
            };

            /*************************************** RECURRENCE FUNCTIONS - SECTION END ***************************************/

            /*************************************** CONSENT FUNCTIONS - SECTION START ***************************************/

            function bindConsentOption() {
                consentOptionService = new BLACKBAUD.api.ConsentOptionService();
                consentOptionService.getConsentOptions(consentPartId, function (d) {
                    if (!cnstType && d.SolicitCodes.length > 0) { $("#myModal").css("display", "block"); }
                    $("#consentTitle").append("<b></b>").text(d["Title"]);
                    if (d["hdnCRMSolicitCode"] != null) { $("#hdnCRMSolicitCode").val(d["hdnCRMSolicitCode"]); }
                    if (d["hdnCRMConsentSolicitCode"] != null) { $("#hdnCRMConsentSolicitCode").val(d["hdnCRMConsentSolicitCode"]); }
                    $("#consentStatement").text(d["ConsentStatement"]);
                    if (d["PrivacyPolicy"] != null) {
                        $("#privacylink").attr("onclick", "javascript:window.open('" + d["PrivacyPolicy"] + "', '_blank' ,height=600, width=800, resizable='yes', scrollbars='yes' )");
                    } else { $("#privacylink").css("display", "none"); }
                    var count = 0;
                    $.each(d.SolicitCodes, function () {
                        if (this["ConsentCode"] === 3) {
                            $("#consentOption").append($("<tr></tr>").attr("id", this["SolicitCodeID"])
                                .append($("<td colspan='3' style='width:100%;text-align:left; font-weight:bold;'></td>").html(this["Caption"]))
                            );
                            if (count % 2 != 0) { $("#consentOption tr[id=" + this["SolicitCodeID"] + "]").css("background-color", "#efefef"); }
                            count = count + 1;
                        } else {
                            if (this["ConsentCode"] == 1) {
                                $("#consentOption").append($("<tr></tr>").attr("id", this["SolicitCodeID"]).attr("IsRequired", this["IsRequired"])
                                    .append($("<td style='width:35%'></td>").append($("<label></label>").text(this["Caption"])))
                                    .append($("<td></td>").append($("<input>").attr("type", "radio").val("2").attr("name", "radio" + this["Caption"]).prop("checked", this["ConsentPreferenceCode"] === 2)))
                                    .append($("<td></td>").append($("<input>").attr("type", "radio").val("1").attr("name", "radio" + this["Caption"]).prop("checked", this["ConsentPreferenceCode"] === 1)))
                                );
                                if (count % 2 != 0) { $("#consentOption tr[id=" + this["SolicitCodeID"] + "]").css("background-color", "#efefef"); }
                                count = count + 1;
                            }
                            else if (this["ConsentCode"] == 2) {
                                $("#consentOption").append($("<tr></tr>").attr("id", this["SolicitCodeID"]).attr("IsRequired", this["IsRequired"])
                                    .append($("<td style='width:35%'></td>").append($("<label></label>").text(this["Caption"])))
                                    .append($("<td></td>").append($("<input>").attr("type", "radio").val("2").attr("name", "radio" + this["Caption"]).prop("checked", this["ConsentPreferenceCode"] === 2)))
                                    .append($("<td></td>").append($("<input>").attr("type", "radio").val("1").attr("name", "radio" + this["Caption"]).prop("checked", this["ConsentPreferenceCode"] === 1)))
                                );
                                if (count % 2 != 0) { $("#consentOption tr[id=" + this["SolicitCodeID"] + "]").css("background-color", "#efefef"); }
                                count = count + 1;
                            }
                            else if (this["ConsentCode"] == 0) {
                                $("#consentOption").append($("<tr></tr>").attr("id", this["SolicitCodeID"]).attr("IsRequired", this["IsRequired"])
                                    .append($("<td  style='width:35%'></td>").append($("<label></label>").text(this["Caption"])))
                                    .append($("<td colspan='2'></td>").append($("<input>").attr("type", "checkbox").val("2").attr("name", "radio" + this["Caption"]).prop("checked", this["ConsentPreferenceCode"] === 2)))
                                );
                                if (count % 2 != 0) { $("#consentOption tr[id=" + this["SolicitCodeID"] + "]").css("background-color", "#efefef"); }
                                count = count + 1;
                            }
                        }
                    });
                    var requiredRows = $("#consentOption tr[IsRequired]");
                    for (i = 0; i < requiredRows.length; i++) { if (requiredRows[i].getAttribute("IsRequired") == "true") { $("#consentOption tr[id=" + requiredRows[i].getAttribute("id") + "]").find("td:first").append("<span style='color:red;'>*</span>"); } }
                });
                if (cnstType) {
                    $("#myModal").css({ "display": "none", "align": "center" });
                }
                else {
                    $("#myModal").css("width", "600px");
                    $("#consentTitle").attr("class", "BBListingHeading DonationListingHeading");
                }
                $("#myModal").attr("cnstFilled", "0");
            }

            //this function open overlay Consent dialog on screen
            function openDialog() {
                var rows = $("#consentOption tr[isRequired]").find("td:first");
                for (i = 0; i < rows.length; i++) {
                    rows[i].style.width = "60%";
                }
                $(function () {
                    $("#myModal").dialog({
                        dialogClass: "no-close",
                        modal: true,
                        autoOpen: false,
                        maxHeight: 393,
                        maxWidth: 474
                    });
                    $('#myModal').dialog('open');
                    $('#myModal').css({ "position": "fixed", "top": "25%", "background-color": "white", "overflow": "auto", "max-height": "393px", "max-width": "473px", "z-index": "101" });
                    $('.ui-widget-overlay').css({ "position": "fixed", "width": "100%", "height": "100%", "background-color": "gray", "opacity": "0.6", "top": "0%", "left": "0%" });
                    $("#consentOption").css("width", "100%");
                    $("#consentOption th").attr({ "border": "1px solid black", "border-color": "#efefef" })
                });
            }

            /*************************************** CONSENT FUNCTIONS - SECTION END ***************************************/

            /*************************************** COUNTRY/STATE FUNCTIONS - SECTION START ***************************************/

            // bind the List of Country to Donor Country & Tribute Acknowledgee Country Dropdown
            function bindCountryDropdown() {
                countryService = new BLACKBAUD.api.CountryService();
                countryService.getCountries(function (d) {
                    $.each(d, function () {
                        $("#country").append($("<option></option>").val(this["Description"]).text(this["Description"]).attr("id", this["Id"]).attr("iso", this["ISO"]));
                        $("#acknowledgeeCountry").append($("<option></option>").val(this["Description"]).text(this["Description"]).attr("id", this["Id"]).attr("iso", this["ISO"]));
                    });
                    $("#country").find("option[value='United States']").attr("selected", "selected");
                    $("#country").change(function () { bindStateDropdown(undefined, undefined) });
                    bindStateDropdown(true, undefined);

                    // if you are going to add Tribute Acknowledgee Section then add below line of code
                    $("#acknowledgeeCountry").find("option[value='United States']").attr("selected", "selected");
                    $("#acknowledgeeCountry").change(function () { bindAcknowledgeeStateDropdown(undefined, undefined) });
                    bindAcknowledgeeStateDropdown(true, undefined);
                });
            }

            function bindStateDropdown(val, data) {
                $("#state").empty();
                var countryId = $("#country").find(":selected").attr("id");
                countryService = new BLACKBAUD.api.CountryService();
                countryService.getStates(countryId, function (d) {
                    $.each(d, function () {
                        switch (countryId.toUpperCase()) {
                            case 'D81CEF85-7569-4B2E-8F2E-F7CF998A3342':
                                $("#state").append($("<option></option>").val(this["Abbreviation"]).text(this["Abbreviation"]).attr("iso", this["ISO"]));
                                break;
                            case 'D9EE54CD-2183-490C-A3AD-11152B271335':
                                $("#state").append($("<option></option>").val(this["Abbreviation"]).text(this["Abbreviation"]).attr("iso", this["ISO"]));
                                break;
                            case 'F189F24C-2538-46A1-8458-1E3F3967B843':
                                $("#state").append($("<option></option>").val(this["Abbreviation"]).text(this["Abbreviation"]).attr("iso", this["ISO"]));
                                break;
                            default:
                                $("#state").append($("<option></option>").val(this["Description"]).text(this["Description"]).attr("iso", this["ISO"]));
                                break;
                        }
                        $("#acknowledgeeState").append($("<option></option>").val(this["Id"]).text(this["Description"]));
                        if (data) {
                            part.find("#state").val(data);
                        }
                    });
                    updateAddressLabels();
                    if (val) {
                        bindUserData();
                    }
                });
            }

            // Bind the State after changing the Tribute Acknowledgee Country value
            function bindAcknowledgeeStateDropdown(val, data) {
                $("#acknowledgeeState").empty();
                var countryId = $("#acknowledgeeCountry").find(":selected").attr("id");
                countryService = new BLACKBAUD.api.CountryService();
                countryService.getStates(countryId, function (d) {
                    $.each(d, function () {
                        switch (countryId.toUpperCase()) {
                            case 'D81CEF85-7569-4B2E-8F2E-F7CF998A3342':
                                $("#acknowledgeeState").append($("<option></option>").val(this["Abbreviation"]).text(this["Abbreviation"]).attr("iso", this["ISO"]));
                                break;
                            case 'D9EE54CD-2183-490C-A3AD-11152B271335':
                                $("#acknowledgeeState").append($("<option></option>").val(this["Abbreviation"]).text(this["Abbreviation"]).attr("iso", this["ISO"]));
                                break;
                            case 'F189F24C-2538-46A1-8458-1E3F3967B843':
                                $("#acknowledgeeState").append($("<option></option>").val(this["Abbreviation"]).text(this["Abbreviation"]).attr("iso", this["ISO"]));
                                break;
                            default:
                                $("#acknowledgeeState").append($("<option></option>").val(this["Description"]).text(this["Description"]).attr("iso", this["ISO"]));
                                break;
                        }
                    });
                    updateAcknowledgeeAddressLabels();
                });
            }

            function getCountryMappings() {
                //this is use for direct debit validations
                countryData = {};
                countryService.getCountries(function (d) {
                    $.each(d, function () {
                        var tmpData = {};
                        tmpData.Id = this["Id"];
                        tmpData.Abbreviation = this["Abbreviation"];
                        tmpData.Description = this["Description"];
                        switch (this["Id"].toUpperCase()) {
                            case 'D81CEF85-7569-4B2E-8F2E-F7CF998A3342':
                                countryData.USA = tmpData;
                                break;
                            case 'A2ECC209-3D20-4DDA-BC4C-7585C8E2E701':
                                countryData.UK = tmpData;
                                break;
                            case 'D9EE54CD-2183-490C-A3AD-11152B271335':
                                countryData.CAD = tmpData;
                                break;
                            case 'F189F24C-2538-46A1-8458-1E3F3967B843':
                                countryData.AUS = tmpData;
                                break;
                            case 'DA42443E-AB81-40EE-A239-91ED699C0801':
                                countryData.NZ = tmpData;
                                break;
                        }
                    });
                });
            }

            /*************************************** COUNTRY/STATE FUNCTIONS - SECTION END ***************************************/

            /*************************************** DIRECT DEBIT FUNCTIONS - SECTION START ***************************************/

            function showHideDirectDebitDiv() {
                if (part.find("#paymentDirectDebit").prop("checked")) {
                    part.find("#directDebitInformation").show();
                    hideAndVisible_BankingTypeField();
                    addCountryHandler();
                }
                else {
                    part.find("#directDebitInformation").hide();
                }
            }

            function hideAndVisible_BankingTypeField() {
                if ($('[id="ddlBankingSystemType"] option').length == 1) {
                    $('#tr_BankingSystemType').css('display', 'none');
                } else {
                    $('#tr_BankingSystemType').css('display', '');
                }
            }

            function bindDirectDebitData() {
                donationService.getBankingTypeData(function (d) {
                    $.each(d, function () {
                        $("#ddlBankingSystemType").append($("<option></option>").val(this["Abbreviation"]).text(this["Description"]));
                    });
                });
                donationService.getAccountTypeData(function (d) {
                    $.each(d, function () {
                        $("#ddlAccountType").append($("<option></option>").val(this["Id"]).text(this["Description"]));
                    });
                });
                donationService.getOriginIdAndTime(function (d) {
                    $("#lbl_CurrentDate").text(d["Time"]);
                    $("#lbl_OrigNumber").text(d["OriginId"]);
                });
            }

            // handling the functionality, when chnage the Country from Country Dropdown
            function addCountryHandler() {
                var bankingSystemType = $('[id="ddlBankingSystemType"]'), addrCtl = $("[id='country'] :selected"), selectBankingOption, exists = false, bankingOptions;
                if (bankingSystemType && bankingSystemType.length > 0) {
                    bankingOptions = $('[id="ddlBankingSystemType"] option');
                    if (bankingOptions.length > 0) {
                        if (!(bankingOptions.length === 1)) {
                            if (countryData && (validateCountry(addrCtl.val(), countryData.NZ) || validateCountry(addrCtl.val(), countryData.AUS))) {
                                selectBankingOption = "Aus_NZ";
                            }
                            else if (countryData && validateCountry(addrCtl.val(), countryData.UK)) {
                                selectBankingOption = "UK";
                            }
                            else if (countryData && validateCountry(addrCtl.val(), countryData.CAD) || validateCountry(addrCtl.val(), countryData.USA)) {
                                selectBankingOption = "USA";
                            }
                            exists = 0 !== bankingSystemType.find('option[value="' + selectBankingOption + '"]').length;
                            if (exists && exists === true) {
                                bankingSystemType.val(selectBankingOption);
                            } else {
                                bankingSystemType.val("Please Select");
                            }
                        }
                    }
                    //bind event so when ever ddl change we can reset the field
                    hideAndVisible_DirectDebitFields();
                }
            }

            function hideAndVisible_DirectDebitFields() {
                var bankingType = "Please Select", htmlElement = "", routingNumberTextBoxLabel = "", selectedCountry = "", routingNumberTextBox = "", transitNumberBox = "",
                    routingNumber = $('[id="txtRoutingNumber"]'),
                    transitNumber = $('[id="txtCanTransitNumber"]'),
                    routingNumberLabel = $('[id="lblRoutNumLBL"]'),
                    addressCTL = $("[id='country'] :selected"),
                    bankingSystemLabel = $('[id="lblBankingSystemType"]'),
                    bankingSystemType = $('[id="ddlBankingSystemType"] :selected'),
                    accountType = $('[id="tr_AccountType"],[id*="DC_AccountType"]'),
                    accountNo = $('[id="spn_AccountNo"]'),
                    accountNoNZ = $('[id="spn_AccountNoNZ"]'),
                    financialInstitution = $('[id="lblFinancialLBL"]'),
                    accountNoLabel = $('[id="lblAccountNumber"]'),
                    routingNumberHelpSymbol = $('[id="lnk_BankHelp"]'),
                    requiredFieldAccountType = $('[id="RequiredFieldAccountType"]'),
                    ukFields = $('[id="tr_DDInstructions"], [id="tr_OrigNumber"], [id="tr_CurrentDate"], [id="tr_DDBankInstructions"], [id="tr_DDPDFInstructions"], [id="tr_DDPDFInstructions2"],[id="DC_DDInstructions"],[id="DC_OrigNumber"],[id="DC_CurrentDate"],[id="DC_DDBankInstructions"],[id="DC_DDPDFInstructions"],[id="DC_DDPDFInstructions2"]');
                if (!routingNumber || routingNumber.length <= 0) {
                    return;
                }
                if (bankingSystemType && bankingSystemType.length > 0) {
                    bankingType = bankingSystemType.attr("Value");
                }
                if (routingNumber && routingNumber.length > 0) {
                    routingNumberTextBox = routingNumber;
                }
                if (addressCTL && addressCTL.length > 0) {
                    selectedCountry = addressCTL.val();
                }
                if (routingNumberLabel && routingNumberLabel.length > 0) {
                    routingNumberTextBoxLabel = routingNumberLabel;
                }
                if (transitNumber && transitNumber.length > 0) {
                    transitNumberBox = transitNumber;
                    $('[id="tr_CanadaTransitNum"]').css("display", "none");
                }
                accountNo.css("display", "");
                accountNoNZ.css("display", "");
                accountNoLabel.html("Account Number:");
                routingNumberHelpSymbol.css("display", "");
                if (ukFields && ukFields.length > 0) {
                    ukFields.css('display', 'none');
                }
                if (countryData && validateCountry(selectedCountry, countryData.CAD) && transitNumberBox && transitNumberBox.length > 0 && bankingType === "USA") {
                    routingNumberTextBoxLabel.html("Institution ID:");
                    routingNumberTextBox.attr("maxlength", "4");
                    routingNumberTextBox.val('');
                    accountType.css("display", "none");
                    accountNoNZ.css("display", "none");
                    $('[id="tr_CanadaTransitNum"]').css("display", "");
                } else {
                    if (bankingType !== "Please Select") {
                        if (bankingType === "USA") {
                            routingNumberTextBoxLabel.html("Routing Number:");
                            routingNumberTextBox.attr("maxlength", "9");
                            routingNumberTextBox.val('');
                            accountType.css("display", "");
                            accountNoNZ.css("display", "none");
                        }
                        else if (bankingType === "UK") {
                            routingNumberTextBoxLabel.html("Sort Code:");
                            routingNumberTextBox.attr("maxlength", "6");
                            routingNumberTextBox.val('');
                            accountType.css("display", "none");
                            accountNoNZ.css("display", "none");
                            if (ukFields) {
                                ukFields.css('display', '');
                            }
                        }
                        else if (bankingType === "Europe") {
                            routingNumberTextBoxLabel.html("BIC:");
                            routingNumberTextBox.attr("maxlength", "11");
                            routingNumberTextBox.val('');
                            accountType.css("display", "");
                            accountNoNZ.css("display", "none");
                            routingNumberHelpSymbol.css("display", "none");
                        }
                        else if (bankingType === "Aus_NZ") {
                            routingNumberTextBoxLabel.html("BSB Number:");
                            routingNumberTextBox.attr("maxlength", "6");
                            routingNumberTextBox.val('');
                            accountType.css("display", "none");
                            accountNoNZ.css("display", "none");
                            if (countryData && validateCountry(selectedCountry, countryData.NZ)) {
                                accountNo.css("display", "none");
                                accountNoNZ.css("display", "");
                                routingNumberTextBoxLabel.html("Bank/Branch No.:");
                                accountNoLabel.html("Account No./Suffix:");
                                routingNumberTextBox.attr("maxlength", "7");
                                routingNumberTextBox.val('');
                            }
                        }
                        else if (bankingType === "Other") {
                            routingNumberTextBoxLabel.html("Bank Code:");
                            routingNumberTextBox.attr("maxlength", "25");
                            routingNumberTextBox.val('');
                            accountType.css("display", "");
                            accountNoNZ.css("display", "none");
                            routingNumberHelpSymbol.css("display", "none");
                        }
                        else {
                            routingNumberTextBoxLabel.html("Routing Number:");
                            routingNumberTextBox.attr("maxlength", "9");
                            routingNumberTextBox.val('');
                            accountType.css("display", "");
                            accountNoNZ.css("display", "none");
                        }
                    }
                    else {
                        routingNumberTextBoxLabel.html("Routing Number:");
                        routingNumberTextBox.attr("maxlength", "9");
                        accountType.css("display", "");
                        accountNoNZ.css("display", "none");
                    }
                }
            }

            function donationBankHelp() {
                var sFeatures = 'WIDTH=392px,HEIGHT=400px,RESIZABLE=YES,SCROLLBARS=NO,TOOLBAR=NO,LEFT=5,TOP=20,location=No;status=No', oPopUp,
                    bankingType = $('[id="ddlBankingSystemType"] :selected'), addressCTL = $("[id='country'] :selected"), selectedValue = "", selectedCountry = "", qParam = "";
                if (bankingType && bankingType.length > 0) {
                    selectedValue = bankingType.attr("Value");;
                }
                if (addressCTL && addressCTL.length > 0) {
                    selectedCountry = addressCTL.val();
                }
                if (countryData && validateCountry(selectedCountry, countryData.AUS) && selectedValue === 'Aus_NZ') {
                    qParam = 'AUS';
                } else if (countryData && validateCountry(selectedCountry, countryData.NZ) && selectedValue === 'Aus_NZ') {
                    qParam = 'NZ';
                } else if (countryData && validateCountry(selectedCountry, countryData.CAD) && selectedValue === 'USA' && $('[id="tr_CanadaTransitNum"]') && $('[id="tr_CanadaTransitNum"]').length > 0) {
                    qParam = 'CAD';
                } else {
                    switch (selectedValue) {
                        case 'USA':
                            qParam = "USA";
                            break;
                        case "Aus_NZ":
                            qParam = "AUS";
                            break;
                        case "UK":
                            qParam = "UK";
                            break;
                        default:
                            qParam = "USA";
                            break;
                    }
                }
                oPopUp = new PopUpDialogBB('~/Admin/DonationHelp.ascx', '_blank', sFeatures, '&mode=2&displayfor=' + qParam);
                oPopUp.Show();
            }

            /*************************************** DIRECT DEBIT FUNCTIONS - SECTION END ***************************************/

            // gift aid declaration
            function dDGuarantee() {
                var sFeatures = 'WIDTH=650px,HEIGHT=415px,RESIZABLE=YES,SCROLLBARS=NO,TOOLBAR=NO,LEFT=5,TOP=20,location=No;status=No',
                    oPopUp = new PopUpDialogBB('~/Admin/DonationHelp.ascx', '_blank', sFeatures, '&mode=3');
                oPopUp.Show();
            }

            // return the donation amount
            function getDonationAmount() {
                if (part.find("#amtOther").prop("checked")) {
                    return part.find("#txtAmount").val();
                } else {
                    return part.find("[name='radioAmount']:checked").val();
                }
            }

            // return which payment method is selected on the page
            function GetPaymentType() {
                paymentMethod = part.find("[name='paymentMethod']:checked").val();
                return paymentMethod;
            }

            /*************************************** PROCESSING PAYMENT FUNCTIONS - SECTION START ***************************************/

            // calls the payment api to open the checkout pop up with all the parameters
            this.makePayment = function () {
                var donor = data.Donor,
                    selectedcountry = part.find("#country :selected").attr("iso"),
                    selectedstate = part.find("#state :selected").attr("iso");
                if (selectedcountry && selectedcountry.toLowerCase() == "gb") {
                    selectedcountry = "UK";
                }
                bbcheckout.Configuration.Data.Amount = data.Gift.Designations[0].Amount;
                bbcheckout.Configuration.Data.BillingAddressCity = donor.Address.City;
                bbcheckout.Configuration.Data.BillingAddressCountry = selectedcountry;
                bbcheckout.Configuration.Data.BillingAddressLine = donor.Address.StreetAddress;
                bbcheckout.Configuration.Data.BillingAddressPostCode = donor.Address.PostalCode;
                bbcheckout.Configuration.Data.BillingAddressState = selectedstate;
                bbcheckout.Configuration.Data.BillingAddressEmail = donor.EmailAddress;
                bbcheckout.Configuration.Data.BillingAddressFirstName = donor.FirstName + " " + (donor.MiddleName ? donor.MiddleName : "");
                bbcheckout.Configuration.Data.BillingAddressLastName = donor.LastName;
                bbcheckout.Configuration.Data.Cardholder = donor.FirstName + " " + donor.LastName;
                bbcheckout.Configuration.Data.UseVisaCheckout = (data.Gift && !data.Gift.Recurrence);
                bbcheckout.Configuration.Data.UseMasterpass = (data.Gift && !data.Gift.Recurrence);
                bbcheckout.Configuration.Data.UseApplePay = (data.Gift && !data.Gift.Recurrence);
                bbcheckout.Configuration.TransactionType = bbcheckout.TransactionType.Card_Not_Present;
                bbcheckout.Configuration.Data.CardToken = null;
                if (data.Gift && data.Gift.Recurrence && !data.Gift.Recurrence.ProcessNow) {
                    bbcheckout.Configuration.Data.CardToken = CheckoutModel.DataKey;
                    bbcheckout.Configuration.TransactionType = bbcheckout.TransactionType.Store_Card; //Store card transactions
                } else if (data.Gift && data.Gift.Recurrence) {      //Set CardToken value only in case of recurring gifts.
                    bbcheckout.Configuration.Data.CardToken = CheckoutModel.DataKey;
                }
                //Set Donor Info so that it will be passed to finish the transaction at the end.
                data.DonationSource = bbcheckout.Configuration.DonationSource.ADF;
                data.Type = bbcheckout.Configuration.TranType.Donation;
                bbcheckout.DonorInfo = data;
                bbcheckout.openCheckout();
            }

            // call ProcessCCPayment(), submitDonationToServer(data) for further Donation Procesing
            function sendData() {
                if (CheckoutModel && CheckoutModel.MACheckoutSupported && GetPaymentType() == 0) {
                    ProcessCCPayment();
                }
                else {
                    var data;
                    setValidationMessage("");
                    setConsentValidationMessage("");
                    data = extractDataFromForm();
                    submitDonationToServer(data);
                }
            }

            // use this method for credit card payment through popup
            function ProcessCCPayment() {
                data = extractDataFromForm();
                onValidationSuccess = function (result) {
                    makePayment();
                    return false;
                };
                onValidationFailed = function (error) {
                    setValidationMessage(convertErrorsToHtml(error));
                };
                //check Client validation
                donationService.validateDonationRequest(data, onValidationSuccess, onValidationFailed);
            }

            // call when we click on "Donate" button
            function onSubmitClick() {
                if (validateFormClientSide()) {
                    if ($("table[id='consentOption'] tr[isRequired]").length > 0) {
                        if (cnstType) {
                            $("#overlay").css("display", "block");
                            openDialog();
                            $("#myModal button").css("display", "block");
                            $("#myModal button").unbind("click");
                            $("#myModal button").click(function () {

                                if (consentValidation()) {
                                    $("#myModal").attr("cnstFilled", "1");
                                    $('#myModal').dialog('close');
                                    sendData();
                                }
                            });
                        }
                        else {
                            $("#inline").css("display", "block");
                            if (validateFormClientSide() && consentValidation()) {
                                sendData();
                            }
                        }
                    }
                    else {
                        sendData();
                    }
                }
            }

            /*************************************** PROCESSING PAYMENT FUNCTIONS - SECTION END ***************************************/

            // Initialize all properties which required for Checkout pop-up by creating new object BBCheckoutProcessor()
            function InitializeBBCheckout() {
                bbcheckout = new BBCheckoutProcessor(checkoutFunctions(), CheckoutModel.APIControllerName, CheckoutModel.TokenId, '[class*="donationForm"]');
                bbcheckout.Configuration.Data.Key = CheckoutModel.PublicKey;
                bbcheckout.Configuration.TransactionType = CheckoutModel.TransactionType;
                bbcheckout.Configuration.Data.ClientAppName = CheckoutModel.ClientAppName;
                bbcheckout.Configuration.Data.MerchantAccountId = CheckoutModel.MerchantAccountId;
                bbcheckout.Configuration.Data.IsEmailRequired = CheckoutModel.IsEmailRequired;
                bbcheckout.Configuration.Data.IsNameVisible = CheckoutModel.IsNameVisible;
                bbcheckout.Configuration.Data.PrimaryColor = CheckoutModel.PrimaryColor;
                bbcheckout.Configuration.Data.SecondaryColor = CheckoutModel.SecondaryColor;
                bbcheckout.Configuration.Data.FontFamily = CheckoutModel.FontFamily;
                bbcheckout.Configuration.Data.UseCaptcha = CheckoutModel.UseCaptcha;
                bbcheckout.Configuration.WorkflowType = CheckoutModel.WorkFlowType;
                bbcheckout.Configuration.HandleBrowserClosing = (CheckoutModel.HandleBrowserClosing === true ? "True" : "False");
                bbcheckout.Configuration.APITokenID = CheckoutModel.TokenId;
                // You can add your own message to display on screen, after checkout pop-up close
                bbcheckout.Configuration.TempConfirmationHtml = "Thank you for your contribution, please wait while we process your transaction.";
                bbcheckout.intializeCheckout();
            }

            function checkoutFunctions() {
                // If you want to override the functionality of any below mentioned events, then you can write your required code in respective Checkout Events Block
                checkoutEvents = {
                    checkoutComplete: function (e) {
                        // Invoke after Payment will successfully Completed
                        bbcheckout.postCheckoutFinish();
                    },
                    checkoutError: function (data) {
                        //Place any code if you want to do anything on error.
                    },
                    checkoutExpired: function () {
                        // If your Checkout modal dialog will expire, due to inactivity on page. Then write code in this block.
                    },
                    checkoutReady: function () {
                        // If your Checkout modal dialog will Ready for Loading, after Donate button click. Then write code in this block.
                    },
                    browserClose: function () {
                        // If you Close the Browser. Then write code in this block.
                    },
                    checkoutCancel: function () {
                        // If your Cancel the Checkout modal dialog. Then write code in this block.
                    },
                    checkoutLoaded: function () {
                        // If your Checkout modal dialog will Load on page. Then write code in this block.
                    }
                }
                return checkoutEvents;
            }

            /*------------------------------------------- JAVASCRIPT FUNCTIONS - SECTION END -------------------------------------------*/

            // this function set-up/bind all required controls of Donation Form on Page Load
            function setupForm() {
                bindDesignationDropdown();
                bindCountryDropdown();
                bindTitleDropdown();
                //bindUserData();
                bindConsentOption();
                getCountryMappings();
                bindDirectDebitData();
                part.find(".submit").click(function () {
                    onSubmitClick();
                });
                part.find("#txtAmount").change(function () {
                    part.find("#amtOther").attr("checked", "checked");
                    if (part.find("#recMonthly").prop("checked")) {
                        updateEverythingPossible();
                    }
                });
                part.find("#isCorporate").click(function () {
                    part.find("#organizationNameDiv").toggleClass("invisible");
                });
                part.find("#includeTribue").click(function () {
                    part.find("#tribute").toggleClass("invisible");
                });
                part.find("#includeAcknowledgee").click(function () {
                    part.find("#acknowledgee").toggleClass("invisible");
                    part.find("#acknowledgeeCountry").change(function () { addCountryHandler(); })
                });
                part.find("#number-of-installments").change(function () { updateEverythingPossible(); });
                part.find("#start-date").change(function () { updateEverythingPossible(); });
                part.find("#frequency").change(function () { updateEverythingPossible(); });
                part.find("#day-of-month").change(function () { updateEverythingPossible(); });
                part.find("#month").change(function () { updateEverythingPossible(); });
                part.find("#day-of-week").change(function () { updateEverythingPossible(); });
                part.find("#recMonthly").click(function () {
                    showHideRecurrenceDiv();
                    part.find("#billMeLater").css("display", "none");
                    part.find("#directDebit").css("display", "");
                });
                part.find("#recOneTime").click(function () {
                    showHideRecurrenceDiv();
                    part.find("#billMeLater").css("display", "");
                    part.find("#directDebit").css("display", "none");
                });
                part.find("#paymentDirectDebit").click(function () { showHideDirectDebitDiv(); })
                part.find("#ddlBankingSystemType").change(function () { hideAndVisible_DirectDebitFields(); })
                part.find("#country").change(function () { addCountryHandler(); })
                part.find("#paymentCreditCard").click(function () { part.find("#directDebitInformation").hide(); });
                part.find("#lnk_BankHelp").click(function () { donationBankHelp(); });
                part.find("#lnk_DDGuarantee").click(function () { dDGuarantee(); });
                function tributeKindChange() {
                    var kind = part.find("[name='radioTribute']:checked").val();
                    if (kind === "1") {
                        part.find("#specificTribute").removeClass("invisible");
                        part.find("#generalTribute").addClass("invisible");
                    } else {
                        part.find("#generalTribute").removeClass("invisible");
                        part.find("#specificTribute").addClass("invisible");
                    }
                }
                part.find("#kindGeneral").click(tributeKindChange);
                part.find("#kindSpecific").click(tributeKindChange);
                part.find("#includeAttribute1").click(function () {
                    part.find("#attribute1").toggleClass("invisible");
                });
                part.find("#includeAttribute2").click(function () {
                    part.find("#attribute2").toggleClass("invisible");
                });
                //Make sure this default HTML is configured for use:
                if (designationQueryId === "00000000-0000-0000-0000-000000000000" || merchantAccountId === "00000000-0000-0000-0000-000000000000") {
                    setValidationMessage("DesignationQueryId and MerchantAccountId must be configured before this form can be used.")
                }
            }

            /*------------------------------------------- PAGE LOAD METHOD - START -------------------------------------------*/

            function PageLoad() {
                //Wait until the blockUI script is loaded before we start loading the page.
                var t;
                blocked = false,
                    part = $(".donationForm"),
                    partInstanceId = part.parents(".BBDonationApiContainer").attr("data-partid"),
                    ClientSitesID = part.parents(".BBDonationApiContainer").attr("ClientSitesID"),
                    CheckoutModel = JSON.parse(checkoutData),
                    serverMonth = part.parents(".BBDonationApiContainer").attr("serverMonth") - 1,
                    serverDay = part.parents(".BBDonationApiContainer").attr("serverDay"),
                    serverYear = part.parents(".BBDonationApiContainer").attr("serverYear");
                ServerDate = new Date(serverYear, serverMonth, serverDay);
                // Create an instance of the DonationService
                donationService = new BLACKBAUD.api.DonationService(partInstanceId);

                // Initialize the all checkout related property
                InitializeBBCheckout();

                t = BLACKBAUD.api.querystring.getQueryStringValue("t")
                if (t) {
                    part.find(".form").hide();
                    part.find(".confirmation").show();
                    completeBBSPPayment(t);
                } else {
                    part.find(".form").show();
                    part.find(".confirmation").hide();
                    setupForm();
                }
            }
            PageLoad();

            /*------------------------------------------- PAGE LOAD METHOD - END -------------------------------------------*/

        }());
/* Currently using Bootstrap styles and some default style */
	.no-close .ui-dialog-titlebar {
            display: none;
	}
	
	#privacylink {
            color: blue;
            text-decoration: none;
    }

	#privacylink:hover {
		cursor: pointer;
	}
	
	.donationForm .validation {
            color: Red;
	}

	.consentValidation {
		color: Red;
	}

	.donationForm ul {
		list-style-type: none;
	}
	
	.donationForm .DonationListingHeading {
            font-size: large;
            font-weight: bold;
    }
	
    .donationForm .confirmation {
            min-height: 400px;
    }

	.donationForm .invisible {
		display: none;
	}
	
	.DonationListingHeading {
            height: 2.25em !important;
    }


ADF - Complete Example(Legacy)

This example will continue to work with Service Pack 25 release, however, it will not utilize the transaction workflow optimization code included as part of that release. Please refer to Example - Complete (New) for updated sample that incorporates the optimized Blackbaud Checkout Code.

All our other examples available on the Developer Site are designed to be inserted into an Advanced Donation Form Part; however the following example is designed as a complete standalone solution – applicable even on a different server than the one serving your BBIS website.

Please note you will need to update the references in the example below to your BBIS installation.

  1. The following ADF JS is only valid for BBSP, Checkout pop-up and IATS. This is not applicable for Payment 2.0.
  2. If you change the ID of any HTML control, then you will need to update/change all instances of that ID in both HTML and JS.
  3. Ensure you are using all the validations and If conditions and pass all the values in the same format as mentioned in the sample.
  4. Changing the visual appearance of page : Modify the default CSS Class written under the CSS tab as per your own requirements.
  5. Configuring Designation : Change the value of variable - designationQueryId="" :
    1. Use of this variable to display All Available Designation(s) on UI.
    2. In the PART CONFIGURATION SECTION, Change the value of the variable - designationQueryId="". This value can be found using SQL against your application Database by executing query (Select * from ADHOCQUERY Where NAME = '{your respective CRM application Ad-hoc Query Name of Designation Record Type}') on table. In this table you can copy the ID column value.
  6. Add/Remove Feature Section : In this example we have two types of feature section. The first being the HTML tab, used for Controls available on Page UI. Secondly, the JAVASCRIPT tab, used for handling functionality of these HTML Controls.
    1. For adding Recurring Gift capability, add the HTML content between "RECURRING GIFT - SECTION START AND RECURRING GIFT - SECTION END" under HTML tab. Also add JAVASCRIPT between "RECURRENCE FUNCTIONS - SECTION START AND RECURRENCE FUNCTIONS - SECTION END" under JAVASCRIPT tab.
    2. For adding Gift Amount, choose HTML DESIGN between "GIFT AMOUNT - SECTION START AND GIFT AMOUNT - SECTION END" under HTML tab. Also add JAVASCRIPT between "RECURRENCE FUNCTIONS - SECTION START AND RECURRENCE FUNCTIONS - SECTION END" under JAVASCRIPT tab.
    3. For adding Consent capability, choose HTML DESIGN between "CONSENT - SECTION START AND CONSENT - SECTION END" under HTML tab. Also add JAVASCRIPT between "CONSENT VALIDATION FUNCTIONS - SECTION START AND CONSENT VALIDATION FUNCTIONS - SECTION END" under JAVASCRIPT tab.
<!DOCTYPE html>
<html lang="en">
<head>
  
  <title>ADF - Complete Example(Legacy)</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    
  <script type="text/javascript">

        /*------------------------------------------- PART CONFIGURATION - SECTION START -------------------------------------------*/

        var designationQueryId = "8d9fccdf-dea8-4590-8ec2-355a4c59df04";  /* Ad-hoc Query of Designation Type With Enable query for CMS REST API */

        var consentPartId = parseInt($('.BBDonationApiContainer').attr('partid'), 10);

        var cnstType = ($('.BBDonationApiContainer').attr('cnsttype') == "True");

        /*------------------------------------------- PART CONFIGURATION - SECTION END -------------------------------------------*/

  </script>
	
</head>
<body>
  <div id="bbspLoadingOverlay" class="bbspLoadingOverlay">
        <img src="images/FormEngine/Loading.gif" alt="" class="bbspLoadingImage" />
    </div>

    <div class="donationForm container">
        <div class="alert" style="background-color:#b6cbe5;">
            <h3>Advanced Donation Form <small>Complete Example(Legacy)</small></h3>
        </div>
        <div class="validation"></div>
        <div class="consentValidation" id="inline" style="display:none"></div>
        <div class="form">
            <fieldset class="donationInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Gift Information</span></div>
                </div>
                <div class="row">
                    <!-- *********************************************** GIFT AMOUNT - SECTION START *********************************************** -->
                    <div class="col-sm-5">
                        <div class="giftAmount">
                            <label class="required">Select Gift Amount:</label>
                            <ul class="list-group">
                                <li>
                                    <input id="amt1000" type="radio" name="radioAmount" value="1000" />
                                    <label for="amt1000">
                                        <span class="term">Platinum</span>
                                        <span class="value">$1,000</span>
                                    </label>
                                </li>
                                <li>
                                    <input id="amt500" type="radio" name="radioAmount" value="500" />
                                    <label for="amt500">
                                        <span class="term">Gold</span>
                                        <span class="value">$500</span>
                                    </label>
                                </li>
                                <li>
                                    <input id="amt100" type="radio" name="radioAmount" value="100" />
                                    <label for="amt100">
                                        <span class="term">Silver</span>
                                        <span class="value">$100</span>
                                    </label>
                                </li>
                                <li>
                                    <input id="amt25" type="radio" name="radioAmount" value="25" />
                                    <label for="amt25">
                                        <span class="term">Bronze</span>
                                        <span class="value">$25</span>
                                    </label>
                                </li>
                                <li class="other">
                                    <input id="amtOther" type="radio" name="radioAmount" value="-1" checked="checked" />
                                    <label for="amtOther">
                                        <span class="term">Enter an amount</span>
                                    </label>
                                    <input id="txtAmount" type="text" placeholder="$">
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!-- *********************************************** GIFT AMOUNT - SECTION END *********************************************** -->
                    <div class="col-sm-7">
                        <div class="recurrence">
                            <label class="required">Recurrence:</label>
                            <ul class="list-group">
                                <li>
                                    <input id="recOneTime" type="radio" name="radioRecurrence" value="0" checked="checked" />
                                    <label for="recOneTime">
                                        Make a one time gift.
                                    </label>
                                </li>
                                <li>
                                    <input id="recMonthly" type="radio" name="radioRecurrence" value="1" />
                                    <label for="recMonthly">
                                        Recurring Gift.
                                    </label>
                                </li>
                            </ul>
                        </div>

                        <!-- *********************************************** RECURRING GIFT - SECTION START *********************************************** -->

                        <div id="divRecurringGift" style="display:none;">
                            <h5>What's good?</h5>
                            <div class="row">
                                <div class="col-sm-9">
                                    I want to pledge above amount to the Avengers Initiative in
                                </div>
                                <div class="col-sm-2">
                                    <input id="number-of-installments" type="text" class="form-control" />
                                </div>
                                <div class="col-sm-1">
                                    installments.
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    I pledge to pay
                                </div>
                                <div class="col-sm-4">
                                    <label id="installment-amount">$0.00</label> every
                                </div>
                                <div id="divFrequency" class="col-sm-5">
                                    <div class="row">
                                        <div class="col-sm-6">
                                            <select id="frequency" class="form-control">
                                                <option value="">Select Frequency</option>
                                                <option value="1">Weekly</option>
                                                <option value="2">Monthly</option>
                                                <option value="3">Quarterly</option>
                                                <option value="4">Annually</option>
                                                <option value="7">Every4Weeks</option>
                                            </select>
                                        </div>
                                        <div id="divDayOfWeek" class="col-sm-6" style="display:none;">
                                            <select id="day-of-week" class="form-control">
                                                <option value="">Select Day-of-Week</option>
                                                <option value="0">Sunday</option>
                                                <option value="1">Monday</option>
                                                <option value="2">Tuesday</option>
                                                <option value="3">Wednesday</option>
                                                <option value="4">Thursday</option>
                                                <option value="5">Friday</option>
                                                <option value="6">Saturday</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-2">
                                    on the
                                </div>
                                <div id="divDayOfMonth" class="col-sm-4">
                                    <select id="day-of-month" class="form-control">
                                        <option value="">Select Day-Of-Month</option>
                                        <option>1</option>
                                        <option>2</option>
                                        <option>3</option>
                                        <option>4</option>
                                        <option>5</option>
                                        <option>6</option>
                                        <option>7</option>
                                        <option>8</option>
                                        <option>9</option>
                                        <option>10</option>
                                        <option>11</option>
                                        <option>12</option>
                                        <option>13</option>
                                        <option>14</option>
                                        <option>15</option>
                                        <option>16</option>
                                        <option>17</option>
                                        <option>18</option>
                                        <option>19</option>
                                        <option>20</option>
                                        <option>21</option>
                                        <option>22</option>
                                        <option>23</option>
                                        <option>24</option>
                                        <option>25</option>
                                        <option>26</option>
                                        <option>27</option>
                                        <option>28</option>
                                        <option>29</option>
                                        <option>30</option>
                                        <option>31</option>
                                    </select>
                                </div>
                                <div class="col-sm-1">
                                    of
                                </div>
                                <div id="divMonth" class="col-sm-5">
                                    <select id="month" class="form-control">
                                        <option value="">Month</option>
                                        <option value="1">January</option>
                                        <option value="2">February</option>
                                        <option value="3">March</option>
                                        <option value="4">April</option>
                                        <option value="5">May</option>
                                        <option value="6">June</option>
                                        <option value="7">July</option>
                                        <option value="8">August</option>
                                        <option value="9">September</option>
                                        <option value="10">October</option>
                                        <option value="11">November</option>
                                        <option value="12">December</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-2">
                                    starting on
                                </div>
                                <div class="col-sm-3">
                                    <input type="text" id="start-date" class="form-control" placeholder="mm/dd/yyyy" />
                                </div>
                                <div class="col-sm-7">
                                    . My final payment will be made on <label id="end-date" class="col-form-label" />
                                </div>
                            </div>

                            <!-- *********************************************** RECURRING GIFT - SECTION END *********************************************** -->
                        </div>
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Additional Information</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <input type="checkbox" id="isAnonymous">
                        <label for="isAnonymous" class="col-form-label">
                            Make this gift anonymously
                        </label>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <input type="checkbox" id="createGiftAidDeclaration">
                        <label for="createGiftAidDeclaration" class="col-form-label checkbox-inline">
                            Create gift aid declaration
                        </label>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-4">
                        <label for="Comments" class="col-form-label">
                            Comments:
                        </label>
                        <input type="text" class="form-control" placeholder="comments" id="comments" maxlength="400">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="appealId" class="col-form-label">
                            Appeal ID:
                        </label>
                        <input type="text" class="form-control" id="appealId" maxlength="60" placeholder="enter an appeal GUID">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="designation" class="col-form-label">
                            Designation:
                        </label>
                        <select class="form-control" id="designation" name=" "></select>
                    </div>
                </div>
            </fieldset>
            <!-- *********************************************** CONSENT - SECTION START *********************************************** -->

            <div>
                <div id="myModal" class="modal-content" style="display:none">
                    <div class="consentValidation" id="overlay" style="display:none;padding: 7px 0px 8px 7px"></div>
                    <fieldset style="border:none;">
                        <legend>
                            <span id="consentTitle">Consent Start</span><br />
                            <hr />
                            <label id="consentStatement" style="text-align:center;"></label><br />
                        </legend>
                        <input type="hidden" value="" id="hdnCRMConsentSolicitCode" />
                        <input type="hidden" value="" id="hdnCRMSolicitCode" />
                        <table id="consentOption" class="table">
                            <tr>
                                <th style="border:1px solid black;border-color:#efefef;">Communication Type</th>
                                <th style="border:1px solid black;border-color:#efefef;">Opt-in</th>
                                <th style="border:1px solid black;border-color:#efefef;">Opt-out</th>
                            </tr>
                        </table>
                        <legend>
                            <a id="privacylink">View Privacy Policy</a><br /><br />
                            <button style="display:none" class="btn btn-primary" type="button">Submit</button>
                        </legend>
                    </fieldset>
                </div>
            </div>

            <!-- *********************************************** CONSENT - SECTION END *********************************************** -->
            <!-- *********************************************** BILLING/DONOR INFORMATION - SECTION START *********************************************** -->

            <fieldset class="billingInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Finder Number</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="finderNumber" class="col-form-label">
                            Finder number:
                        </label>
                        <input type="text" class="form-control" id="finderNumber" maxlength="60" placeholder="enter a finder number">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Billing Information</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="title" class="col-form-label">
                            Title:
                        </label>
                        <select class="form-control" id="title" name=" ">
                            <option value="" selected="selected">select a value</option>
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="firstName" class="col-form-label">
                            First name:
                        </label>
                        <input type="text" class="form-control" id="firstName" maxlength="30" placeholder="enter your first name">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="middleName" class="col-form-label">
                            Middle name:
                        </label>
                        <input type="text" class="form-control" id="middleName" maxlength="30" placeholder="enter your middle name">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="lastName" class="required col-form-label">
                            Last name:
                        </label>
                        <input type="text" class="form-control" id="lastName" maxlength="60" placeholder="enter your last name">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="country" class="col-form-label required">
                            Country:
                        </label>
                        <select class="form-control" id="country"></select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="streetAddress" class="col-form-label required" id="streetAddressLabel">
                            Address:
                        </label>
                        <textarea class="form-control" id="streetAddress" cols="20" rows="1"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="city" class="col-form-label required" id="cityLabel">
                            City:
                        </label>
                        <input type="text" class="form-control" id="city" maxlength="50" placeholder="enter a city">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="state" class="col-form-label required" id="stateLabel">
                            State/Province:
                        </label>
                        <select class="form-control" id="state"></select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="postalCode" class="col-form-label required" id="postalCodeLabel">
                            ZIP/Postal code:
                        </label>
                        <input type="text" class="form-control" id="postalCode" maxlength="10" placeholder="enter a zip code">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 required">
                        <label for="emailAddress" class="col-form-label required">
                            Email:
                        </label>
                        <input type="email" class="form-control" id="emailAddress" maxlength="120" placeholder="enter an email">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4">
                        <label for="phone" class="col-form-label">
                            Phone:
                        </label>
                        <input type="text" class="form-control" id="phone" placeholder="enter a phone">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Payment Information</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="formrow required">
                            <ul class="list-group">
                                <li id="creditCard">
                                    <input id="paymentCreditCard" type="radio" name="paymentMethod" value="0" checked="checked" />
                                    <label for="paymentCreditCard">
                                        Credit Card
                                    </label>
                                </li>
                                <li id="billMeLater">
                                    <input id="paymentBillMeLater" type="radio" name="paymentMethod" value="1" />
                                    <label for="paymentBillMeLater">
                                        Bill Me Later
                                    </label>
                                </li>
                                <li id="directDebit" style="display:none;">
                                    <input id="paymentDirectDebit" type="radio" name="paymentMethod" value="2" />
                                    <label for="paymentDirectDebit">
                                        DirectDebit
                                    </label>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Matching Gifts</span></div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <input type="checkbox" id="isCorporate">
                        <label for="isCorporate" class="col-form-label">
                            This donation if on behalf of a company
                        </label>
                    </div>
                </div>
                <div class="row required invisible" id="organizationNameDiv">
                    <div class="col-sm-4">
                        <label for="organizationName" class="col-form-label">
                            Company name:
                        </label>
                        <input type="text" id="organizationName" maxLength="60" placeholder="enter your company name" class="form-control">
                    </div>
                </div>
            </fieldset>

            <!-- *********************************************** BILLING/DONOR INFORMATION - SECTION END *********************************************** -->
            <!-- *********************************************** TRIBUTE - SECTION START *********************************************** -->

            <fieldset class="tribueInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Tribute /Acknowledgee Information</span></div>
                </div>
                <div>
                    <div class="row">
                        <div row="col-sm-12">
                            &nbsp;&nbsp;
                            <input type="checkbox" id="includeTribue">
                            <label for="includeTribue" class="col-form-label">
                                Include tribute:
                            </label>
                        </div>
                    </div>
                    <div class="invisible" id="tribute">
                        <div class="row">
                            <div class="col-sm-6">
                                <label class="required">What kind of tribute:</label>
                                <ul class="pagination">
                                    <li>
                                        <input id="kindSpecific" type="radio" name="radioTribute" value="1" checked="checked" />
                                        <label for="kindSpecific">
                                            <span class="term">Specific</span>
                                        </label>
                                    </li>
                                    <li>
                                        &nbsp;&nbsp;&nbsp;
                                        <input id="kindGeneral" type="radio" name="radioTribute" value="2" />
                                        <label for="kindGeneral">
                                            <span class="term">General</span>
                                        </label>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="row">
                            <div id="specificTribute" class="col-sm-6">
                                <div class="formrow">
                                    <label for="tributeID" class="col-form-label">
                                        Tribute ID:
                                    </label>
                                    <input type="text" class="form-control" id="tributeID" maxlength="60" placeholder="enter a tribute GUID">
                                </div>
                            </div>
                        </div>
                        <div class="invisible" id="generalTribute">
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="tributeFirstName" class="col-form-label">
                                        First name:
                                    </label>
                                    <input type="text" class="form-control" id="tributeFirstName" placeholder="enter a first name">
                                </div>
                                <div class="col-sm-3">
                                    <label for="tributeLastName" class="col-form-label">
                                        Last name:
                                    </label>
                                    <input type="text" class="form-control" id="tributeLastName" placeholder="enter a last name">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="tributeType" class="col-form-label">
                                        Type:
                                    </label>
                                    <input type="text" class="form-control" id="tributeType" placeholder="enter a tribute type">
                                </div>
                                <div class="col-sm-3">
                                    <label for="tributeDescription" class="col-form-label">
                                        Description:
                                    </label>
                                    <input type="text" class="form-control" id="tributeDescription" placeholder="enter a description">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12">
                                <input type="checkbox" id="includeAcknowledgee">
                                <label for="includeAcknowledgee" class="col-form-label">
                                    Include acknowledgee:
                                </label>
                            </div>
                        </div>
                        <div class="invisible" id="acknowledgee">
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="acknowledgeeFirstName" class="col-form-label">
                                        First name:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeFirstName" placeholder="enter a first name">
                                </div>
                                <div class="col-sm-3">
                                    <label for="acknowledgeeLastName" class="col-form-label">
                                        Last name:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeLastName" placeholder="enter a last name">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="acknowledgeeCountry" class="col-form-label">
                                        Country:
                                    </label>
                                    <select class="adfSelect form-control required" id="acknowledgeeCountry"></select>
                                </div>
                                <div class="col-sm-3">
                                    <label for="acknowledgeeAddressLines" id="streetAddressLabelAcknowledgee" class="col-form-label">
                                        Address lines:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeAddressLines" placeholder="enter address lines">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-2">
                                    <label for="acknowledgeeCity" id="cityLabelAcknowledgee" class="col-form-label">
                                        City:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeCity" placeholder="enter city">
                                </div>
                                <div class="col-sm-2">
                                    <label for="acknowledgeeState" id="stateLabelAcknowledgee" class="col-form-label">
                                        State:
                                    </label>
                                    <select class="adfSelect form-control required" placeholder="State" id="acknowledgeeState"></select>
                                </div>
                                <div class="col-sm-2">
                                    <label for="acknowledgeePostalCode" id="postalCodeLabelAcknowledgee" class="col-form-label">
                                        Postal code:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeePostalCode" placeholder="enter postal code">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-3">
                                    <label for="acknowledgeeEmail" class="col-form-label">
                                        Email:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeeEmail" placeholder="enter email">
                                </div>
                                <div class="col-sm-3">
                                    <label for="acknowledgeePhone" class="col-form-label">
                                        Phone:
                                    </label>
                                    <input type="text" class="form-control" id="acknowledgeePhone" placeholder="enter phone">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>

            <!-- *********************************************** TRIBUTE - SECTION END *********************************************** -->
            <!-- *********************************************** ATTRIBUTE INFORMATION - SECTION START *********************************************** -->

            <fieldset class="attributeInformation">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Attributes</span></div>
                </div>
                <div>
                    <div class="row">
                        <div class="col-sm-12">
                            <input type="checkbox" id="includeAttribute1">
                            <label for="includeAttribute1" class="col-form-label">
                                Include attribute 1:
                            </label>
                        </div>
                    </div>
                    <div class="invisible" id="attribute1">
                        <div class="row">
                            <div class="col-sm-3">
                                <label for="attribute1ID" class="col-form-label">
                                    Attribute ID:
                                </label>
                                <input type="text" class="form-control" id="attribute1ID" placeholder="enter attribute GUID">
                            </div>
                            <div class="col-sm-3">
                                <label for="attribute1Value" class="col-form-label">
                                    Value:
                                </label>
                                <input type="text" class="form-control" id="attribute1Value" placeholder="enter value">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <input type="checkbox" id="includeAttribute2">
                            <label for="includeAttribute2" class="col-form-label">
                                Include attribute 2:
                            </label>
                        </div>
                    </div>
                    <div class="invisible" id="attribute2">
                        <div class="row">
                            <div class="col-sm-3">
                                <label for="attribute2ID" class="col-form-label">
                                    Attribute ID:
                                </label>
                                <input type="text" class="form-control" id="attribute2ID" placeholder="enter attribute GUID">
                            </div>
                            <div class="col-sm-3">
                                <label for="attribute2Value" class="col-form-label">
                                    Value:
                                </label>
                                <input type="text" class="form-control" id="attribute2Value" placeholder="enter value">
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>

            <!-- *********************************************** ATTRIBUTE INFORMATION - SECTION END *********************************************** -->
            <!-- *********************************************** DIRECT DEBIT - SECTION START *********************************************** -->

            <fieldset id="directDebitInformation" style="display:none;">
                <div class="row">
                    <div class="col-md-12"><span class="btn form-control" style="background-color: #339;color:#fff;">Direct Debit</span></div>
                </div>
                <div id="directDebitSection">
                    <div class="row" id="tr_DDPDFInstructions">
                        <div class="col-sm-12 text-justify">
                            <span>
                                <i>
                                    In order to set up a Direct Debit instruction online, you must be the account holder of
                                    a personal bank or building society account. If you are not the only required signatory
                                    on your account or you would rather send us a paper version please
                                    <a ID="lnkDDPDF" title="Direct Debit PDF" href="#"
                                       Target="_blank" rel="noopener noreferrer">click here</a>
                                </i>
                            </span>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-3">
                            <label ID="lblFinancialLBL" class="col-form-label">Financial Institution:</label>
                            <input type="text" ID="txtFinancialInstitution" MaxLength="100" class="form-control" />
                        </div>
                        <div class="col-sm-3">
                            <label ID="lblBranchName" class="col-form-label">Branch Name:</label>
                            <input type="text" ID="txtBranchName" MaxLength="100" class="form-control" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-2" id="tr_BankingSystemType">
                            <label ID="lblBankingSystemType" class="col-form-label">Banking System Type:</label>
                            <select ID="ddlBankingSystemType" class="form-control"></select>
                        </div>
                        <div class="col-sm-2">
                            <label ID="lblRoutNumLBL" class="col-form-label">Routing Number:</label>
                            <input type="text" ID="txtRoutingNumber" MaxLength="9" class="form-control" />
                            <a ID="lnk_BankHelp" title="Display help details in another window" style="cursor:pointer;">
                                <img alt="help" title="Help" style="height:32px;width:36px;vertical-align:bottom; border:0;" />
                            </a>
                        </div>
                        <div class="col-sm-2">
                            <label ID="lblAccountNumber" class="col-form-label">Account Number:</label>
                            <span id="spn_AccountNo">
                                <input type="text" ID="txtAccountNumber" MaxLength="20" class="form-control" />
                            </span>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="row">
                                <div class="col-sm-4" id="tr_CanadaTransitNum">
                                    <label ID="lblCanadaTransitNum" class="col-form-label">Transit Number:</label>
                                    <input type="text" ID="txtCanTransitNumber" MaxLength="5" class="form-control" />
                                </div>
                                <div class="col-sm-8" id="spn_AccountNoNZ">
                                    <br />
                                    <table>
                                        <tr>
                                            <td>
                                                <input type="text" ID="txtAccountNumberNZ" MaxLength="7" class="form-control" />
                                            </td>
                                            <td>
                                                <span>-</span>
                                            </td>
                                            <td>
                                                <input type="text" ID="txtSuffixNZ" MaxLength="3" class="form-control" />
                                            </td>
                                            <td>
                                                <label ID="lblSuffixNZ" Visible="false" class="col-form-label"></label>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-3" id="tr_AccountType">
                        <label ID="lblAccountType" class="col-form-label">Account Type:</label>
                        <select ID="ddlAccountType" class="form-control"></select>
                    </div>
                    <div class="col-sm-3">
                        <label ID="lblAccountHolderName" class="col-form-label">Account Holder's Name:</label>
                        <input type="text" ID="txtAccountHolder" MaxLength="50" class="form-control" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-3" id="tr_CurrentDate">
                        <label ID="lblDebitDate" class="col-form-label">Date :</label>
                        <label ID="lbl_CurrentDate" class="col-form-label"></label>
                    </div>
                    <div class="col-sm-3" id="tr_OrigNumber">
                        <label ID="lblOriginatorID" class="col-form-label">Service user's ID number :</label>
                        <label ID="lbl_OrigNumber" class="col-form-label"></label>
                    </div>
                </div>
                <div id="tr_DDBankInstructions" class="text-justify">
                    <span colspan="3">
                        <label><b>Instruction to your Bank or Building Society</b></label>
                        <label ID="lbl_DDBankInstructions" class="col-form-label">
                            <i>
                                Please pay %1 Direct Debits from the account detailed in this Instruction subject to the safeguards assured by
                                the Direct Debit Guarantee. I understand that this Instruction may remain with %1 and, if so, details will be passed
                                electronically to my Bank/Building Society.
                            </i>
                        </label>
                        <label>
                            <i>Banks and Building Societies may not accept Direct Debit Instructions for some types of account.</i>
                        </label>
                    </span>
                </div>
                <div id="tr_DDInstructions">
                    <span colspan="3">
                        <img alt="Direct Debit" title="Direct Debit" style="text-align: center;" />
                        <a ID="lnk_DDGuarantee" title="Display the Direct Debit Guarantee in another window" href="#"
                           style="cursor:pointer;color:blue;text-decoration:underline;">The Direct Debit Guarantee</a>
                    </span>
                </div>
                <div id="tr_DDPDFInstructions2" class="text-justify">
                    <span colspan="2">
                        <label>
                            <i>By clicking 'Donate Now' you are confirming that you are the account holder and that you are the only person required to authorize debits from this account.</i>
                        </label>
                    </span>
                </div>
            </fieldset>

            <!-- *********************************************** DIRECT DEBIT - SECTION END *********************************************** -->
            <br />
            <!-- This is the final 'Donate' button, when Donor fill the all required field of page after that press this button for Submit Donation. -->
            <div class="row">
                <div class="col-sm-6">
                    <input id="donate" class="submit btn btn-success form-control" type="button" value="Donate" />
                </div>
                <div class="col-sm-6">
                    <input class="btn btn-danger form-control" type="reset" value="Reset" />
                </div>
            </div>

        </div>

        <!-- Its a compulsory div, it display the Confirmation screen with Donor details after successful donation. -->
        <div class="confirmation container"></div>
    </div>

</body>
</html>
(function () {
		
		/*------------------------------------------- VARIABLE DECLARATION - SECTION START -------------------------------------------*/

        var IsPopUpLoaded = false,
            blocked,
            donationService,
            part,
            partInstanceId,
            addressLinesCaption,
            cityCaption,
            stateCaption,
            postCodeCaption,
            installmentAmt,
            SrtDt,
            publicKey,
            merchantAccountId,
            donationData,
            EditorContent,
            ServerDate,
            checkoutGenericError = "There was an error while performing the operation.The page will be refreshed.";

        /*------------------------------------------- VARIABLE DECLARATION - SECTION END -------------------------------------------*/

            this.transactionID = null;

            //Checkout Payment pop-up is loaded in this form
            if ($('form[data-formtype="bbCheckout"]').length <= 0) {
                var form = '<form method=\'get\' id=\"paymentForm\" data-formtype=\'bbCheckout\' data-disable-submit=\'false\' novalidate><\/form>';
                $('body').append(form);
            }

            $("#paymentForm").submit(function paymentComplete(e) {
                // prevent form from refreshing and show the transaction token
                e.preventDefault();
            });

            /*------------------------------------------- JAVASCRIPT - VALIDATION FUNCTIONS - SECTION START -------------------------------------------*/

            function validateEmail(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);
            }

            function validatePhone(phone) {
                if (phone) {
                    var re = /^[0-9 \+\)\(\-]{6,20}\s?((([xX]|[eE][xX][tT])\.?\s*(\d+))*)$/;
                    return re.test(phone);

                } else {

                    return true;
                }

            }

            function validateCountry(country, ctryData) {
                if (country.toUpperCase() === ctryData.Id.toUpperCase() || country.toUpperCase() === ctryData.Abbreviation.toUpperCase() || country.toUpperCase() === ctryData.Description.toUpperCase()) {
                    return true;
                }
                return false;
            }

            function validateStartDate(startDate) {
                if (startDate) {
                    var pattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
                    return pattern.test(startDate);
                } else {
                    return false;
                }
            }

            function ValidateDonationRequest(data) {
                return new Promise(function (resolve, reject) {
                    onSuccess = function (result) {
                        resolve();
                    };
                    onFail = function (error) {
                        setValidationMessage(convertErrorsToHtml(error));
                    };
                    donationService.validateDonationRequest(data, onSuccess, onFail)
                });
            }

            // this function validate all required fields of donation page
            function validateFormClientSide() {

                $(".validation").html("");
                var errs = "";
                //Amount
                if (getDonationAmount() <= 0) {
                    errs += "Gift amount is not valid.<br/>";
                }
                //Last Name
                if (!part.find("#lastName").val()) {
                    errs += "Last name is required.<br/>";
                }
                //Email Address
                if (!validateEmail(part.find("#emailAddress").val())) {
                    errs += "Email is not valid.<br/>";
                }
                //Street Address
                if (!part.find("#streetAddress").val()) {
                    errs += addressLinesCaption + " is required.<br/>";
                }
                //City
                if (!part.find("#city").val()) {
                    errs += cityCaption + " is required.<br/>";
                }
                //Postal Code
                if (!part.find("#postalCode").val()) {
                    errs += postCodeCaption + " is required.<br/>";
                }
                //Phone
                if (!validatePhone(part.find("#phone").val())) {
                    errs += "Phone is not valid.<br/>";
                }
                // Organization name
                if (part.find("#isCorporate").prop("checked") && !part.find("#organizationName").val()) {
                    errs += "Company name is required if this donation is on behalf of a company";
                }
                // No Of Installation
                if (part.find("#recMonthly").prop("checked") && part.find("#number-of-installments").val() < 2) {
                    errs += "Number Of installments should be greater than 1 in case of recurring gift.";
                }
                //Payment Method
                if (part.find("#recMonthly").prop("checked")) {
                    if (!part.find("#paymentCreditCard").prop("checked") && !part.find("#paymentDirectDebit").prop("checked")) {
                        errs += "Select Payment Method"
                    }
                }
                if (part.find("#recOneTime").prop("checked")) {
                    if (!part.find("#paymentCreditCard").prop("checked") && !part.find("#paymentBillMeLater").prop("checked")) {
                        errs += "Select Payment Method"
                    }
                }

                if (errs === "") {
                    return true;
                } else {
                    setValidationMessage(errs);
                    return false;
                }
            }

            function setValidationMessage(html) {
                part.find(".validation").html(html);
            }

            /*************************************** CONSENT VALIDATION FUNCTIONS - SECTION START ***************************************/

            function consentValidation() {
                $(".consentValidation").html("");
                var errs = "";
                // Consent info
                var solicitCodeCount = $("table[id='consentOption'] tr[isRequired]").length
                if (solicitCodeCount > 0) {
                    for (var i = 1; i <= solicitCodeCount; i++) {
                        if ($($("#consentOption tr[isRequired]")[i - 1]).attr("isrequired") == "true" && $($("#consentOption tr[isRequired]")[i - 1]).find(':checked').val() === undefined) {
                            errs += $($("#consentOption tr[isRequired]")[i - 1]).find("label")[0].innerHTML + " is required.<br/>"
                        }
                    }
                }
                if (errs === "") {
                    return true;
                } else {
                    setConsentValidationMessage(errs);
                    return false;
                }
            }

            function setConsentValidationMessage(html) {
                $(".consentValidation").html(html);
            }

            /*************************************** CONSENT VALIDATION FUNCTIONS - SECTION END ***************************************/

            /*------------------------------------------- JAVASCRIPT - VALIDATION FUNCTIONS - SECTION END -------------------------------------------*/

            /*------------------------------------------- JAVASCRIPT FUNCTIONS - SECTION START -------------------------------------------*/

            function convertErrorToString(error) {
                if (error) {
                    if (error.Message) return error.Message;
                    switch (error.ErrorCode) {
                        case 101:
                            return error.Field + " is required.";
                        case 105:
                            return error.Field + " is not valid.";
                        case 106:
                            return "Record for " + error.Field + " was not found.";
                        case 203:
                            return "Donation not completed on BBSP.";
                        case 107:
                            return "Max length for " + error.Field + " exceeded.";
                        default:
                            return "Error code " + error.ErrorCode + ".";
                    }
                }
            }

            function convertErrorsToHtml(errors) {
                var i, message = "Unknown error.<br/>";
                if (errors) {
                    message = "";
                    for (i = 0; i < errors.length; i++) {
                        message = message + convertErrorToString(errors[i]) + "<br/>";
                    }
                }
                return message;
            }

            // Extract the data entered by the user and fill the result object for transaction processing.
            function extractDataFromForm() {
                var paymentMethod,
                    result,
                    organizationName = "",
                    consentOptions,
                    solicitCodeCount;

                if (part.find("#isCorporate").prop("checked")) {
                    organizationName = part.find("#organizationName").val();
                }
                paymentMethod = part.find("[name='paymentMethod']:checked").val();
                result = {};
                // Donor information
                result.Donor = {
                    Title: part.find("#title").val(),
                    FirstName: part.find("#firstName").val(),
                    MiddleName: part.find("#middleName").val(),
                    LastName: part.find("#lastName").val(),
                    EmailAddress: part.find("#emailAddress").val(),
                    Phone: part.find("#phone").val(),
                    Address: {
                        Country: part.find("#country").val(),
                        State: part.find("#state").val(),
                        City: part.find("#city").val(),
                        StreetAddress: part.find("#streetAddress").val(),
                        PostalCode: part.find("#postalCode").val()
                    },
                    OrganizationName: organizationName
                };
                // Consent Information
                consentOptions = [];
                solicitCodeCount = $("table[id='consentOption'] tr[isRequired]").length;
                if (solicitCodeCount > 0) {
                    for (var i = 1; i <= solicitCodeCount; i++) {
                        consentOptions.push({
                            SolicitCodeID: $("table[id='consentOption'] tr[isRequired]")[i - 1].id,
                            IsRequired: $("table[id='consentOption'] tr[isRequired]")[i - 1].isrequired,
                            ConsentPreferenceCode: $($("table[id='consentOption'] tr[isRequired]")[i - 1]).find(':checked').val()
                        });
                    }
                }
                result.ContactConsents = { ConsentPartId: consentPartId, SolicitCodes: consentOptions };
                result.Gift = {                    
                    PaymentMethod: paymentMethod,
                    Designations: [{
                        Amount: (part.find("#recMonthly").prop("checked")) ? installmentAmt : getDonationAmount(),
                        DesignationId: part.find("#designation").val()
                    }],
                    FinderNumber: part.find("#finderNumber").val(),                    
                    Comments: part.find("#comments").val(),
                    CreateGiftAidDeclaration: part.find("#createGiftAidDeclaration").prop("checked"),
                    IsAnonymous: part.find("#isAnonymous").prop("checked"),
                    IsCorporate: part.find("#isCorporate").prop("checked")
                };
                // Recurring Gift Information
                if (part.find("#recMonthly").prop("checked")) {
                    result.Gift.Recurrence = {
                        DayOfMonth: part.find('#day-of-month').val(),
                        Month: (part.find("#frequency").val() == "2" || part.find("#frequency").val() == "3") ? "" : part.find('#month').val(),
                        Frequency: part.find("#frequency").val(),
                        StartDate: part.find("#start-date").val(),
                        EndDate: part.find("#end-date").text(),
                        DayOfWeek: part.find("#day-of-week").val(),
                        ProcessNow: isProcessNow()
                    };
                }
                // Tribute Information
                if (part.find("#includeTribue").prop("checked")) {
                    var kind = part.find("[name='radioTribute']:checked").val();
                    if (kind === "1") {
                        result.Gift.Tribute = {
                            TributeId: part.find("#tributeID").val()
                        };
                    } else {
                        result.Gift.Tribute = {
                            TributeDefinition: {
                                Name: part.find("#tributeFirstName").val() + " " + part.find("#tributeLastName").val(),
                                FirstName: part.find("#tributeFirstName").val(),
                                LastName: part.find("#tributeLastName").val(),
                                Type: part.find("#tributeType").val(),
                                Description: part.find("#tributeDescription").val()
                            }
                        };
                    }
                    if (part.find("#includeAcknowledgee").prop("checked")) {
                        result.Gift.Tribute.Acknowledgee = {
                            FirstName: part.find("#acknowledgeeFirstName").val(),
                            LastName: part.find("#acknowledgeeLastName").val(),
                            Country: part.find("#acknowledgeeCountry").val(),
                            AddressLines: part.find("#acknowledgeeAddressLines").val(),
                            City: part.find("#acknowledgeeCity").val(),
                            State: part.find("#acknowledgeeState").val(),
                            PostalCode: part.find("#acknowledgeePostalCode").val(),
                            Phone: part.find("#acknowledgeePhone").val(),
                            Email: part.find("#acknowledgeeEmail").val()
                        };
                    }
                }
                // Attribute Information
                if (part.find("#includeAttribute1").prop("checked") || part.find("#includeAttribute2").prop("checked")) {
                    result.Gift.Attributes = [];
                    var index = 0;
                    if (part.find("#includeAttribute1").prop("checked")) {
                        result.Gift.Attributes[index] = {
                            AttributeId: part.find("#attribute1ID").val(),
                            Value: part.find("#attribute1Value").val()
                        };
                        index += 1;
                    }
                    if (part.find("#includeAttribute2").prop("checked")) {
                        result.Gift.Attributes[index] = {
                            AttributeId: part.find("#attribute2ID").val(),
                            Value: part.find("#attribute2Value").val()
                        };
                        index += 1;
                    }
                }
                // Fetching Direct Debit related information
                if (paymentMethod === "2" && part.find("#paymentDirectDebit").prop("checked")) {
                    result.Gift.DirectDebitInformation = {};
                    var selectedCountry = part.find("#country :selected").val(), bankingType = part.find("#ddlBankingSystemType :selected").val();
                    result.Gift.DirectDebitInformation.FinancialInstitution = part.find("#txtFinancialInstitution").val();
                    result.Gift.DirectDebitInformation.BranchName = part.find("#txtBranchName").val();
                    result.Gift.DirectDebitInformation.AccountHolderName = part.find("#txtAccountHolder").val();
                    result.Gift.DirectDebitInformation.BankingType = bankingType;
                    if (countryData && validateCountry(selectedCountry, countryData.CAD) && bankingType === "USA") {
                        result.Gift.DirectDebitInformation.RoutingNumber = part.find("#txtRoutingNumber").val();
                        result.Gift.DirectDebitInformation.TransitNumber = part.find("#txtCanTransitNumber").val();
                    }
                    else {
                        result.Gift.DirectDebitInformation.RoutingNumber = part.find("#txtRoutingNumber").val();
                    }
                    if (countryData && validateCountry(selectedCountry, countryData.NZ) && bankingType === "Aus_NZ") {
                        result.Gift.DirectDebitInformation.AccountNumber = part.find("#txtAccountNumberNZ").val();
                        result.Gift.DirectDebitInformation.SuffixNo = part.find("#txtSuffixNZ").val();
                    }
                    else {
                        result.Gift.DirectDebitInformation.AccountNumber = part.find("#txtAccountNumber").val();
                    }
                    if (bankingType === "Europe" || bankingType === "Other" || countryData && (!validateCountry(selectedCountry, countryData.CAD) && bankingType === "USA")) {
                        result.Gift.DirectDebitInformation.AccountType = part.find("#ddlAccountType :selected").val();
                    }
                    else {
                        result.Gift.DirectDebitInformation.AccountType = "";
                    }
                }
                result.Origin = {
                    PageId: BLACKBAUD.api.pageInformation.pageId,
                    AppealId: part.find("#appealId").val(),
                    PartId: partInstanceId
                };
                result.BBSPTemplateSitePageId = BLACKBAUD.api.pageInformation.pageId;
                if (paymentMethod == 0) {
                    result.BBSPReturnUri = window.location.href;
                }
                result.MerchantAccountId = merchantAccountId;
                result.PartId = partInstanceId;
                return result;
            }

            // this function submit Donation using CreateDonation() of donationService
            function submitDonationToServer(data) {
                onSuccess = function (d) {
                    // For Pledge, go ahead and show the confirmation.  For credit card, you will be redirected to BBSP already.
                    if (d.Donation.TransactionStatus === 1) {
                        part.find(".form").hide();
                        part.find(".confirmation").show();
                        getConfirmationHtml(d.Donation.Id);
                    }
                    if (d.Donation.Gift.PaymentMethod === 2) {
                        window.location.href = window.location.href + "?t=" + d.Donation.Id;
                    }
                };
                onFail = function (d) {
                    setValidationMessage(convertErrorsToHtml(d));
                };
                if (data && data.Donor && data.Donor.Address) {
                    data.Donor.Address.State = part.find("#state :selected").attr("iso");
                }
                donationService.createDonation(data, onSuccess, onFail);

            }

            // Success Callback from Secure Payment Page
            function completeBBSPPayment(id) {
                onSuccess = function (d) {
                    '<%Session["' + d.Id + '"] = "' + true + '"; %>';
                    getConfirmationHtml(d.Id);
                };
                onFail = function (d) {
                    setValidationMessage(convertErrorsToHtml(d));
                };
                donationService.completeBBSPDonation(id, onSuccess, onFail);
            }

            // Display the Final Confirmation screen after Successful Doantion
            function getConfirmationHtml(id) {
                onSuccess = function (d) {
                    part.find(".confirmation").html(d);
                };
                onFail = function (d) {
                    setValidationMessage(convertErrorsToHtml(d));
                };
                donationService.getDonationConfirmationHtml(id, onSuccess, onFail);
            }

            // bind the Designation
            function bindDesignationDropdown() {
                queryService = new BLACKBAUD.api.QueryService();
                statusFilter = { columnName: 'Is active', value: 'True' };
                queryService.getResults(designationQueryId, function (d) {
                    var rows = d.Rows;
                    $.each(rows, function () {
                        var values = this['Values'];
                        $("#designation").append($("<option></option>").val(values[0]).text(values[1]));
                    });
                }, null, [statusFilter]);
            }

            // populate the Title Dropdown with available list of Title
            function bindTitleDropdown() {
                codeTableService = new BLACKBAUD.api.CodeTableService();
                codeTableService.getTitles('456FFD4C-0FBF-49DB-A503-0726F86E2A39', function (d) {
                    $.each(d, function () {
                        $("#title").append($("<option></option>").val(this["Description"]).text(this["Description"]));
                    });
                });
            }

            // bind the Linked user Details to the HTML Controls of Page, when we logged in with Linked User
            function bindUserData() {
                userService = new BLACKBAUD.api.UserService();
                userService.getProfile(function (d) {
                    part.find("#firstName").val(d["FirstName"]);
                    part.find("#lastName").val(d["LastName"]);
                    part.find("#phone").val(d["Phone"]);
                    // only bind the Primary Address of Linked user
                    if (d.Addresses && d.Addresses.length > 0) {
                        var ads = d.Addresses.find(function (x) {
                            return x.IsPrimary === true;
                        });
                        if (ads) {
                            part.find("#country").val(ads["Country"]);
                            bindStateDropdown(undefined, ads["State"]);
                            part.find("#city").val(ads["City"]);
                            part.find("#streetAddress").val(ads["StreetAddress"]);
                            part.find("#postalCode").val(ads["PostalCode"]);
                        }
                    }
                    // only bind the Primary Email Address of Linked user
                    if (d.EmailAddresses && d.EmailAddresses.length > 0) {
                        var email = d.EmailAddresses.find(function (x) {
                            return x.IsPrimary === true;
                        });

                        if (email) {
                            part.find("#emailAddress").val(email["EmailAddress"]);
                        }

                    }
                });
            }

            // change the Address related Label of Page, when change the Country from Country dropdown
            function updateAddressLabels() {
                var countryId = $("#country").find(":selected").attr("id");
                countryService = new BLACKBAUD.api.CountryService();
                countryService.getAddressCaptions(countryId, function (d) {
                    if (!!d) {
                        addressLinesCaption = d["AddressLines"];
                        cityCaption = d["City"];
                        stateCaption = d["State"];
                        postCodeCaption = d["PostCode"];
                    }
                    else {
                        addressLinesCaption = "Address lines";
                        cityCaption = "City";
                        stateCaption = "State/Providence";
                        postCodeCaption = "Zip/Postal code";
                    }
                    $("#streetAddressLabel").text(addressLinesCaption + ":");
                    $("#cityLabel").text(cityCaption + ":");
                    $("#stateLabel").text(stateCaption + ":");
                    $("#postalCodeLabel").text(postCodeCaption + ":");
                }, function () {
                });
            }

            // change the Tribute Acknowledge Address related Label of Page, when change the Tribute Acknowledge Country from Country dropdown
            function updateAcknowledgeeAddressLabels() {
                var countryId = $("#acknowledgeeCountry").find(":selected").attr("id");
                countryService = new BLACKBAUD.api.CountryService();
                countryService.getAddressCaptions(countryId, function (d) {
                    if (!!d) {
                        addressLinesCaption = d["AddressLines"];
                        cityCaption = d["City"];
                        stateCaption = d["State"];
                        postCodeCaption = d["PostCode"];
                    }
                    else {
                        addressLinesCaption = "Address lines";
                        cityCaption = "City";
                        stateCaption = "State/Providence";
                        postCodeCaption = "Zip/Postal code";
                    }
                    $("#streetAddressLabelAcknowledgee").text(addressLinesCaption + ":");
                    $("#cityLabelAcknowledgee").text(cityCaption + ":");
                    $("#stateLabelAcknowledgee").text(stateCaption + ":");
                    $("#postalCodeLabelAcknowledgee").text(postCodeCaption + ":");
                }, function () {
                });
            }


            /*************************************** RECURRENCE FUNCTIONS - SECTION START ***************************************/

            function showHideRecurrenceDiv() {
                if (part.find("#recMonthly").prop("checked")) {
                    part.find("#divRecurringGift").show();
                }
                else {
                    part.find("#divRecurringGift").hide();
                }
                part.find("#directDebitInformation").hide();
            }

            function updateEverythingPossible() {
                var donationAmount = getDonationAmount();
                var numberOfInstallments = part.find("#number-of-installments").val();
                var installmentAmount = donationService.getRecurringGiftInstallmentAmount(donationAmount, numberOfInstallments);
                var startDate = part.find("#start-date").val();
                var frequency = part.find("#frequency").val();
                var dayOfMonth = part.find('#day-of-month').val();
                var dayOfWeek = part.find("#day-of-week").val();
                var month = part.find('#month').val();
                if (numberOfInstallments < 2) {
                    setValidationMessage("Number Of installments should be greater than 1 in case of recurring gift.");
                    return false;
                }
                else {
                    setValidationMessage("");
                    if (frequency == 1) {//Weekly
                        part.find("#divDayOfWeek").show();
                        part.find("#divMonth").hide();
                        part.find("#annual-options").hide();
                        part.find("#divDayOfMonth").hide();
                    } else if (frequency == 2 || frequency == 3) {//Monthly| Quarterly
                        part.find("#divMonth").hide();
                        part.find("#divDayOfMonth").show();
                        part.find("#divDayOfWeek").hide();
                    } else if (frequency == 4) {//Annually
                        part.find("#divMonth").show();
                        part.find("#divDayOfMonth").show();
                        part.find("#divDayOfWeek").hide();
                        if (frequency == 4) {
                            part.find("#annual-options").css("display", "inline");
                        }
                        else {
                            part.find("#annual-options").hide();
                        }
                    } else if (frequency == 7) {    //Every4Weeks
                        part.find("#divDayOfWeek").hide();
                        part.find("#divMonth").hide();
                        part.find("#annual-options").hide();
                        part.find("#divDayOfMonth").hide();
                    } else {
                        part.find("#divDayOfWeek").hide();
                        part.find("#divMonth").show();
                        part.find("#divDayOfMonth").show();
                        part.find("#annual-options").hide();
                    }
                    if (validateStartDate(startDate)) {
                        if (frequency == 1) {
                            var StartDate1 = new Date(startDate);
                            var dayOfStartDate = StartDate1.getDay();
                            if (dayOfStartDate != dayOfWeek && !isNaN(parseInt(dayOfWeek, 10))) {
                                var startDateCopy = new Date(StartDate1);
                                var firstDayOfCurrentWeek = new Date(startDate);
                                firstDayOfCurrentWeek.setHours(0, 0, 0, 0);
                                // if start date's day of week is not monday then calculate the first day(i.e. monday) of the week of start date
                                //{0-Sunday,1-Monday,2-Tuesday,3-Wednesday,4-Thursday,5-Friday,6-Saturday}
                                if (dayOfStartDate != 1) {
                                    firstDayOfCurrentWeek.setDate(StartDate1.getDate() - dayOfStartDate + (dayOfStartDate == 0 ? -6 : 1));
                                }
                                // if the installment's day of week is not same as start date's day of week , then adjust the start date.
                                while (firstDayOfCurrentWeek < startDateCopy ||
                                    firstDayOfCurrentWeek.getDay() != parseInt(dayOfWeek, 10)) {
                                    firstDayOfCurrentWeek.setDate(firstDayOfCurrentWeek.getDate() + 1);
                                }
                                // set the start date's to the expected day of week
                                StartDate1 = firstDayOfCurrentWeek;
                            }
                            var endDate = new Date(StartDate1);
                            endDate.setDate(StartDate1.getDate() + (7 * (numberOfInstallments - 1)));
                            var