
var rateid = null;
var shipmentid = null;
var price = null;
var cardElement = null;
var disableGetRateButton = false;
var disablePayButton = true;
var printed = false;

function getRateAndValidateAddress() {
    $("#getRateAndValidateAddressButton").html('<i class="far fa-spinner fa-spin"></i> Working...</a>');
    disableGetRateButton = true;
    $("#addresserror").text("");
    $.ajax({
        type: "POST",
        url: "makeshipment.php",
        data: $("#addressform").serialize(),
        success: function (resp) {
            if (resp.status == "OK") {
                $("input[name=to_name]").val(resp.address.name);
                $("input[name=to_company]").val(resp.address.company);
                $("input[name=to_street]").val(resp.address.street1);
                $("input[name=to_street2]").val(resp.address.street2);
                $("input[name=to_city]").val(resp.address.city);
                $("input[name=to_state]").val(resp.address.state);
                $("input[name=to_zip]").val(resp.address.zip);

                $("input[name=from_name]").val(resp.fromaddress.name);
                $("input[name=from_street]").val(resp.fromaddress.street1);
                $("input[name=from_street2]").val(resp.fromaddress.street2);
                $("input[name=from_city]").val(resp.fromaddress.city);
                $("input[name=from_state]").val(resp.fromaddress.state);
                $("input[name=from_zip]").val(resp.fromaddress.zip);
                $("input[name=from_email]").val(resp.fromaddress.email);

                $("#toaddr").html(
                        resp.address.name
                        + (resp.address.name != "" && resp.address.company != "" ? "<br>" : "")
                        + resp.address.company
                        + "<br>" + resp.address.street1
                        + (resp.address.street2 == "" ? "" : "<br>" + resp.address.street2)
                        + "<br>" + resp.address.city + " " + resp.address.state + " " + resp.address.zip
                        );

                $("#fromaddr").html(
                        resp.fromaddress.name
                        + "<br>" + resp.fromaddress.street1
                        + (resp.fromaddress.street2 == "" ? "" : "<br>" + resp.fromaddress.street2)
                        + "<br>" + resp.fromaddress.city + " " + resp.fromaddress.state + " " + resp.fromaddress.zip
                        );

                rateid = resp.rate.id;
                shipmentid = resp.shipmentid;
                price = resp.rate.price;

                $("#paymentamount").text("$" + price.toFixed(2));

                var elements = stripe.elements();

                cardElement = elements.create('card', {});
                cardElement.mount('#card-element');
                cardElement.addEventListener('change', function (event) {
                    var displayError = document.getElementById('paymenterror');
                    if (event.error) {
                        displayError.textContent = event.error.message;
                    } else {
                        displayError.textContent = '';
                    }
                });

                $("#paymentform").css("display", "");
                $("#addressform").css("display", "none");
                $("#getRateAndValidateAddressButton").html('<i class="far fa-chevron-right"></i> Next</a>');
                $("#header-small-text").text("Confirm and Pay");
                document.getElementById("label").scrollIntoView();
                $("#addresserror").text("");
                disablePayButton = false;
            } else {
                $("#addresserror").text(resp.message);
                $("#getRateAndValidateAddressButton").html('<i class="far fa-chevron-right"></i> Next</a>');
                disableGetRateButton = false;
            }
        },
        dataType: "json",
        timeout: 1000 * 10
    }).fail(function () {
        $("#addresserror").text("There was a network glitch or your request took too long. Please try again.");
        $("#getRateAndValidateAddressButton").html('<i class="far fa-chevron-right"></i> Next</a>');
        disableGetRateButton = false;
    });
}

