var payment_type = 'donate';
var no_payment_type_option = false;
var no_allocation_items = true
var recurring_payment_admin_override_mode = false;

$j(document).ready(function () {

    //RECURRING PAYMENT
    $j('select[name=num_payments]').change(function () {
           
        if ($j('select[name=num_payments]').val() != '0') {
            
            if($j('select[name=num_payments]').val() == 1){
                localStorage.setItem('not_recurring', 'N');
            }
            else {
                localStorage.setItem('not_recurring', '');
            }
            $j('.has_recurring').show();

            if ($j('select[name=num_payments]').val() != 1) {
                $j('.has_frequency').show();
            }
            else {
                $j('.has_frequency').hide();
            }

        } else {
            $j('.has_recurring').hide();
        }

    }).change();

    if ((parseFloat($j('#account_balance').text()) <= 0 && $j("input[name='allocate[]'].current").length == 0) ||
        should_force_donate) {
        $j('input[name=payment_type][value=donate]').prop('checked', true);
    }

    //DONATION REASON
    if (override_payment_type != '') {
        payment_type = override_payment_type;
        setupPaymentAmountArea();
    }
    else {

        $j('input[name=payment_type]').change(function () {

            if ($j('input[name=payment_type]:checked').val() == 'pay') {
                payment_type = 'pay';
            } else {
                payment_type = 'donate';
            }

            setupPaymentAmountArea()
        }).change();

        updateRecurringInfo();
    }

    $j('input[name=pay_amount]').change(function () {
        updateRecurringInfo();
    });

    $j('.has_frequency').change(function () {
        updateRecurringInfo();
    });

    var loading = true;

    //PAYMENT ALLOCATION TABLE
    $j('#pay_row').on('change', "input[name='allocate[]']", function () {

        //when selection allocations, set the amount to the sum of the allocations
        var id = $j(this).val();
        var amount = parseFloat($j(this).data('amount'));
        var $input = $j('input[name=allocation_' + id + ']');

        $input.val(amount.toFixed(2));

        if ($j(this).prop('checked')) {

            //make the input input
            $input.prop('disabled', false);
            //enforce this number
            enforceNumber($input, false, false, 0);

        }
        else {
            $input.prop('disabled', true);
        }

        if (!loading) {
            updateAllocationTotal();
        }

    }).on('change', ".amount_cell input", function () {

        if (!loading) {
            updateAllocationTotal();
        }

    });

    //start with everything checked
    $j("input[name='allocate[]'].current").prop('checked', true).change();

    if ($j("input[name='autoselect_future']").val() == 'Y') {
        $j("input[name='allocate[]'].future").prop('checked', true).change();
    }

    if (loading) {
        updateAllocationTotal();
        loading = false;
    }

    $j('#pay_row').on('click', '.check_all', function () {

        var check_all_val = $j(this).prop('checked');

        //stop it from calculating each time
        loading = true;

        $j("#pay_row input[name='allocate[]']").each(function () {
            $j(this).prop('checked', check_all_val);
        });

        loading = false;
        updateAllocationTotal();

    });

    $j('.recurring_payment_can_be_overridden_by_admin_button').click(function () {
        recurring_payment_admin_override_mode = true;
        updateRecurringInfo();
        $j('.recurring_payment_can_be_overridden_by_admin_button').hide();
        return false;
    });

    $j('select[name=start_day],input[name=start_day],input[name=text_start_day]').change(function () {
        updateRecurringInfo();
    });

    //DEDICATION SECTION
    $j('select[name=dedication_type]').change(function () {

        if ($j('select[name=dedication_type] :selected').val() != '') {
            $j('.dedication_only').show();
        }
        else {
            $j('.dedication_only').hide();
        }

        var example_text = $j('select[name=dedication_type] option:selected').data('example_message');

        if (example_text) {
            example_text = decodeURIComponent(example_text.replace(/\+/g, ' '));
            example_text = 'Example: "'+example_text+'" ';
        }

        $j('.dedication_example_message').text(example_text);

    }).change();

    $j('input[name=dedication_notify]').data('dirty', false).change(function () {
        $j(this).data('dirty', true);
    });

    formname = 'begin_form';
    var saved_attr = $j('#' + formname + ' .account_name').val();

    account_ajax = gift_aid_mode ?
        '/admin/ajax.user_autocomplete.php?type=sam_all'
        : '/admin/ajax.user_autocomplete.php?type=accounts';

    $j('#' + formname + ' .account_name').autocomplete({

        source: account_ajax,
        minLength: 2,

        select: function (event, ui) {

            if (ui.item) {

                saved_attr = ui.item.label;
                $j('#' + formname + ' .account_id').attr('hidden_name', ui.item.label);
                $j('#' + formname + ' .account_id').val(ui.item.id);

                if (gift_aid_mode) {
                    $j('#' + formname + ' .account_id').val(ui.item.site_account_id);
                    $j('#' + formname + ' .gift_aid_site_account_member_id').val(ui.item.id);
                }
                else {
                    $j('#' + formname + ' .account_id').val(ui.item.id);
                }

                $j('#' + formname + ' .account_name').val(ui.item.label);
                $j('#' + formname + ' .no_account_selected').hide();

                refreshAllocationTable();
            }

            return false;

        }

    }).bind('keypress', function (e) {

        if (13 === e.keyCode) {
            return false;
        }

    }).change(function () {

        if ($j(this).attr('hidden_name') !== $j(this).val() && saved_attr !== $j(this).val()) {

            $j('#' + formname + ' .account_id').val(0);
            $j('#' + formname + ' .no_account_selected').show();
            saved_attr = '';
            refreshAllocationTable();

        }

        return false;

    });

    //ADMIN ACCOUNT CHANGE 
    $j(document).on('change', '#account_id', function () {

        $j('select[name=site_account_member_id]').val(0);
        $j('#' + formname + ' .gift_aid_site_account_member_id').val(0);
        refreshAllocationTable();

    });

    $j('#account_id').change();

    //THIRD PARTY PAYER
    var saved_attr_tpp = $j('#' + formname + ' .third_party_name').val();

    $j('#' + formname + ' .third_party_name').autocomplete({

        source: account_ajax,
        minLength: 2,

        select: function (event, ui) {

            if (ui.item) {
                saved_attr_tpp = ui.item.label;
                $j('#' + formname + ' .third_party_id').attr('hidden_name', ui.item.label);
                $j('#' + formname + ' .third_party_id').val(ui.item.id);
                $j('#' + formname + ' .third_party_id').val(ui.item.id);
                $j('#' + formname + ' .third_party_name').val(ui.item.label);
            }

            return false;

        }

    }).bind('keypress', function (e) {

        if (13 === e.keyCode) {
            return false;
        }

    }).change(function () {

        if ($j(this).attr('hidden_name') !== $j(this).val() &&
            saved_attr_tpp !== $j(this).val()) {
            $j('#' + formname + ' .third_party_id').val(0);
            saved_attr_tpp = '';
        }

        return false;

    });

    //DONATION TYPE RULES
    $j('select[name=donation_type_id]').change(function () {
        setupPaymentAmountArea();
    });

    $j('select[name=member_id]').change(showHideAllocationTableRows);
    $j('select[name=division_id]').change(showHideAllocationTableRows);

    $j('.unknown_email').click(function () {

        $j('input[name=dedication_email]').prop('disabled', $j(this).prop('checked'));

        if ($j(this).prop('checked')) {
            $j('#dedication_email_error').text('');
            $j('input[name=dedication_email]').removeClass('error');
        }

    });

    $j('.unknown_address').click(function () {

        $j('input[name=dedication_address]').prop('disabled', $j(this).prop('checked'));
        $j('.dedication_address_area')[$j(this).prop('checked') ? 'hide' : 'show']();

        if ($j(this).prop('checked')) {
            $j('#dedication_address_error').text('');
            $j('input[name=dedication_address]').removeClass('error');
        }

    });

    //notify box
    /*
    if(typeof $j.fn.autocomplete=='function'){
        var skip_keypress=false;
        $j('input[name=dedication_notify]').autocomplete({
            source: '/ajax/ajax.users.php?all_members=true',
            minLength: 2,
            select: function( event, ui ) {
                if(ui.item){
                    $j('input[name=dedication_notify_id]').val(ui.item.id);
                }
                else{
                    $j('input[name=dedication_notify_id]').val(0);
                }
            }                
        }).keypress(function(event, ui){
            var chr = String.fromCharCode(event.which)
            var is_char = chr.match(/\w/);
            if(!skip_keypress && is_char){
                $j('input[name=dedication_notify_id]').val(0);
            }
            else if(event.which==13){
                return false;
            }
            skip_keypress= false;
        });    
    }*/

    $j('.address_country').change(function () {

        var s = $j(this).val();
        $j('.address_state_none')[s != 'USA' && s != 'CAN' ? 'show' : 'hide']().prop('disabled', (s == 'USA' || s == 'CAN'));
        $j('.address_state_can')[s == 'CAN' ? 'show' : 'hide']().prop('disabled', s != 'CAN');
        $j('.address_state_us')[s == 'USA' ? 'show' : 'hide']().prop('disabled', s != 'USA');


    }).change();

    setupPaymentAmountArea();

    //VALIDATE
    $j('#begin_form').submit(function () {

        var error_count = 0;

        // test amount is valid
        var amount = parseFloat($j.trim($j('input[name=pay_amount]').val()));

		// get default amount for comparision
		var $selected = $j('select[name=donation_type_id] :selected');
		var default_amount = parseFloat( $selected.attr('default_price') );
		var selected_type = $j('select[name=donation_type_id] :selected').text();

        // For legitimate type selection
        if(selected_type == 'STRUCTURE ONLY') {
            $j('#type_error').text('Please select legitimate charge type');     
            error_count++;
        }
        else {
            $j('#type_error').text('');
        }

		// If no default amount set to 0
		if (!default_amount) {
			default_amount = 0;
		}

		if(amount == 0){
			$j('#pay_amount_error').text('Amount must be a number greater than 0');
            $j('input[name=pay_amount]').addClass('error');
            error_count++;
		}
		else if(($j('select[name=donation_type_id] :selected').data('rule')=='minimum')&& (amount < default_amount)){
			$j('#pay_amount_error').text('Amount must be at least ' + default_amount).show();
			error_count++;
		}
		else if (amount > 0) {
            $j('#pay_amount_error').text('');
            $j('input[name=pay_amount]').removeClass('error');
        }


        //public enforce email/name and address
        var $name = $j('input[name=name]');
        var $email = $j('input[name=public_email]');
        var start_day = $j.trim($j('input[name=start_day]').val());
        var currentDate = moment().format('YYYY-MM-DD'); ;
        if (start_day != '') {
            if(start_day < currentDate){
                $j('#date_error').text('Please select current date or in the future date').show();
                $j('input[name=start_day]').addClass('error');
                error_count++;
            }
            else {
                $j('#date_error').hide('');
                $j('input[name=start_day]').removeClass('error');
            }
        }

        if ($name.length > 0 || $email.length > 0) {

            if ($j.trim($name.val()) == '') {
                $j('#name_error').text('You must enter your name');
                $j('input[name=name]').addClass('error');
                error_count++;
            }
            else {
                $j('#name_error').text('');
                $j('input[name=name]').removeClass('error');
            }

            if (!emailOk($email.val()) || $j.trim($email.val()) == '') {

                $j('#public_email_error').text('You must use a valid email');
                $j('input[name=public_email]').addClass('error');
                error_count++;
            }
            else {
                $j('#public_email_error').text('');
                $j('input[name=public_email]').removeClass('error');
            }

            if ($j('input[name=public_phone]').data('required_completed') == 'Y') {
                $j('#public_phone_error').text('You must enter a phone number');
                $j('input[name=public_phone]').addClass('error');
                error_count++;
            }
            else {
                $j('#public_phone_error').text('');
                $j('input[name=public_phone]').removeClass('error');
            }

        }

        $j('#notes_error').text('');
        $j('textarea[name=notes]').removeClass('error');

        $j('#dedication_notes_error').text('');
        $j('textarea[name=dedication_notes]').removeClass('error');

        $j('#dedication_salutation_error').text('');
        $j('input[name=dedication_notify]').removeClass('error');

        $j('#dedication_salutation_error').text('');
        $j('input[name=dedication_notify]').removeClass('error');

        $j('#dedication_email_error').text('');
        $j('input[name=dedication_email]').removeClass('error');

        $j('#dedication_address_error').text('');
        $j('input[name=dedication_address]').removeClass('error');

        $j('#donation_type_id_error').text('');

        if (payment_type == 'donate') {

            //force notes for untyped donation.
            var lit_id = !$j('select[name=donation_type_id]').length ? 0 : parseInt($j('select[name=donation_type_id]').val());
            var notes = $j.trim($j('textarea[name=notes]').val());

            if (lit_id < 1) {
                $j('#donation_type_id_error').text('Please enter a donation type');
                error_count++;
            }
            else if ($j.inArray(lit_id, requires_notes) > -1 && notes == '') {
                $j('#notes_error').text('Notes must be filled');
                $j('textarea[name=notes]').addClass('error');
                error_count++;
            }

            var dedication_type = $j.trim($j('select[name=dedication_type]').val());

            if (dedication_type != '') {

                if ($j.trim($j('textarea[name=dedication_notes]').val()) == '') {
                    $j('#dedication_notes_error').text('You must enter tribute text');
                    $j('textarea[name=dedication_notes]').addClass('error');
                    error_count++;
                }

                if ($j.trim($j('input[name=dedication_notify]').val()) == '') {
                    $j('#dedication_salutation_error').text('Please Fill this in.');
                    $j('input[name=dedication_notify]').addClass('error');
                    error_count++;
                }

                if (!$j('.unknown_email').prop('checked')
                    && (!emailOk($j('input[name=dedication_email]').val()) || $j.trim($j('input[name=dedication_email]').val()) == '')) {
                    $j('#dedication_email_error').text('Please enter a valid email');
                    $j('input[name=dedication_email]').addClass('error');
                }

                if (!$j('.unknown_address').prop('checked') && $j('input[name=dedication_address]').val() == '') {
                    $j('#dedication_address_error').text('Please enter a valid address');
                    $j('input[name=dedication_address]').addClass('error');
                }

            }

        }

        //NOW RETURN
        if (error_count > 0) {
            $j('#main_error_area').text('Please fix the below errors to continue');
            return false;
        }
        else {
            $j('#main_error_area').text('');
            $j("input[name=submit_payment]").prop("disabled", true);
            return true; 
        }

    }); 
});

