$(function(){

    jQuery.validator.addMethod("sixBottles", function(value, element, params) { 
        return value > 0 && value % 6 == 0; 
    }, jQuery.validator.format("Bottles must be purcased in lots of 6.")); 

    $('input.qty').keyup(function() {
        UpdateTotals();
    });
    
    $('div.shipping > select').change(function() {
        UpdateTotals();
    });
    
    UpdateTotals();
});


// Arguments: number to round, number of decimal places
function roundNumber(rnum, rlength)
{
    var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
     // Output the result to the form field (change for your purposes)
    return newnumber;
}

function UpdateTotals()
{
    var subTotal = 0;
    var deliveryAmount = 0;
    var bottleCount = 0;
    var totalAmount = 0;
    
    $('div.order-item').each(function(i) {
        var linePriceEa = parseFloat($(this).children('input.priceea').val());
        var lineQty = parseInt($(this).children('input.qty').val(), 10);
        var lineTotal = roundNumber(linePriceEa * lineQty, 2);
        
        if (isNaN(lineTotal))
        {
            $(this).children('input.priceline').val(0);
        } else {
            $(this).children('input.priceline').val(lineTotal.toFixed(2));
            subTotal += lineTotal;
            bottleCount += lineQty;
        }
    });
   
    // Get delivery total 
    deliveryAmount = parseFloat($('div.shipping > select > option:selected').attr('data-amount'));
   
    // Set delivery
    if (isNaN(deliveryAmount))
    {
        $('div.shipping > input').val(0);
    } else {
        $('div.shipping > input').val(deliveryAmount.toFixed(2));
    }
   
    // Set sub-total
    if (isNaN(subTotal))
    {
        $('div.order-calculations > div.sub > input').val(0);
    } else {
        subTotal = roundNumber(subTotal, 2);
        $('div.order-calculations > div.sub > input').val(subTotal.toFixed(2));
    }
    
    // Total Amount
    totalAmount = deliveryAmount + subTotal;
    if (isNaN(totalAmount))
    {
        $('div.total > input').val(0);    
    } else {
        totalAmount = roundNumber(totalAmount, 2);
        $('div.total > input').val(totalAmount.toFixed(2));
    }
    
    // Set bottle count
    $('#hidBottleCount').val(bottleCount);
    $('#hidBottleCount').change();
}
