jQuery(function ($) {
	'use strict';
	
	// Function to check if browser is online
	function isOnline() {
		return navigator.onLine;
	}
	jQuery("#capture-button").off("click").on("click", function (e) { //To avoid duplicate handlers 
		if (jQuery('#capture-button').hasClass('disabled')) {
			jQuery('#capture-button').prop('disabled', true);
			return false;
		}
		// Check if browser is online before proceeding
		if (!isOnline()) {
			alert('Unable to capture payment: No internet connection detected. Please check your network connection and try again.');
			return false;
		}
		var capture_data = anet_capture_order;
		// get the order_id from the button tag
		var order_id = capture_data['order_id'];
		// get the product_id from the button tag
		var gateway_id = capture_data['gateway_id'];
		if (confirm(capture_data['capture_message'])) {
			try {
				$.ajax({
					type: 'POST',
				url: anet_capture_order.ajax_url,
					dataType: 'json',
					data: {
					action: anet_capture_order.capture_action,
					nonce: anet_capture_order.capture_nonce,
						order_id: order_id,
						gateway_id: gateway_id,
					},
					beforeSend: function () {
						jQuery("#woocommerce-order-items").block({
							message: null,
							overlayCSS: {
								background: "#fff",
								opacity: .6
							}
						});
					},
					success: function (data, textStatus, XMLHttpRequest) {
				if (anet_capture_order.anet_yes == data.success ||
					anet_capture_order.anet_val_one == data.success) {
							alert("Credit Card Capture of " + data.amount + " has been Approved. (Transaction ID " + data.trans_id + ")");
							jQuery("#woocommerce-order-items").unblock()
							location.reload();
						}
						else {
							alert(data.description);
							jQuery("#woocommerce-order-items").unblock()
						}
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						// Check if error is due to network disconnection
						if (!navigator.onLine || textStatus === 'timeout' || XMLHttpRequest.status === 0) {
							alert('Unable to capture payment: Network connection lost during the operation. Please check your internet connection and try again.');
						} else {
							alert(errorThrown);
						}
						jQuery("#woocommerce-order-items").unblock();
					},
					timeout: 30000 // 30 second timeout
				});
			} catch (exception) {
				alert(exception);
			}
		} else {
			e.preventDefault();
		}
	});
});
