{% extends 'base.html' %}

{% block title %}{{ _('Make a Donation') }} - MetaBrainz Foundation{% endblock %}

{% block content %}
  <div id="payment">
    <h1 class="page-title">{{ _('Make a Donation') }}</h1>

    <p>
      {{ _('If you feel that our projects are a worthwhile effort, please consider contributing money to the
      MetaBrainz Foundation, which is a <a href="%(wikipedia_non_profit_url)s">
      501(c)(3) tax-exempt non-profit</a> based in California. All of your donations will be tax-deductible
      and you will receive a receipt that you can use to deduct your donation off your taxes if you are a
      US taxpayer.', wikipedia_non_profit_url='https://en.wikipedia.org/wiki/Non-profit_organization') }}
    </p>

    <p>
      {{ _('Your donations will be used to operate projects of the MetaBrainz Foundation. This includes paying
      for ongoing expenses like hosting, hardware, maintaining a modest office, and paying a minimal
      salary for MetaBrainz employees.') }}
    </p>

    <p>{{ _('Where has my contribution gone? See our <a href="%(finance_reports_url)s">transparent finances</a>.', finance_reports_url=url_for('financial_reports.index')) }}</p>
    <p>{{ _('Who else is contributing? See our list of <a href="%(donors_url)s">donors</a>.', donors_url=url_for('payments.donors')) }}</p>

    {% if config.PAYMENT_PRODUCTION != True %}
      <div class="alert alert-warning" role="alert">
        {{ _('<b>Be careful!</b> This is a development version of the website. Do NOT
        use your real credit card credentials! If you want to send an actual
        donation, go to <a href="%(mb_url)s">metabrainz.org</a>.', mb_url='https://metabrainz.org/') }}
      </div>
    {% endif %}

    <div id="payment-panel" class="panel panel-default">
      <form id="payment-form" method="POST" class="panel-body form-horizontal" role="form">
        {{ form.hidden_tag() }}

        <div class="form-group">
          <label for="input-amount" class="col-sm-offset-2 col-sm-3 control-label">{{ _('Amount') }}</label>
          <div class="col-sm-4">
            <div id="input-amount-fg">
              {{ form.amount(id="input-amount", class="form-control") | safe }}
              <div id="currency-selector" class="btn-group" data-toggle="buttons">
                {% for subfield in form.currency %}
                  <label class="btn btn-primary {{ 'active' if subfield.checked }}">
                    {{ subfield }}
                    {{ subfield.label.text }}
                  </label>
                {% endfor %}
              </div>
            </div>
          </div>
          <div id="big-amount-info" class="col-sm-offset-3 col-sm-6" style="display:none">
            {{ _('If you would like to make a large donation, please contact us at
            <a href="%(mail_link)s">donations@metabrainz.org</a>
            before you do.', mail_link='mailto:donations@metabrainz.org') }}
          </div>
        </div>

        <div class="form-group">
          <div class="col-sm-offset-3 col-sm-6">
            <div class="checkbox">
              <label>
                {{ form.recurring(id="recurring-flag") | safe }}
                {{ _('I want this to be a recurring monthly donation') }}
              </label>
            </div>
          </div>
        </div>

        <div id="input-editor-fg" class="form-group">
          <div class="col-sm-offset-3 col-sm-6">
            {{ form.editor(id="input-editor", class="form-control", placeholder=_('MusicBrainz username'), data_toggle="tooltip", data_placement="bottom") | safe }}
          </div>
        </div>

        <div class="form-group">
          <div class="col-sm-offset-3 col-sm-6">
            <div class="checkbox">
              <label>
                {{ form.can_contact(id="can-contact-flag") | safe }}
                {{ _('Email me about future fundraising events') }}
                <br /><small>{{ _('This will be very seldom') }}</small>
              </label>
            </div>
          </div>
          <div class="col-sm-offset-3 col-sm-6">
            <div class="checkbox">
              <label>
                {{ form.anonymous(id="anonymous-flag") | safe }}
                {{ _('I would like this donation to be anonymous') }}
                <br /><small>{{ _('Your name won\'t appear in the donors list') }}</small>
              </label>
            </div>
          </div>
        </div>

        <div id="buttons" class="form-group">
          <div class="col-sm-offset-3 col-sm-6">
            <button id="btn-stripe" type="button" class="btn">{{ _('Donate with Credit Card') }}</button>
            <button id="btn-paypal" type="button" class="btn">
              <img src="{{ url_for('static', filename='img/payments/paypal.svg') }}" />
            </button>
          </div>
        </div>

      </form>

    </div>

    <p>
      <small>
        {{ _('The personal information provided to the MetaBrainz Foundation during the
        donation process will not be shared with anyone. For more information,
        please take a look at our <a href="%(privacy_policy_url)s">
        privacy policy</a>.', privacy_policy_url=url_for('index.privacy_policy')) }}
      </small>
    </p>

    <p>
      <small>
        {{ _('To find out how to cancel recurring donations take a look at
        <a href="%(cancel_recurring_url)s">this page</a>.', cancel_recurring_url=url_for('payments.cancel_recurring')) }}
      </small>
    </p>

    <h2>{{ _('Other ways to donate') }}</h2>

    <h3>GitHub</h3>
    <p>{{ _('If you use GitHub to sponsor your favourite projects, you can click below to Sponsor @metabrainz on GitHub Sponsors:') }}</p>
    <p><a href="https://github.com/sponsors/metabrainz">https://github.com/sponsors/metabrainz</a></p>

    <h3>{{ _('Non-US Bank transfer') }}</h3>
    <p>{{ _('You can make a donation, or recurring donations, via bank transfer to the following IBAN:') }}</p>
    <p><em style="margin-left: 2em">BE96 9670 3472 0205 (BIC: TRWIBEB1XXX)</em></p>
    <p>{{ _('Please indicate your name and use the word <em>%(donation_fixed_string)s</em> in the description field.', donation_fixed_string='DONATION') }}</p>

    <h3>{{ _('US Check') }}</h3>
    <p>{{ _('Due to the increased unreliability of the US Postal Service we have stopped accepting paper checks. Sorry!') }}</p>

  </div>
{% endblock %}

{% block scripts %}
  {{ super() }}
  <script src="https://js.stripe.com/v3/"></script>
  <script>
    $(document).ready(function () {

      var form = $("#payment-form");

      var CURRENCY = {
        // These must match form definitions.
        US_Dollar: {
          code: "USD",
          paypal_id: '{{ config['PAYPAL_ACCOUNT_IDS']['USD'] }}'
        },
        Euro: {
          code: "EUR",
          paypal_id: '{{ config['PAYPAL_ACCOUNT_IDS']['USD'] }}'
        }
      };

      //////////////////
      // PAYMENT BUTTONS
      //////////////////

      var buttons = {
        stripe: $('#btn-stripe'),
        paypal: $('#btn-paypal')
      };

      function setButtonsState(enabled) {
        if (enabled === true) {
          $.each(buttons, function( index, button ) {
            button.removeAttr('disabled');
          });

        } else { // Disabled
          $.each(buttons, function( index, button ) {
            button.attr('disabled', 'disabled');
          });
        }
      }

      ///////////////
      // AMOUNT INPUT
      ///////////////
      var MAX_AMOUNT = 900000;
      var amount = $("#input-amount");
      var bigAmountInfo = $("#big-amount-info");
      amount.on('input', function () {
        var value = amount.val();
        if (value > MAX_AMOUNT) {
          bigAmountInfo.show();
          setButtonsState(false);
        } else {
          bigAmountInfo.hide();
          setButtonsState(true);
        }
      });

      /////////////////
      // CURRENCY INPUT
      /////////////////
      var selectedCurrency = CURRENCY.US_Dollar;
      $('input:radio[name=currency]').change(function() {
        if (this.value.toUpperCase() === CURRENCY.US_Dollar.code.toUpperCase()) {
          selectedCurrency = CURRENCY.US_Dollar;
        } else if (this.value.toUpperCase() === CURRENCY.Euro.code.toUpperCase()) {
          selectedCurrency = CURRENCY.Euro;
        } else {
          console.error("Unknown currency:", this.value)
        }
      });

      ///////////////
      // EDITOR INPUT
      ///////////////
      var editor = $("#input-editor");
      var editorFormGroup = $("#input-editor-fg");

      function setEditorTooltip(text, state) {
        editor.tooltip('destroy');
        editor.tooltip({title: text});
        editorFormGroup.removeClass(function (index, css) {
          return (css.match(/(^|\s)has-\S+/g) || []).join(' ');
        });
        if (editor !== null) {
          editorFormGroup.addClass('has-' + state);
        }
      }

      var defaultEditorTooltipText = "{{ _('Enter your MusicBrainz username to have Picard/MusicBrainz stop nagging you') }}";
      setEditorTooltip(defaultEditorTooltipText, null);

      editor.on('input', function () { setEditorTooltip(defaultEditorTooltipText, null); });
      editor.change(function () {
        var value = editor.val();
        if (value.length == 0) {
          setEditorTooltip(defaultEditorTooltipText, null);
        } else {
          $.ajax({
            url: "{{ url_for('payments.check_editor') }}",
            data: {q: value},
            dataType: "json",
            success: function (response) {
              if (response.error) {
                setEditorTooltip("{{ _('MusicBrainz is currently unavailable.') }} " +
                "{{ _('Please, make sure that your username is correct.') }}", 'warning');
              } else if (response.found == true && response.editor == value) {
                setEditorTooltip("{{ _('Your donation will be associated with this account.') }}", 'success');
              } else {
                setEditorTooltip("{{ _('We can\'t find this account. Please, make sure it\'s correct') }}", 'error');
              }
            }
          });
        }
      });


      ///////////
      // PAYMENTS
      ///////////

      // Stripe
      buttons.stripe.on('click', function(e) {
        setButtonsState(false);
        e.preventDefault();
        form.attr("action", "{{ url_for('payments_stripe.pay', donation=True) }}");
        form.submit();
      });

      // PayPal
      buttons.paypal.on('click', function(e) {
        setButtonsState(false);
        {% if config.PAYMENT_PRODUCTION %}
          form.attr("action", "https://www.paypal.com/cgi-bin/webscr");
        {% else %}
          form.attr("action", "https://www.sandbox.paypal.com/cgi-bin/webscr");
        {% endif %}

        {# Info about variables can be found at https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/ #}

        $('<input>').attr({type: 'hidden', name: 'business', value: selectedCurrency.paypal_id}).appendTo(form);
        $('<input>').attr({type: 'hidden', name: 'no_shipping', value: '2'}).appendTo(form);
        $('<input>').attr({type: 'hidden', name: 'return', value: '{{ url_for('payments.complete', is_donation=True, _external=True, _scheme=config.PREFERRED_URL_SCHEME) }}'}).appendTo(form);
        $('<input>').attr({type: 'hidden', name: 'cancel_return', value: '{{ url_for('payments.cancelled', is_donation=True, _external=True, _scheme=config.PREFERRED_URL_SCHEME) }}'}).appendTo(form);
        $('<input>').attr({type: 'hidden', name: 'notify_url', value: '{{ url_for('payments_paypal.ipn', _external=True, _scheme=config.PREFERRED_URL_SCHEME) }}'}).appendTo(form);
        $('<input>').attr({type: 'hidden', name: 'currency_code', value: selectedCurrency.code}).appendTo(form);

        if ($('#recurring-flag').is(":checked")) { // Recurring donations
          $('<input>').attr({type: 'hidden', name: 'cmd', value: '_xclick-subscriptions'}).appendTo(form);
          $('<input>').attr({type: 'hidden', name: 'item_name', value: 'Recurring donation to the MetaBrainz Foundation'}).appendTo(form);
          $('<input>').attr({type: 'hidden', name: 't3', value: 'M'}).appendTo(form); {# units of duration ('M' is month) #}
          $('<input>').attr({type: 'hidden', name: 'p3', value: '1'}).appendTo(form); {# subscription duration #}
          $('<input>').attr({type: 'hidden', name: 'src', value: '1'}).appendTo(form); {# recurring payments #}
          $('<input>').attr({type: 'hidden', name: 'sra', value: '1'}).appendTo(form); {# reattempt on failure #}

        } else {  // One-time donation
          $('<input>').attr({type: 'hidden', name: 'cmd', value: '_xclick'}).appendTo(form);
          $('<input>').attr({type: 'hidden', name: 'item_name', value: 'Donation to the MetaBrainz Foundation'}).appendTo(form);
        }

        {# Reconfiguring inputs for PayPal #}
        if ($('#recurring-flag').is(":checked")) { // Recurring donations
          amount.attr('name', 'a3');
        } else {  // One-time donation
          amount.attr('name', 'amount');
        }

        editor.attr('name', 'custom');

        $('<input>').attr({type: 'hidden', name: 'on3', value: 'is_donation'}).appendTo(form);
        $('<input>').attr({type: 'hidden', name: 'os3', value: 'yes'}).appendTo(form);

        $('<input>').attr({type: 'hidden', name: 'on0', value: 'contact'}).appendTo(form);
        $("#can-contact-flag").attr('name', 'os0');
        $("#can-contact-flag").attr('value', 'yes'); {# Boolean values are compared to 'yes' in IPN processor. #}

        $('<input>').attr({type: 'hidden', name: 'on1', value: 'anonymous'}).appendTo(form);
        $("#anonymous-flag").attr('name', 'os1');
        $("#anonymous-flag").attr('value', 'yes'); {# Boolean values are compared to 'yes' in IPN processor. #}

        form.submit();
        return false;
      });

    });
  </script>
{% endblock %}
