var MYTONERLIST = function() {
    function pullId(el) {
        if (el && el.id) {
            return el.id.substring(el.id.indexOf('-') + 1);
        } else {
            return undefined;
        }
    }

    function update(id) {
        var quantity = parseFloat($('#desired-' + id).val());
        
        var rate = parseFloat($('#bid-' + id).val());
        if (isNaN(rate)) {
            rate = 0;
        }
        
        var subtotal = parseFloat($('#subtotal-' + id).html());
        if (isNaN(subtotal)) {
            subtotal = 0;
        }
        
        var total = parseFloat($('#total').html());
        if (isNaN(total)) {
            total = 0;
        }
        total -= subtotal;
        
        subtotal = quantity * rate;
        $('#subtotal-' + id).html(subtotal.toFixed(2));
        
        total += subtotal;
        $('#total').html(total.toFixed(2));
    }

    function refreshSubtotals() {
        $('.desired-input').each(function() {
            update(pullId(this));
        });
    }

    function revealSubtotals() {
        $('.subtotal').show();
        $('#total-label').show();
    }

    function validate() {
        var name = $('#bidder-name'),
            email = $('#bidder-email');
        
        if (name.val() == '') {
            $('#error-bidder-name').show();
            return false;
        } else {
            $('#error-bidder-name').hide();
        }
        
        if (!email.val().match(/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i)) {
            $('#error-bidder-email').show();
            return false;
        } else {
            $('#error-bidder-email').hide();
        }
            
        return true;
    }

    $(document).ready(function() {
        $('.desired-input').change(function() {
            update(pullId(this));
        });

        $('.bid-input').change(function() {
            update(pullId(this));
            var value = parseFloat($(this).val());
            if (isNaN(value)) {
                value = 0;
            }
            $(this).val(value.toFixed(2));
        }).keyup(function() {
            update(pullId(this));
        });

        $('#bidder-name').add('#bidder-email').keypress(function() {
            $('#error-' + this.id).hide();
        });

        $('#bid').submit(function() {
            return validate();
        });

        revealSubtotals();
    });
}();

