function fetch_pricing() {
    var url = '/pricing/' + $('input[name="pricing_name"]').val() + '/calculate/';
    var cores = $('#cores').val();
    var memory = $('#memory').val();
    var storage = $('#storage').val();
    $.ajax({ 
        type: 'GET', 
        url: url, 
        data: { cores: cores, memory: memory, storage: storage}, 
        dataType: 'json',
        success: function (data) { 
            if (data && data['total']) {
                $('#recurring_price').text(data['recurring_price'] + " CHF");
                $('#vat').text(data['vat_amount'] + " CHF");
                $('#total').text(data['total'] + " CHF");
                var balance = parseFloat($('#balance').data('balance'));
                if(data['total'] > balance) {
                    $('#has-enough-balance').hide();
                    $('#cards-section').show();
                    window.cardNumberElement = loadStripe(stripe);
                } else {
                    $('#cards-section').hide();
                    $('#has-enough-balance').show();
                }
            }
        }
    });
};

function incrementValue(e) {
    var valueElement = $(e.target).parent().parent().find('input');
    var step = $(valueElement).attr('step');
    var min = parseInt($(valueElement).attr('min'));
    var max = parseInt($(valueElement).attr('max'));
    var new_value = 0;
    if (e.data.inc == 1) {
        new_value = Math.min(parseInt($(valueElement).val()) + parseInt(step) * e.data.inc, max);
    } else {
        new_value = Math.max(parseInt($(valueElement).val()) + parseInt(step) * e.data.inc, min);
    }
    $(valueElement).val(new_value);
    fetch_pricing();
    return false;
};

$(document).ready(function () {
    var stripe = Stripe(window.stripeKey);

    if ($('#pricing_name') != undefined) {
        fetch_pricing();
    }

    $('.fa-plus-circle.right').bind('click', {inc: 1}, incrementValue);

    $('.fa-minus-circle.left').bind('click', {inc: -1}, incrementValue);

    var hasCreditcard = window.hasCreditcard || false;
    if (hasCreditcard) {
        window.cardNumberElement = loadStripe(stripe);
    }

    function submitBillingForm(pmId) {
        var order_form = $('#order_form');
        order_form.append('<input type="hidden" name="id_payment_method" value="' + pmId + '" />');
        order_form.submit();
    }

    var $form_new = $('#payment-form-new');
    $form_new.submit(payWithPaymentIntent);
    window.result = "";
    window.card = "";
    function payWithPaymentIntent(e) {
        e.preventDefault();
        function stripePMHandler(paymentMethod) {
            // Insert the token ID into the form so it gets submitted to the server
            $('#id_payment_method').val(paymentMethod.id);
            submitBillingForm(paymentMethod.id);
        }
        stripe.createPaymentMethod({
            type: 'card',
            card: window.cardNumberElement,
          })
          .then(function(result) {
            // Handle result.error or result.paymentMethod
              window.result = result;
              if(result.error) {
                  var errorElement = document.getElementById('card-errors');
                  errorElement.textContent = result.error.message;
              } else {
                  console.log("created paymentMethod " + result.paymentMethod.id);
                  stripePMHandler(result.paymentMethod);
              }
          });
        window.card = window.cardNumberElement;
    }

    /* Form validation */
    $.validator.addMethod("month", function (value, element) {
        return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value);
    }, "Please specify a valid 2-digit month.");

    $.validator.addMethod("year", function (value, element) {
        return this.optional(element) || /^[0-9]{2}$/.test(value);
    }, "Please specify a valid 2-digit year.");

    validator = $form_new.validate({
        rules: {
            cardNumber: {
                required: true,
                creditcard: true,
                digits: true
            },
            expMonth: {
                required: true,
                month: true
            },
            expYear: {
                required: true,
                year: true
            },
            cvCode: {
                required: true,
                digits: true
            }
        },
        highlight: function (element) {
            $(element).closest('.form-control').removeClass('success').addClass('error');
        },
        unhighlight: function (element) {
            $(element).closest('.form-control').removeClass('error').addClass('success');
        },
        errorPlacement: function (error, element) {
            $(element).closest('.form-group').append(error);
        }
    });
    
    $('#checkout-btn').click(function () {
        if($('input[name="payment_card"]:checked').length == 1) { 
            var id = $('input[name="payment_card"]:checked').val();
            if (id != 'new') {
                $('#id_card').val(id);
                submitBillingForm(id);
            }
        }
    });
    $('#continue-btn').click(function () {
        submitBillingForm();
    });


    $('input[name="payment_card"]').change(function(e) {
        if($('input[name="payment_card"]:checked').val() == 'new') {
            $('#checkout-btn').hide();
            $('#newcard').show();
        } else {
            $('#newcard').hide();
            $('#checkout-btn').show();
        }
    });

});
