function getValue(e) {
    var p = parseInt(document.getElementById(e).value, 10);
    if (!p) return 0;
    return p;
}

function pretty_num(n) {
    n += '';
    var o = '';
    for (i=n.length; i>3; i-=3) {
        o = ',' + n.slice(i-3, i) + o;
    }
    o = n.slice(0, i) + o;
    return o;
}

function pluralise(n) {
    if (n!=1) return 's';
    return '';
}

function update_text() {
    var hay = getValue('hay');
    var carrots = getValue('carrots');
    var bells = getValue('bells');
    var total = 50 * bells + 30 * hay + 10 * carrots;
    var out = 'You are ordering '
        + pretty_num(hay) + ' bushel' + pluralise(hay) + ' of hay, '
        + pretty_num(carrots) + ' carrot' + pluralise(carrots)
        + ', and ' + pretty_num(bells) + ' shiny bell' + pluralise(bells)
        + ', at a total cost of <strong>' + pretty_num(total)
        + '</strong> gold pieces. Thank you.';
    document.getElementById('preview').innerHTML = out;
}

window.onload = function() {
    var inputs = document.getElementsByTagName('input');
    for (i=0; i<inputs.length-2; i++) {
        inputs[i].onchange = update_text;
    }
    document.forms[0].onsubmit = function() { return false; };
};


