{% extends "account/base.html" %}

{% load url from future %}
{% load i18n crispy_forms_tags %}

{% block head_title %}{% trans "Signup" %}{% endblock %}

{% block content %}
<div class="container">
  <div class="row">
    <div class="col-md-5">
      <h2>{% trans "Sign Up" %}</h2>

      <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p>

      <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
        {% csrf_token %}
        {{ form|crispy }}
        {% if redirect_field_value %}
        <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
        {% endif %}
        <span class="stripe-errors"></span>
        <button class="btn" type="submit">{% trans "Sign Up" %} &raquo;</button>
      </form>

    </div>
  </div>
</div>
{% endblock content %}

{% block javascript %}
{{ block.super }}
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
  jQuery(function($) {
    Stripe.setPublishableKey('{{ STRIPE_PUBLIC_KEY }}');
    
    $('#signup_form').submit(function(event) {
        var $form = $(this);

        // Disable the submit button to prevent repeated clicks
        $form.find('button').prop('disabled', true);

        Stripe.createToken($form, stripeResponseHandler);

        // Prevent the form from submitting with the default action
        return false;
    });
    var stripeResponseHandler = function(status, response) {
      var $form = $('#signup_form');

      if (response.error) {
        // clean up previous errors
        $('div.has-error').removeClass("has-error");

        // Show the errors on the form
        var id = "#id_" + response.error.param;
        var input = $(id);
        var control = input.parent().parent();
        input.focus();
        control.addClass("has-error");

        $('.stripe-errors').text(response.error.message);
        
        $form.find('button').prop('disabled', false);
      } else {
        console.log("processing");
        // token contains id, last4, and card type
        var token = response.id;
        // Insert the token into the form so it gets submitted to the server
        $('#id_stripe_token').val(token);
        $form.get(0).submit();
      }
    };
  });
</script>
{% endblock javascript %}