function showHideAllocationTableRows() {

    if ($j('select[name=member_id]').length > 0) {

        var member_id = $j('select[name=member_id]').val();

        $j('#allocation_table tbody tr').each(function () {

            if ($j(this).attr('member_id') == member_id) {
                $j(this).show();
                $j(this).find('input').prop('disabled', false)
            }
            else {
                $j(this).hide();
                $j(this).find('input').prop('disabled', true)
            }

        });

    }

    if ($j('select[name=division_id]').length > 0) {

        var division_id = $j('select[name=division_id]').val();

        $j('#allocation_table tbody tr').each(function () {

            if ($j(this).attr('division_id') == division_id || division_id < 1) { //all sees all
                $j(this).show();
                $j(this).find('input').prop('disabled', false)
            }
            else {
                $j(this).hide();
                $j(this).find('input').prop('disabled', true)
            }

        });

    }

}

var refreshAllocationTable = function () {

    var account_id = $j('#begin_form input[name=account_id]').val();
    var site_account_member_id = $j('#begin_form select[name=site_account_member_id] :selected').val();

    if (account_id > 1) {

        //is an account
        no_payment_type_option = false;
        payment_type = $j('input[name=payment_type]:checked').val();
        //showLoadingMessage('Loading', 'Loading the account');

        $j.ajax({
            url: '/ajax/ajax.payments.php',
            data: {
                'account_id': account_id,
                'site_account_member_id': site_account_member_id
            },
            dataType: 'json',
            success: function (data) {

                if (data.error == -1) {
                    no_payment_type_option = true;
                    payment_type = 'donate';
                    $j('.account_balance_container').hide();
                    setupPaymentAmountArea();
                }
                else {

                    $j('.account_balance_container').show();
                    $j('#account_balance').text(data.balance);
                    $j('.open_payments_message').html(data.open_payments_message);
                    $j('.future_open_charges_message').html(data.future_open_charges_message);

                    if (data.balance > 0) {
                        $j('.payment_type_option .statement_link').addClass('read_more_top');
                    }
                    else {
                        $j('.payment_type_option .statement_link').removeClass('read_more_top');
                    }

                    if (!data.unpaid_items) {
                        //nothing to allocate.
                        has_allocation_items = false;
                        $j('#pay_row').hide();
                    }
                    else {
                        $j('#allocation_table').html(data.unpaid_items);
                        $j('#pay_row').show();
                        has_allocation_items = true;
                    }

                    if ($j('.other_sam_area').length == 1) {
                        $j('.other_sam_area').html(data.member_select);
                    }

                    //hideLoadingMessage();
                    setupPaymentAmountArea();
                    $j("input[name='allocate[]'].current").prop('checked', true).change();

                    if ($j("input[name='autoselect_future']").val() == 'Y') {
                        $j("input[name='allocate[]'].future").prop('checked', true).change();
                    }

                }

            }

        });

    }
    else {
        no_payment_type_option = true;
        payment_type = 'donate';
        setupPaymentAmountArea();
    }

}

