
/**
 * Validates input and prepares variables for price calculation.
 * @param formNum: Index number of the form.
 * @param fieldId: Identifier of the field.
 */
function calc()
{
    if (document.getElementById)
    {
        //retrieve/prep variables
        var total = [];
            total[1] = document.getElementById('book[1]').value;
            total[2] = document.getElementById('book[2]').value;
            total[3] = document.getElementById('book[3]').value;
            total[4] = document.getElementById('book[4]').value;
            total[5] = document.getElementById('book[5]').value;
            
        var cost = [];
            cost[1] = 99.95;
            cost[2] = 65;
            cost[3] = 65;
            cost[4] = 88;
            cost[5] = 59;
            
        var subtotal = 0;
        var shipping = 0;
        var quantity = 0;
        
        //calculation
        for (i in total)
        {
            //make sure values of totals are numbers
            total[i] = parseInt(total[i], 10);
            if (isNaN(total[i])) total[i] = 0;
            
            if (i >= 1 && i <= 5) {
                quantity += total[i];
                total[i] *= cost[i];
                
                //tally up new cost
                subtotal += total[i];
            }
            
        }
        
        calcTotal(subtotal, quantity);
                
    } //browser check
} //end calc()

/**
 * Called by calc().
 * Calculates total price in real-time.
 * @param arr total: array of all the calculated prices of items
 */
function calcTotal (subtotal, quantity)
{
    var one = 15;
    var more = 5;
    var total = 0;
    
    document.getElementById('subtotal').innerHTML = '$'+set2Digits(subtotal);
    document.getElementById("total[subtotal]").value = '$'+set2Digits(subtotal);
    
    var shipping = one + ((quantity-1) * more);
    document.getElementById('shipping').innerHTML = '$'+set2Digits(shipping);
    document.getElementById("total[shipping]").value = '$'+set2Digits(shipping);
    
    var total = shipping + subtotal;
    document.getElementById('total').innerHTML = '$'+set2Digits(total);
    document.getElementById("total[total]").value = '$'+set2Digits(total);
} //end calcTotal()

/**
 * Called by calcTotal().
 * Sets two decimal digits of calculated end totals.
 * @param str value:
 * @return str s
 */
function set2Digits (value)
{
    s = value.toString();
    
    //detect decimal point location
    if (s.indexOf('.') > 0)
    {
        dec = s.substring(s.indexOf('.')+1);

        //1 dec, append a 0
        if (dec.length==1) {
            return s += 0;
        }
    }
    //there is no decimal
    else {
        //0 dec, append 2 0s
        return s += ".00";
    }
    
    //return to normal if above detects 2 digits
    return s;
}
