/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

var stripeLoaded = false;

function loadStripeJs(callback) {
    if (stripeLoaded) {
        callback();
    } else {
        $.getScript("https://js.stripe.com/v3/", function () {
            stripeLoaded = true;
            callback();
        });
    }
}

function initStripeJs(callback) {
    // Wait for Stripe to be loaded
    if (typeof Stripe == 'undefined') {
        setTimeout(initStripeJs, 500);
        return;
    }
    stripe = Stripe(SETTINGS["stripe_pubkey"]);
    callback();
}


function initStripeElements(elementsselector, errormsgselector) {
    elements = stripe.elements();

    card = elements.create('card');

    // stop console warning "This Element will be mounted to a DOM element that contains child nodes."
    $(elementsselector).html("");

    card.mount(elementsselector);

    card.addEventListener('change', function (event) {
        if (event.error) {
            $(errormsgselector).text(event.error.message);
        } else {
            $(errormsgselector).text("");
        }
    });
}