function updateAllocationTotal(amount) {
    //pre-existing amount is now preserved while defaulting to 0.00
    var amt = parseFloat(amount) || 0.00;

    if ($j('#pay_row').is(":visible")) {

        $j("input[name='allocate[]']:checked").each(function () {
            var val = parseFloat($j(this).data('amount'));
            var the_input_val = $j('input[name=allocation_' + $j(this).val() + ']').val();
            var toadd = parseFloat(the_input_val);
            // if(val>0 && the_input_val>val)toadd=val; //allow overpayements
            amt += toadd;
        });

    }

    if (should_force_donate) {
        return;
    }

    $j('input[name=pay_amount]').val(amt.toFixed(2));
    updateRecurringInfo();

}

function setupPaymentAmountArea() {

    //get attributes
    var $selected = $j('select[name=donation_type_id] :selected');
    var default_amount = parseFloat( $selected.attr('default_price') );

    if (!default_amount) {
        default_amount = 0;
    }

    //get areas
    var $amount = $j('input[name=pay_amount]');
    var $amount_label = $j('.amount_label');
    $amount.val(default_amount);

    //set defaults
    $amount_label.text('').hide();
    $amount.prop('disabled', false);
    enforceNumber($j('input[name=pay_amount]'));

    var rule = $selected.data('rule');

    if (no_payment_type_option) {
        $j('.payment_type_option').hide();
    }
    else {
        $j('.payment_type_option').show();
    }

    if (payment_type == 'donate') {

        $j('.donate_only').show();
        $j('.pay_only').hide();

        //now apply rules
        if (rule == 'fixed') {
            $amount.prop('disabled', true);
            $amount_label.html('(Fixed&nbsp;amount)').show();
        }
        else if (rule == 'minimum') {
			// Commented below as it was forcing the amount to default on focus out without giving any alert to user on donation.
            //enforceNumber($j('input[name=pay_amount]'), false, false, default_amount);
            $amount_label.html('(Minimum&nbsp;' + default_amount + ')').show();
        }
        else if (rule == 'suggested') {
            $amount_label.html('(Suggested&nbsp;' + default_amount + ')').show();
        }

    }
    else {

        $j('.pay_only').show();
        $j('.donate_only').hide();

        if (has_allocation_items) {
            $j('#pay_row').show();
        }
        else {
            $j('#pay_row').hide();
        }

    }
    
    //if payment_type is account balance, total is summed in updateAllocationTotal() so pass in 0
    var dollarAmt = (payment_type == "donate") ? default_amount : 0;
    updateAllocationTotal( dollarAmt );
    updateRecurringInfo();

}

