/*
 * 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/.
 */

$("#add_camper").click(function () {
    var copyfrom = $("#camper_list .person-list-item").first();
    $.get("parts/template_person.php", {
        type: "camper",
        lastname: $("input[data-name=lastname]", copyfrom).val(),
        parentname: $("input[data-name=parentname]", copyfrom).val(),
        address: $("input[data-name=address]", copyfrom).val(),
        zip: $("input[data-name=zip]", copyfrom).val(),
        phone1: $("input[data-name=phone1]", copyfrom).val(),
        phone2: $("input[data-name=phone2]", copyfrom).val(),
        email: $("input[data-name=email]", copyfrom).val(),
        unit: $("input[data-name=unit]", copyfrom).val()
    }, function (resp) {
        $("#camper_list").append(resp);
        updateTotal();
    });
});

$("#add_adult").click(function () {
    var copyfrom = $("#adult_list .person-list-item").first();
    $.get("parts/template_person.php", {
        type: "adult",
        lastname: $("input[data-name=lastname]", copyfrom).val(),
        address: $("input[data-name=address]", copyfrom).val(),
        zip: $("input[data-name=zip]", copyfrom).val(),
        phone1: $("input[data-name=phone1]", copyfrom).val(),
        phone2: $("input[data-name=phone2]", copyfrom).val(),
        email: $("input[data-name=email]", copyfrom).val()
    }, function (resp) {
        $("#adult_list").append(resp);
        updateTotal();
    });
});

$("#add_youth").click(function () {
    var copyfrom = $("#youth_list .person-list-item").first();
    $.get("parts/template_person.php", {
        type: "youth",
        lastname: $("input[data-name=lastname]", copyfrom).val(),
        address: $("input[data-name=address]", copyfrom).val(),
        zip: $("input[data-name=zip]", copyfrom).val(),
        parentname: $("input[data-name=parentname]", copyfrom).val(),
        phone2: $("input[data-name=phone2]", copyfrom).val(),
        email: $("input[data-name=email]", copyfrom).val()
    }, function (resp) {
        $("#youth_list").append(resp);
    });
});

$("#camper_list").on("change", "input[data-name=firstname]", function () {
    updateTotal();
});

$("#adult_list").on("change", "input[data-name=days]", function () {
    updateTotal();
});

$("#youth_list").on("change", "input[data-name=days]", function () {
    updateTotal();
});

$("#adult_list").on("change", "select[data-name=shirt]", function () {
    updateTotal();
});

$("#youth_list").on("change", "select[data-name=shirt]", function () {
    updateTotal();
});

$("input[name=campcoupons]").on("input paste change blur", function () {
    updateTotal();
});

$(".list-group").on("click", ".rmpersonbtn", function () {
    $(this).parent().remove();
    updateTotal();
});

function updateTotal() {
    totalcharge = $(".person-list-item[data-persontype=camper] input[data-name=firstname]").filter(function () {
        return $(this).val() != '';
    }).length * prices.camp;

    totalcharge = totalcharge - $(".person-list-item[data-persontype=adult] input[data-name=days]:checked").filter(function () {
        return $(this).val() != '';
    }).length * prices.adult_volunteer_daily_discount;

    // Add charge for adult shirts
    totalcharge = totalcharge + $(".person-list-item[data-persontype=adult]").filter(function () {
        if (prices.adult_tshirt == false) {
            return false;
        }
        var days = $("input[data-name=days]:checked", $(this)).length;
        if (prices.alone_adult_free_tshirt == true && $(".person-list-item[data-persontype=camper]").length == 0) {
            return false;
        }
        if (days < prices.adult_tshirt && $("select[data-name=shirt]", $(this)).val() != "NO" && $("select[data-name=shirt]", $(this)).val() != "") {
            return true;
        }
        return false;
    }).length * prices.tshirt;

    // Add charge for youth shirts
    totalcharge += $(".person-list-item[data-persontype=youth]").filter(function () {
        if (prices.youth_tshirt == false) {
            return false;
        }
        var days = $("input[data-name=days]:checked", $(this)).length;
        if (days < prices.youth_tshirt && $("select[data-name=shirt]", $(this)).val() != "NO" && $("select[data-name=shirt]", $(this)).val() != "") {
            return true;
        }
        return false;
    }).length * prices.tshirt;

    var couponcharge = ($("input[name=campcoupons]").val() * 1.0);
    var cardcharge = Math.max(totalcharge - couponcharge, 0);
    if (prices.add_stripe_fees) {
        cardcharge = (cardcharge + 0.3) / (1 - 0.029);
    }

    totalcharge = Math.max(cardcharge + couponcharge, 0);

    // The server will refuse to finish the registration if this doesn't match
    // the backend-calculated amount, don't bother being a haxxor
    $("#total").text(totalcharge);
    $("input[name=totalcharge]").val(totalcharge);
    if (totalcharge <= 0) {
        $("#payment-methods").css("display", "none");
    } else {
        $("#payment-methods").css("display", "");
    }
}

// Create a Stripe client.
var stripe = Stripe(stripe_pubkey);

// Create an instance of Elements.
var elements = stripe.elements();

// Create an instance of the card Element.
var card = elements.create('card');

// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');

card.addEventListener('change', function (event) {
    if (event.error) {
        $("#card-errors").removeClass("d-none");
        $("#card-errors").text(event.error.message);
    } else {
        $("#card-errors").addClass("d-none");
        $("#card-errors").text("");
    }
});

$("#savebutton").click(function (event) {
    var form = $("#registrationform");

    console.log("Validating...");
    if (form[0].checkValidity() === false) {
        console.log("Invalid!");
        event.preventDefault();
        event.stopPropagation();
    }
    form.addClass('was-validated');
});


$("#registrationform").on("submit", function (event) {
    event.preventDefault();

    // If we have any charge left after subtracting camp coupons/scout bucks
    if ($("input[name=totalcharge]").val() - $("input[name=campcoupons]").val() > 0) {
        console.log("Charging card...");
        // prevent multiple clicks since Stripe can take a few seconds
        $("#savebutton").prop("disabled", true);
        $("#savebutton-text").addClass("d-none");
        $("#savebutton-wait").removeClass("d-none");
        var stripe_finished = false;
        var stripe_timeout = false;
        stripe.createToken(card).then(function (result) {
            if (result.error) {
                // Inform the customer that there was an error.
                stripe_finished = true;
                stripe_timeout = false;
                $("#card-errors").removeClass("d-none");
                $("#card-errors").text(event.error.message);
                $("#savebutton").prop("disabled", false);
                $("#savebutton-text").removeClass("d-none");
                $("#savebutton-wait").addClass("d-none");
            } else {
                stripe_finished = true;
                if (stripe_timeout) {
                    stripe_timeout = false;
                    return;
                }
                $("#stripe-token").val(result.token.id);
                console.log(result.token);
                document.getElementById('registrationform').submit();
            }
        });
        // Something went wrong
        setTimeout(function () {
            if (!stripe_finished) {
                stripe_timeout = true;
                stripe_finished = true;
                $("#card-errors").removeClass("d-none");
                $("#card-errors").text("Something went wrong.  Your card was not charged.  Please try again.");
                $("#savebutton").prop("disabled", false);
                $("#savebutton-text").removeClass("d-none");
                $("#savebutton-wait").addClass("d-none");
            }
        }, 1000 * 60);
    } else {
        console.log("Submitting without card...");
        document.getElementById('registrationform').submit();
    }
});