(function($) {
    'use strict';
    var initialized = false;
    $(document.body).on('updated_checkout', function() {
        if (initialized) {
            return;
        }
        invoice_pay_func();
        initialized = true;
    });

    function invoice_pay_func() {
        var invoicesubmitBtn = $('div#payment .place-order button#place_order'),
            termsContainer = $('div#payment .woocommerce-terms-and-conditions-wrapper'),
            termsField = $('div#payment [name="terms-field"]'),
            showInvoiceCheckout = function() {
                // resursFormloader();
                invoicesubmitBtn.addClass('disableBtn')
                    .attr("disabled", true)
                    .hide();
                termsContainer.hide();
                termsField.val('0');
                $('.woocommerce-billing-fields').hide();
                $('.woocommerce-shipping-fields').hide();

                if ($('#resurs-checkout-container').length > 0)
                {
                    $('#resurs-checkout-container').show();
                    $('#resurs-checkout-container iframe').css('overflow', 'visiable');
                    $('#resurs-checkout-container iframe').css('width', '100%');
    
                    $('html, body').animate({
                        scrollTop: $("#resurs-checkout-container").offset().top - 200
                    }, 500);
                }
            },
            hideInvoiceCheckout = function() {
                invoicesubmitBtn.removeClass('disableBtn')
                    .removeAttr("disabled")
                    .show();
                termsContainer.show();
                termsField.val('1');
                $('.woocommerce-billing-fields').show();
                $('.woocommerce-shipping-fields').show();
                $('#resurs-checkout-container').hide();
            },
            paymentMethodSelected = function() {
                if ($("input#payment_method_invoice_pays:checked").length > 0) {
                    showInvoiceCheckout();
                } else {
                    hideInvoiceCheckout();
                }
            },
            init = function() {
                paymentMethodSelected();
                $('form.checkout').on('click', 'input[name="payment_method"]', paymentMethodSelected);
            };

        init();
    }
})(jQuery);
