(function ($) {

	function alsendoAdminSettingsClearErrors() {
		$( '.notice-error' ).each(
			function (i, elem) {
				( elem ).remove();
			}
		);
	}
	function alsendoAdminSettingsChangeParcelTypeActions(type) {

		let apaczka_parcel_length = $( '#alsendo_connect_settings_general_package_length' );
		let apaczka_parcel_width  = $( '#alsendo_connect_settings_general_package_width' );
		let apaczka_parcel_height = $( '#alsendo_connect_settings_general_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 apaczkaFillPackageFormByTemplate(templateSlug) {
		let apaczka_package_templates = alsendo_admin.gateway_templates;
		console.log( 'FillPackage' );
		console.log( apaczka_package_templates );
		for (const [key, value] of Object.entries( apaczka_package_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					$( '#' + key2 ).val( value2 );
				}
			}
		}
		let api_type = alsendo_admin.api_type;
		if ( 'zaslat' === api_type ) {
			zaslatValidateShippingPointSelected();
		}

		let selected_template = $( '#alsendo_connect_settings_general_select_package_template option:selected' ).text();
		if (typeof selected_template != 'undefined' && selected_template !== null) {
			$( '#alsendo_connect_settings_general_new_package_template_name' ).val( selected_template );
		}

		const package_contents_select = $( '#alsendo_connect_settings_general_package_contents' );
		if (typeof package_contents_select != 'undefined' && package_contents_select !== null ) {
			let package_contents_value = $( '#alsendo_connect_settings_general_package_contents' ).val();
			const $target_tr_row       = $( package_contents_select ).closest( 'tr' ).next( 'tr' );
			if ( 'custom_text' === package_contents_value ) {
				$target_tr_row.show();
			} else {
				$target_tr_row.hide();
			}
		}
	}

	function apaczkaFillFormByTemplate(templateSlug) {
		let apaczka_sender_templates = alsendo_admin.templates;
		for (const [key, value] of Object.entries( apaczka_sender_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					if (key2 === 'order_status_completed_auto') {
						if (value2 === 'yes') {
							$( '#alsendo_connect_' + key2 ).prop( 'checked', true );
						} else {
							$( '#alsendo_connect_' + key2 ).prop( 'checked', false );
						}
					} else {
						$( '#' + key2 ).val( value2 )
					}
				}
			}
		}
		let selected_template = $( '#alsendo_connect_settings_general_select_sender_template option:selected' ).text();
		if (typeof selected_template != 'undefined' && selected_template !== null) {
			$( '#alsendo_connect_settings_general_new_sender_template_name' ).val( selected_template );
		}

	}

	function zaslatValidateShippingPointSelected() {
		let selectedService = $( '#alsendo_connect_settings_general_service' ).val();

		$( 'label[for^="alsendo_connect_settings_general_dispath_point_"]' ).each(
			function (index, label) {
				$( label ).closest( 'tr' ).hide();
			}
		);

		$( '#alsendo_connect_settings_general_parcel_type option[value="P2P"]' ).prop( 'disabled', false );
		$( '#alsendo_connect_settings_general_parcel_type option[value="P2H"]' ).prop( 'disabled', false );
		$( '#alsendo_connect_settings_general_parcel_type option[value="P2P"]' ).prop( 'disabled', false );
		$( '#alsendo_connect_settings_general_parcel_type option[value="P2H"]' ).prop( 'disabled', false );

		$( 'select[name="alsendo_connect_settings_general_shipping_method"]' ).prop( 'disabled', false );
		$( 'select[name="alsendo_connect_settings_general_parcel_type"]' ).prop( 'disabled', false );

		let operate_mode_select = $( '#alsendo_connect_settings_general_shipping_method' );
		if ( 'BALIKOVNA' === selectedService || 'ZASILKOVNA' === selectedService ) {
			$( 'select[name="alsendo_connect_settings_general_shipping_method"]' ).val( 'ONDEMAND' );
			$( 'select[name="alsendo_connect_settings_general_parcel_type"]' ).val( 'P2P' );
			$( 'select[name="alsendo_connect_settings_general_parcel_type"]' ).prop( 'disabled', true );
			$( 'select[name="alsendo_connect_settings_general_shipping_method"]' ).prop( 'disabled', true );
			if ( 'BALIKOVNA' === selectedService ) {
				$( 'label[for="alsendo_connect_settings_general_dispath_point_balikovna"]' ).closest( 'tr' ).show();
			}
			if ( 'ZASILKOVNA' === selectedService ) {
				$( 'label[for="alsendo_connect_settings_general_dispath_point_zasilkovna"]' ).closest( 'tr' ).show();
			}

		}

		if ( 'PPL' === selectedService ) {
			$( 'label[for="alsendo_connect_settings_general_dispath_point_ppl"]' ).closest( 'tr' ).show();
		}
		if ( 'GLS' === selectedService ) {
			$( 'label[for="alsendo_connect_settings_general_dispath_point_gls"]' ).closest( 'tr' ).show();
		}
		if ( 'DPD' === selectedService ) {
			$( 'label[for="alsendo_connect_settings_general_dispath_point_dpd"]' ).closest( 'tr' ).show();
		}

		if ( 'WEDO' === selectedService || 'TOPTRANS' === selectedService || 'UPS' === selectedService || 'FEDEX' === selectedService ) {
			if ('WEDO' === selectedService) {
				$( '#alsendo_connect_settings_general_parcel_type option[value="P2P"]' ).prop( 'disabled', true );
				$( '#alsendo_connect_settings_general_parcel_type option[value="P2H"]' ).prop( 'disabled', true );
			} else {
				$( '#alsendo_connect_settings_general_parcel_type option[value="P2P"]' ).prop( 'disabled', true );
				$( '#alsendo_connect_settings_general_parcel_type option[value="P2H"]' ).prop( 'disabled', true );
				$( '#alsendo_connect_settings_general_parcel_type option[value="H2P"]' ).prop( 'disabled', true );
			}
		}

	}

	function validateShippingPointSelected() {

		console.log( 'alsendo connect validateShippingPointSelected_function' );

		const PocztaKurier48              = 160;
		const PocztaKurier48Punkty        = 162;
		const AllegroSMARTKurier48Punkty  = 164;
		const AllegroSMARTPocztaKurier48  = 165;
		const AllegroSMARTPaczkomatInPost = 40;
		const PaczkomatInPost             = 41;
		const UPSAPPunktDrzwi             = 13;
		const UPSAPPunktPunkt             = 14;
		const DPD_kurier                  = 21;

		let selectedService              = parseInt( $( '#alsendo_connect_settings_general_service' ).val() );
		let dispathPointInpostSelected   = $( '#alsendo_connect_settings_general_dispath_point_inpost' ).val() !== '';
		let dispathPointKurier48Selected = $( '#alsendo_connect_settings_general_dispath_point_kurier48' ).val() !== '';
		let dispathPointUpsSelected      = $( '#alsendo_connect_settings_general_dispath_point_ups' ).val() !== '';
		let dispathPointDPDSelected      = $( '#alsendo_connect_settings_general_dispath_point_dpd' ).val() !== '';
		let dispathPointDHLSelected      = $( '#alsendo_connect_settings_general_dispath_point_dhl' ).val() !== '';

		let error = null;

		if ((selectedService === PocztaKurier48
				|| selectedService === PocztaKurier48Punkty
				|| selectedService === AllegroSMARTKurier48Punkty
				|| selectedService === AllegroSMARTPocztaKurier48
			) &&
			! dispathPointKurier48Selected
		) {
			error = '#alsendo_connect_settings_general_dispath_point_kurier48';
		}

		if ((selectedService === AllegroSMARTPaczkomatInPost
				|| selectedService === PaczkomatInPost
			) &&
			! dispathPointInpostSelected
		) {
			error = '#alsendo_connect_settings_general_dispath_point_inpost';
		}

		if ((selectedService === UPSAPPunktPunkt
				|| selectedService === UPSAPPunktPunkt
			) &&
			! dispathPointUpsSelected
		) {
			error = '#alsendo_connect_settings_general_dispath_point_ups';
		}

		if (error !== null) {
			$( error ).addClass( 'apaczka_missing_field' );

			if (error !== '#alsendo_connect_settings_general_dispath_point_ups') {
				$( '#alsendo_connect_settings_general_dispath_point_ups' ).removeClass( 'apaczka_missing_field' );
			}
			if (error !== '#alsendo_connect_settings_general_dispath_point_inpost') {
				$( '#alsendo_connect_settings_general_dispath_point_inpost' ).removeClass( 'apaczka_missing_field' );
			}
			if (error !== '#alsendo_connect_settings_general_dispath_point_kurier48') {
				$( '#alsendo_connect_settings_general_dispath_point_kurier48' ).removeClass( 'apaczka_missing_field' );
			}
			if (error !== '#alsendo_connect_settings_general_dispath_point_dpd') {
				$( '#alsendo_connect_settings_general_dispath_point_dpd' ).removeClass( 'apaczka_missing_field' );
			}

			$( '.button-primary.woocommerce-save-button' ).prop( 'disabled', 'disabled' );
		} else {
			$( '#alsendo_connect_settings_general_dispath_point_kurier48' ).removeClass( 'apaczka_missing_field' );
			$( '#alsendo_connect_settings_general_dispath_point_ups' ).removeClass( 'apaczka_missing_field' );
			$( '#alsendo_connect_settings_general_dispath_point_inpost' ).removeClass( 'apaczka_missing_field' );
			$( '#alsendo_connect_settings_general_dispath_point_dpd' ).removeClass( 'apaczka_missing_field' );
			$( '.button-primary.woocommerce-save-button' ).prop( 'disabled', '' );
		}

	}

	function alsendo_connect_change_api(api_name) {

		$( '#alsendo_connect_settings_general_package_length' ).prop( 'required', false );
		$( '#alsendo_connect_settings_general_package_width' ).prop( 'required', false );
		$( '#alsendo_connect_settings_general_package_height' ).prop( 'required', false );
		$( '#alsendo_connect_settings_general_package_weight' ).prop( 'required', false );

		if ( 'apaczka' === api_name ) {
			$( '.alsendo_connect_ecolet_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_zaslat_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_apaczka_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'table-row' );
				}
			);
		} else if ( 'ecolet' === api_name ) {
			$( '.alsendo_connect_apaczka_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_zaslat_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_ecolet_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'table-row' );
				}
			);
		} else if ( 'zaslat' === api_name ) {
			$( '.alsendo_connect_apaczka_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_ecolet_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_zaslat_setting' ).each(
				function (i, elem) {
					let parent = $( elem ).closest( 'tr' );
					$( parent ).css( 'display', 'table-row' );
				}
			);
		} else {
			$( '.form-table' ).each(
				function (i, table) {
					$( table ).find( 'tr' ).each(
						function (i, tr) {
							$( tr ).css( 'display', 'none' );
						}
					);
				}
			);

			$( '#alsendo_connect_settings_general_app_id' ).closest( 'tr' ).css( 'display', 'none' );
			$( '#alsendo_connect_settings_general_app_secret' ).closest( 'tr' ).css( 'display', 'none' );
			$( '#alsendo_connect_settings_general_global_api_type' ).closest( 'tr' ).css( 'display', 'table-row' );

			$( '#alsendo_connect_settings_general_global_api_type' ).val( 'none' ).trigger( 'change' );
		}

	}

	$( document ).ready(
		function () {

			console.log( 'Alsendo_connect:admin_js' );
			console.log( 'Alsendo package templates' );
			console.log( alsendo_admin.gateway_templates );

			let nonce_input = '<input type="hidden" name="alsendo_connect_settings_nonce" value="' + alsendo_admin.settings_nonce + '">';
			$( '#mainform' ).append( nonce_input );

			$( '#alsendo_connect_settings_general_refresh_settings' ).closest( 'fieldset' ).hide();
			$( '#alsendo_connect_settings_nonce' ).closest( 'tr' ).hide();
			$( '#alsendo_connect_settings_general_create_sender_template' ).val( 'no' ).trigger( 'change' );
			$( '#alsendo_connect_settings_general_create_package_template' ).val( 'no' ).trigger( 'change' );

			let global_api        = 'apaczka';
			let global_api_chosen = $( '#alsendo_connect_settings_general_global_api_type' ).val();
			if (typeof global_api_chosen != 'undefined' && global_api_chosen !== null) {
				if ( 'apaczka' === global_api_chosen || 'ecolet' === global_api_chosen || 'zaslat' === global_api_chosen ) {
					global_api = global_api_chosen;
				}
			}

			let api_type = alsendo_admin.api_type;
			if ( 'zaslat' === api_type ) {
				let selected_operator = $( '#alsendo_connect_settings_general_service' ).val();
				if ( '' !== selected_operator && typeof selected_operator != 'undefined' && selected_operator !== null ) {
					zaslatValidateShippingPointSelected();
				}
			}

			alsendo_connect_change_api( global_api );

			// Get the text input.
			var $input  = $( '#ecolet_auth_button' );
			var value   = $input.val();
			var classes = $input.attr( 'class' ) || 'button button-secondary';

			let preloader_path = alsendo_admin.preloader;

			let ecolet_auth_button = '<button id="ecolet_auth_button" class="' + classes + '">' +
				'<span id="alsendo_connect_btn_text">'
				+ alsendo_admin.btn_text1 + '</span>' +
				'<span id="alsendo_connect_preloader"><img src="' + preloader_path + '"></span>' +
				'<span style="display:none;" class="status ecolet-connection-status" title="Ecolet API status"></span>' +
				'</button><span id="ecolet_connection_result"></span>';
			$input.replaceWith( ecolet_auth_button );

			if ( 'none' === global_api_chosen || 'apaczka' === global_api_chosen || 'zaslat' === global_api_chosen ) {
				$( '.ecolet-connection-status' ).css( 'display', 'none' );
				$( '#ecolet_auth_button' ).css( 'display', 'none' );
			} else {

				if ( 'ecolet' === global_api_chosen ) {

					console.log( 'API: ecolet' );
					$( '#ecolet_auth_button' ).css( 'display', 'inline-block' );
					const ecolet_api_status = window.alsendo_ecolet_api;
					//console.log( 'API status' );
					//console.log( ecolet_api_status );
					if (typeof ecolet_api_status != 'undefined') {

						console.log( ecolet_api_status.connected );

						if (ecolet_api_status.connected) {
							console.log( 'API: Ecolet connected' );
							$( '.ecolet-connection-status' ).css( 'display', 'inline-block' );
							$( '#alsendo_connect_btn_text' ).text( alsendo_admin.btn_text2 );
							alsendoAdminSettingsClearErrors();
						} else {
							console.log( 'API: Ecolet NOT connected' );
							$( '#alsendo_connect_btn_text' ).text( alsendo_admin.btn_text1 );
							$( '#ecolet_connection_result' ).html( '<span style="color:#dc1919; font-weight:bold;">' + alsendo_admin.ecolet_status_text + '</span>' );
						}

					} else {

						if (alsendo_admin.ecolet_connected) {
							console.log( 'API: Ecolet connected' );
							$( '.ecolet-connection-status' ).css( 'display', 'inline-block' );
							$( '#alsendo_connect_btn_text' ).text( alsendo_admin.btn_text2 );
						} else {
							console.log( 'API: Ecolet NOT connected' );
							$( '#alsendo_connect_btn_text' ).text( alsendo_admin.btn_text1 );
							$( '#ecolet_connection_result' ).html( '<span style="color:#dc1919; font-weight:bold;">' + alsendo_admin.ecolet_status_text + '</span>' );
						}
					}
				}
			}

			$( '#alsendo_connect_settings_general_ecolet_email' ).on(
				'change',
				function () {
					alsendoAdminSettingsClearErrors();
				}
			);

			$( '#alsendo_connect_settings_general_ecolet_password' ).on(
				'change',
				function () {
					alsendoAdminSettingsClearErrors();
				}
			);

			$( '#alsendo_connect_settings_general_ecolet_client_id' ).on(
				'change',
				function () {
					alsendoAdminSettingsClearErrors();
				}
			);

			$( '#alsendo_connect_settings_general_ecolet_app_secret' ).on(
				'change',
				function () {
					alsendoAdminSettingsClearErrors();
				}
			);

			let alsendo_connect_parcel_type_handle = $( '#alsendo_connect_settings_general_parcel_type' );
			if (typeof alsendo_connect_parcel_type_handle != 'undefined' && alsendo_connect_parcel_type_handle !== null) {
				alsendoAdminSettingsChangeParcelTypeActions( alsendo_connect_parcel_type_handle.val() );
				alsendo_connect_parcel_type_handle.change(
					function (e) {
						alsendoAdminSettingsChangeParcelTypeActions( $( this ).val() )
					}
				);
			}

			const package_contents_select = $( '#alsendo_connect_settings_general_package_contents' );
			if (typeof package_contents_select != 'undefined' && package_contents_select !== null ) {
				let package_contents_value = $( '#alsendo_connect_settings_general_package_contents' ).val();
				const $target_tr_row       = $( package_contents_select ).closest( 'tr' ).next( 'tr' );
				if ( 'custom_text' === package_contents_value ) {
					$target_tr_row.show();
				} else {
					$target_tr_row.hide();
				}

				$( '#alsendo_connect_settings_general_package_contents' ).on(
					'change',
					function () {
						if ( 'custom_text' === $( this ).val() ) {
							$target_tr_row.fadeIn();
						} else {
							$target_tr_row.hide();
						}
					}
				);
			}

			let apaczka_geowidget_modal       = document.createElement( 'div' );
			let modal_html                    = '<div ' +
				'class="apaczka_geowidget_modal"' + ' style="display:none;"' +
				' id="apaczka_geowidget_modal_dynamic" style="display: none">' +
				'<div class="apaczka_geowidget_modal_inner">' +
				'<span id="apaczka_geowidget_modal_cross">&times;</span>' +
				'<div id="apaczka_geowidget_modal_inner_content"></div>' +
				'</div>' +
				'</div>';
			apaczka_geowidget_modal.innerHTML = modal_html;
			document.body.appendChild( apaczka_geowidget_modal );

			let map_sender_initial_address = $( '#alsendo_connect_settings_general_sender_city' ).val();

			$( '#ecolet_auth_button' ).click(
				function (e) {
					e.preventDefault();
					let email         = $( '#alsendo_connect_settings_general_ecolet_email' ).val();
					let password      = $( '#alsendo_connect_settings_general_ecolet_password' ).val();
					let client_id     = $( '#alsendo_connect_settings_general_ecolet_client_id' ).val();
					let client_secret = $( '#alsendo_connect_settings_general_ecolet_app_secret' ).val();
					let api_type      = $( '#alsendo_connect_settings_general_ecolet_api_type' ).val();

					// Basic client-side validation before sending credentials.
					if ( ! $.trim( email ) || ! $.trim( password ) || ! $.trim( client_id ) || ! $.trim( client_secret ) ) {
						alert( 'Please fill in Ecolet credentials: Email, Password, Client ID and Client Secret.' );
						return;
					}

					$( '#ecolet_connection_result' ).html( '' );
					$( '.ecolet-connection-status' ).css( 'display', 'none' );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							dataType: 'json',
							data: {
								action: 'alsendo_connect',
								alsendo_connect_action: 'ecolet_auth',
								security: alsendo_admin.nonce,
								email: $.trim( email ),
								password: $.trim( password ),
								client_id: $.trim( client_id ),
								client_secret: $.trim( client_secret ),
								api_type: api_type
							},
							beforeSend: function () {
								$( this ).attr( 'disabled', 'disabled' );
								$( '#alsendo_connect_preloader' ).css( 'display', 'inline-block' );
							},
							success: function (response) {
								console.log( "Success response" );
								console.log( response );
								if ( 'success' in response && response.success ) {
									console.log( 'Connected OK' );
									$( '#ecolet_connection_result' ).html( '<span style="color:#20b920">' + alsendo_admin.btn_text3 + '</span>' );
									$( '.ecolet-connection-status' ).css( 'display', 'inline-block' );
								} else {
									console.log( 'Error API Ecolet' );
									let error_details = false;
									if ( 'data' in response ) {
										if ( 'code' in response.data ) {
											error_details = 'API response code: ' + response.data.code;
										}
										if ( 'error' in response.data ) {
											error_details += '<br>' + response.data.error;
										}
										if ( 'error_description' in response.data ) {
											error_details += '<br>' + response.data.error_description;
										}
									}

									if ( error_details ) {
										console.log( 'Error details' );
										console.log( error_details );
									} else {
										error_details = 'Some error is occores, check line "alsendo-api-oauth" in Woo logs section'
									}

									$( '#ecolet_connection_result' ).html( '<span style="color:#dc1919">' + error_details + '</span>' );
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( this ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								$( '#alsendo_connect_settings_general_refresh_settings' ).trigger( 'click' );
							}
						}
					);
				}
			);

			// validation postal code.
			const sender_zip_code         = document.getElementById( 'alsendo_connect_settings_general_sender_postal_code' );
			let sender_country            = $( "#alsendo_connect_settings_general_sender_country" ).val();
			let sender_zip_code_order     = $( 'input[name="_apaczka[sender][postal_code]"]' );
			let receiver_country_code_val = '';
			let receiver_country_code     = $( 'input[name="_apaczka[receiver][country_code]"]' );
			if (typeof receiver_country_code != 'undefined' ) {
				receiver_country_code_val = $( 'input[name="_apaczka[receiver][country_code]"]' ).val();
			}
			if ( 'apaczka' === api_type) {
				if (typeof sender_zip_code != 'undefined' && sender_zip_code !== null) {

					sender_zip_code.addEventListener(
						'input',
						function (e) {
							let cursor_position = this.selectionStart;
							let old_value       = this.value;
							let new_value       = format_zip_code( old_value );
							if (new_value !== old_value) {
								this.value = new_value;
								if (cursor_position) {
									if (new_value.charAt( cursor_position - 1 ) === '-') {
										cursor_position++;
									}
									if (cursor_position > new_value.length) {
										cursor_position = new_value.length;
									}
									this.setSelectionRange( cursor_position, cursor_position );
								}
							}
						}
					);

					function format_zip_code(value) {
						// Remove all non-digit characters.
						let digits    = value.replace( /\D/g, '' );
						let formatted = '';
						for (let i = 0; i < digits.length && i < 5; i++) {
							if (i === 2) {
								formatted += '-';
							}
							formatted += digits[i];
						}

						return formatted;
					}
				}
			}

			const bank_account_input = document.getElementById( 'alsendo_connect_settings_general_sender_bank_account_number' );
			if (typeof bank_account_input != 'undefined' && bank_account_input !== null) {

				if ( 'apaczka' === global_api || 'PL' === map_sender_country ) {
					bank_account_input.addEventListener(
						'input',
						function (e) {
							let cursor_position = this.selectionStart;
							let old_value       = this.value;
							let new_value       = format_bank_account( old_value );
							if (new_value !== old_value) {
								this.value = new_value;
								if (cursor_position) {
									if (new_value.charAt( cursor_position - 1 ) === ' ') {
										cursor_position++;
									}
									if (cursor_position > new_value.length) {
										cursor_position = new_value.length;
									}
									this.setSelectionRange( cursor_position, cursor_position );
								}
							}
						}
					);

					function format_bank_account(value) {
						let digits    = value.replace( /\D/g, '' );
						let formatted = '';
						for (let i = 0; i < digits.length && i < 26; i++) {
							// Add space after positions: 2, 6, 10, 14, 18, 22.
							if (i === 2 || (i > 2 && (i - 2) % 4 === 0)) {
								formatted += ' ';
							}
							formatted += digits[i];
						}
						return formatted;
					}
				}
			}

			$( '#alsendo_connect_settings_general_sender_city' ).on(
				'keyup',
				function () {
					map_sender_initial_address = $( this ).val();
				}
			);

			let sender_phone_number = $( 'input[name="alsendo_connect_settings_general_sender_phone"]' );

			$( "#alsendo_connect_settings_general_global_api_type" ).change(
				function (e) {
					e.preventDefault();
					global_api = $( this ).val();
					if ( 'none' !== global_api ) {
						alsendo_connect_change_api( global_api );
					}

					alsendoAdminSettingsClearErrors();

					if ( 'ecolet' === global_api ) {
						$( '#ecolet_auth_button' ).css( 'display', 'inline-block' );
						$( '.ecolet-connection-status' ).css( 'display', 'none' );
						$( '#alsendo_connect_btn_text' ).text( alsendo_admin.btn_text1 );
					} else {
						$( '.ecolet-connection-status' ).css( 'display', 'none' );
						$( '#ecolet_auth_button' ).css( 'display', 'none' );
					}

					$( '.alsendo-switch-api-warning' ).remove();

					let package_settings = $( '#alsendo_connect_settings_general_shipping_method' );
					if (typeof package_settings != 'undefined' && package_settings !== null) {
						$( package_settings ).closest( '.form-table' ).css( 'display', 'none' );
					}

					let address_section_begin = $( '#alsendo_connect_settings_general_sender_is_residential' );
					if (typeof address_section_begin != 'undefined' && address_section_begin !== null) {
						let table_settings_1st = $( address_section_begin ).closest( 'table[class="form-table"]' );
						$( table_settings_1st ).css( 'display', 'none' );
					}
					let services_section_begin = $( '#alsendo_connect_settings_general_service' );
					if (typeof services_section_begin != 'undefined' && services_section_begin !== null) {
						let table_settings_2st = $( services_section_begin ).closest( 'table[class="form-table"]' );
						$( table_settings_2st ).css( 'display', 'none' );
						$( '#alsendo_connect_load_sender_settings_btn' ).css( 'display', 'none' );
						$( '#alsendo_connect_remove_sender_template_btn' ).css( 'display', 'none' );
						$( '#alsendo_connect_remove_package_template_btn' ).css( 'display', 'none' );
						$( '#alsendo_connect_sender_template_btn' ).css( 'display', 'none' );
						$( '#alsendo_connect_load_package_settings_btn' ).css( 'display', 'none' );
						$( 'button[name="alsendo_connect_remove_parcel_template"]' ).css( 'display', 'none' );
						$( 'h2' ).each(
							function (i, elem) {
								$( elem ).css( 'display', 'none' );
							}
						);
						$( '#alsendo_connect_settings_general_apaczka_debug_mode' ).closest( 'table[class="form-table"]' ).prepend( '<p class="alsendo-switch-api-warning" style="color:red;"><b>' + alsendo_admin.alert_text + '</b></p>' );
					}

					let zaslat_address_settings = $( '#alsendo_connect_settings_general_zaslat_address_id' );
					if (typeof zaslat_address_settings != 'undefined' && zaslat_address_settings !== null) {
						let table_settings_3rd = $( zaslat_address_settings ).closest( 'table[class="form-table"]' );
						$( table_settings_3rd ).css( 'display', 'none' );
					}

					let iban = $( 'input[name="alsendo_connect_settings_general_sender_bank_account_number"]' );
					if (typeof iban != 'undefined' ) {
						$( iban ).val( '' );
					}

					let help_notice = $( '#help_settings-description' );
					if (typeof help_notice != 'undefined' && help_notice !== null && help_notice.length > 0 ) {

						let form_link     = '';
						let support_title = 'Support';
						if ( 'apaczka' === global_api ) {
							form_link     = 'https://panel.apaczka.pl/formularz-kontaktowy';
							support_title = 'Support Apaczka:';
						}
						if ( 'ecolet' === global_api ) {
							form_link     = 'https://ecolet.ro/contact/';
							support_title = 'Support Ecolet:';
						}
						if ( 'zaslat' === global_api ) {
							form_link     = 'https://www.zaslat.cz/kontakt';
							support_title = 'Support Zaslat:';
						}

						let support_text = '<div id="help_settings-description"><p><b id="alsendo-connect-help-title">' + support_title + '</b><br><b>' +
							'In case of questions/problems related to the plugin,\n' +
							'please contact us via the </b><a href="' + form_link + '" target="_blank">Contact form\n' +
							'</a><br>Probably you can find some logs <a\n' +
							'        href="' + alsendo_admin.logs_url + '"\n' +
							'        target="_blank">here</a></p>\n' +
							'</div>';
						$( help_notice ).replaceWith( support_text );
					}
				}
			);

			$( "#alsendo_connect_load_package_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#alsendo_connect_settings_general_select_package_template' ).val();
					apaczkaFillPackageFormByTemplate( selectedTemplateSlug );
					$( '#alsendo_connect_settings_general_refresh_settings' ).trigger( 'click' );
				}
			);

			$( "#alsendo_connect_settings_general_select_sender_template" ).change(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug              = $( this ).val();
					const apaczkaRemoveSenderTemplateSlug = $( "#alsendo_connect_remove_sender_template_slug" );
					apaczkaRemoveSenderTemplateSlug.val( selectedTemplateSlug );
					apaczkaRemoveSenderTemplateSlug.attr( 'disabled', false );
					$( "#alsendo_connect_remove_parcel_template_slug" ).attr( 'disabled', true );
				}
			);

			$( "#alsendo_connect_settings_general_select_package_template" ).change(
				function (e) {
					e.preventDefault();
					const apaczkaRemoveParcelTemplateSlug = $( "#alsendo_connect_remove_parcel_template_slug" );
					apaczkaRemoveParcelTemplateSlug.attr( 'disabled', false );
					let selectedTemplateSlug = $( this ).val();
					apaczkaRemoveParcelTemplateSlug.val( selectedTemplateSlug );
					$( "#alsendo_connect_remove_sender_template_slug" ).attr( 'disabled', true )
				}
			);

			$( "#alsendo_connect_remove_sender_template_btn" ).click(
				function (e) {
					e.preventDefault();
					$( "#alsendo_connect_remove_sender_template" ).val( 1 );
					$( '[name="save"]' ).click();

					return false;
				}
			);

			$( "#alsendo_connect_remove_parcel_template_btn" ).click(
				function (e) {
					e.preventDefault();
					$( "#alsendo_connect_remove_parcel_template" ).val( 1 );
					$( '[name="save"]' ).click();

					return false;
				}
			);

			$( '#alsendo_connect_remove_sender_template_slug' ).val( $( '#alsendo_connect_settings_general_select_sender_template' ).val() )

			$( "#alsendo_connect_load_sender_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#alsendo_connect_settings_general_select_sender_template' ).val();
					apaczkaFillFormByTemplate( selectedTemplateSlug );
					$( '#alsendo_connect_settings_general_refresh_settings' ).trigger( 'click' );
				}
			);

			if ( 'apaczka' === api_type || 'ecolet' === api_type ) {
				$( "#alsendo_connect_settings_general_service" ).change(
					function (e) {
						validateShippingPointSelected();
					}
				);
			} else {
				$( "#alsendo_connect_settings_general_service" ).change(
					function (e) {
						zaslatValidateShippingPointSelected();
					}
				);
			}

			$( "#alsendo_connect_settings_general_dispath_point_ups" ).change(
				function (e) {
					validateShippingPointSelected();
				}
			);

			$( "#alsendo_connect_settings_general_dispath_point_kurier48" ).change(
				function (e) {
					validateShippingPointSelected();
				}
			);

			$( "#alsendo_connect_settings_general_dispath_point_inpost" ).change(
				function (e) {
					validateShippingPointSelected();
				}
			);

			$( "#alsendo_connect_settings_general_dispath_point_dpd" ).change(
				function (e) {
					validateShippingPointSelected();
				}
			);

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

					if (target.hasAttribute( 'name' ) && 'save' === target.getAttribute( 'name' ) ) {
					}

					if (target.hasAttribute( 'id' ) ) {

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

						if ( 'alsendo_connect_settings_general_dispath_point_dpd' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_dhl' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_ups' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_kurier48' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_inpost' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_cargus' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_fan_courier' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_gls' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_sameday' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_ppl' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_zasilkovna' === target.getAttribute( 'id' )
							|| 'alsendo_connect_settings_general_dispath_point_balikovna' === target.getAttribute( 'id' )

						) {

							let api_type = alsendo_admin.api_type;
							//let dispatch_zip = $( '#alsendo_connect_settings_general_sender_postal_code').val();
							let dispatch_zip = '20-002';
							if ( 'apaczka' === api_type ) {
								map_sender_country         = 'PL';
								map_sender_initial_address = 'Warszawa';
							}
							if ( 'ecolet' === api_type ) {
								map_sender_country         = 'RO';
								dispatch_zip               = '420081';
								map_sender_initial_address = 'Bucuresti';
							}

							if ( 'zaslat' === api_type ) {
								map_sender_country         = 'CZ';
								dispatch_zip               = '14000';
								let cz_address             = $( '#alsendo_connect_settings_general_zaslat_address_full option:selected' ).text();
								let cz_city_name           = cz_address.split( ',' )[2].trim();
								map_sender_initial_address = cz_city_name;
							}

							const field = target;
							e.preventDefault();
							console.log( 'admin: dispath_point' );
							console.log( map_sender_initial_address + ' ' + dispatch_zip );
							console.log( 'admin: map_country_code :' + map_sender_country );
							let operators = '';

							if ( 'alsendo_connect_settings_general_dispath_point_sameday' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'SAMEDAY' }];
							}

							if ( 'alsendo_connect_settings_general_dispath_point_gls' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'GLS' }];
							}

							if ( 'alsendo_connect_settings_general_dispath_point_fan_courier' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'FAN_COURIER' }];
							}

							if ( 'alsendo_connect_settings_general_dispath_point_cargus' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'CARGUS' }];
							}

							if ( 'alsendo_connect_settings_general_dispath_point_dpd' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'DPD' }];
							}
							if ( 'alsendo_connect_settings_general_dispath_point_dhl' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'DHL' }];
								if ( 'apaczka' !== api_type ) {
									operators = [{ operator: 'DHL_PARCEL' }];
								}
							}
							if ( 'alsendo_connect_settings_general_dispath_point_ups' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'UPS' }];
							}
							if ( 'alsendo_connect_settings_general_dispath_point_kurier48' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'POCZTA' }];
							}
							if ( 'alsendo_connect_settings_general_dispath_point_inpost' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'INPOST' }];
							}
							if ( 'alsendo_connect_settings_general_dispath_point_ppl' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'PPL' }];
							}
							if ( 'alsendo_connect_settings_general_dispath_point_zasilkovna' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'PACKETA' }];
							}
							if ( 'alsendo_connect_settings_general_dispath_point_balikovna' === target.getAttribute( 'id' ) ) {
								operators = [{ operator: 'BALIKOVNA' }];
							}

							console.log( 'admin: operator' );
							console.log( operators );

							BPWidget.init(
								document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
								{
									callback: function (point) {
										console.log( point );
										field.value             = point.code;
										let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
										map_modal.style.display = 'none';
										$( '#alsendo_connect_settings_general_refresh_settings' ).trigger( 'click' );
									},
									language: alsendo_admin.lang,
									posType: 'DELIVERY',
									mapOptions: { zoom: 12 },
									codOnly: false,
									operatorMarkers: true,
									countryCodes: map_sender_country,
									initialAddress: map_sender_initial_address + ' ' + dispatch_zip,
									operators: operators,
									codeSearch: true,
									is_for_sender: true
								}
							);

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

					}

				},
				false
			);

		}
	);
})( jQuery );