
function buildApplePayRequest() {
    var req = {};
 
    try {
        req.ApplePayPaymentRequest = JSON.parse('{"countryCode":"CA","currencyCode":"CAD","merchantCapabilities":["supports3DS"],"supportedNetworks":["visa","masterCard","amex"],"total":{"label":"' + (lang=='fr' ? 'Le montant total de votre don' : 'Your total donation amount') + '","type":"final","amount":"' + parseFloat(amount).toFixed(2).toString() + '"}}');
        req.ApplePayShippingContactUpdate = JSON.parse('{}');
        req.ApplePayPaymentAuthorizationResult = JSON.parse('{"status":0}');
    } catch(err) {
        alert("Your input does not seem to be a valid JSON object.");
        return;
    }

    // TODO: get all the pieces from the various inputs and glue them together into a single object for startApplePaySession() to use
    return req;
}

function startApplePaySession() {
    //alert('apple pay session started');
    if (typeof ApplePaySession === 'undefined') {
        alert("Your browser does not support Apple Pay. Please switch to a supported browser.");
    }

    var o = buildApplePayRequest();

    if (o["ApplePayPaymentRequest"] == null) {
        alert("Your input needs to include ApplePayPaymentRequest as a top level key.");
        return;
    }

    request = o["ApplePayPaymentRequest"];
    version = 3;


    session = new ApplePaySession(version, request);
    window.session = session;
    MonerisApplePay.setApplePaySession(session);

    /**
    * Payment Authorization
    * Here you receive the encrypted payment data. You would then send it
    * on to your payment provider for processing, and return an appropriate
    * status in session.completePayment()
    */
    session.onpaymentauthorized = (event) => {
        // Send payment for processing...
        const payment = event.payment;
        const paymentJson = JSON.stringify(payment);
    
    	j$('#spinner-overlay').show();
        var offset = Math.round( j$('#spinner').width() / 2 );
        j$('#spinner').css('left', ((window.innerWidth / 2) - offset) + 'px' ).show();
    
        Visualforce.remoting.Manager.invokeAction(remoteMethods.getAPtoken,
        	level == 'riding', document.getElementById('donatePage:form-payment:monerisOrderId').value, parseFloat(amount).toFixed(2).toString(), function(result, ev){
            var moneris_request = {
                ticket: result, 
                payment: event.payment
            }
            var transType = "preauth";
            if (typeof (window.MonerisApplePay[transType]) === "function") {
                window.MonerisApplePay[transType](moneris_request, function (receipt) {
                    //make call to your backend to check async response
                    //console.log(receipt);
                    /*if (receipt.receipt.ResponseCode
                        && !isNaN(receipt.receipt.ResponseCode)
                        && parseInt(receipt.receipt.ResponseCode) < 50) {*/
                        session.completePayment(ApplePaySession.STATUS_SUCCESS);
                        Visualforce.remoting.Manager.invokeAction(remoteMethods.processAPresponse,
                                                      receipt.receipt, cid, function(result, event){
                            var redirectUrl = '/trac_DonateSuccess?cust_id=' + cid;
                            if (getQSParameterByName('frame', window.location.href) == '1')                                                          
                                redirectUrl += '&frame=1';
                            if (window.location.href.indexOf('mcid') != -1)
                                redirectUrl += '&mcid=' + getQSParameterByName('mcid', window.location.href);
                    
                            redirectUrl += (term ? '/apex' + redirectUrl + '&term=1' : '');
                            window.location.href = redirectUrl;                             
                                                      });                                  
                    /*} else {
                        session.completePayment(ApplePaySession.STATUS_FAILURE);
                    } */
                }); 
           }
                  
       });
       
    }

    session.onvalidatemerchant = function onvalidatemerchant(event) {
        MonerisApplePay.validateSession(event.validationURL, function (successResponse) {
                session.completeMerchantValidation(successResponse);
        }, function (errorResponse) {

                alert('ERROR: ' + JSON.stringify(errorResponse));
        });

    };

    session.begin();
}