// Create and initialize a payment form object
var paymentForm;

// ---------------------------------------------------------------------------------------------------------------------

function init() {

	paymentForm = new SqPaymentForm({
  
		// Initialize the payment form elements
		applicationId: applicationId,
		locationId: locationId,
		autoBuild: false,
	  
		inputClass: 'sq-input',

		// Customize the CSS for SqPaymentForm iframe elements
		inputStyles: [{
			fontSize: '1.25em',
			fontFamily: 'sans-serif',
			color: 'white',
			backgroundColor: '#0f193c',
			fontWeight: 'normal',
			padding: '5px 10px'
		}],
	  
		applePay: false,
		googlePay: false,
		masterpass: false,

		// Initialize the credit card placeholders
		cardNumber: {
			elementId: 'sq-card-number',
			placeholder: '•••• •••• •••• ••••'
		},
		cvv: {
			elementId: 'sq-cvv',
			placeholder: 'CVV'
		},
		expirationDate: {
			elementId: 'sq-expiration-date',
			placeholder: 'MM/YY'
		},
		postalCode: {
			elementId: 'sq-postal-code'
		},
	  
		// SqPaymentForm callback functions
		callbacks: {
	  
			methodsSupported: function (methods) {
			},

			unsupportedBrowserDetected: function() {
				alert('UNSUPPORTED BROWSER');
			},
	
			cardNonceResponseReceived: function(errors, nonce, cardData, billingContact, shippingContact) {
				if (errors) {
					// Log errors from nonce generation to the Javascript console
					console.log("Encountered errors:");
					errors.forEach(function(error) {
						console.log('  ' + error.message);
					});
					return;
				}
				alert('Nonce received: ' + nonce); /* FOR TESTING ONLY */
				document.getElementById('card-nonce').value = nonce; // Assign the nonce value to the hidden form field
				document.getElementById('nonce-form').submit();	// POST the nonce form to the payment processing page
			}
		}
	});

	paymentForm.build();
	return paymentForm;
}

// ---------------------------------------------------------------------------------------------------------------------

// Called when 'Pay With Card' is clicked
function requestCardNonce(event) {
	event.preventDefault(); // Don't submit the form until SqPaymentForm returns with a nonce
	paymentForm.requestCardNonce(); // Request a nonce from the SqPaymentForm object
}

// ---------------------------------------------------------------------------------------------------------------------

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {  // `DOMContentLoaded` already fired
    init();
}