MediaWiki:FR2013/Resources/BannerFormCore-WP.js

From Meta, a Wikimedia project coordination wiki

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
<!-- Tweaked BannerFormCore.js for WorldPay -->
<style>
/* No monthly for Worldpay */
.frequency-options input,
.frequency-options label,
.frbanner-frequency,
.recurring-details {
  display: none;
}
</style>
<script>
/**
 * Core code for forms in banners.
 * Handles showing the correct payment methods, validating input, and sending on to payments wiki.
 * (Note that localizing amount options is done elsewhere, in BannerFormAmountOptions.js)
 *
 * Dependencies: FR2013/Resources/CurrencyMinimums.js
 *               FR2013/Resources/Country2Currency.js
 */
 
function checkPaymentOutages() {
    /*  Check against the scheduled payment method outages below
     *  and hide the relevant button for any which are ongoing.
     */
    {{MediaWiki:FR2013/Resources/PaymentOutages.js}}
    var now = new Date();

    for (var i = outages.length - 1; i >= 0; i--) {
        if ( now > outages[i]['start'] && now < outages[i]['end'] ) {
            if (outages[i]['country'] === undefined || outages[i]['country'] == Geo.country) {
                $('.paymentmethod-' + outages[i]['method']).hide();
            }
        }
    };
}

function validateForm(form) {
    var error = true;
 
    // Get amount selection
    var amount = null;
    for (var i = 0; i < form.amount.length; i++) {
        if (form.amount[i].checked) {
            amount = form.amount[i].value;
        }
    }
    if (form.amountGiven.value != '') {
        var otherAmount = form.amountGiven.value;
        otherAmount = otherAmount.replace(/[,.](\d)$/, '\:$10');
        otherAmount = otherAmount.replace(/[,.](\d)(\d)$/, '\:$1$2');
        otherAmount = otherAmount.replace(/[\$,.]/g, '');
        otherAmount = otherAmount.replace(/:/, '.');
        form.amountGiven.value = otherAmount;
        amount = otherAmount;
    }
    // Check amount is a real number
    error = ( amount == null || isNaN(amount) || amount.value <= 0 );
    // Check amount is at least the minimum
    var currency = form.currency_code.value;
    if (amount < getMinimum(currency) || error) {
        alert('{{{validation-error-minimum|{{int:fr2013-dropdown-smallamount-error}}}}}'.replace('$1', getMinimum(currency) + ' ' + currency));
        error = true;
    }
    return !error;
}
 
function redirectPayment(paymentMethod, paymentSubMethod, skipValidation) {
    if (typeof paymentSubMethod == 'undefined'){
        paymentSubMethod = '';
    }
    var form = document.paypalcontribution; // we should really change this some day
    var language = $("input[name='language']").val();
 
    var paymentsURL = 'https://payments.wikimedia.org/index.php/Special:GatewayFormChooser';
 
    var params = {
        'uselang' : language,
        'language' : language,
        'currency_code' : $("input[name='currency_code']").val(),
        'country' : $("input[name='country']").val(),
        'paymentmethod' : paymentMethod
    };
    if( paymentSubMethod != '' ){
        params['submethod'] = paymentSubMethod;
    }
 
    // WorldPay override for cc
    if( paymentMethod === 'cc' ) {
      params.gateway = 'worldpay';
      params.ffname = 'worldpay';
    }

    var frequency = $("input[name='frequency']:checked").val();
    if( frequency !== 'monthly' ){
        frequency = 'onetime';
    } else {
        params['recurring'] = 'true';
        // the following line is both obsolete, and is causing errors.
        // paymentMethod = 'r' + paymentMethod;
    }
 
    form.action = paymentsURL + '?' + $.param(params);
    form.payment_method.value = paymentMethod;
    if( paymentSubMethod != '' ) {
        form.payment_method.value = form.payment_method.value + '.' + paymentSubMethod;
    }
    form.utm_source.value = '{{{banner}}}.no-LP' + '.' + form.payment_method.value;
 
    if (skipValidation || validateForm(document.paypalcontribution)) {
        form.submit();
    }
}
 
