/**
 * Check the URL param to dynamically display the default WooCommerce submit button when the test param is passed to the URL
 */

"use strict"
function ready(callbackFunc) {
    if (document.readyState !== 'loading') {
        // Document is already ready, call the callback directly
        callbackFunc();
    } else if (document.addEventListener) {
        // All modern browsers to register DOMContentLoaded
        document.addEventListener('DOMContentLoaded', callbackFunc);
    } else {
        // Old browsers IE, etc...
        document.attachEvent('onreadystatechange', function () {
            if (document.readyState === 'complete') {
                callbackFunc();
            }
        });
    }
}

ready(function () {

    /**
     * DOM Selectors
     */
    var currentURL = window.location.toString();
    var chequePaymentMethod = document.querySelector('#order_review');

    /**
     * Using MutationObserver we observe mutations/changes to make sure that
     */
    var observeChequePaymentForm = function () {
        var targetNode = chequePaymentMethod;
        var config = {
            attributes: false,
            childList: true,
            subtree: true,
            characterData: true
        };
        var mutationChecker = function (mutationsList, observer) {
            for (var mutation of mutationsList) {
                if (mutation.addedNodes && mutation.type === 'childList') {
                    var addedElements = mutation.addedNodes;
                    addedElements.forEach(function (element) {
                        var elementChildren = element.childNodes;
                        if (elementChildren !== '' && element.id === 'payment') {
                            var woocommerceBtnContainer = element.querySelector('.place-order');
                            woocommerceBtnContainer.style.display = 'block';
                            observer.disconnect();
                        }
                    });
                }
            }
        };
        var observer = new MutationObserver(mutationChecker);
        observer.observe(targetNode, config);
    }

    /**
     * Call the function only if the test param is passed
     */
    if (currentURL.match(/rg_offline=true/gi)) {
		var woocommerceBtnContainer = document.querySelector('.place-order');
		woocommerceBtnContainer.style.display = 'block';
        observeChequePaymentForm();
    }
	
});


