(function ($) {

	const EcoletFANCourierStandard          = 1;
	const EcoletStandardDPD                 = 42;
	const EcoletCargusStandard              = 4;
	const EcoletFANMarfaCourier             = 70;
	const EcoletInternationalImportZoneDPD1 = 71;
	const EcoletInternationalImportZoneDPD2 = 72;
	const EcoletInternationalImportZoneDPD3 = 73;
	const EcoletFANboxCourierAutomatul      = 59;
	const EcoletFANboxAutomatulAutomatul    = 60;
	const EcoletFANnboxAutomatulCourier     = 61;
	const EcoletBucuresti24                 = 53;
	const EcoletSamedayCourierAutomatul     = 41;
	const EcoletSamedayAutomatulAutomatul   = 63;
	const EcoletNextday                     = 8;
	const EcoletMetropolitan                = 55;
	const EcoletExpressRegionalDPD          = 57;
	const EcoletStandardGLS                 = 5;
	const EcoletExpressRegionalDPDCzechia   = 56;
	const EcoletExpressRegionalDPDBulgaria  = 12;
	const EcoletExpressRegionalDPDHungary   = 13;
	const EcoletExpressRegionalDPDGreece    = 14;
	const EcoletClassicInternationalDPD1    = 16;
	const EcoletClassicInternationalDPD2    = 17;
	const EcoletClassicInternationalDPD3    = 19;
	const EcoletDPDAutomatulCourier         = 44;
	const EcoletDPDCourierAutomatul         = 45;
	const EcoletOfficePointToPointDPD       = 46;
	const EcoletOfficePointToCourierDPD     = 47;
	const EcoletOfficeCourierToPointDPD     = 48;
	const EcoletEasyCollectLockerXLCargus   = 84;
	const EcoletEasyCollectCargus           = 49;
	const EcoletInternationalGLS1           = 64;
	const EcoletInternationalGLS2           = 65;
	const EcoletInternationalGLS3           = 66;
	const EcoletInternationalGLS4           = 67;
	const EcoletInternationalGLS5           = 68;
	const EcoletGLSCourierAutomatul         = 74;
	const EcoletGLSAutomatulAutomatul       = 75;
	const EcoletGLSAutomatulCourier         = 76;
	const EcoletStandardUPS1                = 86;
	const EcoletStandardUPS4                = 89;
	const EcoletStandardUPS2                = 87;
	const EcoletStandardUPS3                = 88;
	const EcoletExpressUPS1                 = 91;
	const EcoletExpressUPS2                 = 92;
	const EcoletExpressUPS3                 = 93;
	const EcoletExpressUPS4                 = 94;
	const EcoletImportStandardUPS2          = 99;
	const EcoletImportStandardUPS1          = 100;
	const EcoletImportStandardUPS3          = 101;
	const EcoletImportStandardUPS4          = 102;
	const EcoletImportExpressUPS1           = 103;
	const EcoletImportExpressUPS2           = 104;
	const EcoletImportExpressUPS3           = 105;
	const EcoletImportExpressUPS4           = 106;
	const EcoletImportStandardMultipackUPS1 = 107;
	const EcoletImportStandardMultipackUPS2 = 108;
	const EcoletImportStandardMultipackUPS3 = 109;
	const EcoletImportStandardMultipackUPS4 = 110;
	const EcoletStandardMultipackUPS1       = 95;
	const EcoletStandardMultipackUPS2       = 96;
	const EcoletStandardMultipackUPS3       = 97;
	const EcoletStandardMultipackUPS4       = 98;
	const EcoletWorldwideDHL1               = 78;
	const EcoletWorldwideDHL2               = 79;
	const EcoletWorldwideDHL3               = 80;
	const EcoletEasyCollectLockerSCargus    = 81;
	const EcoletEasyCollectLockerMCargus    = 82;
	const EcoletEasyCollectLockerLCargus    = 83;
	const EcoletStadard30PlusCargus         = 85;
	const EcoletPostaRomanaStandard         = 90;

	function getNextBusinessDay(date) {
		const result = new Date( date );
		result.setDate( result.getDate() + 1 );

		// Keep adding days until we get a business day (Mon-Fri).
		while (result.getDay() === 0 || result.getDay() === 6) {
			result.setDate( result.getDate() + 1 );
		}

		return result;
	}

	function alsendo_connect_add_border_to_selected_service() {
		const elements = document.querySelectorAll( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']" );
		if (elements) {

			elements.forEach(
				function (element) {
					if (element.checked) {
						is_any_element_checked = true;
						element.closest( ".apaczka-calculate-item" ).classList.toggle( "selected" );
						element.setAttribute( "checked", "checked" );
					}
					let radioInputs = document.querySelectorAll( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']" );
					radioInputs.forEach(
						function (radioElement) {
							if (radioElement.checked === false) {
								radioElement.closest( ".apaczka-calculate-item" ).classList.remove( "selected" );
								radioElement.removeAttribute( "checked" );
							}
						}
					);
				}
			);

		}
	}

	function formatJSON(obj, indent = 0) {
		const indentStr = '  '.repeat( indent );
		let output      = '';

		if (Array.isArray( obj )) {
			output += 'array:' + obj.length + ' [▼\n';
			obj.forEach(
				function (item, index) {
					output += indentStr + '  ' + index + ' => ' + formatJSON( item, indent + 1 ) + '\n';
				}
			);
			output += indentStr + ']';
		} else if (typeof obj === 'object' && obj !== null) {
			output += 'array:' + Object.keys( obj ).length + ' [▼\n';
			Object.entries( obj ).forEach(
				function (entry) {
					let key   = entry[0];
					let value = entry[1];
					output   += indentStr + '  "' + key + '" => ' + formatJSON( value, indent + 1 ) + '\n';
				}
			);
			output += indentStr + ']';
		} else {
			output += JSON.stringify( obj );
		}

		return output;
	}

	function alsendo_process_api_response(object) {
		let api_response = '';
		if (typeof object === 'string') {
			api_response = object;
		} else if (Array.isArray( object )) {
			let errorsString = '\n\n';
			object.forEach(
				function (errorObj) {
					if (errorObj.field && errorObj.message) {
						errorsString += errorObj.field + ' => ' + errorObj.message + '\n';
					}
				}
			);
			api_response += errorsString;
		} else {
			if (object.status_code) {
				api_response += 'API response code: ' + object.status_code + '\n\n';
			}
			if (object.message) {
				api_response += object.message + '\n\n';
			}
			// Handle errors, whether they're in object.errors or directly in the object.
			let errors = object.errors || object;
			if (typeof errors === 'object' && ! Array.isArray( errors )) {
				let errorsString = '\n\n';
				// Iterate through each error.
				for (let key in errors) {
					if (Object.prototype.hasOwnProperty.call( errors, key )) {
						let errorValue = errors[key];
						if (Array.isArray( errorValue )) {
							errorValue.forEach(
								function (error) {
									errorsString += key + ' => ' + error + '\n';
								}
							);
						} else if (typeof errorValue === 'string') {
							errorsString += key + ' => ' + errorValue + '\n';
						}
					}
				}
				api_response += errorsString;
			}
		}

		api_response = api_response.trim();
		return api_response;
	}

	function changeShippingMethodTriggers(method) {

		let api_type = alsendo_order_metabox.api_type;
	}

	function createOperator(operatorId, operatorName) {
		operatorName = operatorName.toUpperCase();
		return {
			operator: operatorName,
			price: null
		};
	}

	function fillSenderFormByTemplate(templateSlug) {
		console.log( 'templateSlug' );
		console.log( templateSlug );
		let apaczka_sender_templates = alsendo_order_metabox.sender_templates;
		for (const [key, value] of Object.entries( apaczka_sender_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					key2_new = key2.replace( "alsendo_connect_settings_general_sender_", "" );
					$( '#' + '_apaczka\\[sender\\]\\[' + key2_new + '\\]' ).val( value2 )
				}
			}
		}
	}

	function fillPackagePropertiesFormByTemplate(templateSlug) {

		let apaczka_package_properties_templates = alsendo_order_metabox.package_properties_templates;

		let maybe_custom_package_contents = false;
		let custom_package_contents_value = '';
		let package_contents_value        = '';
		let package_contents_tag          = '';
		let package_contents_disabled     = true;

        let shipping_method_option = '';
		
		let declare_content_as_order = alsendo_order_metabox.declare_content_as_order;
		console.log('declare_content_as_order : ' + declare_content_as_order);

		for (const [key, value] of Object.entries( apaczka_package_properties_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					key2_new = key2.replace( "alsendo_connect_settings_general_", "" );

                    //console.log('Ecolet key2_new: ' + key2_new);
                    //console.log('Ecolet value2: ' + value2);


                    if ('shipping_method' === key2_new) {
                        shipping_method_option = value2;
                    }
					
					if ('declared_content' === key2_new) {
						if( declare_content_as_order ) {
							continue;
						}
					}


					if ('custom_text_content' === key2_new) {
						custom_package_contents_value = value2;
					}
					if ('package_contents' === key2_new) {
						package_contents_tag = value2;
						if ('custom_text' === value2) {
							maybe_custom_package_contents = true;
							package_contents_disabled     = false;
						}
						if ('order_id' === value2) {
							package_contents_value = alsendo_order_metabox.text_contents_order_id;
						}
						if ('product_id' === value2) {
							package_contents_value = alsendo_order_metabox.text_contents_product_id;
						}
						if ('product_name' === value2) {
							package_contents_value = alsendo_order_metabox.text_contents_product_name;
						}
					}

					$( '#' + '_apaczka\\[package_properties\\]\\[' + key2_new + '\\]' ).val( value2 );


				}
			}
		}

        console.log('Ecolet shipping_method_option: ' + shipping_method_option );

        if ( shipping_method_option.startsWith( 'SELF_' ) || shipping_method_option.startsWith( 'self_' ) ) {

            console.log('Ecolet shipping_method_option: set as SELF' );

            let shipping_method_select = $( '#' + '_apaczka\\[package_properties\\]\\[shipping_method\\]' );
            var options = shipping_method_select.find('option');
            console.log(options );

            for (var i = 0; i < options.length; i++) {
                if (options[i].value && options[i].value !== 'COURIER') {
                    shipping_option_self_value = options[i].value;
                    break;
                }
            }
            console.log('Ecolet shipping_option_self_value: ' + shipping_option_self_value );

            $( '#' + '_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val( shipping_option_self_value );

        } else {
            //$( '#' + '_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val( 'COURIER' );
        }

		if (maybe_custom_package_contents) {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).val( custom_package_contents_value );
		} else {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).val( package_contents_value );
		}

		if (package_contents_disabled) {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', true );
			let hidden_input_tag_content = '<input type="hidden" name="_apaczka[package_properties][package_contents_tag]" id="_apaczka[package_properties][package_contents_tag]" value="' + package_contents_tag + '">';
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).append( hidden_input_tag_content );
		} else {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' ).each(
				function (ind, elem) {
					jQuery( elem ).remove();
				}
			);

			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', false );
		}

		$( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).trigger( 'change' );

	}

	function serviceIdToApmSupplierId(serviceId) {

		switch (serviceId) {
			case 14:
			case 15:
			case 16:
				return 'UPS';
			case 20:
			case 23:
			case 26:
			case 29:
				return 'DPD';
			case 50:
			case 53:
				return 'RUCH';
			case 40:
			case 41:
			case 45:
			case 46:
				return 'INPOST';
			case 163:
				return 'POCZTA';
			case 64:
				return 'POCZTA';
			case 66:
				return 'POCZTA';
			case 162:
				return 'POCZTA';
			case 86:
				return 'DHL';
			case 68:
				return 'POCZTA';
			default:
				return null
		}

	}

	function serviceIdToApmSupplierIdEcolet(serviceId) {
		switch (serviceId) {
			case 59:
			case 60:
				return 'FAN_COURIER';
			case 43:
			case 45:
			case 46:
			case 48:
				return 'DPD';
			case 41:
			case 8:
			case 63:
				return 'SAMEDAY';
			case 84:
			case 49:
			case 81:
			case 82:
			case 83:
			case 85:
				return 'CARGUS';
			case 74:
			case 75:
				return 'GLS';
			default:
				return null;
		}
	}

	function is_cod_amount_defined() {
		return parseInt( $( '#_apaczka\\[additional_options\\]\\[cod_amount\\]' ).val() ) > 0
	}

	function alsendo_debug_print_r(obj) {
		function inpost_intl_format_value(value) {
			if (typeof value === 'string') {
				return '"' + value + '"';
			}
			if (Array.isArray( value )) {
				return 'Array\n' + alsendo_debug_format_object( value );
			}
			if (typeof value === 'object' && value !== null) {
				return alsendo_debug_format_object( value );
			}
			return value;
		}

		function alsendo_debug_format_object(obj) {
			let result = '(\n';
			for (let key in obj) {
				if (obj.hasOwnProperty( key )) {
					result += '    [' + key + '] => ' + inpost_intl_format_value( obj[key] ) + '\n';
				}
			}
			result += ')';
			return result;
		}

		return alsendo_debug_format_object( obj );
	}

	function alsendo_process_api_response(object) {
		let api_response = '';

		// Check if object is a string.
		if (typeof object === 'string') {
			api_response = object;
		} else if (Array.isArray( object )) {
			let errorsString = '\n\n';
			object.forEach(
				function (errorObj) {
					if (errorObj.field && errorObj.message) {
						errorsString += errorObj.field + ' => ' + errorObj.message + '\n';
					}
				}
			);
			api_response += errorsString;
		} else {
			if (object.status_code) {
				api_response += 'API response code: ' + object.status_code + '\n\n';
			}
			if (object.message) {
				api_response += object.message + '\n\n';
			}
			// Handle errors, whether they're in object.errors or directly in the object.
			let errors = object.errors || object;
			if (typeof errors === 'object' && ! Array.isArray( errors )) {
				let errorsString = '\n\n';
				// Iterate through each error.
				for (let key in errors) {
					if (Object.prototype.hasOwnProperty.call( errors, key )) {
						let errorValue = errors[key];
						if (Array.isArray( errorValue )) {
							errorValue.forEach(
								function (error) {
									errorsString += key + ' => ' + error + '\n';
								}
							);
						} else if (typeof errorValue === 'string') {
							errorsString += key + ' => ' + errorValue + '\n';
						}
					}
				}
				api_response += errorsString;
			}
		}

		api_response = api_response.trim();
		return api_response;
	}

	/**
	 * /**
	 *  * UPS Access Point (service id: 14,15, 16)
	 * DPD Pickup (service id: 23, 26)
	 * ORLEN Paczka  (service id: 50)
	 * Paczkomaty InPost  (service id: 41)
	 * Poczta Polska Ekspres24 Punkty  (service id: 163)
	 * DHL POP  (service id: 86)
	 * Poczta Polska Kurier48 Punkty  (service id: 162)
	 * DHL_PARCEL
	 * DPD
	 * INPOST
	 * POCZTA
	 * UPS
	 */
	function handleCalculateDynamicFields(selectedService) {

		console.log( 'handleCalculateDynamicFields: selectedService' );
		console.log( selectedService );

		let shipping_method = $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val();
		let debug           = serviceIdToApmSupplierId( selectedService );
		console.log( 'serviceIdToApmSupplierId' );
		console.log( debug );

		let api_type = alsendo_order_metabox.api_type;

		$( '#apaczka_delivery_point_id_wrapper' ).addClass( 'apaczka-hidden' );

		/*if (serviceIdToApmSupplierIdEcolet(selectedService) !== null) {
			$('#apaczka_delivery_point_id_wrapper').removeClass('apaczka-hidden');
		} else {
			$('#apaczka_delivery_point_id_wrapper').addClass('apaczka-hidden');
		}*/

		let method = null;

		if (selectedService === EcoletStandardDPD
			|| selectedService === EcoletInternationalImportZoneDPD1
			|| selectedService === EcoletInternationalImportZoneDPD2
			|| selectedService === EcoletInternationalImportZoneDPD3
			|| selectedService === EcoletExpressRegionalDPD
			|| selectedService === EcoletExpressRegionalDPDCzechia
			|| selectedService === EcoletExpressRegionalDPDBulgaria
			|| selectedService === EcoletExpressRegionalDPDHungary
			|| selectedService === EcoletExpressRegionalDPDGreece
			|| selectedService === EcoletClassicInternationalDPD1
			|| selectedService === EcoletClassicInternationalDPD2
			|| selectedService === EcoletClassicInternationalDPD3
			|| selectedService === EcoletOfficePointToPointDPD
			|| selectedService === EcoletOfficePointToCourierDPD
			|| selectedService === EcoletOfficeCourierToPointDPD

		) {
			method = 'dpd';
		}

		if (selectedService === EcoletFANCourierStandard
			|| selectedService === EcoletFANMarfaCourier
			|| selectedService === EcoletFANboxCourierAutomatul
			|| selectedService === EcoletFANboxAutomatulAutomatul
			|| selectedService === EcoletFANnboxAutomatulCourier

		) {
			method = 'fan_courier';
		}

		if (selectedService === EcoletCargusStandard
			|| selectedService === EcoletEasyCollectLockerXLCargus
			|| selectedService === EcoletEasyCollectCargus
			|| selectedService === EcoletEasyCollectLockerSCargus
			|| selectedService === EcoletEasyCollectLockerMCargus
			|| selectedService === EcoletEasyCollectLockerLCargus
			|| selectedService === EcoletStadard30PlusCargus

		) {
			method = 'cargus';
		}

		if (selectedService === EcoletSamedayCourierAutomatul
			|| selectedService === EcoletSamedayAutomatulAutomatul
			|| selectedService === EcoletNextday
		) {
			method = 'sameday';
		}

		if (selectedService === EcoletStandardGLS
			|| selectedService === EcoletInternationalGLS1
			|| selectedService === EcoletInternationalGLS2
			|| selectedService === EcoletInternationalGLS3
			|| selectedService === EcoletInternationalGLS4
			|| selectedService === EcoletInternationalGLS5
			|| selectedService === EcoletGLSCourierAutomatul
			|| selectedService === EcoletGLSAutomatulAutomatul
			|| selectedService === EcoletGLSAutomatulCourier
		) {
			method = 'gls';
		}

		if (selectedService === EcoletStandardUPS1
			|| selectedService === EcoletStandardUPS4
			|| selectedService === EcoletStandardUPS2
			|| selectedService === EcoletStandardUPS3
			|| selectedService === EcoletExpressUPS1
			|| selectedService === EcoletExpressUPS2
			|| selectedService === EcoletExpressUPS3
			|| selectedService === EcoletExpressUPS4
			|| selectedService === EcoletImportStandardUPS2
			|| selectedService === EcoletImportStandardUPS1
			|| selectedService === EcoletImportStandardUPS3
			|| selectedService === EcoletImportStandardUPS4
			|| selectedService === EcoletImportExpressUPS1
			|| selectedService === EcoletImportExpressUPS2
			|| selectedService === EcoletImportExpressUPS3
			|| selectedService === EcoletImportExpressUPS4
			|| selectedService === EcoletImportStandardMultipackUPS1
			|| selectedService === EcoletImportStandardMultipackUPS2
			|| selectedService === EcoletImportStandardMultipackUPS3
			|| selectedService === EcoletImportStandardMultipackUPS4
			|| selectedService === EcoletStandardMultipackUPS1
			|| selectedService === EcoletStandardMultipackUPS2
			|| selectedService === EcoletStandardMultipackUPS3
			|| selectedService === EcoletStandardMultipackUPS4
		) {
			method = 'ups';
		}

		console.log( 'Alsendo connect - selectedService: ' + selectedService );
		console.log( 'api_type: ' + api_type );
		console.log( 'selected_method: ' + method );
		console.log( 'handleCalculateDynamicFields: shipping_method ' + shipping_method );

		// Hide dispatch point field forever.
		$( '#apaczka_delivery_point_id_wrapper' ).addClass( 'apaczka-hidden' );

		if (shipping_method.startsWith( 'SELF_' ) || shipping_method.startsWith( 'self_' )) {

			// cargus_easy_collect.
			// easy_collect_locker_m.
			// easy_collect_locker_s.
			// easy_collect_locker_l.
			// easy_collect_locker_xl.
			if (49 === selectedService
				|| 81 === selectedService
				|| 82 === selectedService
				|| 83 === selectedService
				|| 84 === selectedService
			) {

				$( '#dispath_point_cargus_wrapper' ).removeClass( 'apaczka-hidden' );

				$( '#dispath_point_gls_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_sameday_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_fancourier_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );

				$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka\\[package_properties\\]\\[dispath_point_cargus\\]' ).val() );
			}

			// GLS locker_automat_automat.
			if (75 === selectedService
			) {

				$( '#dispath_point_gls_wrapper' ).removeClass( 'apaczka-hidden' );

				$( '#dispath_point_cargus_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_sameday_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_fancourier_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );

				$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka\\[package_properties\\]\\[dispath_point_gls\\]' ).val() );
			}

			// FAN fan_courier_locker_to_locker.
			if (60 === selectedService
			) {

				$( '#dispath_point_fancourier_wrapper' ).removeClass( 'apaczka-hidden' );

				$( '#dispath_point_cargus_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_sameday_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_gls_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );

				$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka\\[package_properties\\]\\[dispath_point_fancourier\\]' ).val() );
			}

			// SAMEDAY sameday_locker_automatul_automatul.
			if (63 === selectedService
			) {

				$( '#dispath_point_sameday_wrapper' ).removeClass( 'apaczka-hidden' );

				$( '#dispath_point_cargus_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_gls_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_fancourier_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );

				$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka\\[package_properties\\]\\[dispath_point_sameday\\]' ).val() );
			}

			// DPD dpd_automat_locker_to_locker.
			if (43 === selectedService || 46 === selectedService
			) {

				console.log( 'show DPD default dispatch point' );

				$( '#dispath_point_dpd_wrapper' ).removeClass( 'apaczka-hidden' );

				$( '#dispath_point_cargus_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_gls_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_fancourier_wrapper' ).addClass( 'apaczka-hidden' );
				$( '#dispath_point_sameday_wrapper' ).addClass( 'apaczka-hidden' );

				let sender_dispatch_point_dpd = $( '#_apaczka\\[package_properties\\]\\[dispath_point_dpd\\]' ).val();
				console.log( 'default_dpd_point_from_settings:' );
				console.log( sender_dispatch_point_dpd );

				$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( sender_dispatch_point_dpd );
			}
		}

	}

	function alsendoMtaboxChangeParcelTypeActions(type) {

		let apaczka_parcel_length = $( '#_apaczka\\[package_properties\\]\\[package_length\\]' );
		let apaczka_parcel_width  = $( '#_apaczka\\[package_properties\\]\\[package_width\\]' );
		let apaczka_parcel_height = $( '#_apaczka\\[package_properties\\]\\[package_height\\]' );

		switch (type) {
			case 'europalette':
				apaczka_parcel_length.val( 120 );
				apaczka_parcel_width.val( 80 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 );
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			case 'palette_60x80':
				apaczka_parcel_width.val( 60 );
				apaczka_parcel_length.val( 80 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 )
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			case 'palette_120x100':
				apaczka_parcel_width.val( 100 );
				apaczka_parcel_length.val( 120 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 )
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			case 'palette_120x120':
				apaczka_parcel_length.val( 120 );
				apaczka_parcel_width.val( 120 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 )
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			default:
				apaczka_parcel_length.prop( 'readonly', false );
				apaczka_parcel_width.prop( 'readonly', false );
				apaczka_parcel_height.removeAttr( 'max' )
		}
	}

	function alsendo_connect_maybe_need_recalculate() {
		//console.log( 'alsendo_connect_maybe_need_recalculate' );
		$( '#alsendo-recalc-notice' ).remove();
		let send_parcel_button = $( '#apaczka_send' );
		if (typeof send_parcel_button != 'undefined' && send_parcel_button !== null) {
			if ($( '#apaczka_send' ).css( 'display' ) === 'block') {
				let notice = '<span id="alsendo-recalc-notice"><b><pre>' + alsendo_order_metabox.recalc_notice + '</pre></b></span>';
				$( "#apaczka_send" ).prop( "disabled", true );
				$( "#apaczka_send" ).after( notice );

			}
		}
	}

	$( document ).ready(
		function () {
			$( 'body #woocommerce-order-downloads .buttons .select2-container' ).css( "width", "100% !important" );
		}
	);

	$( document ).ready(
		function () {

			console.log( 'alsendo-connect-order-metabox.js' );
			let api_type = alsendo_order_metabox.api_type;

			(function hideEcoletAdditionalAddressFieldsInOrderAddressBlock() {
				const labelsToHide = [
					'Street number',
					'House block',
					'House entrance',
					'Floor',
					'Flat',
					// ro_RO labels.
					'Numărul străzii',
					'Cladirea',
					'Blocul',
					'Intrarea',
					'Etajul',
					'Apartamentul',
				];

				// Hide <p> blocks with our additional Ecolet fields to keep order address compact.
				$( '.address p strong' ).each(
					function () {
						const $strong = $( this );
						const rawText = ( $strong.text() || '' ).trim();
						const label = rawText.replace( /:\s*$/, '' ); // "Street number:" -> "Street number"

						if ( labelsToHide.indexOf( label ) === -1 ) {
							return;
						}

						$strong.closest( 'p' ).hide();
					}
				);
			})();

			let parcelCounter       = 0;
			let is_order_caclulated = $( '#alsendo_connect_calculated' ).val();

			let selected_sender_template = alsendo_order_metabox.selected_sender_template;

			$( '#alsendo_connect' ).on(
				'keyup',
				'input',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[sender\\]\\[is_residential\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[pickup_hour_from\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[pickup_hour_to\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[pickup_date\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);

			let dispatch_point_map_country_param = 'RO';

			// $('#alsendo_connect_load_package_properties_settings_btn').trigger('click');
			//let selectedTemplateSlug = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).val();
			//fillPackagePropertiesFormByTemplate( selectedTemplateSlug );

			const fieldsToHideShow = [
				'._apaczka\\[package_properties\\]\\[package_length\\]_field',
				'._apaczka\\[package_properties\\]\\[package_width\\]_field',
				'._apaczka\\[package_properties\\]\\[package_height\\]_field',
				'._apaczka\\[package_properties\\]\\[package_weight\\]_field',
				'._apaczka\\[package_properties\\]\\[is_nstd\\]_field'
			];

			let shipment_type = $( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).val();

			if ('envelope' === shipment_type) {
				$( '#ecolet_add_parcel' ).css( 'display', 'none' );
				$( '#ecolet_add_parcel' ).prev( 'label' ).css( 'display', 'none' );

				fieldsToHideShow.forEach(
					function (fieldSelector) {
						const originalField = $( fieldSelector );
						if (originalField.length > 0) {
							$( originalField ).css( 'display', 'none' );
						}
					}
				);

			}

			// if ( '1' !== is_order_caclulated ) {
			fillSenderFormByTemplate( selected_sender_template );
			fillPackagePropertiesFormByTemplate( alsendo_order_metabox.selected_package_template );
			// }

			let iban_order                = $( 'input[name="_apaczka[sender][bank_account_number]"]' );
			let sender_phone_number_order = $( 'input[name="_apaczka[sender][phone]"]' );

			let order_metabox_parcel_type_handle = $( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' );

			if (typeof order_metabox_parcel_type_handle != 'undefined' && order_metabox_parcel_type_handle !== null) {
				alsendoMtaboxChangeParcelTypeActions( order_metabox_parcel_type_handle.val() );
				order_metabox_parcel_type_handle.change(
					function (e) {
						alsendoMtaboxChangeParcelTypeActions( $( this ).val() );

						const fieldsToHideShow = [
							'._apaczka\\[package_properties\\]\\[package_length\\]_field',
							'._apaczka\\[package_properties\\]\\[package_width\\]_field',
							'._apaczka\\[package_properties\\]\\[package_height\\]_field',
							'._apaczka\\[package_properties\\]\\[package_weight\\]_field',
							'._apaczka\\[package_properties\\]\\[is_nstd\\]_field'
						];

						if ('envelope' === $( this ).val()) {
							$( '#ecolet_add_parcel' ).css( 'display', 'none' );
							$( '#ecolet_add_parcel' ).prev( 'label' ).css( 'display', 'none' );

							fieldsToHideShow.forEach(
								function (fieldSelector) {
									const originalField = $( fieldSelector );
									if (originalField.length > 0) {
										$( originalField ).css( 'display', 'none' );
									}
								}
							);

						} else {
							$( '#ecolet_add_parcel' ).css( 'display', 'block' );
							fieldsToHideShow.forEach(
								function (fieldSelector) {
									const originalField = $( fieldSelector );
									if (originalField.length > 0) {
										$( originalField ).css( 'display', 'block' );
									}
								}
							);
						}

					}
				);
			}

			// let apaczka_calculate_selected_service = 0.
			let apaczka_calculate_selected_service        = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
			let apaczka_dispath_point_handler_to_validate = false;

			let map_country_code          = 'PL';
			let sender_country_code_field = $( '#_apaczka\\[sender\\]\\[country\\]' );
			if (typeof sender_country_code_field != 'undefined' && sender_country_code_field !== null) {
				let sender_country_code = $( sender_country_code_field ).val();
				if (typeof sender_country_code != 'undefined' && sender_country_code !== null) {
					map_country_code = sender_country_code;
				}
			}

			// console.log('map_country_code');
			// console.log(map_country_code);

			$( "#apaczka_calculate_radio > .apaczka-calculate-item > input[type='radio']" ).change(
				function (e) {
					console.log( "change", e );
				}
			);

			$( '#alsendo_connect_calculate_price_btn' ).click(
				function (e) {
					let observer = new MutationObserver(
						function (mutations) {
							if ($( "#apaczka_calculate_radio" ).length) {
								let selected_tile = false;
								$( '.apaczka-calculate-item' ).each(
									function (ind, element) {
										if ($( element ).hasClass( 'selected' )) {
											selected_tile                      = true;
											apaczka_calculate_selected_service = $( element ).attr( 'data-service_id' );
											handleCalculateDynamicFields( parseInt( apaczka_calculate_selected_service ) );
										}
									}
								);
								if ( ! selected_tile) {
									$( "#apaczka_calculate_radio > .apaczka-calculate-item:first-child" ).click();
									const valOfFirstItem = $( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']:checked" ).val();
									console.log( "valOfFirstItem", valOfFirstItem );
									apaczka_calculate_selected_service = valOfFirstItem;
									handleCalculateDynamicFields( parseInt( valOfFirstItem ) );
								}
								observer.disconnect();
							}
						}
					);
					// Start observing.
					observer.observe(
						document.body,
						{
							childList: true,
							subtree: true
						}
					);
				}
			);

			$( "#ecolet_add_parcel" ).click(
				function (e) {
					e.preventDefault();

					if (parcelCounter >= 9) {
						alert( alsendo_order_metabox.text_max_parcels );
						return false;
					}

					parcelCounter++;
					const wrapId = 'parcel_wrap_' + parcelCounter;

					// Get the default wrapper to clone fields from.
					const ecolet_default_parcel = $( '.ecolet-cloned-fields-wrapper.default-wrapper' );

					if (typeof ecolet_default_parcel !== 'undefined' && ecolet_default_parcel.length > 0) {
						// Fields to clone (search only within the default wrapper).
						const fieldsToClone = [
							'._apaczka\\[package_properties\\]\\[package_length\\]_field',
							'._apaczka\\[package_properties\\]\\[package_width\\]_field',
							'._apaczka\\[package_properties\\]\\[package_height\\]_field',
							'._apaczka\\[package_properties\\]\\[package_weight\\]_field',
							'._apaczka\\[package_properties\\]\\[package_contents\\]_field',
							'._apaczka\\[package_properties\\]\\[declared_content\\]_field'
						];

						let class_name = 'ecolet-additional-parcel_' + parcelCounter;

						const wrapper = $(
							'<div>',
							{
								'class': 'ecolet-cloned-fields-wrapper',
								'data-wrap-id': wrapId
							}
						).append(
							$(
								'<span>',
								{
									'class': class_name,
									'text': alsendo_order_metabox.text_additional_parcel
								}
							)
						);

						// Clone each field from the default wrapper only.
						fieldsToClone.forEach(
							function (fieldSelector) {
								const originalField = ecolet_default_parcel.find( fieldSelector );
								if (originalField.length > 0) {
									const clonedField = originalField.clone();

									// Update IDs and names to make them unique.
									clonedField.find( 'input, select' ).each(
										function () {
											const originalId   = $( this ).attr( 'id' );
											const originalName = $( this ).attr( 'name' );

											if ('_apaczka[package_properties][package_contents_tag]' === originalId) {
												return;
											}

											if (originalId) {
												//console.log('originalId');
												//console.log(originalId);
												$( this ).attr( 'id', originalId + '_' + parcelCounter );
											}

											if ('_apaczka[package_properties][package_contents]' === originalId) {
												console.log( 'un-disable' );
												$( this ).prop( 'disabled', false );
											}

											if (originalName) {
												// Update name to include parcel index.
												const newName = originalName.replace(
													/_apaczka\[package_properties\]/,
													'_apaczka[package_properties][' + parcelCounter + ']'
												);
												$( this ).attr( 'name', newName );
											}

											// Clear values for inputs.
											if ($( this ).is( 'input[type="number"]' ) || $( this ).is( 'input[type="text"]' )) {
												$( this ).val( '' );
											}
										}
									);

									// Update label for attribute.
									clonedField.find( 'label' ).each(
										function () {
											const originalFor = $( this ).attr( 'for' );
											if (originalFor) {
												$( this ).attr( 'for', originalFor + '_' + parcelCounter );
											}
										}
									);

									wrapper.append( clonedField );
								}
							}
						);

						// Create remove button.
						const removeButton = $(
							'<button>',
							{
								'class': 'ecolet_remove_parcel button-secondary',
								'data-wrap-id': wrapId,
								'text': alsendo_order_metabox.text_remove_parcel
							}
						);

						wrapper.append( removeButton );

						// Insert before the add parcel button.
						$( '.ecolet_add_parcel_field' ).before( wrapper );
					}

				}
			);

			// Remove parcel functionality (using event delegation).
			$( document ).on(
				'click',
				'.ecolet_remove_parcel',
				function () {
					const wrapId = $( this ).data( 'wrap-id' );
					$( '[data-wrap-id="' + wrapId + '"]' ).remove();
					parcelCounter--;
				}
			);

			$( "#alsendo_connect_load_sender_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#_apaczka\\[sender_template\\]' ).val();
					fillSenderFormByTemplate( selectedTemplateSlug );
					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( "#alsendo_connect_load_package_properties_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).val();
                    console.log('Ecolet selectedTemplateSlug: ' + selectedTemplateSlug);
					fillPackagePropertiesFormByTemplate( selectedTemplateSlug );
					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).change(
				function (e) {
					if ($( '#apaczka-calculate-wrapper' ).html() !== '') {
						$( '#apaczka_calculate_price_btn' ).click();
						return false;
					}
				}
			);

			$( ".apaczka_calculate_price" ).click(
				function () {
					let shipment_type = $( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).val();

					$( '#alsendo-recalc-notice' ).remove();

					if ('ecolet' !== api_type && 'envelope' !== shipment_type) {
						if ( ! $( this ).closest( "form" )[0].checkValidity()) {
							$( this ).closest( "form" )[0].reportValidity();
							return false;
						}
					}

					$( 'div' ).each(
						function () {
							let id = $( this ).attr( 'id' );
							if (id && id.startsWith( 'dispath_point_' )) {
								$( this ).addClass( 'apaczka-hidden' );
							}
							if (id && id.startsWith( 'apaczka_delivery_point_id_wrapper' )) {
								$( this ).addClass( 'apaczka-hidden' );
							}
						}
					);

					$( "#apaczka-calculate-wrapper" ).html( '' );
					$( this ).parent().find( ".spinner_courier" ).hide();
					$( this ).parent().find( ".spinner" ).hide();

					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'calculate',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						alsendo_connect_calculate: {
							sender: {},
							receiver: {},
							package_properties: {},
							additional_options: {},
						}
					};

					let package_properties      = $( 'input[id^="_apaczka[package_properties]"], select[id^="_apaczka[package_properties]"]' );
					let sender                  = $( 'input[id^="_apaczka[sender]"]' );
					let receiver                = $( 'input[id^="_apaczka[receiver]"]' );
					let additional_options      = $( 'input[id^="_apaczka[additional_options]"]' );
					let is_residential_sender   = $( 'select[id="_apaczka[sender][is_residential]"]' ).val();
					let is_residential_receiver = $( 'select[id="_apaczka[receiver][is_residential]"]' ).val();

					sender.each(
						function () {
							data.alsendo_connect_calculate.sender[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_calculate.sender['is_residential'] = is_residential_sender;

					receiver.each(
						function () {
							data.alsendo_connect_calculate.receiver[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_calculate.receiver['is_residential'] = is_residential_receiver;

					let parcelGroups = {};
					let parcels      = [];

					let contents_tag_value = false;
					let contents_tag       = '';

					package_properties.each(
						function (index, element) {
							let key          = $( this ).data( 'key' );
							let parcel_value = $( this ).val();
							let name         = $( this ).attr( 'name' );

							// if tag used as package contents.
							if ('package_contents' === key) {
								let may_be_contents_tag_used = $( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' );
								if (typeof may_be_contents_tag_used != 'undefined' && may_be_contents_tag_used !== null) {
									contents_tag = $( may_be_contents_tag_used ).val();
									if (typeof contents_tag != 'undefined' && contents_tag !== null) {
										contents_tag_value = true;
									}
								}
							}

							if (key && ['package_length', 'package_width', 'package_height', 'package_weight', 'package_contents', 'declared_content'].includes( key )) {
								// Extract parcel index from name.
								let parcelIndex = 0; // default for original fields
								let matches     = name.match( /_apaczka\[package_properties\]\[(\d+)\]/ );
								if (matches) {
									parcelIndex = parseInt( matches[1] );
								}

								// Initialize parcel group if not exists.
								if ( ! parcelGroups[parcelIndex]) {
									parcelGroups[parcelIndex] = {};
								}

								// Add field to parcel group.
								parcelGroups[parcelIndex][key] = parcel_value;
								if (contents_tag_value) {
									if (0 === parcelIndex) {
										parcelGroups[parcelIndex]['contents_tag'] = contents_tag;
									}
								}

							} else if (key) {
								// Non-parcel specific properties.
								data.alsendo_connect_calculate.package_properties[key] = parcel_value;
							}
						}
					);

					// Convert parcel groups to array.
					Object.keys( parcelGroups ).sort( (a, b) => a - b ).forEach(
						function (parcelIndex) {
							parcels.push( parcelGroups[parcelIndex] );
						}
					);

					data.alsendo_connect_calculate.parcels = parcels;

					additional_options.each(
						function () {
							data.alsendo_connect_calculate.additional_options[$( this ).data( 'key' )] = $( this ).val()
						}
					);

					let receiver_postal_code = data.alsendo_connect_calculate.receiver.postal_code;

					$( '#alsendo_pre_js_debug' ).remove();
					$( '#apaczka_error' ).html( '' );

					console.log( "alsendo connect evaluation data - prepared:" );
					console.log( data );

					$( this ).attr( 'disabled', true );
					$( '#alsendo_connect_preloader' ).css( 'display', 'inline-block' );
					$( '.apaczka_send' ).css( 'display', 'none' );

					if( $(this).hasClass('alsendo_full') ) {
						console.log( 'we need all available services' );
						data.alsendo_connect_calculate.alsendo_full = 1;
					}

					// return;

					$.post(
						ajaxurl,
						data,
						function (response) {
							console.log( 'Alsendo connect: evaluate package response' );
							if (response != 0) {
								response = JSON.parse( response );
								console.log( response.status );
								// console.log( response );
								if (response.status === 'ok') {
									$( '.apaczka_send' ).css( 'display', 'block' );
									$( '#apaczka_error' ).html( '' );
									let calculate_html   = response.calculate_html;
									let calcualted_tiles = $.parseHTML( calculate_html );
									$( "#apaczka-calculate-wrapper" ).html( calcualted_tiles );
									$( "#apaczka_send" ).prop( "disabled", false );
									changeShippingMethodTriggers( $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val() );
									// $('.apaczka-calculate-item[data-item="0"]').click();
								} else {
									console.log( 'Calculation: error:' );
									console.log( response.status );
									console.log( response );
									$( '#apaczka_error' ).html( '' );
									let api_response = '';
									if ('errors' in response) {
										console.log( response.errors );
										if (typeof response.errors === 'object' && response.errors !== null) {
											if ('errors' in response.errors) {
												api_response += '<br>' + alsendo_process_api_response( response.errors.errors );
											}
										} else {
											api_response += '<br>' + alsendo_process_api_response( response.errors );
										}
									}
									if ('error_messages' in response) {
										console.log( response.error_messages );
										api_response += alsendo_process_api_response( response.error_messages );
									}
									if ('status' in response && response.status.length > 0) {
										// api_response += '<br>' + 'Status: ' + response.status;
									}
									if ('status_code' in response && response.status_code.length > 0) {
										api_response += '<br>' + 'Status code: ' + response.status_code;
									}
									if ('message' in response) {
										console.log( response.message );
										api_response += '<br>' + alsendo_process_api_response( response.message );
									}

									console.log( 'Error: api_response' );
									console.log( api_response );

									if (typeof api_response != 'undefined' && api_response !== null && api_response != '') {
										$( '#apaczka_error' ).html( '<pre>' + api_response.replace( /\n/g, '<br>' ) + '</pre>' );
									} else {
										let formatted_JSON = formatJSON( response );
										$( '#apaczka_error' ).html( '<pre>' + formatted_JSON + '</pre>' );
									}

									$( "#apaczka-calculate-wrapper" ).html( '' );
									$( "#apaczka_send" ).prop( "disabled", true );
								}

								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								$( '.apaczka_calculate_price' ).attr( 'disabled', false );

								$( '#apaczka_delivery_point_id_wrapper' ).addClass( 'apaczka-hidden' );

								return false;

							} else {
								$( '#apaczka_error' ).html( 'Invalid response.' );
							}

						}
					);

					return false;
				}
			);

			$( document ).on(
				"click",
				'.apaczka_calculate_radio',
				function (event) {
					apaczka_calculate_selected_service = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
					handleCalculateDynamicFields( parseInt( apaczka_calculate_selected_service ) )
				}
			);

			$( "#apaczka_send" ).click(
				function (e) {

					let selected_operator_tile = $( '.apaczka-calculate-item.selected' );
					if ( ! selected_operator_tile || typeof selected_operator_tile == 'undefined' || selected_operator_tile === null) {
						e.preventDefault();
						alert( alsendo_order_metabox.text_no_selected );
						return false;
					}

					if (selected_operator_tile.length === 0) {
						e.preventDefault();
						alert( alsendo_order_metabox.text_no_selected );
						return false;
					}

					let shipping_method = $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val();

					if (false !== apaczka_dispath_point_handler_to_validate) {
						if ('' === apaczka_dispath_point_handler_to_validate.val()) {
							alert( "Punkt nadania nie może być pusty." );
							return false;
						}
					}

					let delivery_point_id;
					console.log( 'Ecolet:get point_id' );
					let hidden_delivery_point_input_val = $( '#_apaczka\\[delivery_point_id\\]' ).val();
					if (typeof hidden_delivery_point_input_val != 'undefined' && hidden_delivery_point_input_val !== null) {
						if ('' !== hidden_delivery_point_input_val) {
							delivery_point_id = hidden_delivery_point_input_val;
						}
					}

					if ( ! $( this ).closest( "form" )[0].checkValidity()) {
						$( this ).closest( "form" )[0].reportValidity();
						return false;
					}

					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'create_package',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						alsendo_connect_create: {
							sender: {},
							receiver: {},
							package_properties: {},
							additional_options: {},
							delivery_point: {},
							delivery_point_id: delivery_point_id,
							selected_service: apaczka_calculate_selected_service,
							selected_supplier: '',

						}
					};

					let package_properties = $( 'input[id^="_apaczka[package_properties]"], select[id^="_apaczka[package_properties]"]' );
					let sender             = $( 'input[id^="_apaczka[sender]"]' );

					let additional_options      = $( 'input[id^="_apaczka[additional_options]"]' );
					let receiver                = $( 'input[id^="_apaczka[receiver]"]' );
					let delivery_point          = $( 'input[name^="_apaczka[delivery_point]"]' );
					let is_residential_sender   = $( 'select[id="_apaczka[sender][is_residential]"]' ).val();
					let is_residential_receiver = $( 'select[id="_apaczka[receiver][is_residential]"]' ).val();

					receiver.each(
						function () {
							data.alsendo_connect_create.receiver[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_create.receiver['is_residential'] = is_residential_receiver;

					sender.each(
						function () {
							data.alsendo_connect_create.sender[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_create.sender['is_residential'] = is_residential_sender;

					data.alsendo_connect_create.sender['apm_foreign_access_point_id'] = $( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val();

					package_properties.each(
						function () {
							data.alsendo_connect_create.package_properties[$( this ).data( 'key' )] = $( this ).val();
						}
					);

					additional_options.each(
						function () {
							data.alsendo_connect_create.additional_options[$( this ).data( 'key' )] = $( this ).val();
						}
					);

					data.alsendo_connect_create.selected_service = $( selected_operator_tile ).attr( 'data-service_id' );

					if ('COURIER' === shipping_method) {
						console.log( 'Ecolet:clear point for sender' );
						data.alsendo_connect_create.sender['apm_foreign_access_point_id'] = null;
					}
					if (shipping_method.startsWith( 'SELF_' ) || shipping_method.startsWith( 'self_' )) {
						$( 'input[id^="_apaczka[package_properties][dispath_point_"]' ).each(
							function (ind, element) {
								let parent_div = $( element ).closest( $( 'div[id^="dispath_point_"]' ) )
								if ( ! $( parent_div ).hasClass( 'apaczka-hidden' )) {
									let sender_dispatch_point = $( element ).val();
									console.log( 'Ecolet: set point for sender' );
									console.log( sender_dispatch_point );
									data.alsendo_connect_create.sender['apm_foreign_access_point_id'] = sender_dispatch_point;
								}
							}
						);
					}

					let cod_amount = +$( 'input[name="_apaczka\\[package_properties\\]\\[declared_content\\]"]' ).val();
					if (90 == data.alsendo_connect_create.selected_service && (cod_amount < 20)) {
						alert( alsendo_order_metabox.text_posta_romana_code );
						return false;
					}

					let parcelGroups = {};
					let parcels      = [];

					let contents_tag_value = false;
					let contents_tag       = '';

					package_properties.each(
						function (index, element) {
							let key          = $( this ).data( 'key' );
							let parcel_value = $( this ).val();
							let name         = $( this ).attr( 'name' );

							// console.log('Processing field:', name, 'key:', key, 'value:', parcel_value);

							// if tag used as package contents.
							if ('package_contents' === key) {
								let may_be_contents_tag_used = $( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' );
								if (typeof may_be_contents_tag_used != 'undefined' && may_be_contents_tag_used !== null) {
									contents_tag = $( may_be_contents_tag_used ).val();
									if (typeof contents_tag != 'undefined' && contents_tag !== null) {
										contents_tag_value = true;
									}
								}
							}

							if (key && ['package_length', 'package_width', 'package_height', 'package_weight', 'package_contents', 'declared_content'].includes( key )) {

								let parcelIndex = 0;
								let matches     = name.match( /_apaczka\[package_properties\]\[(\d+)\]/ );
								if (matches) {
									parcelIndex = parseInt( matches[1] );
								}

								if ( ! parcelGroups[parcelIndex]) {
									parcelGroups[parcelIndex] = {};
								}

								// Add field to parcel group.
								parcelGroups[parcelIndex][key] = parcel_value;
								if (contents_tag_value) {
									if (0 === parcelIndex) {
										parcelGroups[parcelIndex]['contents_tag'] = contents_tag;
									}
								}

							} else if (key) {
								data.alsendo_connect_create.package_properties[key] = parcel_value;
							}
						}
					);

					Object.keys( parcelGroups ).sort( (a, b) => a - b ).forEach(
						function (parcelIndex) {
							parcels.push( parcelGroups[parcelIndex] );
						}
					);

					data.alsendo_connect_create.parcels = parcels;

					$( '#alsendo_pre_js_debug' ).remove();
					$( '#apaczka_error' ).html( '' );
					$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
					$( this ).attr( 'disabled', true );

					console.log( 'Alsendo connect: create_order_ajax_data' );
					console.log( data );

					$.post(
						ajaxurl,
						data,
						function (response) {
							if (response != 0) {
								response = JSON.parse( response );
								if (response.status === 'ok') {
									console.log( response );

									if ('ecolet_order' in response) {
										if ('ecolet_ok' in response) {
											console.log( 'Order created in Ecolet.ro' );
											window.location.reload();
										}
									}

									/*if ('apaczka_order' in response) {
										if ('apaczka_ok' in response) {
											console.log('Order created in Apaczka.pl');
											window.location.reload();
											console.log('window.location.reload');
										}
									}
									*/

								} else {

									console.log( 'Alsendo: send_order_error' );
									console.log( response.status );
									console.log( response );

									$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
									let order_id = $( '#alsendo_connect_wc_order_id' ).val();

									let api_response = '';

									if ('api_error' in response) {
										api_response += 'API error: ' + response.api_error + '\n\n';
									} else if ('ecolet_error' in response) {
										api_response += 'Error: ';
										api_response += alsendo_order_metabox.text_no_order_id + '\n\n';
										api_response += alsendo_order_metabox.text_order_section + '\n\n';
										api_response += alsendo_order_metabox.text_order_details + '\n\n';
									}

									if ('status_code' in response) {
										api_response += '<br>' + 'API response code: ' + response.status_code + '\n\n';
									}
									if ('error_messages' in response) {
										console.log( response.error_messages );
										api_response += alsendo_process_api_response( response.error_messages );
									}
									if ('error' in response) {
										console.log( response.error );
										api_response += alsendo_process_api_response( response.error );
									}
									if ('errors' in response) {
										console.log( response.errors );
										if ('errors' in response.errors) {
											console.log( 'eeeeeeeeeee' );
											console.log( response.errors.errors );
											api_response += alsendo_process_api_response( response.errors.errors );
										} else {
											api_response += alsendo_process_api_response( response.errors );
										}

									}

									if ('status_text' in response) {
										api_response += 'Details: ' + response.status_text + '\n\n';
									}
									if ('raw_json' in response) {
										api_response += response.raw_json + '\n\n';
									}

									if ('apaczka_response' in response) {
										if ('status_code' in response.apaczka_response) {
											api_response += 'API response code: ' + response.apaczka_response.status_code + '\n\n';
										}
										if ('message' in response.apaczka_response || 'errors' in response.apaczka_response) {
											if ('message' in response.apaczka_response) {
												api_response += '<br>' + alsendo_process_api_response( response.apaczka_response.message );
											}
											if ('errors' in response.apaczka_response) {
												console.log( 'additional_api_errors:' );
												console.log( response.apaczka_response.errors );
												api_response += '<br>' + alsendo_process_api_response( response.apaczka_response.errors );
											}
										}
									}

									console.log( 'api_response_errors:' );
									console.log( api_response );

									let woo_logs_section_url = ' <a target="blank_" href="' + alsendo_order_metabox.log_path + '">' + alsendo_order_metabox.text_here + '</a>';
									api_response            += "<br>Check log file 'alsendo-connect-apaczka-get-waybill-order-" + order_id + "'" + woo_logs_section_url + "</span>";

									$( '#apaczka_error' ).html( '<pre>' + api_response.replace( /\n/g, '<br>' ) + '</pre>' );

									$( '.apaczka_send' ).attr( 'disabled', false );
									// $( this ).parent().find( ".spinner" ).removeClass( 'is-active' );
									$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								}

								return false;
							} else {
								// console.log('Invalid response.');
								$( '#apaczka_error' ).html( 'Invalid response.' );
								$( '.apaczka_send' ).attr( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
							}

						}
					);

					return false;
				}
			);

			let ecolet_preloader_tracking = $( '#ecolet_preloader_tracking' );

			let ecolet_wc_order_id = $( '#ecolet_wc_order_id' ).attr( 'data-id' );
			let is_ecolet_order    = $( '#ecolet_api_order' ).val();
			if (is_ecolet_order && typeof ecolet_wc_order_id != 'undefined' && ecolet_wc_order_id !== null) {
				if (typeof ecolet_preloader_tracking != 'undefined' && ecolet_preloader_tracking !== null && ecolet_preloader_tracking.length > 0) {

					let order_id  = $( '#ecolet_wc_order_id' ).attr( 'data-id' );
					let ecolet_id = $( '#ecolet_preloader_tracking' ).attr( 'data-ecolet-id' );

					let data = {
						action: 'alsendo_connect',
						alsendo_connect_action: 'ecolet_get_awb',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						ecolet_id: ecolet_id,
						order_id: order_id
					};

					console.log( 'AJAX ecolet_get_awb tracking data' );
					console.log( data );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: data,
							beforeSend: function () {
							},
							success: function (response) {
								console.log( "Ecolet ecolet_get_awb response:" );
								console.log( response );
								if (0 != response) {
									if ('success' in response && response.success) {
										if ('data' in response) {
											if (typeof response.data === 'object' && 'message' in response.data) {
												if (typeof response.data.message != 'undefined' && response.data.message !== null) {
													let message = response.data.message;
													// meassage =+ '<br>Please re-load page';.
													$( '#ecolet_wc_order_id' ).after( '<span style="color:#26be22">' + message + '</span>' );
												}
											} else if (typeof response.data != 'undefined' && response.data !== null) {
												let awb_number   = response.data;
												let tracking_url = alsendo_admin.ecolet_panel + 'track/' + awb_number;
												let tracking     = '<a href="' + tracking_url + '" target="_blank"><span style="color:#26be22">' + awb_number + '</span></a>';
												$( '#ecolet_preloader_tracking' ).replaceWith( tracking );
											}

										}
									}
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Ecolet get abw:" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {

							}
						}
					);
				}
			}

			$( '#ecolet_cancel' ).click(
				function (e) {
					e.preventDefault();
					console.log( 'ecolet_order_cancel' );
					let order_id = $( '#ecolet_wc_order_id' ).attr( 'data-id' );
					$( '#json-display-alsendo' ).text( '' );
					$( '#json-display-alsendo' ).css( 'display', 'none' );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: {
								action: 'alsendo_connect',
								alsendo_connect_action: 'ecolet_cancel_order',
								security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
								ecolet_id: $( this ).attr( 'data-ecolet-id' ),
								order_id: order_id
							},
							beforeSend: function () {
								$( '#ecolet_cancel' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
								$( '#ecolet_some_error' ).remove();
							},
							success: function (response) {
								console.log( "Ecolet ecolet_order_cancel response:" );
								console.log( response );
								if (0 !== response) {
									if ('success' in response && response.success) {
										console.log( "Ecolet ecolet_order_cancel OK:" );
										if ('data' in response) {
											if ('message' in response.data) {
												if (typeof response.data.message != 'undefined' && response.data.message !== null) {
													let message = '<br><br>' + response.data.message;
													message    += '<br>' + alsendo_order_metabox.reload_message;
													$( '#ecolet_wc_order_id' ).after( '<span style="color:#236c20"><b>' + message + '</b></span>' );
													// Reload page after 5 seconds.
													setTimeout(
														function () {
															location.reload();
														},
														5000
													);
												}
											}
										}
									} else {
										if ('data' in response) {
											console.log( "Ecolet ecolet_order_cancel:" );
											console.log( response.data );

											let error_message = '<br>';
											if ('message' in response.data) {
												error_message += '<br>Message: ' + response.data.message;
											}
											if ('error' in response.data) {
												error_message += alsendo_process_api_response( response.data.error );
											}
											if ('status_code' in response.data) {
												error_message += '<br>Status code: ' + response.data.status_code;
											}
											if ('raw_json' in response.data) {
												error_message += alsendo_process_api_response( response.data.raw_json );
											}

											$( '#ecolet_wc_order_id' ).after( '<span id="ecolet_some_error" style="color:#e03636"><b><pre>' + error_message + '</pre></b></span>' );
										}
									}
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on cancel Ecolet order:" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( '#ecolet_cancel' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);

				}
			);

			$( '#ecolet_get_waybill' ).click(
				function (e) {
					e.preventDefault();
					console.log( 'ecolet_get_waybill' );
					let order_id = $( '#ecolet_wc_order_id' ).attr( 'data-id' );
					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							//dataType: 'json',
							xhrFields: {
								responseType: 'blob' // Set the response type to blob.
							},
							data: {
								action: 'alsendo_connect',
								alsendo_connect_action: 'ecolet_get_waybill',
								security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
								ecolet_id: $( this ).attr( 'data-ecolet-id' ),
								order_id: order_id
							},
							beforeSend: function () {
								$( '#ecolet_get_waybill' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
								$( '#ecolet_some_error' ).remove();
							},
							success: function (response) {
								console.log( "Ecolet waybill response:" );
								console.log( response );

								if (false && 'pdf' in response.data) {
									let win = window.open();
									win.document.write( '<iframe src="data:application/pdf;base64,' + response.data.pdf + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>' );

								}

								if (true) {
									let filename  = 'ecolet_woo_order_' + order_id + '.pdf';
									let blob      = new Blob( [response], {type: 'application/pdf'} );
									let link      = document.createElement( 'a' );
									link.href     = window.URL.createObjectURL( blob );
									link.download = filename;
									document.body.appendChild( link );
									link.click();
									document.body.removeChild( link );
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on get Ecolet waybill:" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
								let woo_logs_section_url = ' <a target="blank_" href="' + alsendo_order_metabox.log_path + '">' + alsendo_order_metabox.text_here + '</a>';
								let error_message        = "<br><br>Error:<br> Unexpected response from server.<br>Check log file 'alsendo-connect-apaczka-get-waybill-order-" + order_id + "'" + woo_logs_section_url + "</span>";
								$( '#ecolet_wc_order_id' ).after( '<span id="ecolet_some_error" style="color:#e03636"><b>' + error_message + '</b></span>' );

							},
							complete: function (response) {
								$( '#ecolet_get_waybill' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);

				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_inpost\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_inpost_opeartor = ['INPOST'];

					let operators = dispath_point_inpost_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_inpost_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_fancourier\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_fancourier_opeartor = ['FAN_COURIER'];

					let operators = dispath_point_fancourier_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_fancourier_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_sameday\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_sameday_opeartor = ['SAMEDAY'];

					let operators = dispath_point_sameday_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_sameday_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_gls\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					console.log( 'alsendo_order_metabox: dispath_point_gls_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: [{operator: 'GLS'}],
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_cargus\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					console.log( 'alsendo_order_metabox: dispath_point_gls_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: [{operator: 'CARGUS'}],
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_kurier48\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_kurier48_opeartor = ['POCZTA'];

					let operators = dispath_point_kurier48_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_kurier48_click' );
					console.log( dispath_point_kurier48_opeartor );
					console.log( operators );
					console.log( map_country_code );

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								console.log( point );
								console.log( point.code );
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: 'PL',
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_ups\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_ups = ['UPS'];

					let operators = dispath_point_ups.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_ups_click' );

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: 'PL',
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_dpd\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_dpd = ['DPD'];

					let operators = dispath_point_dpd.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_dpd_click' );
					console.log( 'map_country_code: ' + map_country_code );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: false,
							operatorMarkers: true,
							countryCodes: map_country_code,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[delivery_point_id\\]' ).click(
				function (e) {
					let field = $( this );
					e.preventDefault();
					let cod_amount_defined = is_cod_amount_defined();
					let is_cod_only        = false;
					if (cod_amount_defined) {
						is_cod_only = true;
					}

					console.log( 'alsendo_order_metabox: delivery_point_id_click' );
					console.log( 'alsendo_order_metabox__selected_service ID: ' + apaczka_calculate_selected_service );
					console.log( [serviceIdToApmSupplierId( parseInt( apaczka_calculate_selected_service ) )] );

					let operatorsArray = [];

					operatorsArray = [serviceIdToApmSupplierIdEcolet( parseInt( apaczka_calculate_selected_service ) )];

					console.log( 'operatorsArray' );
					console.log( operatorsArray );

					let operators = operatorsArray.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'operators' );
					console.log( operators );

					let shipping_country = document.getElementById( "_apaczka[receiver][country_code]" ).value;
					if (typeof shipping_country != 'undefined' && shipping_country !== null) {
						shipping_country = shipping_country.toUpperCase();
					}

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								console.log( point.code );
								field.val( point.code );
								// $('#_apaczka_apm_access_point_id').val(record.foreign_access_point_id);
								$( 'input[id=_apaczka_apm_access_point_id]' ).each(
									function (ind, elem) {
										$( elem ).val( point.code );
									}
								);

								// $('#_apaczka_apm_supplier').val(record.supplier);
								$( 'input[id=_apaczka_apm_supplier]' ).each(
									function (ind, elem) {
										$( elem ).val( point.operator );
									}
								);

								// $('#_apaczka_apm_name').val(record.name);
								$( 'input[id=_apaczka_apm_name]' ).each(
									function (ind, elem) {
										$( elem ).val( point.description );
									}
								);

								// $('#_apaczka_apm_foreign_access_point_id').val(record.foreign_access_point_id);
								$( 'input[id=_apaczka_apm_foreign_access_point_id]' ).each(
									function (ind, elem) {
										$( elem ).val( point.code );
									}
								);

								// $('#_apaczka_apm_street').val(record.street);
								$( 'input[id=_apaczka_apm_street]' ).each(
									function (ind, elem) {
										$( elem ).val( point.street );
									}
								);

								// $('#_apaczka_apm_city').val(record.city);
								$( 'input[id=_apaczka_apm_city]' ).each(
									function (ind, elem) {
										$( elem ).val( point.city );
									}
								);

								// $('#_apaczka_apm_postal_code').val(record.postal_code);
								$( 'input[id=_apaczka_apm_postal_code]' ).each(
									function (ind, elem) {
										$( elem ).val( point.postalCode );
									}
								);

								// $('#_apaczka_apm_country_code').val(record.country_code);
								$( 'input[id=_apaczka_apm_country_code]' ).each(
									function (ind, elem) {
										$( elem ).val( shipping_country );
									}
								);

								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: {zoom: 12},
							codOnly: is_cod_only,
							operatorMarkers: true,
							countryCodes: shipping_country,
							initialAddress: $( '#_apaczka\\[receiver\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}

				}
			);

		}
	);

	document.addEventListener(
		'click',
		function (e) {
			e          = e || window.event;
			let target = e.target || e.srcElement;

			let api_type = alsendo_order_metabox.api_type;

			if (target.hasAttribute( 'id' ) && 'alsendo_connect_alert_modal_close_button' === target.getAttribute( 'id' )) {
				// hide cancel package alert modal.
				$( "#apaczka_alert_modal" ).removeClass( "active" );
			}

			if (target.closest( '#apaczka_calculate_radio' )) {
				// orange borders.
				console.log( 'CLOSEST: apaczka_calculate_radio' );
				alsendo_connect_add_border_to_selected_service();
			}

			if (target.hasAttribute( 'id' )) {
				if (target.getAttribute( 'id' ) === 'ecolet_get_order_details') {
					e.preventDefault();
					console.log( 'ecolet_get_order_details' );

					$( '#json-display-alsendo' ).text( '' );
					$( '#json-display-alsendo' ).css( 'display', 'none' );

					let data = {
						action: 'alsendo_connect',
						alsendo_connect_action: 'ecolet_get_order',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						ecolet_id: target.getAttribute( 'data-ecolet-id' )
					};

					console.log( data );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: data,
							beforeSend: function () {
								$( '#ecolet_get_order_details' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
								$( '#ecolet_some_error' ).remove();
							},
							success: function (response) {
								console.log( "Ecolet ecolet_get_order_details response:" );
								console.log( response );
								if (0 !== response && '0' !== response) {
									if ('success' in response && response.success) {
										if ('data' in response /*&& 'data' in response.data*/) {
											// let order_data = JSON.parse( response.data.data );
											// console.log( response.data );
											let formatted_JSON = formatJSON( response.data );
											$( '#json-display-alsendo' ).text( formatted_JSON );
											$( '#json-display-alsendo' ).css( 'display', 'block' );

										}
									}
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Ecolet get order details:" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( '#ecolet_get_order_details' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);
				}

				if (target.getAttribute( 'id' ) === 'apaczka_geowidget_modal_cross') {
					e.preventDefault();
					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'none';
					}
				}
			}
		},
		false
	);

})( jQuery );