$(document).ready(function() {

    var $inputs = $('input:text[name^=monthlyIncome], input:text[name^=monthlyExpense], input:text[name^=recoveryExpense]');

    /*
     * "commify" a number, i.e. add commas as thousand separators
     */
    function commify(num) {
        return num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})(?=\d)/img,'$1,').split('').reverse().join('');
    };
    
    /*
     * reverse of commify()
     */
    function uncommify(num) {
        return num.toString().replace(/,/, '');
    };
    
    /*
     * update total amounts
     */
    function updateTotals() {
        var totalExpenses = 0;
        $inputs.each(function() {
            var value = uncommify(this.value);
            if (!(isNaN(value))) {
                totalExpenses += Number(value);
            }
        });
        $('.totalExpenses, .minCoverage').html( commify(Math.ceil(totalExpenses)) );
    };
    
    // enforce valid integer values and update totals
    $inputs.change(function() {
        var $input = $(this);
        var value = Number( uncommify($input.val()) );
        if (isNaN(value)) {
            value = 0;
        }
        $input.val( Math.ceil(value) );
    }).keyup(updateTotals);
    
    // for browsers that remember input values on page reload (e.g. Firefox), enforce required formatting and trigger calculations on page load
    $inputs.each(function() {
        if ($(this).val() != '') {
            $(this).change();
        }
    });
    updateTotals();
    
});

