/* Minification failed. Returning unminified contents.
(224,25-26): run-time warning JS1004: Expected ';': f
(363,17-18): run-time warning JS1004: Expected ';': c
(364,17-18): run-time warning JS1004: Expected ';': b
(545,20-21): run-time warning JS1004: Expected ';': c
(570,21-22): run-time warning JS1004: Expected ';': r
(699,17-18): run-time warning JS1004: Expected ';': m
(821,17-18): run-time warning JS1004: Expected ';': a
(831,17-18): run-time warning JS1004: Expected ';': p
(868,21-22): run-time warning JS1004: Expected ';': c
(939,25-26): run-time warning JS1004: Expected ';': a
(942,25-26): run-time warning JS1004: Expected ';': b
(943,25-26): run-time warning JS1004: Expected ';': s
(954,25-26): run-time warning JS1004: Expected ';': a
(955,25-26): run-time warning JS1004: Expected ';': b
(963,25-26): run-time warning JS1004: Expected ';': a
(969,25-26): run-time warning JS1004: Expected ';': r
(993,17-18): run-time warning JS1004: Expected ';': e
(1004,17-18): run-time warning JS1004: Expected ';': c
(1005,17-18): run-time warning JS1004: Expected ';': c
(1029,17-18): run-time warning JS1004: Expected ';': o
(1039,21-22): run-time warning JS1004: Expected ';': t
(1041,21-22): run-time warning JS1004: Expected ';': d
(1062,17-18): run-time warning JS1004: Expected ';': a
(1064,21-22): run-time warning JS1004: Expected ';': i
(1064,50-51): run-time warning JS1006: Expected ')': ;
(1064,55-56): run-time warning JS1004: Expected ';': )
(1064,57-58): run-time warning JS1004: Expected ';': {
(1068,9-10): run-time warning JS1002: Syntax error: }
(1070,65-66): run-time warning JS1004: Expected ';': {
(1072,17-18): run-time warning JS1004: Expected ';': d
(1075,21-22): run-time warning JS1004: Expected ';': a
(1082,10-11): run-time warning JS1195: Expected expression: ,
(1084,66-67): run-time warning JS1004: Expected ';': {
(1085,17-18): run-time warning JS1004: Expected ';': f
(1089,10-11): run-time warning JS1195: Expected expression: ,
(1091,79-80): run-time warning JS1004: Expected ';': {
(1096,10-11): run-time warning JS1195: Expected expression: ,
(1098,48-49): run-time warning JS1004: Expected ';': {
(1099,17-18): run-time warning JS1004: Expected ';': a
(1110,10-11): run-time warning JS1195: Expected expression: ,
(1112,41-42): run-time warning JS1004: Expected ';': {
(1120,10-11): run-time warning JS1195: Expected expression: ,
(1122,45-46): run-time warning JS1004: Expected ';': {
(1133,4-5): run-time warning JS1195: Expected expression: ,
(1134,34-35): run-time warning JS1195: Expected expression: )
(1137,3-4): run-time warning JS1002: Syntax error: }
(1138,39-40): run-time warning JS1195: Expected expression: )
(1142,3-4): run-time warning JS1002: Syntax error: }
(1145,31-32): run-time warning JS1004: Expected ';': {
(1162,1-2): run-time warning JS1002: Syntax error: }
(1162,18-19): run-time warning JS1195: Expected expression: )
(1770,1-2): run-time warning JS1002: Syntax error: }
(1772,32-33): run-time warning JS1010: Expected identifier: (
(1850,10-11): run-time warning JS1195: Expected expression: ,
(1851,33-34): run-time warning JS1010: Expected identifier: (
(1861,20-25): run-time warning JS1010: Expected identifier: catch
(1864,10-11): run-time warning JS1195: Expected expression: ,
(1865,21-29): run-time warning JS1197: Too many errors. The file might not be a JScript .NET file: function
(1088,13-32): run-time warning JS1018: 'return' statement outside of function: return filterArray;
(1095,13-28): run-time warning JS1018: 'return' statement outside of function: return closest;
(1861,20-25): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
 */
/**
 * Global JavaScript Object
 *
 * @author      Macmillan
 * @version     0.0.1
 */
