jQuery(document).ready(function () {
    var iframe = document.getElementById("TrustPayFrame");

    iframe.style.position = 'fixed';
    iframe.style.left = 0;
    iframe.style.right = 0;
    iframe.style.top = 0;
    iframe.style.bottom = 0;
    iframe.style.width = 0;
    iframe.style.height = 0;
    iframe.style.border = 'none';
    iframe.style.opacity = 0;
    iframe.style.transition = 'opacity .5s ease-in-out';
    iframe.style.zIndex = '99999';

    if (window.addEventListener) {
        window.addEventListener("message", onMessage, false);
    }
    else if (window.attachEvent) {
        window.attachEvent("onmessage", onMessage, false);
    }

    jQuery(".show-popup").on("click",
        function (e) {
            if(jQuery('#payment_method_trustpay_gateway').is(':checked')) {
                e.preventDefault();
                openPopup();
            }
            else {
                jQuery('form.checkout').trigger('submit');
            }
        });
});

function onMessage(event) {
    var data = event.data;

    if (typeof(window[data.func]) === "function") {
        window[data.func].call(null, data.message);
    }
}

function openPopup() {
    var iframe = document.getElementById("TrustPayFrame");
    iframe.style.opacity = 1;
    iframe.style.width = '100%';
    iframe.style.height = '100%';
    iframe.focus();
    iframe.contentWindow.postMessage('redirectMessage', '*');
    iframe.contentWindow.postMessage('authorizationMessage', '*');
}

function closePopup(message) {
    var iframe = document.getElementById('TrustPayFrame');
    iframe.style.opacity = 0;

    // Delay execution so that the iframe changes dimension only after opacity is 0
    setTimeout(function() {
        iframe.style.width = 0;
        iframe.style.height = 0;
    }, 1000);
}

function redirectPopup(url) {
    window.top.location.href = url;
}
