if (typeof(jQuery) !== 'undefined') {
    /* global jQuery, setTimeout, clearTimeout */
    (function($) {
        "use strict";
        $(document).ready(function() {
            if (typeof(oktagon_wc_xconnect_frontend_data) !== 'undefined') {
                /* global oktagon_wc_xconnect_frontend_data */

                var oktagon_wc_xconnect_frontend_select_pick_up_point_request = null;

                var oktagon_wc_xconnect_frontend_select_custom_zip_code_request = null;

                var oktagon_wc_xconnect_frontend_get_shipping_rates_meta_data_request = null;

                var oktagon_wc_xconnect_frontend_previous_shipping_packages = null;

                var oktagon_wc_xconnect_frontend_shipping_rates_meta_data = {};

                /**
                 * @param {Function} callback
                 */
                function oktagon_wc_xconnect_frontend_debug(callback) {
                    if (oktagon_wc_xconnect_frontend_data.is_debug === '1') {
                        callback();
                    }
                }

                /**
                 * @param {String} nonce
                 * @param {Function} successCallback
                 */
                function oktagon_wc_xconnect_frontend_get_shipping_rates_meta_data(
                    nonce,
                    successCallback
                ) {
                    if (oktagon_wc_xconnect_frontend_get_shipping_rates_meta_data_request) {
                        oktagon_wc_xconnect_frontend_get_shipping_rates_meta_data_request.abort();
                    }
                    oktagon_wc_xconnect_frontend_get_shipping_rates_meta_data_request = $.ajax({
                        data: {
                            action: 'oktagon-x-connect-for-woocommerce-frontend-get-shipping-rates-meta-data',
                            nonce: nonce
                        },
                        dataType: 'json',
                        error: function(response) {
                            console.log('ajax error response');
                            console.log(response);
                        },
                        success: function(response) {
                            oktagon_wc_xconnect_frontend_debug(function() {
                                console.log('ajax response:');
                                console.log(response);
                            });

                            if (
                                typeof(response.success) === 'boolean'
                                && response.success === true
                                && typeof(response.meta_data) === 'object'
                                && response.meta_data !== null
                            ) {
                                successCallback(response.meta_data);
                            }
                        },
                        type: 'post',
                        url: oktagon_wc_xconnect_frontend_data.ajax_url
                    });
                }

                /**
                 * @param {String} nonce
                 * @param {String} zipCode
                 */
                function oktagon_wc_xconnect_frontend_select_custom_zip_code(
                    nonce,
                    zipCode
                ) {
                    if (oktagon_wc_xconnect_frontend_select_custom_zip_code_request) {
                        oktagon_wc_xconnect_frontend_select_custom_zip_code_request.abort();
                    }
                    oktagon_wc_xconnect_frontend_select_custom_zip_code_request = $.ajax({
                        data: {
                            action: 'oktagon-x-connect-for-woocommerce-frontend-select-custom-zip-code',
                            nonce: nonce,
                            zipCode: zipCode
                        },
                        dataType: 'json',
                        error: function(response) {
                            console.log('ajax error response');
                            console.log(response);
                        },
                        success: function(response) {
                            oktagon_wc_xconnect_frontend_debug(function() {
                                console.log('ajax response:');
                                console.log(response);
                            });

                            if (
                                typeof(response.success) === 'boolean'
                                && response.success === true
                                && typeof(response.zipCode) === 'string'
                            ) {
                                var newZipCode = response.zipCode;

                                var updatedClientSide = false;

                                // Set zip-code here and then update checkout if any values changed
                                if ($('#billing_postcode').length) {
                                    var old = $('#billing_postcode').val();
                                    if (old !== newZipCode) {
                                        $('#billing_postcode').val(newZipCode);
                                        updatedClientSide = true;
                                    }
                                }

                                if (updatedClientSide) {
                                    $(document.body).trigger('update_checkout');
                                }

                                // Trigger update of block based checkout
                                if (
                                    typeof(window.wc) !== 'undefined'
                                    && typeof(window.wc.blocksCheckout) !== 'undefined'
                                    && typeof(window.wc.blocksCheckout.extensionCartUpdate) !== 'undefined'
                                ) {
                                    window.wc.blocksCheckout.extensionCartUpdate({ namespace: 'oktagon-x-connect-update-frontend' });
                                    oktagon_wc_xconnect_frontend_previous_shipping_packages = null;
                                }
                            }
                        },
                        type: 'post',
                        url: oktagon_wc_xconnect_frontend_data.ajax_url
                    });
                }

                /**
                 * @param {String} nonce
                 * @param {String} packageHashKey
                 * @param {String} rateId
                 * @param {String} address
                 * @param {String} id
                 * @param {String} title
                 * @param {Object} element
                 */
                function oktagon_wc_xconnect_frontend_select_pick_up_point(
                    nonce,
                    packageHashKey,
                    rateId,
                    address,
                    id,
                    title,
                    element
                ) {
                    if (oktagon_wc_xconnect_frontend_select_pick_up_point_request) {
                        oktagon_wc_xconnect_frontend_select_pick_up_point_request.abort();
                    }
                    oktagon_wc_xconnect_frontend_select_pick_up_point_request = $.ajax({
                        data: {
                            action: 'oktagon-x-connect-for-woocommerce-frontend-select-pick-up-point',
                            address: address,
                            id: id,
                            nonce: nonce,
                            package: packageHashKey,
                            rateId: rateId,
                            title: title
                        },
                        dataType: 'json',
                        error: function(response) {
                            console.log('ajax error response');
                            console.log(response);
                        },
                        success: function(response) {
                            oktagon_wc_xconnect_frontend_debug(function() {
                                console.log('ajax response:');
                                console.log(response);
                            });
                            $(
                                '.xconnect-checkout-chosen-agent',
                                $(element).parent().parent()
                            ).text(response.title);
                            $(
                                '.xconnect-checkout-chosen-agent',
                                $(element).parent().parent()
                            ).attr('data-id', response.id);
                            $(
                                '.xconnect-checkout-chosen-agent-description',
                                $(element).parent().parent()
                            ).text(response.address);
                            $(element).val('');
                        },
                        type: 'post',
                        url: oktagon_wc_xconnect_frontend_data.ajax_url
                    });
                }

                oktagon_wc_xconnect_frontend_debug(function() {
                    console.log('Oktagon WooCommerce X-Connect Configuration:');
                    console.log(oktagon_wc_xconnect_frontend_data);
                });

                // Clicking on a not selected shipping method
                $('.woocommerce').on('click', '.xconnect-checkout-option-not-selected', function(event) {
                    $('input.shipping_method', $(this).parent()).trigger('click');
                });

                // Selecting a pick up point
                $('.woocommerce').on('change', '.xconnect-checkout-option-select', function(event) {
                    var nonce = oktagon_wc_xconnect_frontend_data.nonce;
                    var rateId = $(this).attr('data-rate-id');
                    var packageHashKey = $(this).attr('data-package');
                    var selectedOption = $('option:selected', this);
                    var address = $(selectedOption).attr('data-address');
                    var id = $(selectedOption).val();
                    var title = $(selectedOption).attr('data-title');
                    if (id !== '') {
                        oktagon_wc_xconnect_frontend_debug(function() {
                            console.log('Selected pick up point:');
                            console.log(id);
                        });
                        oktagon_wc_xconnect_frontend_select_pick_up_point(
                            nonce,
                            packageHashKey,
                            rateId,
                            address,
                            id,
                            title,
                            this
                        );
                    }
                });

                // Searching a zip-code in the zip-code selector
                $('.woocommerce').on('keypress', '.xconnect-checkout-search-input', function(event) {
                    var code = event.keyCode || event.which;
                    if (code == 13) {
                        event.preventDefault();
                        var nonce = oktagon_wc_xconnect_frontend_data.nonce;
                        var zipCode = $(this).val();
                        if (zipCode !== '') {
                            oktagon_wc_xconnect_frontend_select_custom_zip_code(
                                nonce,
                                zipCode
                            );
                        }
                    }
                });
                $('.woocommerce').on('click', '.xconnect-checkout-search-input-button', function(event) {
                    event.preventDefault();
                    var nonce = oktagon_wc_xconnect_frontend_data.nonce;
                    var zipCode = $('.woocommerce .xconnect-checkout-search-input').val();
                    if (zipCode !== '') {
                        oktagon_wc_xconnect_frontend_select_custom_zip_code(
                            nonce,
                            zipCode
                        );
                    }
                });

                $('body').addClass('oktagon-x-connect-for-woocommerce-frontend');

                if (oktagon_wc_xconnect_frontend_data.adjust_order_review_design) {
                    $('body').addClass('oktagon-x-connect-for-woocommerce-frontend-do-adjust-order-review');
                } else {
                    $('body').addClass('oktagon-x-connect-for-woocommerce-frontend-do-not-adjust-order-review');
                }

                // Checkout Blocks support
                function loadCheckoutBlocks(pause)
                {
                    if (
                        typeof(window) !== 'object'
                            || typeof(window.wp) !== 'object'
                            || typeof(window.wp.data) !== 'object'
                            || typeof(window.wp.data.select) !== 'function'
                            || typeof(window.wc) !== 'object'
                            || typeof(window.wc.wcBlocksData) !== 'object'
                            || typeof(window.wc.wcBlocksData.CART_STORE_KEY) !== 'string'
                    ) {
                        oktagon_wc_xconnect_frontend_debug(function() {
                            console.log('Did not detect WooCommerce Checkout Blocks');
                        });
                        setTimeout(
                            function() {
                                loadCheckoutBlocks(pause);
                            },
                            pause
                        );
                        return;

                    }
                    oktagon_wc_xconnect_frontend_debug(function() {
                        console.log('Detected WooCommerce Checkout Blocks');
                    })
                    var shippingPackages =
                        window.wp.data.select(window.wc.wcBlocksData.CART_STORE_KEY).getShippingRates();
                    if (
                        typeof(shippingPackages) !== 'object'
                            || shippingPackages === null
                    ) {
                        oktagon_wc_xconnect_frontend_debug(function() {
                            console.log('Shipping packages is undefined');
                        })
                        setTimeout(
                            function() {
                                loadCheckoutBlocks(pause);
                            },
                            pause
                        );
                        return;
                    }

                    if (
                        JSON.stringify(shippingPackages) === oktagon_wc_xconnect_frontend_previous_shipping_packages
                    ) {
                        oktagon_wc_xconnect_frontend_debug(function() {
                            console.log('Shipping packages equal previous, ignoring re-process');
                        })
                        setTimeout(
                            function() {
                                loadCheckoutBlocks(pause);
                            },
                            pause
                        );
                        return;
                    }
                    oktagon_wc_xconnect_frontend_previous_shipping_packages =
                        JSON.stringify(shippingPackages);
                    oktagon_wc_xconnect_frontend_debug(function() {
                        console.log('Detected new shippingPackages:');
                        console.log(shippingPackages);
                    });

                    oktagon_wc_xconnect_frontend_get_shipping_rates_meta_data(
                        oktagon_wc_xconnect_frontend_data.nonce,
                        function(metaData) {
                            var shippingPackages =
                                window.wp.data.select(window.wc.wcBlocksData.CART_STORE_KEY).getShippingRates();
                            var shippingPackageKey, shippingPackage;
                            var shippingPackageHashKey, shippingPackageItemKey, shippingPackageItem, shippingPackageItemCount;
                            var shippingRates, shippingRateKey, shippingRate, shippingRateId, shippingRateInput, shippingRateInputSelector, shippingRateContainer;
                            var shippingRateMetaData, shippingRateHtml, shippingRateMetaDataKey, shippingRateMetaDataObject;
                            var showZipCodeSelector = oktagon_wc_xconnect_frontend_data.show_zip_code_selector;
                            var shippingRatesContainer = $('.wc-block-components-shipping-rates-control').first();
                            var alreadyAddedSearchForm = $('.oktagon-x-connect-search-container').length > 0;
                            if (
                                shippingRatesContainer
                                && !alreadyAddedSearchForm
                                && showZipCodeSelector
                            ) {
                                var searchZipCodeHtml = '<div class="oktagon-x-connect-search-container">'
                                    + '<p class="xconnect-checkout-search-header-text">'
                                    + oktagon_wc_xconnect_frontend_data.i18n.SEARCH_DELIVERY_OPTIONS_HEADING
                                    + '</p>'
                                    + '<div class="xconnect-checkout-search-input-box">'
                                    + '<input class="xconnect-checkout-search-input" type="text" placeholder="ex. 123 45" />'
                                    + '<div class="xconnect-checkout-search-input-placeholder">'
                                    + '<span class="xconnect-checkout-search-input-placeholder-text">'
                                    + oktagon_wc_xconnect_frontend_data.i18n.ENTER_YOUR_ZIP_CODE_PLACEHOLDER
                                    + '</span>'
                                    + '</div>'
                                    + '<button type="button" class="xconnect-checkout-search-input-button">'
                                    + oktagon_wc_xconnect_frontend_data.i18n.SEARCH_BUTTON_LABEL
                                    + '</button>'
                                    + '</div>'
                                    + '<div class="xconnect-checkout-header-box">'
                                    + '<p class="xconnect-checkout-header-text">'
                                    + oktagon_wc_xconnect_frontend_data.i18n.CHOOSE_DELIVERY_OPTION_HEADING
                                    + '</p>'
                                    + '</div>'
                                    + '</div>';
                                shippingRatesContainer.prepend(searchZipCodeHtml);

                                // Searching a zip-code in the zip-code selector
                                $('.wp-block-woocommerce-checkout-shipping-methods-block').on('keypress', '.xconnect-checkout-search-input', function(event) {
                                    var code = event.keyCode || event.which;
                                    if (code == 13) {
                                        event.preventDefault();
                                        var nonce = oktagon_wc_xconnect_frontend_data.nonce;
                                        var zipCode = $(this).val();
                                        if (zipCode !== '') {
                                            oktagon_wc_xconnect_frontend_select_custom_zip_code(
                                                nonce,
                                                zipCode
                                            );
                                        }
                                    }
                                });
                                $('.wp-block-woocommerce-checkout-shipping-methods-block').on('click', '.xconnect-checkout-search-input-button', function(event) {
                                    event.preventDefault();
                                    var nonce = oktagon_wc_xconnect_frontend_data.nonce;
                                    var zipCode = $('.wp-block-woocommerce-checkout-shipping-methods-block .xconnect-checkout-search-input').val();
                                    if (zipCode !== '') {
                                        oktagon_wc_xconnect_frontend_select_custom_zip_code(
                                            nonce,
                                            zipCode
                                        );
                                    }
                                });

                                oktagon_wc_xconnect_frontend_debug(function() {
                                    console.log('Added the search form');
                                });
                            } else if (!shippingRatesContainer && !alreadyAddedSearchForm) {
                                oktagon_wc_xconnect_frontend_debug(function() {
                                    console.log('Found nowhere to place the search form!');
                                });
                            }

                            for (shippingPackageKey in shippingPackages) {
                                if (shippingPackages.hasOwnProperty(shippingPackageKey)) {
                                    shippingPackage =
                                        shippingPackages[shippingPackageKey];
                                    shippingPackageHashKey = '';
                                    shippingPackageItemCount = 0;
                                    if (typeof(shippingPackage.items) === 'object') {
                                        for (shippingPackageItemKey in shippingPackage.items) {
                                            if (!shippingPackage.items.hasOwnProperty(shippingPackageItemKey)) {
                                                continue;
                                            }
                                            shippingPackageItem = shippingPackage.items[shippingPackageItemKey];
                                            if (typeof(shippingPackageItem.key) !== 'string') {
                                                continue;
                                            }
                                            if (shippingPackageItemCount > 0) {
                                                shippingPackageHashKey += ',';
                                            }
                                            shippingPackageHashKey += shippingPackageItem.key;
                                            shippingPackageItemCount++;
                                        }
                                    }
                                    oktagon_wc_xconnect_frontend_debug(function() {
                                        console.log('shippingPackageHashKey: ' + shippingPackageHashKey);
                                    });
                                    if (
                                        typeof(shippingPackage.shipping_rates) !== 'object'
                                            || shippingPackage.shipping_rates === null
                                    ) {
                                        continue;
                                    }
                                    for (shippingRateKey in shippingPackage.shipping_rates) {
                                        if (!shippingPackage.shipping_rates.hasOwnProperty(shippingRateKey)) {
                                            continue;
                                        }
                                        shippingRate =
                                            shippingPackage.shipping_rates[shippingRateKey];
                                        oktagon_wc_xconnect_frontend_debug(function() {
                                            console.log('shippingRate:');
                                            console.log(shippingRate);
                                        });
                                        shippingRateId =
                                            shippingRate.rate_id;
                                        shippingRateInputSelector =
                                            'input[type="radio"][value="' + shippingRateId + '"]';
                                        shippingRateInput =
                                            $(shippingRateInputSelector);
                                        if (shippingRateInput.length === 0) {
                                            oktagon_wc_xconnect_frontend_debug(function() {
                                                console.log(
                                                    'Failed to find shipping rate selector: '
                                                        + shippingRateInputSelector
                                                );
                                            });
                                            continue;
                                        }
                                        if (
                                            typeof(shippingRate.method_id) !== 'string'
                                                ||shippingRate.method_id !== 'oktagon-x-connect-for-woocommerce'
                                        ) {
                                            oktagon_wc_xconnect_frontend_debug(function() {
                                                console.log('Shipping rate is of not from us, skipping..');
                                            });
                                            continue;
                                        }
                                        if (
                                            typeof(shippingRate.instance_id) !== 'number'
                                        ) {
                                            oktagon_wc_xconnect_frontend_debug(function() {
                                                console.log('Missing shipping rate instance id, skipping..');
                                            });
                                            continue;
                                        }
                                        var instanceId = shippingRate.instance_id;

                                        if (!shippingRateInput.length) {
                                            oktagon_wc_xconnect_frontend_debug(function() {
                                                console.log('Found no selector with: "' + shippingRateInputSelector + '"');
                                            });
                                            continue;
                                        }

                                        shippingRateContainer = shippingRateInput.parent();

                                        // Collect meta data
                                        shippingRateMetaData = metaData[shippingRateId] ?? {
                                            carrier: '',
                                            customLogo: '',
                                            enabledPickUpPointSelection: false,
                                            description: '',
                                            nonce: '',
                                            pickUpAgents: {},
                                            predefinedLogo: '',
                                            selectedPickUpPoint: {},
                                            shippingService: ''
                                        };

                                        if (
                                            typeof(shippingRate.meta_data) === 'object'
                                                && shippingRate.meta_data !== null
                                        ) {
                                            for (shippingRateMetaDataKey in shippingRate.meta_data) {
                                                if (shippingRate.meta_data.hasOwnProperty(shippingRateMetaDataKey)) {
                                                    shippingRateMetaDataObject = shippingRate.meta_data[shippingRateMetaDataKey];
                                                    if (
                                                        typeof(shippingRateMetaDataObject.key) === 'string'
                                                            && shippingRateMetaDataObject.key !== ''
                                                            && typeof(shippingRateMetaDataObject.value) !== 'undefined'
                                                    ) {
                                                        if (
                                                            shippingRateMetaDataObject.key === 'carrier'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.carrier =shippingRateMetaDataObject.value; 
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'customLogo'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.customLogo = shippingRateMetaDataObject.value; 
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'description'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.description = shippingRateMetaDataObject.value; 
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'enabledPickUpPointSelection'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.enabledPickUpPointSelection = shippingRateMetaDataObject.value; 
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'pickUpAgents'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.pickUpAgents = JSON.parse(shippingRateMetaDataObject.value);
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'predefinedLogo'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.predefinedLogo = shippingRateMetaDataObject.value; 
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'selectedPickUpPoint'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.selectedPickUpPoint = JSON.parse(shippingRateMetaDataObject.value);
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'shippingService'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.shippingService = shippingRateMetaDataObject.value; 
                                                        }
                                                        if (
                                                            shippingRateMetaDataObject.key === 'nonce'
                                                                && typeof(shippingRateMetaDataObject.value) === 'string'
                                                                && shippingRateMetaDataObject.value !== ''
                                                        ) {
                                                            shippingRateMetaData.nonce = shippingRateMetaDataObject.value; 
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        oktagon_wc_xconnect_frontend_debug(function() {
                                            console.log('shippingRateMetaData:');
                                            console.log(shippingRateMetaData);
                                        });

                                        shippingRateHtml = '<div class="oktagon-x-connect-shipping-rate-meta" '
                                            + 'data-rate-id="' + shippingRate.rate_id + '" '
                                            + 'data-package-hash="' + shippingPackageHashKey + '"'
                                            + 'data-shipping-service="' + shippingRateMetaData.shippingService + '" '
                                            + 'data-nonce="' + shippingRateMetaData.nonce + '" '
                                            + '>';

                                        if (shippingRateMetaData.description) {
                                            shippingRateHtml += '<span class="oktagon-x-connect-shipping-rate-description">'
                                                + shippingRateMetaData.description
                                                + '</span>';
                                        }

                                        if (shippingRateMetaData.customLogo) {
                                            shippingRateHtml += '<img src="' + shippingRateMetaData.customLogo + '" '
                                                + 'class="oktagon-x-connect-shipping-rate-logo" alt="carrier-logo" />';
                                        } else if (shippingRateMetaData.predefinedLogo) {
                                            shippingRateHtml += '<img src="' + shippingRateMetaData.predefinedLogo + '" '
                                                + 'class="oktagon-x-connect-shipping-rate-logo" alt="carrier-logo" />';
                                        }

                                        var agentOptions = '';

                                        if (
                                            shippingRateMetaData.enabledPickUpPointSelection
                                        ) {
                                            var agentId, agent, agentIsSelected;
                                            for (agentId in shippingRateMetaData.pickUpAgents) {
                                                if (shippingRateMetaData.pickUpAgents.hasOwnProperty(agentId)) {
                                                    agent =
                                                        shippingRateMetaData.pickUpAgents[agentId];
                                                    if (
                                                        typeof(agent.address) === 'string'
                                                            && agent.address !== ''
                                                            && typeof(agent.title) === 'string'
                                                            && agent.title !== ''
                                                    ) {
                                                        agentIsSelected = false;
                                                        if (
                                                            typeof(shippingRateMetaData.selectedPickUpPoint.id) === 'string'
                                                                && shippingRateMetaData.selectedPickUpPoint.id === agentId
                                                        ) {
                                                            agentIsSelected = true;
                                                        }
                                                        agentOptions += '<option data-address="' + agent.address + '" data-title="' + agent.title + '" '
                                                            + 'value="' + agentId + '"' + (agentIsSelected ? ' checked="checked"' : '')
                                                            + '>' + agent.title + ', ' + agent.address + '</option>';
                                                    }
                                                }
                                            }
                                        }

                                        if (
                                            typeof(shippingRateMetaData.selectedPickUpPoint.address) === 'string'
                                                && typeof(shippingRateMetaData.selectedPickUpPoint.id) === 'string'
                                                && typeof(shippingRateMetaData.selectedPickUpPoint.title) === 'string'
                                                && agentOptions
                                        ) {
                                            shippingRateHtml +=
                                                '<div class="oktagon-x-connect-agents">'
                                                + '<div class="oktagon-x-connect-selected-agent">'
                                                + '<p class="oktagon-x-connect-selected-agent-heading">'
                                                + oktagon_wc_xconnect_frontend_data.i18n.DELIVER_TO_THIS_SERVICE_POINT
                                                + '</p>'
                                                + '<label>'
                                                + '<div class="oktagon-x-connect-selected-agent-data" data-id="'
                                                + shippingRateMetaData.selectedPickUpPoint.id + '">'
                                                + '<span class="oktagon-x-connect-selected-agent-title">'
                                                + shippingRateMetaData.selectedPickUpPoint.title
                                                + '</span>'
                                                + '<span class="oktagon-x-connect-selected-agent-address">'
                                                + shippingRateMetaData.selectedPickUpPoint.address
                                                + '</span>'
                                                + '</div>'
                                                + '<div class="oktagon-x-connect-dropdown-icon-box">'
                                                + '<span class="oktagon-x-connect-dropdown-icon"></span>'
                                                + '</div>'
                                                + '<select class="select-agent">' + agentOptions + '</select>'
                                                + '</label>'
                                                + '</div>';
                                        }

                                        shippingRateHtml += '</div>';

                                        if ($('.oktagon-x-connect-shipping-rate-meta', shippingRateContainer).length > 0) {
                                            $('.oktagon-x-connect-shipping-rate-meta', shippingRateContainer).replaceWith(shippingRateHtml);
                                        } else {
                                            $(shippingRateContainer).append(shippingRateHtml);
                                        }

                                        oktagon_wc_xconnect_frontend_debug(function() {
                                            console.log('Re-painted shipping rate');
                                        });

                                        $('.oktagon-x-connect-agents select', shippingRateContainer).change(function(event) {
                                            var selected = $(this).find('option:selected');
                                            var selectedAgent = {
                                                address: $(selected).attr('data-address'),
                                                id: $(selected).val(),
                                                title: $(selected).attr('data-title')
                                            };

                                            oktagon_wc_xconnect_frontend_debug(function() {
                                                console.log('Changed selected agent to:');
                                                console.log(selectedAgent);
                                            });

                                            $('.oktagon-x-connect-selected-agent-address', $(this).parent()).text(selectedAgent.address);
                                            $('.oktagon-x-connect-selected-agent-data', $(this).parent()).attr('data-id', selectedAgent.id);
                                            $('.oktagon-x-connect-selected-agent-title', $(this).parent()).text(selectedAgent.title);

                                            var rateId =
                                                $(this).parents('.oktagon-x-connect-shipping-rate-meta').first().attr('data-rate-id');
                                            var packageHashKey =
                                                $(this).parents('.oktagon-x-connect-shipping-rate-meta').first().attr('data-package-hash');
                                            var shippingService =
                                                $(this).parents('.oktagon-x-connect-shipping-rate-meta').first().attr('data-shipping-service');
                                            var nonce =
                                                oktagon_wc_xconnect_frontend_data.nonce;
                                            var newCartData =
                                                window.wp.data.select(window.wc.wcBlocksData.CART_STORE_KEY).getCartData();
                                            dance:
                                            for (var newPackageKey in newCartData.shippingRates) {
                                                if (newCartData.shippingRates.hasOwnProperty(newPackageKey)) {
                                                    var newPackage = newCartData.shippingRates[newPackageKey];
                                                    for (var newRateKey in newPackage.shipping_rates) {
                                                        if (newPackage.shipping_rates.hasOwnProperty(newRateKey)) {
                                                            var newRate = newPackage.shipping_rates[newRateKey];
                                                            if (
                                                                typeof(newRate.rate_id) === 'string'
                                                                    && newRate.rate_id === rateId
                                                                    && typeof(newRate.meta_data) === 'object'
                                                            ) {
                                                                for (var newMetaKey in newRate.meta_data) {
                                                                    if (newRate.meta_data.hasOwnProperty(newMetaKey)) {
                                                                        var newMetaObject = newRate.meta_data[newMetaKey];
                                                                        if (
                                                                            typeof(newMetaObject.key) === 'string'
                                                                                && newMetaObject.key === 'selectedPickUpPoint'
                                                                        ) {
                                                                            newCartData.shippingRates[newPackageKey].shipping_rates[newRateKey].meta_data[newMetaKey].value =
                                                                                JSON.stringify(selectedAgent);
                                                                            break dance;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                            oktagon_wc_xconnect_frontend_debug(function() {
                                                console.log('newCartData (before):');
                                                console.log(newCartData);
                                            });

                                            window.wp.data.dispatch(window.wc.wcBlocksData.CART_STORE_KEY).setCartData(newCartData);

                                            oktagon_wc_xconnect_frontend_debug(function() {
                                                console.log('newCartData (after):');
                                                console.log(window.wp.data.select(window.wc.wcBlocksData.CART_STORE_KEY).getCartData());
                                            });

                                            oktagon_wc_xconnect_frontend_select_pick_up_point(
                                                nonce,
                                                packageHashKey,
                                                rateId,
                                                selectedAgent.address,
                                                selectedAgent.id,
                                                selectedAgent.title
                                            );
                                        });
                                    }
                                }
                            }
                        }
                    );

                    setTimeout(
                        function() {
                            loadCheckoutBlocks(pause);
                        },
                        pause
                    );
                }

                function deferLoadingOfCheckoutsBlock(iteration, limit, pause)
                {
                    setTimeout(
                        function() {
                            if ($('.wc-block-components-shipping-rates-control__package').length) {
                                loadCheckoutBlocks(1000);
                                oktagon_wc_xconnect_frontend_debug(function() {
                                    console.log('Successfully loading checkout blocks after ' + iteration + ' iterations.');
                                });
                            } else if (iteration < limit) {
                                deferLoadingOfCheckoutsBlock(iteration + 1, limit, pause);
                            } else {
                                oktagon_wc_xconnect_frontend_debug(function() {
                                    console.log('Failed loading checkout blocks after ' + iteration + ' iterations.');
                                });
                            }
                        },
                        pause
                    );
                }
                deferLoadingOfCheckoutsBlock(1, 100, 50);

            }
        });
    })(jQuery);
}