function toggleMonthly( monthly ){
    if( monthly.type === 'checkbox' ){
        monthly = monthly.checked;
    } 
    if (monthly) {
        $('#{{{banner}}}-form').addClass('form-monthly');
    } else {
        $('#{{{banner}}}-form').removeClass('form-monthly');
    }
}
 
$(document).ready( function () {
    if ( wgCanonicalSpecialPageName != "CentralNotice" && wgCanonicalSpecialPageName != "NoticeTemplate" ) {
        mw.centralNotice.events.bannerLoaded.done(function(e){
            $('[name="paypalcontribution"]').append($('<input>', {
                'type': 'hidden', 'name': 'utm_key', 'value': (mw.centralNotice.bannerData.cookieCount || 0)
            }));
        });
 
        var currency = getCurrency(Geo.country);
        var language = mw.config.get('wgUserLanguage');
 
        // hide CC or PP buttons anywhere we need to
        var noCC = [];
        if ($.inArray(Geo.country, noCC) != -1) {
            $(".paymentmethod-cc").remove();
        }
        var noPP = ['IN', 'RU', 'SG', 'AE', 'QA', 'JP', 'OM', 'BD', 'BO',
                    'PA', 'PE', 'PY', 'GT', 'JM', 'TT', 'DZ'];
        if ($.inArray(Geo.country, noPP) != -1){
            $(".paymentmethod-pp").remove();
        }

        // countries where PP must be in USD
        var ppUSD = ['BG', 'HR', 'LT', 'MK', 'RO', 'UA', 'SA', 'CN', 'ID', 'KR', 
                     'KZ', 'MY', 'VN', 'AR', 'CL', 'DO', 'CO', 'NI', 'UY', 'ZA',
                     'BH', 'LB', 'VE', 'TR', 'IS', 'BA', 'MV', 'BB', 'BM', 'BZ',
                     'CR', 'CW', 'SX', 'HN', 'KN', 'DM', 'AG', 'LC', 'GD', 'FJ',
                     'TN', 'BJ', 'BF', 'CI', 'GW', 'ML', 'NE', 'SN', 'TG'];
        if ($.inArray(Geo.country, ppUSD) != -1){
            $(".paymentmethod-pp").remove();
            $(".paymentmethod-pp-usd").show();
        }
 
        // can't do monthly credit card in India
        if (Geo.country === 'IN') {
            $(".paymentmethod-cc").addClass("no-monthly");
        }
 
        // show any extra local payment methods, or remove them if not needed
        var extrapaymentmethods = {
            'amazon' : ['US'],
            'bpay' : ['AU'],
            'ideal' : ['NL'],
            'yandex' : ['RU'],
            'webmoney' : ['RU'],
            'dd' : ['AT', 'DE', 'ES', 'NL'],
            // 'boletos' : ['BR'],
            'enets' : ['SG'],
            'sofort' : []
        };
 
        for (var method in extrapaymentmethods) {
            var $methodbutton = $('.paymentmethod-' + method);
 
            if ($.inArray(Geo.country, extrapaymentmethods[method]) != -1) { // country is in the list
                $methodbutton.show();
            } else {
                $methodbutton.remove();
            }
        }
        
        checkPaymentOutages();
 
        // set the form fields
        $("input[name='country']").val(Geo.country);
        $("input[name='currency_code']").val(currency);
        $("input[name='language']").val(mw.config.get('wgUserLanguage'));
        $("input[name='return_to']").val("Thank_You/" + mw.config.get('wgUserLanguage'));
 
        // handle pressing Enter on "Other" field
        $('input[name="amountGiven"]').keydown(function(e){
            if (e.keyCode == 13) {
                e.preventDefault();
                redirectPayment('cc'); // use credit card by default. Might be nice to have different defaults for some countries, but this will do for now.
                return false;
            }
        });
 
        // if there are no recurring payment methods available, disable the "monthly" radio button.
        if ( !$('#{{{banner}}}-form *[class^="paymentmethod-"]:not(.no-monthly)').length ) {
            $('#frequency_monthly').prop('disabled', 'disabled');
        }
    }
});
</script>