function submitPayment() {
    disablePayButton = true;
    $("#submitPaymentButton").html('<i class="far fa-spinner fa-spin"></i> Purchasing...</a>');
    stripe.createPaymentMethod(
            {
                type: 'card',
                card: cardElement
            }
    ).then(function (result) {
        if (result.error) {
            // Inform the customer that there was an error.
            disablePayButton = false;
            $("#paymenterror").text(result.error.message);
            $("#submitPaymentButton").html('<i class="far fa-chevron-right"></i> Purchase</a>');
        } else {
            $.ajax({
                type: "POST",
                url: "payshipment.php",
                data: {
                    "shipmentid": shipmentid,
                    "rateid": rateid,
                    "stripeid": result.paymentMethod.id,
                    "price": price,
                    "label_only": document.getElementById('label_only').checked ? "1" : "",
                    "no10_envelope": document.getElementById('no10_envelope').checked ? "1" : ""
                },
                dataType: "json",
                timeout: 1000 * 30,
                success: function (resp) {
                    if (resp.status == "OK") {
                        // load PDF to print
                        $("#pdfframe").attr("src", resp.pdf + "#toolbar=0&navpanes=0&pagemode=none");
                        $("#pdfbackuplink").attr("src", resp.pdf);
                        //$("#pdfframe").attr("src", "assets/pdfjs/web/viewer.html?file=" + encodeURIComponent(resp.pdf) + "#zoom=page-fit&page=1&pagemode=none");
                        $("#printform").css("display", "");
                        $("#paymentform").css("display", "none");
                        $("#trackingnumber").html(resp.trackingcode + " <i class='far fa-external-link'></i>");
                        $("#trackingnumber").attr("href", "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=" + resp.trackingcode);
                        $("#header-small-text").text("Print and Finish");
                        document.getElementById("label").scrollIntoView();
                        // hide tracking info for non-tracked letters
                        if (resp.trackingcode.startsWith("00")) {
                            $("#trackingnumberparagraph").css("display", "none");
                        }
                        _paq.push(['addEcommerceItem',
                            "letter",
                            price * 1.0,
                            1
                        ]);
                        _paq.push(['trackEcommerceOrder',
                            shipmentid,
                            price * 1.0
                        ]);
                    } else {
                        $("#paymenterror").text(resp.message);
                        $("#submitPaymentButton").html('<i class="far fa-chevron-right"></i> Purchase</a>');
                        disablePayButton = false;
                    }
                }
            }).fail(function () {
                $("#paymenterror").html("There was a network glitch or your request took too long to process. It's possible your payment went through; check with your card provider or <a href='https://postalportal.net/#contact' target='_BLANK'>click here to contact us</a>.");
                $("#submitPaymentButton").html('<i class="far fa-chevron-right"></i> Purchase</a>');
                disablePayButton = false;
            });
        }
    });
}

$("#getRateAndValidateAddressButton").on("click", function () {
    if (disableGetRateButton == false) {
        getRateAndValidateAddress();
    }
}
);

$("#submitPaymentButton").on("click", function () {
    if (disablePayButton == false) {
        submitPayment();
    }
});

$("#cancelPaymentButton").on("click", function () {
    if (disablePayButton == false) {
        rateid = null;
        shipmentid = null;
        price = null;
        cardElement = null;
        disableGetRateButton = false;
        $("#paymentform").css("display", "none");
        $("#paymenterror").text("");
        $("#addressform").css("display", "");
        $("#header-small-text").text("Get Started");
        document.getElementById("label").scrollIntoView();
    }
});

$("#printButton").on("click", function () {
    if (printed) {
        if (confirm("You seem to be reprinting the same file. By continuing, you agree that only one copy is to be mailed, under penalty of federal law.")) {
            document.getElementById("pdfframe").contentWindow.print();
        }
    } else {
        document.getElementById("pdfframe").contentWindow.print();
        printed = true;
    }
});

$("#pdfbackuplink").on("click", function () {
    printed = true;
    if (confirm("By continuing, you agree that only one copy of the file is to be mailed, under penalty of federal law.")) {
        window.open($("#pdfbackuplink").attr("src"), "_blank");
    }
});

$("#startOverButton").on("click", function () {
    if (printed || (!printed && confirm("Heads up! If you haven't printed this label yet, press cancel and do that first. You won't be able to get it back once you start over."))) {
        location.hash = 'label';
        location.reload();
    }
});

var mailingdate = new Date();
mailingdate.setDate(mailingdate.getDate() + 1 /*days*/);
$("#mailing_date").val(mailingdate.toISOString().split('T')[0]);
$("#mailing_date").prop("min", (new Date()).toISOString().split('T')[0]);
var datemax = new Date();
datemax.setDate(datemax.getDate() + 14 /*days*/);
$("#mailing_date").prop("max", datemax.toISOString().split('T')[0]);