(function ($) { 
	'use strict';
	
	const appId = ninjacheckout.application_id;
	const locationId = ninjacheckout.location_id;
	
    async function initializeCard(payments) {
		const card = await payments.card();
		await card.attach('#card-container_payment');
		return card;
    }
	
    // Call this function to send a payment token, buyer name, and other details
    // to the project server code so that a payment can be created with 
    // Payments API
	
    async function createPayment(token) {
		console.log('NONCE: ' + token);
		document.getElementById('card-nonce').value = token;
		jQuery('.squareform-container input[type=hidden]').val(token);
		// return true;
		jQuery( ".nf-form-cont .submit-container input[type=button]" ).removeAttr( "disabled" )
		jQuery( ".nf-form-cont .submit-container input[type=button]" ).trigger( "click" );
		
		/* jQuery('.nf-form-cont').each(function(){
			var form = jQuery(this).find('form');
			form.submit();
		}); */
		// jQuery('.nf-form-cont').find('.submit-container').submit();
		// jQuery('.nf-form-cont .submit-container input[type=button]').find('form').submit();
		// document.getElementsByClassName('mepr-square')[0].submit();
    }

    // This function tokenizes a payment method. 
    // The ‘error’ thrown from this async function denotes a failed tokenization,
    // which is due to buyer error (such as an expired card). It is up to the
    // developer to handle the error and provide the buyer the chance to fix
    // their mistakes.
	
    async function tokenize(paymentMethod) {
		const tokenResult = await paymentMethod.tokenize();
			console.log(tokenResult);
		if (tokenResult.status === 'OK') {
			return tokenResult.token;
		} else {
			let errorMessage = `Tokenization failed-status: ${tokenResult.status}`;
		if (tokenResult.errors) {
			errorMessage += ` and errors: ${JSON.stringify(
				tokenResult.errors
			)}`;
		}
		throw new Error(errorMessage);
		}
    }

    // Helper method for displaying the Payment Status on the screen.
    // status is either SUCCESS or FAILURE;
	
    function displayPaymentResults(status) {
		const statusContainer = document.getElementById(
			'payment-status-container'
		);
		if (status === 'SUCCESS') {
			statusContainer.classList.remove('is-failure');
			statusContainer.classList.add('is-success');
		} else {
			statusContainer.classList.remove('is-success');
			statusContainer.classList.add('is-failure');
		}

		statusContainer.style.visibility = 'visible';
    }

    document.addEventListener('DOMContentLoaded', async function () {
		if (!window.Square) {
			throw new Error('Square.js failed to load properly');
		}
		const payments = window.Square.payments(appId, locationId);
		//console.log('PAYMENTS:' + JSON.stringify(payments));
		let card;
		try {
			card = await initializeCard(payments);
		} catch (e) {
			console.error('Initializing Card failed', e);
			return;
		}

		async function handlePaymentMethodSubmission(event, paymentMethod) {
			console.log(paymentMethod);
			//debugger;
			
			
			event.preventDefault();

			try {
				// disable the submit button as we await tokenization and make a
				// payment request.
				jQuery('.ninja_square_container .messages').html("");
				jQuery('.nf-form-cont .submit-container input[type=button]').attr('disabled', 'disabled');
				// jQuery('.nf-form-cont .submit-container input[type=button]').attr('data-submit-payment', 'true');
				
				
				
				const token = await tokenize(paymentMethod);
				console.log('TK: ' + token);
				const paymentResults = await createPayment(token);
				displayPaymentResults('SUCCESS');

				console.debug('Payment Success', paymentResults);
			} catch (e) {
				var html = '';
				// handle errors                                
				html += '<div class="ninja_square_error">' + e.message + '</div>';
				
				jQuery('.nf-form-cont .submit-container input[type=button]').find('.ninja_square_container .messages').html(html);
				jQuery('.nf-form-cont .submit-container input[type=button]').removeAttr('disabled');
				// jQuery('.nf-form-cont .submit-container input[type=button]').removeAttr('data-submit-payment');
				displayPaymentResults('FAILURE');
				console.error(e.message);
			}
		}

		// const cardButton = document.getElementsByClassName(
			// 'ninja-forms-field'
		// )[0];
		
		jQuery('.nf-form-cont .submit-container input[type=submit]').on('click', async function(event){
		// jQuery('.nf-form-cont .submit-container input[type=button]').click( async function (event) {
			
			
		// cardButton.addEventListener('click', async function (event) {
			if(jQuery('#card-nonce').val()){
				console.log(jQuery('#card-nonce').val());
				return true;
			} else {
				console.log('handlePaymentMethodSubmission');
				await handlePaymentMethodSubmission(event, card);
			}
			
			
		});


    });
	
}(jQuery));