function updateRecurringInfo() {

    var force_end_date = 0;

    if (payment_type == 'donate') {
        force_end_date = $j('select[name=donation_type_id] :selected').data('force_end_date');
    }
    else if ($j("input[name='allocate[]']:checked").length) {

        $j("input[name='allocate[]']:checked").each(function () {

            if ($j(this).data('force_end_date')) {

                if (force_end_date > 0) {
                    force_end_date = Math.min(force_end_date, $j(this).data('force_end_date'));
                }
                else {
                    force_end_date = $j(this).data('force_end_date');
                }

            }

        });

    }

    if (force_end_date && !recurring_payment_admin_override_mode) {
        $j('.recurring_payment_can_be_overridden_by_admin_button').show();
    }

    amount = parseFloat($j('input[name=pay_amount]').val() * 1);
    var start_day = $j('[name=start_day]').val();
    var frequency = $j('select[name=frequency]').length ? $j('select[name=frequency]').val() : '1M';
    var frequency_type = frequency.slice(-1);
    frequency = frequency.substring(0, frequency.length - 1);

    if (frequency_type == 'D') {
        frequency_type = 'd';
    }

    if (!start_day || moment(start_day).isBefore(moment())) {
        start_day = moment().format('YYYY-MM-DD');
    }

    $j('select[name=num_payments] option').each(function () {

        if (force_end_date && !recurring_payment_admin_override_mode) {

            //no recurring
            if ($j(this).attr('value') == 0) {
                $j(this).prop('disabled', false);
            }
            else if ($j(this).attr('value') == 1) {
                $j(this).prop('disabled', moment(force_end_date * 1000).isBefore(start_day));
            }
            else if ($j(this).attr('value') == -1) {
                $j(this).prop('disabled', true);
            }
            else if ($j(this).attr('value') > 1) {
                $j(this).prop('disabled', moment(force_end_date * 1000).isBefore(
                    moment(start_day).add(($j(this).attr('value') - 1) * frequency, frequency_type)))
            }

        }
        else {
            $j(this).prop('disabled', false);
        }

        if ($j(this).val() > 1) {
            $j(this).text($j(this).attr('start_wording')
                + (amount * 100 / $j(this).val() / 100).toFixed(2));
        }

    });

    if ($j('select[name=num_payments] option:selected').is(':disabled')) {
        $j('select[name=num_payments]').val($j('select[name=num_payments] option:enabled:first').val()).change();
        $j('#text_id_start_day').val('');
        $j('[name=start_day]').val('');
        $j('select[name=frequency]').val('1M')
        alert('Your payments must be completed by the due date. Please choose a different number of payments');
        updateRecurringInfo()
    }

}
