function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function onLoad()
{

    $('td.qty input').keyup(function(e) {
        var id = $(e.target).attr('name').replace('qty', 'quantity_');
        var qty = $(e.target).val();
        qty = parseFloat(qty);

        if (qty >= 0) {

            var unitPrice = $(e.target).parent().next().html().replace('$', '').replace(',', '');
            var productId = $(e.target).attr('id').replace('qty_', '');

            $.ajax({
                type: 'HEAD',
                url: '/cart/update/productId/' + productId + '/qty/' + qty
            });

            unitPrice = parseFloat(unitPrice);
            var subTotal = unitPrice * qty;
            $(e.target).parent().next().next().html('$' + addCommas(subTotal.toFixed(2)));
            $('#' + id).attr('value', qty);

            var shipping = $('tr.shipping td').html().replace('$', '').replace(',', '');
            shipping = parseFloat(shipping);

            var subTotal = 0;
            $('td.subtotalProduct').each(function(i) {
                var price = $(this).html().replace('$', '').replace(',', '');
                price = parseFloat(price);
                subTotal = subTotal + price;
            });

            var total = subTotal + shipping;

            $('tr.subtotal td').html('$' + addCommas(subTotal.toFixed(2)));
            $('tr.grand_total td').html('AUD&nbsp;$' + addCommas(total.toFixed(2)));

        } else {

            alert('Quantity needs to be zero or greater');

        }

    });

}

$(document).ready(onLoad);