(function ($) {

    var $container = $('.container');
    var $form = $container.find('form.donateform');
    var $steps = $('form.donateform section.step');
    var $stepContainer = $('div.step-container');
    var $progressBar = $('aside.progress', 'form.donateform');
    var stepsLength = $steps.length + 1; // this is because we start at step 2
    var activeStep;
    var referalStep;
    var editStep = false;
    var aniSpeed = 1000;

    macmillan.donationsForm = {
        init: function () {
            activeStep = typeof _activeStep != 'undefined' ? _activeStep : 2;
            macmillan.donationsForm.step1Validate();
            macmillan.donationsForm.initSteps();
            macmillan.donationsForm.setProgressBar();
            macmillan.utils.init();
            macmillan.donationsForm.bindEvents();
            macmillan.donationsForm.validate.init();
            macmillan.donationsForm.init_waypoints();
            macmillan.donationsForm.showOtherField();
            macmillan.donationsForm.getPaymentButtons();
        },

        /* Journey specific functions and form actions */

        step1Validate: function () {
            $('button.customsubmit', 'form.step1').on('click', function (e) {
                e.preventDefault();
                if ($("form.step1").valid()) {
                    $('form').submit();
                } else {
                    macmillan.utils.smoothScroll($('div.errorbox:first', 'form.step1'), 135);
                }
            });
        },

        initSteps: function () {
            $steps.each(function () {

                var $this = $(this),
                    $stpContainer = $this.find('div.step-container'),
                    hgt = $this.find('div.step-container').height();
                $this.data('height', hgt);

                if ($('span[name="IsDirectDebitSetWithProvider"]').length === 1) {
                    activeStep = 3;
                    setTimeout(function () {
                        macmillan.utils.smoothScroll($('#Donation_Payment_DirectDebit_CollectionDay'));
                    }, 1500);
                }

                if (macmillan.donationsForm.getData($this, 'step') !== activeStep) {
                    $stpContainer.animate({
                        height: 0
                    }, {
                        duration: aniSpeed,
                        easing: 'swing',
                        complete: function () {
                            $stpContainer.hide();
                            if (activeStep !== 2) {
                                if ($this.index() < activeStep) {
                                    $('div.summary', $this).show();
                                }
                            }
                        }
                    })
                } else {
                    $this.addClass('activestep');
                    var donationType = $('#Donation_DonationType').val().toLowerCase(), formCode = $('#Donation_DonationForm_FormCode').val();
                }
            });
        },

        resetSteps: function (inactiveStep) {
            $steps.each(function () {
                var $this = $(this),
                    $stpContainer = $this.find('div.step-container');

                if (macmillan.donationsForm.getData($this, 'step') === activeStep) {

                    var hgt = macmillan.donationsForm.getData($this, 'height');

                    $stpContainer.show().animate({
                        height: hgt
                    }, {
                        duration: aniSpeed,
                        easing: 'swing',
                        complete: function () {
                            $this.addClass('activestep');
                            $($stpContainer, $this).css('height', 'auto');
                            macmillan.donationsForm.setProgressBar();
                            var donationType = $('#Donation_DonationType').val().toLowerCase(), formCode = $('#Donation_DonationForm_FormCode').val();
                        }
                    })
                }


                else if (macmillan.donationsForm.getData($this, 'step') === inactiveStep) {
                    macmillan.utils.smoothScroll($('#user-details-section'));
                    $stpContainer.delay(500).animate({
                        height: 0
                    }, {
                        duration: aniSpeed,
                        easing: 'swing',
                        complete: function () {
                            $(this).hide();
                            macmillan.donationsForm.createSummary(inactiveStep);
                            if (editStep === false) {
                                $('.summary', $this).show();
                            }
                            $this.removeClass('activestep');
                        }
                    });
                }
            });
        },

        getData: function (step, dataAttr) {
            return $(step).data(dataAttr);
        },

        createSummary: function (inactiveStep) {

            var summaryStr = '',
                $summaryPath = $('.step' + inactiveStep + ' .formcontent .summary'),
                step2Summary = {
                    Name: $('.your-details #Donation_Donor_FirstName').val() + ' ' + $('.your-details #Donation_Donor_LastName').val(),
                    Email: $('.your-details #Donation_Donor_Email').val(),
                    Address1: $('#Donation_Donor_Address_FirstLine').val(),
                    Address2: $('.your-details #Donation_Donor_Address_SecondLine').val(),
                    Town: $('.your-details #Donation_Donor_Address_PostalTown').val(),
                    Postcode: $('.your-details #Donation_Donor_Address_PostalCode').val(),
                    Tel: $('.your-details #Donation_Donor_Phone_Number').val()
                },
                companyDetailSummary = {
                    Name: $('#Donation_Organisation_Name').val(),
                    Address1: $('#Donation_Organisation_Address_FirstLine').val(),
                    Address2: $('#Donation_Organisation_Address_SecondLine').val(),
                    Town: $('#Donation_Organisation_Address_PostalTown').val(),
                    Postcode: $('#Donation_Organisation_Address_PostalCode').val()
                },
                step3Summary = {},
                theSummary = inactiveStep === 2 ? step2Summary : step3Summary,
                theCompanySummary = companyDetailSummary;


            $.each(theSummary, function (key, value) {
                if (value.length > 1) {
                    summaryStr += '<span>' + value + '</span>';
                }
            });

            //summary = summaryStr.slice(0, summaryStr.length - 8) + summaryStr.slice(summaryStr.length - 7, summaryStr.length);
            //summaryStr = summaryStr.slice(0, summaryStr.length - 8) + summaryStr.slice(summaryStr.length - 7, summaryStr.length);

            if ($('#IsOnBehalfOfOrganisation_true').prop('checked')) {
                summaryStr += "<span class='dm-form-donation-title'>Your donation is on behalf of:</span>";
                $.each(theCompanySummary, function (key, value) {
                    if (value.length > 1) {
                        summaryStr += '<span>' + value + '</span>';
                    }
                });
                //summaryStr = summaryStr.slice(0, summaryStr.length - 8) + summaryStr.slice(summaryStr.length - 7, summaryStr.length);
            };

            var $summaryContainer = $('<p></p>')
                .html(summaryStr)
                .appendTo($summaryPath);
        },

        setSteps: function () {
            // step is ok - reset activestep and form

            var inactive = activeStep;
            if (editStep === true) {
                activeStep = referalStep;
                editStep = false;
                macmillan.donationsForm.resetSteps(inactive);
            }

            else if (activeStep < stepsLength) {
                activeStep += 1;
                macmillan.donationsForm.resetSteps(inactive);
            }

            else {
                //server submit;
                if ($('html').hasClass('ie7') || $('html').hasClass('ie8')) {
                    $('#Donation_Donor_OptInEmail').prev().hasClass('ui-state-active') ? $('#Donation_Donor_OptInEmail').attr('checked', true) : '';
                    $('#Donation_Donor_OptInPhone').prev().hasClass('ui-state-active') ? $('#Donation_Donor_OptInPhone').attr('checked', true) : '';
                    $('#Donation_Donor_OptInText').prev().hasClass('ui-state-active') ? $('#Donation_Donor_OptInText').attr('checked', true) : '';
                    $('#Donation_Donor_OptInPost').prev().hasClass('ui-state-active') ? $('#Donation_Donor_OptInPost').attr('checked', true) : '';
                }
                $form.submit();
                $('section.step' + stepsLength + ' button.customsubmit').attr('disabled', 'disabled');
            }
        },

        setProgressBar: function () {

            $progressBar.find('span.counter:first').text(activeStep);
            if ($('#Donation_DonationType').val() !== undefined && $('#Donation_DonationType').val().toLowerCase() === 'regular') {
                $progressBar.find('span.counter:last').text(stepsLength);
            } else {
                $progressBar.find('span.counter:last').text(stepsLength + 1);
            }
        },

        init_waypoints: function () {
            // Check we have the right page
            if ($progressBar.length) {
                $(window).scroll(function () {
                    document.querySelector('.stepCounter').innerHTML = '2';
                    let footerHeight = $('.footer').height();
                    var distanceToTop = $(this).scrollTop();
                    var bottomOffset = $(document).height() - footerHeight - $progressBar.height() - 75;

                    //between 0 and navigation
                    if (distanceToTop >= 0 && distanceToTop < 250) {
                        $progressBar.css({ 'position': 'absolute', 'bottom': 'auto', 'top': 'auto' });

                        //between navigation and footer
                    } else if (distanceToTop > 250 && distanceToTop < footerHeight + 1000) {
                        $progressBar.css({ 'position': 'fixed', 'bottom': 'auto', 'top': '20px' });

                        // after the lowest point (bottomOffset) we want .progress to stayed position: fixed;
                    } else {
                        document.querySelector('.stepCounter').innerHTML = '3';
                        $progressBar.css({ 'position': 'absolute', 'bottom': '100px', 'top': 'auto' });
                    }
                });
            }

        },

        bindEvents: function () {
            $('div.submit-container button.customsubmit', $steps).on('click', function (e) {
                e.preventDefault();
                if ($("form.donateform").valid()) {
                    macmillan.donationsForm.setSteps();
                } else {
                    // scroll to first error
                    macmillan.utils.smoothScroll($('div.errorbox:first', $form), 135);
                }
            });


            $('div.summary a.edit-step', $steps).on('click', function (e) {
                e.preventDefault();
                editStep = true;
                referalStep = activeStep;
                activeStep = macmillan.donationsForm.getData($(this).parents('section.step'), 'step');
                $('.summary', $(this).parents('section.step')).hide().find('p').remove();
                macmillan.donationsForm.resetSteps(referalStep);

            });

            $('div.radio', $steps).on('click', 'input[name="IsOnBehalfOfOrganisation"]', function (e) {
                if ($(this).attr('id') === 'IsOnBehalfOfOrganisation_true') {
                    $('div.gift-aid', 'div.payment-details').addClass('hidden');
                } else {
                    $('div.gift-aid', 'div.payment-details').removeClass('hidden');
                }
            });

            $('select#Donation_Donor_Title', 'div.your-details').on('change', function () {
                if ($(this).val() === 'Other') {
                    $('div.title-other', 'div.your-details').removeClass('js-hidden');
                } else {
                    $('div.title-other:visible', 'div.your-details').addClass('js-hidden');
                }
            });


            $('select#InMemoryRelationship', 'fieldset.donateoccasion').on('change', function () {
                if ($(this).val() === 'other_value') {
                    $('div.inmemoryrelationship-other', 'fieldset.donateoccasion').removeClass('js-hidden');
                } else {
                    $('div.inmemoryrelationship-other:visible', 'fieldset.donateoccasion').addClass('js-hidden');
                }
            });


            $('select#CelebrationForRelationship', 'fieldset.donateoccasion').on('change', function () {
                if ($(this).val() === 'other_value') {
                    $('div.incelebrationrelationship-other', 'fieldset.donateoccasion').removeClass('js-hidden');
                } else {
                    $('div.incelebrationrelationship-other:visible', 'fieldset.donateoccasion').addClass('js-hidden');
                }
            });


            $('select#InCelebrationOf', 'fieldset.donateoccasion').on('change', function () {
                if ($(this).val() === 'other_value') {
                    $('div.incelebration-other', 'fieldset.donateoccasion').removeClass('js-hidden');
                } else {
                    $('div.incelebration-other:visible', 'fieldset.donateoccasion').addClass('js-hidden');
                }
            });

            $('.postcode-input input').on('blur', function () {
                var pc = $(this).val();
                $(this).val(pc.toUpperCase());
            });
        
            $('#Donation_Donor_Phone_Number, #Donation_Organisation_Phone_Number').on('change', function () {
                $(this)[0].value = $(this)[0].value.replace(/\s/g, '');
            });
        
            $('#Donation_Donor_Address_PostalCode').on('change', function () {
                $(this)[0].value = $(this)[0].value.replace(/^[\s]+|[\s]+$/g, '').toUpperCase();
            });

            // Targets iPhone's smart punctuation and replaces it with the regular apostrophe on all fields allowing them.
            var fieldsWithApostrophe = [
                '#Donation_Donor_FirstName',
                '#Donation_Donor_LastName',
                '#Donation_Donor_Address_FirstLine',
                '#Donation_Donor_Address_SecondLine',
                '#Donation_Donor_Address_ThirdLine',
                '#Donation_Donor_Address_PostalTown',
                '#Donation_Organisation_Firstname',
                '#Donation_Organisation_Lastname',
                '#Donation_Organisation_Address_FirstLine',
                '#Donation_Organisation_Address_SecondLine',
                '#Donation_Organisation_Address_PostalTown'
            ];

            fieldsWithApostrophe.forEach(function(field) {
                $(field).live('keydown', function(e) {
                    if (e.keyCode === 222) {
                        e.preventDefault();
                        $(this)[0].value += "'";
                    }
                });
                $(field).live('change', function(e) {
                    $(this)[0].value = $(this)[0].value.replace(/[‘]|[’]/g, "'");
                });
            });
        },

        showOtherField: function () {
            $('#PromptedToDonateBy').on('change', function () {
                if ($(this).val() === 'other_value') {
                    $('.donation-prompt-other').removeClass('js-hidden');
                } else {
                    $('.donation-prompt-other').addClass('js-hidden');
                }
            });
        },

        getPaymentButtons: function () {
            let className = '';
            let buttons = document.querySelectorAll('.paymentButtonContainer');

            if(buttons.length === 4) {
                if(document.querySelector('#divPay').classList.contains('hideContainer') || document.querySelector('.googlePayCont').classList.contains('hidden')) {
                    className = 'threeButtons';
                }else {
                    className = 'fourButtons';
                }
            }else if (buttons.length === 3) {
                className = 'threeButtons';
            }else if (buttons.length === 2) {
                className = 'twoButtons';
            }

            if(document.querySelector('.paymentOuterCont')) {
                document.querySelector('.paymentOuterCont').classList.add(className);
            }
        }
    };

    $(function () {
        macmillan.donationsForm.init();
    });

})(jQuery);
;$(document).ready(function () {
    // Remove the donation SMS container and extra payment options if DESKTOP
    if ( $('body').hasClass('desktop') ) {
        $('#DonateSmsContainer, #donations-options-container').remove();
    } else {
        // Else (smartphone or tablet), hide the SMS container and donation form
        $('#DonateSmsContainer').hide();
        if ($('.step1').length > 0 && $('#Donation_Payment_Amount').val().length > 0) {
            $('#donationForm').show();
            setActiveClass($('#PaymentOptionCC'));
        }
    }

    function scrollToElement($el){
        $('html, body').animate({
            scrollTop: $($el).offset().top - 20
        }, 300);
    }

    function setActiveClass( $el ){
        if( !$el.hasClass('active') ){
            $('.active').removeClass('active');
            $el.find('.payment-option-label').addClass('active');
        }
    }

    $('#PaymentOptionCC').on('click', function(e){
        e.preventDefault();
        var $this = $(this);
        $('#DonateSmsContainer').hide();
        $('#donationForm').show();
        setActiveClass( $this );
        scrollToElement( $this.attr('href') );
    });

     $('#DonateSmsContainerAnchor').on('click', function(e){
        e.preventDefault();
        var $this = $(this);
        $('#DonateSmsContainer').show();
        $('#donationForm').hide();
        setActiveClass( $this );
        scrollToElement( $this.attr('href') );
     });

    $('#dm-form-accordian').unbind();
    $('#dm-form-accordian').on('click', function(e){
        e.preventDefault();
        var $this = $(this);
        if( $this.hasClass('active-el') ){
            $this.removeClass('active-el').text( $this.data('defaulttext') );
            $('#' + $this.data('targetel')).removeClass('active-el');
        }else{
            $this.addClass('active-el').text( $this.data('changetext') );
            $('#' + $this.data('targetel')).addClass('active-el');
        }
    });
    
    // Remove the toogle interraction from the is on behalf of company radio buttons 
    // when the default otion selected is event.
    if ($('.donation-type').find('.ui-state-active').parent().find('input').val() == 'Event') {
        $('.org-detail').removeClass('hidden');
        $('.gift-toggle-content').addClass('hidden');
        $('.gift-toggle-content').attr('style', 'display:none');
        macmillan.utils.removeReversedRadioToggles();
        macmillan.utils.setRequiredTaxPayer(false);
    }
});;(function () {

    var $container = $('.container'),
        $toggle_wrapper = $container.find($('.js-toggle'));

    macmillan.utils = {
        init: function () {
            //initialize sharing
            if (typeof stLight != 'undefined') {
                stLight.options({
                    publisher: "ur-812ce429-24b5-25ad-75a7-6866b974d886"
                });
            }

            // Reset page defaults

            if ($('#InMemoryRelationship').val() === 'other_value') {
                $('.inmemoryrelationship-other').removeClass('js-hidden');
            }

            if ($('#CelebrationForRelationship').val() === 'other_value') {
                $('.incelebrationrelationship-other').removeClass('js-hidden');
            }

            if ($('#InCelebrationOf').val() === 'other_value') {
                $('.incelebration-other').removeClass('js-hidden');
            }

            macmillan.utils.setRadioToggles();
			macmillan.utils.bindEvents();
            toggleQuestion();
            encloseRadiosInDiv();

            setTimeout(function() {
                macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
            }, 300);
        },// end init

        setRadioToggles: function () {
            // inject the open/closed toggle classes
            var $triggers = $toggle_wrapper.find('div.toggle-radio, div.donations-toggle-radio');

            $('div.radio:not(:eq(1))', $triggers).addClass('js-toggle-closed');
            $('div.radio:eq(1)', $triggers).addClass('js-toggle-open');

            macmillan.utils.setReversedRadioToggles();

            macmillan.init_js_radio_toggle();
            macmillan.utils.accordionRadioToggles();
        },

        setReversedRadioToggles: function(){
            var $reversedTriggers = $toggle_wrapper.find('div.donations-toggle-radio-reversed');
            $('div.radio:not(:eq(1))', $reversedTriggers).addClass('js-toggle-open gift-aid');
            $('div.radio:eq(1)', $reversedTriggers).addClass('js-toggle-closed gift-aid');
        },
        setRequiredTaxPayer: function (value) {
            if (document.getElementById("TaxPayer_true") != null) {
                document.getElementById("TaxPayer_true").required = value;
            }
            if (document.getElementById("TaxPayer_false") != null) {
                document.getElementById("TaxPayer_false").required = value;
            }
        },
        removeReversedRadioToggles: function () {
            var $reversedTriggers = $toggle_wrapper.find('div.donations-toggle-radio-reversed');
            $('div.radio:not(:eq(1))', $reversedTriggers).removeClass('js-toggle-open gift-aid');
            $('div.radio:eq(1)', $reversedTriggers).removeClass('js-toggle-closed gift-aid');
        },

        accordionRadioToggles: function () {

            $('div.radio input', '.donateoccasion').each(function () {
                var $this = $(this),
                    $parent = $this.parent().parent();
                $this.button("refresh");
                if ($this.attr('checked') === "checked") {
                    if ($this.parent().hasClass('js-toggle-closed')) {
                        $parent.next('.donations-toggle-content').hide();
                        $parent.parent().next('.donations-toggle-content').slideUp();
                    } else {
                        $parent.next('.donations-toggle-content').show();
                        $parent.addClass('toggle-active');
                        $parent.next('.donations-toggle-content').addClass('content-active');
                    }
                }
            });

            // Make custom checkbox element clickable
            $('span.checkbox--custom').on('click', function(){
               let checkbox = ($(this).closest('.custom-checkbox').find('input[type=checkbox]'));
               if(checkbox.attr('checked')) {
                   checkbox.removeAttr('checked');
               } else {
                   checkbox.attr('checked', 'checked');
               }
            });

            // Remove seleced class from all tax payer inputs
            function clearSelectedState() {
                $.each($('.taxPayer'), function() {
                    $(this).removeClass('selected');
                })
            }

            // Highlight Gift Aid container once option selected
            $('.taxPayerInput').on('click focus', function() {
                clearSelectedState();
                $(this).closest('.taxPayer').toggleClass('selected');
            })

            // Allow Gift Aid text to trigger checked state to mimic label behavior
            $('#giftAidText').on('click', function(){
                clearSelectedState();
                $(this).closest('.taxPayer').addClass('selected').removeClass('errorbox').siblings('.taxPayer--false').find('.messagebox').hide();
                let radioButton = ($(this).closest('.taxPayer').find('input.taxPayerInput'));
                radioButton.attr('checked', 'checked');
            })
            

            $('div.radio.js-toggle-closed', 'div.donations-toggle-radio').add('.donations-toggle-radio-reversed .js-toggle-closed').on('click', function () {
                var $this = $(this);

                if ($this.hasClass('gift-aid')) {
                    $('.gift-toggle-content').slideUp({
                        complete: function () {
                            $(this).removeClass('content-active');
                            $this.parent().removeClass('toggle-active');
                        }
                    });
                } else {
                    $this.parent().parent().next('.donations-toggle-content').slideUp({
                        complete: function() {
                            $(this).removeClass('content-active');
                            $this.parent().parent().removeClass('toggle-active');
                        }
                    });

					macmillan.utils.clearInMemoryValues();
					macmillan.utils.clearInCelebrationValues();
                    toggleQuestion();
                }
            });

            $('div.radio.js-toggle-open', 'div.donations-toggle-radio').add('.donations-toggle-radio-reversed .js-toggle-open').on('click', function () {
                var $this = $(this);
                if ($this.hasClass('gift-aid')) {
                    $('.gift-toggle-content').slideDown({
                        complete: function () {
                            $this.parent().addClass('toggle-active');
                        }
                    });
                } else {
                    if (!$this.parent().hasClass('toggle-active')) {
                        $this.parent().parent().next('.donations-toggle-content').slideDown({
                            complete: function () {
                                $(this).addClass('content-active');
                                $this.parent().parent().addClass('toggle-active');
                            }
                        });

                        toggleQuestion();
                    }
                }
            });
        },


        smoothScroll: function (elem, offset) {
            var scrollElement = 'html, body';

            // The block below was removed due to it causing an issue with
            // form validation and scrolling and element to the correct place

            // $('html, body').each(function () {
            //     var initScrollTop = $(this).attr('scrollTop');
            //     if( typeof initScrollTop === 'undefined' || typeof initScrollTop === 'NaN'){
            //         initScrollTop = 0;
            //     }
            //     $(this).attr('scrollTop', initScrollTop + 1);
            //     if ($(this).attr('scrollTop') == initScrollTop + 1) {
            //         scrollElement = this.nodeName.toLowerCase();
            //         $(this).attr('scrollTop', initScrollTop);
            //         return false;
            //     }
            // });

            var $target = elem;
            var offsetValue = 0;
            if (offset > 0) {
                offsetValue = parseInt(offset);
            }
            $(scrollElement).stop().animate({
                scrollTop: $target.offset().top - offsetValue
            }, 500, 'swing');
        },

        hideIframeContents: function () {
            if ($('html').hasClass('js')) {
                $('.threeD-secure iframe').addClass('js-hidden');
            }
        },

        bindEvents: function(){


            $('.ui-button-text a.question, .js-option-trigger').on('click', function (e) {
                if(document.querySelector('input[name="Donation.DonationType"]:checked').value == 'OneOff' || document.querySelector('input[name="Donation.DonationType"]:checked').value == 'Regular') {
                    $('.gift-toggle-content').show();
                    $('.gift-toggle-content').removeClass('hidden');
                }else if(document.querySelector('input[name="Donation.DonationType"]:checked').value == 'Event') {
                    $('.gift-toggle-content').hide();
                    $('.gift-toggle-content').addClass('hidden');
                }

                $(this).parents('div.tooltip').find('input').attr('checked', 'checked').button("refresh");
            });

            $('#printbutton').on('click', function (e) {
                e.preventDefault();
                window.print();
            });

            $('.dd-guarantee', '.direct-debit').on('click', function (e) {
                e.preventDefault();
                var url = $(this).attr('href');
                window.open(url, 'dd', 'width=700,height=650');
            });

            $('.twitter a, .fb a').on('click', function () {
                var url = $(this).attr('href');
                window.open(url, 'twitter', 'width=560,height=478');
                return false;
            });

            $('div.tooltip a.question', 'div.slider').on('click', function () {
                $(this).parents('label').siblings('input[type=radio]').change();
            });

            function toFixed(num, fixed) {
                var regEx = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
                return num.toString().match(regEx)[0];
            }

            let mobileAmounts = [
                {
                    'regular': [5, 10, 20, 30, 50],
                    'one-off': [10, 20, 30, 50, 100]
                }
            ];

            var isFromCampaign = $('#FromCampaign').val() == 'true' ? true : false;

            // Get donation type on launch
            var donationType = sessionStorage.getItem('donationTab') ? sessionStorage.getItem('donationTab') : 'one-off';

            if(document.querySelector("span[data-option=" + donationType + "]")) {
                document.querySelector("span[data-option=" + donationType + "]").classList.add('selectedPaymentType');
            }

            var typeOfOneOffDonation = donationType == 'one-off' ? 'OneOff': '';

            macmillan.utils.initialiseSliderValues(mobileAmounts, donationType, isFromCampaign);

            setTimeout(function() {
                if($('.mobileAmountSelector').length && $('.mobileAmountSelector').css('display') != 'none') {
                    $('label[for=Donation_DonationType_OneOff]').find('.ui-button-text').html('This is my personal money');
                    $('label[for=Donation_DonationType_Event]').find('.ui-button-text').html('This is money raised from a collection or fundraiser');
                    if(sessionStorage.getItem('donationRadio')) {
                        if(sessionStorage.getItem('donationRadio') == 'regular') {
                            $('#Donation_DonationType_Regular').prop('checked', true);
                        }else {
                            if(sessionStorage.getItem('donationRadio') == 'OneOff') {
                                $('#Donation_DonationType_OneOff').prop('checked', true);
                                $('#Donation_DonationType_OneOff').addClass('ui-state-active');
                                $('#Donation_DonationType_Event').removeClass('ui-state-active');
                            }else if(sessionStorage.getItem('donationRadio') == 'Event') {
                                $('#Donation_DonationType_Event').prop('checked', true);
                                $('#Donation_DonationType_Event').removeClass('ui-state-active');
                                $('#Donation_DonationType_OneOff').removeClass('ui-state-active');
                            }
                        };
                    }else {
                        $('#Donation_DonationType_OneOff').prop('checked', true);
                        $('#Donation_DonationType_OneOff').addClass('ui-state-active');
                        $('#Donation_DonationType_Event').removeClass('ui-state-active');
                        $('#Donation_DonationType_Regular').removeClass('ui-state-active');
                    };
                }else {
                    if($('#Donation_DonationType_Regular').prop('checked')) {
                        sessionStorage.setItem('donationTab', 'regular');
                    }else {
                        sessionStorage.setItem('donationTab', 'one-off');
                    }
                }
            }, 300);

            $('#Donation_DonationType_Regular').on('click', function() {
                sessionStorage.setItem('donationTab', 'regular');
            });
            $('#Donation_DonationType_OneOff').on('click', function() {
                typeOfOneOffDonation = 'OneOff';
                sessionStorage.setItem('donationTab', 'one-off');
            });
            $('#Donation_DonationType_Event').on('click', function() {
                typeOfOneOffDonation = 'Event';
                sessionStorage.setItem('donationTab', 'one-off');
            });

            $('.paymentOptionContainer').css('display') == 'flex' ? $('.radio.js-option-trigger.donation-type:eq(0)').hide() : $('.radio.js-option-trigger.donation-type:eq(0)').show();

            $('.mobile-payment-option-container').on('click', function() {
                donationType = this.id == 'one-off-donation' ? 'one-off' : 'regular';
                if(donationType == 'regular') {
                    donationType != document.querySelector('.selectedPaymentType').getAttribute('data-option') ? $('#Donation_DonationType_Regular').prop('checked', true) : null;
                }else {
                    if(typeOfOneOffDonation == 'OneOff') {
                        $('#Donation_DonationType_OneOff').prop('checked', true);
                        $('#Donation_DonationType_OneOff').addClass('ui-state-active');
                        $('#Donation_DonationType_Event').removeClass('ui-state-active');
                    }else if(typeOfOneOffDonation == 'Event') {
                        $('#Donation_DonationType_Event').prop('checked', true);
                        $('#Donation_DonationType_Event').removeClass('ui-state-active');
                        $('#Donation_DonationType_OneOff').removeClass('ui-state-active');
                    }
                };

                macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
                $('#DonationTypeAndAmount')[0] ? $('#DonationTypeAndAmount').validate().element('#Donation_Payment_Amount') : $('form.wbcmform').validate().element('#Donation_Payment_Amount');

                sessionStorage.setItem('donationTab', donationType);
                macmillan.utils.initialiseSliderValues(mobileAmounts, donationType, isFromCampaign);
                macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
            })

            if(document.querySelector('.selectedPaymentType')) {
                donationType = document.querySelector('.selectedPaymentType').getAttribute('data-option');

                if(document.querySelector('#one-off-donation')) {
                    document.querySelector('#one-off-donation').addEventListener('click', function() {
                        document.querySelector('input[name="Donation.DonationType"]:checked').value == 'Event' ? $('.gift-toggle-content').hide() : $('.gift-toggle-content').show();
                    })
                }

                // Build the html for the slider
                macmillan.utils.buildMobileSlider(mobileAmounts, donationType);
                macmillan.utils.initialiseSliderValues(mobileAmounts, donationType, isFromCampaign);
            }

            // When user types into the amount input box: Highlight the amount that was selected
            $('#Donation_Payment_Amount').on('keyup', function() {
                if(document.querySelectorAll('.donationAmountSlider').length > 0) {
                    var donationAmounts = macmillan.utils.getDonationAmounts(mobileAmounts[0], donationType);
                    var fieldValue = $('#Donation_Payment_Amount').val();

                    Array.prototype.forEach.call(amountSelectorItems, function(selectorItem) {
                        selectorItem.classList.remove('amountSelected');
                    });
                    Array.prototype.forEach.call(donationAmounts, function(amount, index) {
                        fieldValue == amount ? amountSelectorItems[index].classList.add('amountSelected') : null;
                    })
                }
                $('#DonationTypeAndAmount')[0] ? $('#DonationTypeAndAmount').validate().element('#Donation_Payment_Amount') : $('form.wbcmform').validate().element('#Donation_Payment_Amount');
            });

            // Get node list of all amount items
            let amountSelectorItems = document.querySelectorAll('.donationAmountItem');
            // When user clicks amount item: update the amount in the input box
            Array.prototype.forEach.call(amountSelectorItems, function(selectorItem) {
                selectorItem.addEventListener('click', function(e) {
                    macmillan.utils.updateMobileAmount(e);
                    macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
                    $('#DonationTypeAndAmount')[0] ? $('#DonationTypeAndAmount').validate().element('#Donation_Payment_Amount') : $('form.wbcmform').validate().element('#Donation_Payment_Amount');
                })
            })

            let paymentMethodTabs = document.querySelectorAll('.payment-option-label');

            Array.prototype.forEach.call(paymentMethodTabs, function(tab) {
                tab.addEventListener('click', function(e) {
                    donationType = this.id == 'one-off-donation' ? 'one-off' : 'regular';
                    if(donationType == 'regular') {
                        donationType != document.querySelector('.selectedPaymentType').getAttribute('data-option') ? $('#Donation_DonationType_Regular').prop('checked', true) : null;
                    }else {
                        if(typeOfOneOffDonation == 'OneOff') {
                            $('#Donation_DonationType_OneOff').prop('checked', true);
                            $('#Donation_DonationType_OneOff').addClass('ui-state-active');
                            $('#Donation_DonationType_Event').removeClass('ui-state-active');
                        }else if(typeOfOneOffDonation == 'Event') {
                            $('#Donation_DonationType_Event').prop('checked', true);
                            $('#Donation_DonationType_Event').removeClass('ui-state-active');
                            $('#Donation_DonationType_OneOff').removeClass('ui-state-active');
                        }
                    };

                    macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
                    $('#DonationTypeAndAmount')[0] ? $('#DonationTypeAndAmount').validate().element('#Donation_Payment_Amount') : $('form.wbcmform').validate().element('#Donation_Payment_Amount');

                    sessionStorage.setItem('donationTab', donationType);

                    var currentTab = document.querySelector('.selectedPaymentType').getAttribute('data-option');
                    if(currentTab != tab.getAttribute('data-option')) {
                        macmillan.utils.updateTabs(e, paymentMethodTabs);
                        macmillan.utils.initialiseSliderValues(mobileAmounts, donationType, isFromCampaign);
                    }
                })
                macmillan.utils.initialiseSliderValues(mobileAmounts, donationType, isFromCampaign);
            });

            // functions for optimisation project Aug 2020
            $('.paymentTypes').on('click keydown touchend', 'div', function(e) {
                e.stopPropagation();

                let current_card = event.target;

                if (macmillan.utils.handleInteraction(e, current_card) === true) {
                  var paymentType = $(this).closest('.donation__cards--card')[0].dataset.paymenttype;
                  $('#typeOfDonation').val(paymentType);
                  sessionStorage.setItem('donationType', paymentType);
                  $('#DonationType').submit();

                }

                return false;
            });

            $('.relations').children().attr({'tabIndex': -1});

            function checkInMemoryOfSelected() {
                $('input#IsInMemoryOfSomeone_true:checked')
                .closest('.row.memory')
                .find('.relations')
                .addClass('display')
                .find('input#InMemoryOf')
                .siblings('label[for=InMemoryOf], label[for=InMemoryRelationship] ')
                .css('display', 'inline')
                .siblings('input#InMemoryOf')
                .css('display', 'block')
                .closest('.row.memory')
                .find('select#InMemoryRelationship').show();

                $('input#InMemoryOtherRelationship').attr('tabindex', '0');
            }

            function checkMemoryRelationshipOther() {
                var el =  $('input#IsInMemoryOfSomeone_true:checked')
                .closest('.row.memory')
                .find('select#InMemoryRelationship');

                if($(el).val() === "Other") {
                    $('.otherRelation').css('display', 'block')
                }

                var inMemoryOfTrue = $('#IsInMemoryOfSomeone_true');
                inMemoryOfTrue.on('click change', function(){
                    if($(el).val() === "Other") {
                        $('.otherRelation').css('display', 'block')
                    }
                })
            }

            checkInMemoryOfSelected();
            checkMemoryRelationshipOther();

            // Step 3 Regular - Reveal terms and condition
            $('#display-terms-and-conditions').on('click', function(e) {
                e.preventDefault();
                var expandedState = $(this).attr('aria-expanded');

               if(expandedState === 'false') {
                   console.log('false');
                   $(this).attr('aria-expanded', 'true' );
               } else {
                $(this).attr('aria-expanded', 'false' );
               }
                

                $('.terms-and-conditions').toggleClass('show');
                $('.accordian-expand-icon').toggleClass('expanded');
            })

            $('body')
                .on('click touchend', '.amounts--button', function(e) {
                    e.stopPropagation();
                    let amount = e.target.value;

                    //  Remove selected class from other button and add to current
                    let buttons = $('.amounts--button');
                    let selectedButton = e.target;
                    $.each(buttons, function(i, button){
                        $(button).removeClass('selected')
                    });

                    $(selectedButton).addClass('selected');

                    $('#amountToDonate, .amounts--amount').val(amount);
                    $('#amounts--amount__input').valid();
                })
                .on('change', '#amounts--amount__input', function(e){
                    let amount = e.target.value;
                    let buttons = $('.amounts--button');
                    $.each(buttons, function(i, button){
                        $(button).removeClass('selected');
                    });
                    $('#amountToDonate, .amounts--amount').val(amount);
                })
                .on('focusout', '.amounts--amount', function(e) {
                    e.stopPropagation();
                    let amount = e.target.value;

                    $('#amountToDonate').val(amount);
                })
                .on('change', '.memory input[type="radio"]', function(e) {
                    e.stopPropagation();
                    let relations = $('.relations');

                    if(e.target.value === 'true') {
                        relations.addClass('display').children()
                            .attr({'tabIndex': 0}).not('.otherRelation')
                            .show();
                        $('#InMemoryRelationship').show();
                    } else {
                        relations.removeClass('display').children()
                            .attr({'tabIndex': -1})
                            .hide();
                        $('#InMemoryRelationship').show();
                    }
                })
                .on('change', '#InMemoryRelationship', function (e) {
                    if (e.target.value == "Other") {
                        $('.otherRelation').show();
                    } else {
                        $('.otherRelation').hide();
                    }
                })
        },

        handleInteraction: function (event, card){
            let eventType = event.type;

            switch (eventType) {
                case 'click':
                case 'touchend': return true;
                case 'keydown': if (macmillan.utils.handleKeypress(event, card)) {return true};
                default: return false;
            }
        },

        handleKeypress: function (event, card) {
            let cards = $('.donation__cards--card');
            let code = event.keyCode;

            if ((code === 32) || (code === 13)) {
                return true;
            }

            if (event.shiftKey && code == 9) {
                if (card === cards[0]) {
                    $('.header-donate-cta > a').focus();
                } else {
                    $(card).prev().focus();
                }
            } else if (code === 9) {
                if (card === cards.last()[0]) {
                    $('.keyboard_next_step').focus();
                } else {
                    $(card).next().focus();
                }
            }

            return false;
        },

        updateTabs: function(e, paymentMethodTabs) {
            let optionSelected = e.target.getAttribute('data-option');
            Array.prototype.forEach.call(paymentMethodTabs, function(tab) {
                tab.classList.remove('selectedPaymentType');
            });
            document.querySelector('[data-option=' + optionSelected + ']').classList.add('selectedPaymentType');
            return optionSelected;
        },

        initialiseSliderValues: function(mobileAmounts, donationType, isFromCampaign) {
            if($('#donationForm').data('step') == 1) {
                let type = donationType ? donationType : document.querySelector('.selectedPaymentType').getAttribute('data-option');

                let donationAmounts = macmillan.utils.getDonationAmounts(mobileAmounts[0], type);

                // update amounts displayed on slider
                macmillan.utils.updateAllSliderAmounts(donationAmounts);
                // reset amount selected to default amount

                if(isFromCampaign) {
                    macmillan.utils.updateAmountSelected(Math.round($('#Donation_Payment_Amount').val()));
                    document.querySelector('#Donation_Payment_Amount').value = $('#Donation_Payment_Amount').val();
                }else {
                    // update amounts displayed on slider
                    macmillan.utils.updateAllSliderAmounts(donationAmounts);
                    // reset amount selected to default amount
                    macmillan.utils.updateAmountSelected(donationAmounts[2]);
                    // Update amount in input box
                    //document.querySelector('#Donation_Payment_Amount').value = donationAmounts[2];
                }
            }
        },

        updateAllSliderAmounts: function(filteredAmountsArray) {
            let amountItems = document.querySelectorAll('.donationAmountItem');

            for(let i = 0; i < amountItems.length; i++) {
                amountItems[i].setAttribute('data-amount', filteredAmountsArray[i]);
                amountItems[i].innerHTML = '<span class="poundSign">£</span>' + filteredAmountsArray[i];
            }
        },

        buildMobileSlider: function(amountsArray, donationType) {
            document.querySelector('.mobileAmountSelector').innerHTML = '';
            let donationAmounts = macmillan.utils.getDonationAmounts(amountsArray[0], donationType);

            Array.prototype.forEach.call(donationAmounts, function(amount, index) {
                let amountItem = document.createElement('div');
                amountItem.classList.add('donationAmountItem');
                index == 0 ? amountItem.classList.add('amountSelected') : null;
                amountItem.setAttribute('data-amount', amount);
                amountItem.innerHTML = '<span class="poundSign">£</span>' + amount;
                document.querySelector('.mobileAmountSelector').appendChild(amountItem);
            })
        },

        getDonationAmounts: function(amountsArray, donationType) {
            let filterArray = amountsArray[Object.keys(amountsArray).filter(function(key) {
                return key == donationType;
            })];
            return filterArray;
        },

        getClosestAmount: function(initialAmount, amountsArray, donationType) {
            var closest = macmillan.utils.getDonationAmounts(amountsArray[0], donationType).reduce(function(prev, curr) {
                return (Math.abs(curr - initialAmount) < Math.abs(prev - initialAmount) ? curr : prev);
            });
            return closest;
        },

        updateAmountSelected: function(amount) {
            let amountSelectorItems = document.querySelectorAll('.donationAmountItem');

            Array.prototype.forEach.call(amountSelectorItems, function(selectorItem) {
                selectorItem.classList.remove('amountSelected');
            });

            Array.prototype.forEach.call(amountSelectorItems, function(selectorItem) {
                if(selectorItem.getAttribute('data-amount') == amount) {
                    selectorItem.classList.add('amountSelected');
                }
            });
        },

        updateMobileAmount: function(e) {
            e.preventDefault();

            var amount = e.target.tagName.toLowerCase() == 'span' ? e.target.parentElement.getAttribute('data-amount') : e.target.getAttribute('data-amount');

            document.querySelector('#Donation_Payment_Amount').value = amount;
            sessionStorage.setItem('selectedDonationAmount', amount);
            macmillan.utils.updateAmountSelected(amount);
        },

        setGiftAidMessage: function(amount) {
            if (!isNaN(parseFloat(amount)) && isFinite(amount) && amount != 0) {
                var giftaidedValue = parseFloat(amount) + parseFloat(amount * 0.25);
				$('.gift-aid-donation, .wbcmGiftAidHeader').html('Your donation of \u00A3'
                    + parseFloat(amount).toFixed(2)
                    + ' will be increased to \u00A3'
                    + giftaidedValue.toFixed(2)
                    + ' with Gift Aid with no extra cost to you.');
            } else {
				$('.gift-aid-donation, .wbcmGiftAidHeader').html('Your donation will be increased by 25% with Gift Aid with no extra cost to you.');
            }
		},
		clearInMemoryValues: function () {
			$('#InMemoryOf').val('');
			$('#InMemoryRelationship').val('');
		},
		clearInCelebrationValues: function () {
			$('#CelebrationDedicatedTo').val('');
			$('#CelebrationForRelationship').val('');
			$('#InCelebrationOf').val('');
		}
    }; // end function

    function toggleQuestion() {
        if ($('#IsInMemoryOfSomeone_true').attr('checked') == 'checked') {
            $('.IsInCelebrationOfSomeoneDiv').hide();
		} else {
            $('.IsInCelebrationOfSomeoneDiv').show();
        }

        if ($('#IsInCelebrationOfSomeone_true').attr('checked') == 'checked') {
            $('.IsInMemoryOfSomeoneDiv').hide();
		} else {
            $('.IsInMemoryOfSomeoneDiv').show();
        }
    }
    function encloseRadiosInDiv() {
        $('.IsInMemoryOfSomeoneDiv div.radio').wrapAll("<div class=\"radioGroup\"></div>");
        $('.IsInCelebrationOfSomeoneDiv div.radio').wrapAll("<div class=\"radioGroup\"></div>");
    }
}());;(function () {

    macmillan.donationsForm.validate = {
        init: function () {
            // Resets the page to its default if a user goes back.
            $('.js-option-trigger input[checked=checked]').prop('checked', true);

            $.validator.addMethod('consentRule', function (value, element) {
                var regexData = $(element).data('rule-regex'),
                    regexObj = new RegExp(regexData);

                if (regexObj.test(value)) {
                    return true;
                } else {
                    // For optional fields, such as address second line
                    if ($(element).attr('aria-required') !== 'true' && $(element).val() === '') {
                        $(element).closest('.error').css('display', 'none');
                        return true;
                    }
                    return false;
                };
            }, function (params, element) {
                return '' + $(element).data('msg-regex') + ''
            });

            $.validator.addMethod("valueNotEquals", function (value, element, arg) {
                return arg != value;
            }, "Value must not equal arg.");

            $.validator.addMethod(
                "postcode",
                function (value, element) {
                    var val = value.toUpperCase();
                    return this.optional(element) || /^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])( |)[0-9][ABD-HJLNP-UW-Z]{2})$/.test(val);
                },
                "Postcode is invalid"
            );

            $.validator.addMethod(
                "phoneNumber",
                function (value, element) {
                    return this.optional(element) || /^[0-9\+\(\) ]+( ext ?)?[0-9]+$/.test(value);
                },
                "Phone number is invalid"
            );

             $.validator.addMethod("isNameFormat",
                function (value, element) {
                    var re = /^[A-Za-zÀ-ÿ'\- ]+$/;
                    return this.optional(element) || re.test(value);
                }
            );

            $.validator.addMethod("isTownFormat",
                function (value, element) {
                    var re = /^[A-Za-z'.\-\& ]+$/;
                    return this.optional(element) || re.test(value);
                }
            );

            $.validator.addMethod("isAddressFormat",
                function (value, element) {
                    var re = /^[0-9A-Za-z',.;\-\&/ ]+$/;
                    return this.optional(element) || re.test(value);
                }
            );

            $.validator.addMethod("isValidExpiry", function (value, element) {

                var year = $('#PaymentCardExpiryYear').val();

                var month = $('#PaymentCardExpiryMonth').val();

                var currentYear = (new Date().getFullYear() - 2000);

                var currentMonth = (new Date().getMonth() + 1);

                var retVal = !((currentYear == year) && (month < currentMonth));

                return retVal;

            });

            $.validator.addMethod("isValidStart", function (value, element) {

                var year = $('#PaymentCardStartYear').val();

                var month = $('#PaymentCardStartMonth').val();

                var currentYear = (new Date().getFullYear() - 2000);

                var currentMonth = (new Date().getMonth() + 1);

                if ((currentYear == year) && (month <= currentMonth))
                    return true;
                if (currentYear > year && year != "" && month != "")
                    return true;
                if (year == "" && month == "")
                    return true;
                if (year == "" && month != "")
                    return false;
            });

            $.validator.addMethod("isValidCardNo", function (value, element) {
                var c = $(element).val();
                var cl = parseInt(c.substr(c.length - 1));
                var c = c.slice(0, -1)
                var c = c.split("").reverse().join("");
                var c = c.split("");
                var a = 2;
                var cm = [];
                for (var i = 0; i < c.length; i++) {
                    if (a % 2 == 0) {
                        var t = c[i] * 2;
                        if (t > 9) { var t = (t - 9); }
                        cm.push(t);
                    } else { cm.push(parseInt(c[i])); }
                    a++;
                }
                var f = 0;
                for (var i = 0; i < cm.length; i++) { f += cm[i]; }
                f = f + cl;
                if (f % 10 == 0) {
                    return true;
                } else {
                    return false;
                }
            });

            $("form.donateform").validate({
                onkeyup: false,
                errorElement: "p",
                wrapper: 'div class="messagebox js"',
                errorPlacement: function (error, element, errorClass, validClass) {
                    if(element.hasClass('taxPayerInput')) {
                        error.appendTo(element.closest('.taxPayer--true').siblings('.taxPayer--false'));
                    } else {
                        error.appendTo(element.closest('div.row'));
                    }
                    $(error).find('.error').attr('role', 'alert');
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).closest('div.row').addClass('errorbox');
                    if(element.classList.contains('taxPayerInput')) {
                        $(element).closest('.giftaid').addClass('errorbox');
                    }
                   
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest('div.row').removeClass('errorbox');
                    if(element.classList.contains('taxPayerInput')) {
                        $(element).closest('.giftaid').removeClass('errorbox');
                    }
                },

                messages: {
                    "Donation.Donor.Email": {
                        required: "Please tell us your email address",
                        email: "Please enter a valid email address"
                    },
                    "Donation.Donor.Title": {
                        required: "Please include your title"
                    },
                    "Donation.Donor.Address.PostalCode": {
                        required: "Please include your postcode",
                        postcode: "Postcode is invalid",
                        maxlength: "Please type in no more than 8 characters"
                    },
                    "Donation.Donor.FirstName": {
                        required: "Please include your first name",
                        isNameFormat: "First name accepts only accented letters, hyphens, apostrophes and spaces.",
                        maxlength: "Please type in no more than 32 characters"
                    },
                    "Donation.Donor.LastName": {
                        required: "Please include your last name",
                        isNameFormat: "Last name accepts only accented letters, hyphens, apostrophes and spaces.",
                        maxlength: "Please type in no more than 32 characters"
                    },
                    "Donation.Organisation.Address.PostalCode": {
                        required: "Please include your company's postcode",
                        postcode: "Postcode is invalid",
                        maxlength: "Please type in no more than 8 characters"
                    },
                    'Donation.Donor.Address.FirstLine': {
                        required: "Please include the first line of your address"
                    },
                    'Donation.Donor.Address.PostalTown': {
                        required: "Please include your town/city."
                    },
                    "Donation.Payment.PaymentCard.Number": {
                        required: "Please include the full card number",
                        number: "Please enter numbers only",
                        minlength: jQuery.format("Please include the full {0}-digit card number"),
                        isValidCardNo: "Card number is invalid, please re-enter"
                    },

                    "Donation.Payment.PaymentCard.CardSecurityCode": {
                        required: "Please include the 3 or 4-digit security number",
                        number: "Please enter numbers only",
                        minlength: jQuery.format("the security code should be {0} digits"),
                        maxlength: jQuery.format("the security code should only be {0} digits")
                    },
                    "Donation.Payment.DirectDebit.AccountNumber": {
                        required: "Please include the full 8-digit account number",
                        number: "Please a valid account number",
                        rangelength: "Please include the full 8-digit account number"
                    },
                    "Donation.Payment.DirectDebit.SortCode": {
                        required: "Please include the 6-digit sort code",
                        number: "Please enter a valid sort code",
                        rangelength: "Please include the 6-digit sort code"
                    },

                    "Donation.Payment.DirectDebit.AccountName": {
                        required: "Please include the name of the account holder"
                    },
                    "Donation.Payment.PaymentCard.CardholderName": "Please include the cardholder name",
                    "PaymentCardStartMonth": {
                        isValidStart: true,
                    },
                    "PaymentCardStartYear":
                    {
                        isValidStart: "Please enter a valid start date."
                    },
                    "PaymentCardExpiryMonth": {
                        required: "Please include the expiry date in DD-MM format",
                        isValidExpiry: true,

                    },
                    "PaymentCardExpiryYear": {
                        required: "Please include the expiry date in DD-MM format",
                        isValidExpiry: "Please enter a valid expiry date."
                    },
                    "TaxPayer": {
                        required: "Please choose whether you would like to add Gift Aid"
                    },
                    "Donation.Organisation.Name": "Please tell us your company's name",
                    "Donation_Organisation_Address_FirstLine": "Please include the first line of your company's address",
                    "Donation.Organisation.Address.PostalTown": "Please tell us your company's town/city",
                   
                },

                rules: {
                    "Donation.Donor.Email": {
                        email: true
                    },
                    "Donation.Donor.Title": {
                        required: true
                    },
                    "Donation.Donor.Address.PostalCode": {
                        required: true,
                        maxlength: 8,
                        postcode: true,
                        consentRule: true
                       
                    },
                    "Donation.Donor.FirstName": {
                        required: true,
                        consentRule: true,
                        isNameFormat: true,
                        maxlength: 32
                    },
                    "Donation.Donor.LastName": {
                        required: true,
                        consentRule: true,
                        isNameFormat: true,
                        maxlength: 32
                    },
                    "Donation.Organisation.Address.PostalCode": {
                        required: true,
                        maxlength: 8,
                        postcode: true,
                        consentRule: true
                        
                    },
                    "Donation.Organisation.Address.PostalTown": {
                        required: true,
                        consentRule: true
                    },
                    'Donation.Donor.Address.FirstLine': {
                        required: true,
                        consentRule: true
                    },
                    'Donation.Donor.Address.SecondLine': {
                        consentRule: true
                    },
                    'Donation.Donor.Address.ThirdLine': {
                        consentRule: true
                    },
                    'Donation.Donor.Address.PostalTown': {
                        consentRule: true
                    },
                    "Donation.Donor.Phone.Number": {
                        consentRule: true,
                        phoneNumber: true

                    },
                    "Donation.Payment.DirectDebit.AccountNumber": {
                        required: true,
                        number: true,
                        rangelength: [8, 8]
                    },
                    "Donation.Payment.DirectDebit.SortCode": {
                        required: true,
                        number: true,
                        rangelength: [6, 6]
                    },
                    "Donation.Payment.PaymentCard.Number": {
                        required: true,
                        number: true,
                        minlength: function (elem) {
                            var isAmex = $(elem).val().substr(0, 2);
                            if (isAmex === "34" || isAmex === "37") {
                                return 15;
                            } else {
                                return 16;
                            }
                        },
                        isValidCardNo: true,
                        maxlength: function (elem) {
                            var isAmex = $(elem).val().substr(0, 2);
                            if (isAmex === "34" || isAmex === "37") {
                                return 15;
                            } else {
                                return 16;
                            }
                        }
                    },
                    "PaymentCardStartMonth": {
                        isValidStart: function () { return false; }
                    },
                    "PaymentCardStartYear": {
                        isValidStart: true
                    },
                    "PaymentCardExpiryMonth": {
                        required: true,
                        isValidExpiry: function () { return false; }
                    },
                    "PaymentCardExpiryYear": {
                        required: true,
                        isValidExpiry: true
                    },
                    "Donation.Payment.PaymentCard.CardSecurityCode": {
                        required: true,
                        number: true,
                        maxlength: function () {
                            var isAmex = $('#Donation_Payment_PaymentCard_Number').val().substr(0, 2);
                            if (isAmex === "34" || isAmex === "37") {
                                return 4;
                            } else {
                                return 3;
                            }
                        },
                        minlength: function (elem) {
                            var isAmex = $('#Donation_Payment_PaymentCard_Number').val().substr(0, 2);
                            if (isAmex === "34" || isAmex === "37") {
                                return 4;
                            } else {
                                return 3;
                            }
                        }
                    },

                    "Donation.Payment.DirectDebit.AccountName": {
                        required: true
                    },
                    "TaxPayer": {
                        required: true
                    }
                }
            });

            $("form[id$='DonationTypeAndAmount']").validate({
                onkeyup: function (element) {
                    $(element).valid()
                },
                errorElement: "p",
                focusCleanup: false,
                wrapper: 'div class="js"',
                errorPlacement: function (error, field, errorClass, validClass) {
                    // Workaround to delete validate message from server side
                    $('p[name="Donation_Payment_Amount"]').remove();
                    $('span.field-validation-error.error').remove();

                    error.appendTo(field.closest('div.fieldContainer'));
                    $(error).find('.error').attr('role', 'alert');
                },
                highlight: function (field, errorClass, validClass) {
                    $(field).closest('div.row').addClass('errorbox');
                },
                unhighlight: function (field, errorClass, validClass) {
                    $(field).closest('div.row').removeClass('errorbox');
                },
                rules: {
                    "Donation.Payment.Amount": {
                        required: true,
                        min: function (element) {
                            return sessionStorage.getItem('donationType') == 'Regular' ? 2 : 0.01;
                        },
                        number: true
                    },
                    "Donation.DonationType": {
                        required: true
                    },
                    "TeamReferenceNo": {
                        number: true
                    }
                },
                messages: {
                    "Donation.DonationType": "Please tell us the type of donation you wish to make",
                    "Donation.Payment.Amount": {
                        min: function (element) {
                            return "Sorry, the minimum " + (sessionStorage.getItem('donationType') == 'Regular' ? 'regular' : 'one-off') + " donation we can accept is " + (sessionStorage.getItem('donationType') == 'Regular' ? '£2' : '1p');
                        },
                        required: "Please include the amount you want to donate",
                        number: "Please enter a valid amount"
                    },
                    "TeamReferenceNo": "The team reference number can contain only numbers"
                }
            });

            $("form#UserDetails").validate({
                onkeyup: false,
                errorElement: "p",
                wrapper: 'div class="messagebox js"',
                errorPlacement: function (error, element, errorClass, validClass) {
                    error.appendTo(element.closest('div.row'));
                    $(error).find('.error').attr('role', 'alert');
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).closest('div.row').addClass('errorbox');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest('div.row').removeClass('errorbox');
                },

                messages: {
                    "Donation.Donor.Email": {
                        required: "Please tell us your email address",
                        email: "Please enter a valid email address"
                    },
                    "Donation.Donor.Title": {
                        required: "Please include your title"
                    },
                    "Donation.Donor.Address.PostalCode": {
                        required: "Please include your postcode",
                        postcode: "Postcode is invalid",
                        maxlength: "Postcode must be less than 8 characters"
                    },
                    "Donation.Donor.FirstName": {
                        required: "Please include your first name",
                        isNameFormat: "First name accepts only accented letters, hyphens, apostrophes and spaces.",
                        maxlength: "First name must be less than 32 characters"
                    },
                    "Donation.Donor.LastName": {
                        required: "Please include your last name",
                        isNameFormat: "Last name accepts only accented letters, hyphens, apostrophes and spaces.",
                        maxlength: "First name must be less than 32 characters"
                    },
                    "Donation.Organisation.Address.PostalCode": {
                        required: "Please include your company's postcode",
                        postcode: "Postcode is invalid",
                        maxlength: "Postcode must be less than 8 characters"
                    },
                    'Donation.Donor.Address.FirstLine': {
                        required: "Please include the first line of your address"
                    },
                    'Donation.Donor.Address.PostalTown': {
                        required: "Please include your town/city."
                    },
                    "Donation.Organisation.Name": {
                        required: "Please include the organisation name"
                    },
                    "Donation.Organisation.Address.FirstLine": {
                        required: "Please include organisation address"
                    }
                },

                rules: {
                    "Donation.Donor.Email": {
                        email: true,
                        required: true
                    },
                    "Donation.Donor.Title": {
                        required: true
                    },
                    "Donation.Donor.Address.PostalCode": {
                        required: true,
                        maxlength: 8,
                        postcode: true,
                        consentRule: true
                       
                    },
                    "Donation.Donor.FirstName": {
                        required: true,
                        consentRule: true,
                        isNameFormat: true,
                        maxlength: 32
                    },
                    "Donation.Donor.LastName": {
                        required: true,
                        consentRule: true,
                        isNameFormat: true,
                        maxlength: 32
                    },
                    "Donation.Organisation.Address.PostalCode": {
                        required: true,
                        maxlength: 8,
                        postcode: true,
                        consentRule: true
                        
                    },
                    "Donation.Organisation.Address.PostalTown": {
                        required: true,
                        consentRule: true
                    },
                    'Donation.Donor.Address.FirstLine': {
                        required: true,
                        consentRule: true
                    },
                    'Donation.Donor.Address.SecondLine': {
                        consentRule: true
                    },
                    'Donation.Donor.Address.ThirdLine': {
                        consentRule: true
                    },
                    'Donation.Donor.Address.PostalTown': {
                        consentRule: true
                    },
                    "Donation.Donor.Phone.Number": {
                        consentRule: true,
                        phoneNumber: true
                    },
                    "Donation.Organisation.Name": {
                        required: true
                    },
                    "Donation.Organisation.Address.FirstLine": {
                        required: true
                    },
                    "Donation.Donor.Address.PostalTown": {
                        required: true,
                        consentRule: true
                    }
                }
            });

            $("form#DonationAmount").validate({
                onkeyup: false,
                errorElement: "p",
                wrapper: 'div class="messagebox js"',
                errorPlacement: function (error, element, errorClass, validClass) {                  
                    if(element.hasClass('amounts--amount')) {
                        error.appendTo(element.closest('.amounts--input-container'));
                    }
                    if(element.hasClass('otherRelation')) {
                        console.log(element.closest('.relations'));
                        error.appendTo(element.closest('.relations'));
                    }
                    
                    $(error).find('.error').attr('role', 'alert');
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).closest('.amounts--input-container').addClass('errorbox');

                    if($(element).hasClass('otherRelation')) {
                        $(element).addClass('errorHighlight');
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest('.amounts--input-container').removeClass('errorbox');

                    if($(element).hasClass('otherRelation')) {
                        $(element).removeClass('errorHighlight');
                    }
                },

                messages: {
                    "Donation.Payment.Amount.Hidden": {
                        min: function (element) {
                            return "Sorry, the minimum " + (sessionStorage.getItem('donationType') == 'Regular' ? 'regular' : 'one-off') + " donation we can accept is " + (sessionStorage.getItem('donationType') == 'Regular' ? '£2' : '1p');
                        },
                        required: "Please include the amount you want to donate",
                        number: "Please enter a valid amount"
                    },
                    "InMemoryOtherRelationship": {
                        required: "Please tell us the relationship",
                        isNameFormat: "Please use only accented letters, hyphens, apostrophes and spaces."
                    }
                },

                rules: {
                    "Donation.Payment.Amount.Hidden": {
                        required: true,
                        number: true,
                        min: function (element) {
                            return sessionStorage.getItem('donationType') == 'Regular' ? 2 : 0.01;
                        }
                       
                    },
                    "InMemoryOtherRelationship": {
                        required: true,
                        isNameFormat: true
                    }
                }
            });

        }// end init
    }; // end function
}());;Macmillan = {
    applePay: {
        beginPayment: function (e) {
            var formClassname = '';

            e.preventDefault();

            var subtotal = $('#Donation_Payment_Amount').val();
            var countryCode = $("meta[name='payment-country-code']").attr("content") || "GB";
            var currencyCode = $("meta[name='payment-currency-code']").attr("content") || "GBP";
            var storeName = $("meta[name='apple-pay-store-name']").attr("content");

            var totalAmount = {
                label: storeName,
                amount: subtotal.toString()
            };

            var lineItems = [
                { label: "Total", amount: subtotal, type: "final" }
            ];

            var paymentRequest = {
                countryCode: countryCode,
                currencyCode: currencyCode,
                merchantCapabilities: ['supports3DS'],
                supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
                total: totalAmount,
                supportedCountries: [countryCode]
            };

            // Setup antiforgery HTTP header.
            var antiForgeryToken = $("input[name=__RequestVerificationToken]").val();
            var headers = {};
            headers["__RequestVerificationToken"] = antiForgeryToken;
            var session = new ApplePaySession(1, paymentRequest);
            session.onvalidatemerchant = function (event) {
                var model = {
                    ValidationUrl: event.validationURL,
                };
                $.ajax({
                    url: $("link[rel='merchant-validation']").attr("href"),
                    type: "POST",
                    data: JSON.stringify(model),
                    contentType: "application/json",
                    async: true,
                    headers: headers
                }).then(function (merchantSession) {
                    session.completeMerchantValidation(JSON.parse(merchantSession));
                }, function (reason) {
                    session.abort();
                });
            }

            session.onpaymentmethodselected = function (event) {
                session.completePaymentMethodSelection(totalAmount, lineItems);
            }
            session.onpaymentauthorized = function (event) {
                var token = event.payment.token.paymentData;
                var authorizationResult = {
                    status: ApplePaySession.STATUS_SUCCESS,
                    errors: []
                };
                $('#PaymentToken').val(JSON.stringify(token));
                $('#MobileWalletButton').val("pay by applepay");

                if(document.querySelector('form.donateform')) {
                    formClassname = 'donateform';
                }else if(document.querySelector('form.wbcmform')) {
                    formClassname = 'wbcmform';
                }
                var $form = $("." + formClassname);
                
                if(token.data.length > 0) {
                    $form.submit();
                }else {
                    Macmillan.applePay.showError();
                }
                session.completePayment(authorizationResult);
            };
            session.begin();
        },
        setupApplePay: function () {
            var merchantIdentifier = Macmillan.applePay.getMerchantIdentifier();
            ApplePaySession.openPaymentSetup(merchantIdentifier)
                .then(function (success) {
                    if (success) {
                        Macmillan.applePay.hideSetupButton();
                        Macmillan.applePay.showButton();
                    } else {
                        Macmillan.applePay.showError("Failed to set up Apple Pay.");
                    }
                }).catch(function (e) {
                    Macmillan.applePay.showError("Failed to set up Apple Pay. " + e);
                });
        },
        showButton: function () {
            $('#applePayContainer').removeClass('hideContainer');
            $('#divPay').removeClass('hideContainer');
            document.querySelector('.paypalMobileWalletCont').classList.remove('noApplePay');
            // $('#mobile-wallets-container').removeClass('oneColumnLayout');
            var button = $("#apple-pay-button");
            button.addClass("apple-pay-button");
            button.addClass("apple-pay-button-black");
            button.attr("lang", Macmillan.applePay.getPageLanguage());
            document.querySelector("#apple-pay-button").addEventListener('click', function(e) {
                if(document.querySelector('form.donateform')) {
                    formClassname = 'donateform';
                }else if(document.querySelector('form.wbcmform')) {
                    formClassname = 'wbcmform';
                }

                $("form." + formClassname).valid() ? Macmillan.applePay.beginPayment(e) : null;
            })
            button.removeClass("d-none");
        },
        showSetupButton: function () {
            var button = $("#set-up-apple-pay-button");
            button.attr("lang", Macmillan.applePay.getPageLanguage());
            button.on("click", $.proxy(Macmillan.applePay, "setupApplePay"));
            button.removeClass("d-none");
        },
        hideSetupButton: function () {
            var button = $("#set-up-apple-pay-button");
            button.addClass("d-none");
            button.off("click");
        },
        showError: function (text) {
            var error = $(".apple-pay-error");
            error.text(text);
            error.removeClass("d-none");
        },
        showSuccess: function () {
            //Customize show success message
        },
        supportedByDevice: function () {
            return "ApplePaySession" in window;
        },
        supportsSetup: function () {
            return "openPaymentSetup" in ApplePaySession;
        },
        getPageLanguage: function () {
            return $("html").attr("lang") || "en";
        },
        getMerchantIdentifier: function () {
            return $("meta[name='apple-pay-merchant-id']").attr("content");
        }
    }
};

(function () {

    var merchantIdentifier = Macmillan.applePay.getMerchantIdentifier();
    //Macmillan.applePay.showButton();
    if (!merchantIdentifier) {
        Macmillan.applePay.showError("No Apple Pay merchant certificate is configured.");
    }
    else if (Macmillan.applePay.supportedByDevice()) {
        Macmillan.applePay.showButton();
    }
})();;