$(document).ready(function() {
    if (typeof(gaDonationID) != 'undefined') {
        var checkboxID = $("span.formInputCheckBox:first").children()[0].id;
        var lastUnderscore = checkboxID.lastIndexOf("_") + 1;
        var donationFieldIDPrefix = checkboxID.substring(0, lastUnderscore);
        var donationFieldID = donationFieldIDPrefix + gaDonationID;
        var donationField = $('#' + donationFieldID);

        donationField.change(function() {
            updateGiftAid();
        });
        donationField.blur(function() {
            updateGiftAid();
        });
        donationField.find('select').change(function() {
            updateGiftAid();
        });
        donationField.find('input').blur(function() {
            updateGiftAid(event);
        });
        donationField.find('input').click(function() {
            updateGiftAid(event);
        });
        if ((typeof event) != 'undefined') updateGiftAid(event);
    }
});

function updateGiftAid(event) {
    var checkboxID = $("span.formInputCheckBox:first").children()[0].id;
    var lastUnderscore = checkboxID.lastIndexOf("_") + 1;
    var donationFieldIDPrefix = checkboxID.substring(0, lastUnderscore);
    var donationFieldID = donationFieldIDPrefix + gaDonationID;
    var donationField = $('#' + donationFieldID);
    var donationAmount = '';

    // Selected dropdown option
    if (donationField.find(':selected').length > 0) {
        donationAmount = donationField.find(':selected').val();
    }
    // Selected radio button
    else if (donationField.find(':checked').length > 0) {
        donationAmount = donationField.find(':checked').val();
    }
    donationAmount = donationAmount.match(/[1-9][0-9]*(\.[0-9][0-9]?)?/g);

    if (donationAmount == null || donationAmount == '') {
        if (donationField.find(':text').length > 0) {
            donationAmount = donationField.find(':text').val();
        }
        else {
            donationAmount = donationField.val();
        }
    }
    
    var baseDonation = parseFloat(donationAmount);
    if (isNaN(baseDonation)) {
        baseDonation = 0;
    }

    var giftAid = (baseDonation / 0.8) - baseDonation; // [0.8 = 1 - 20% basic rate]
    var giftAidDisplay = getCurrencyValue(giftAid);
    var donationDisplay = getCurrencyValue(baseDonation);

    $(".formGiftAidDonationAmount").html(donationDisplay);
    $(".formGiftAidClaimAmount").html(giftAidDisplay);
}

function getCurrencyValue(val) {
    var text = '' + (Math.round(val * 100) / 100);
    var decPointPos = text.indexOf('.');
    if (decPointPos == -1) {
        text += ".00";
    }
    else if (text.length - decPointPos == 2) {
        text += "0";
    }
    return text;
}

