$(document).ready(function() {
    var total = 0;

    $('.order-input').change(function() {
        myArray = $(this).attr('name').split("_");
        var id = myArray[0];
        var price_id = id+"_price";
        var price = document.getElementById(price_id).innerHTML;
        price = price.substring(id.length,price.length);
        var no = $(this).attr('value');
        var max_id = id+"_max";
        var max = document.getElementById(max_id).innerHTML;
        myArray2 = max.split("max ");
        myArray2 = myArray2[1].split(" bottles");
        max = myArray2[0];
        var error = false;
        if (parseInt(no) > parseInt(max)) {
            var oldprice = document.getElementById($(this).attr('name')).innerHTML;
            oldprice = oldprice.substring(2,oldprice.length);
            oldprice = parseInt(oldprice);
            total = total - oldprice; 
            total = Math.round(total*100)/100;
            $('#total').html("R "+total);
            alert("You may only order a maximum of "+max+" bottles.");
            $('#'+$(this).attr('name')).html("R 0");
            $(this).val('0');
            error = true;
        }
        else {
            var oldprice = document.getElementById($(this).attr('name')).innerHTML;
            oldprice = oldprice.substring(2,oldprice.length);
            oldprice = parseInt(oldprice);
            $('#'+$(this).attr('name')).html("R "+(no*price));
            if (document.getElementById($(this).attr('name')).innerHTML == 'R NaN') {
                alert('Invalid Input');
                $('#'+$(this).attr('name')).html("R 0");
                $(this).val('0');
                error = true;
                total = total - oldprice; 
                total = Math.round(total*100)/100;
                $('#total').html("R "+total);
            }
            else {
                total = total - oldprice + (no*price);
                total = Math.round(total*100)/100;
            }
        }
        if (!error) {
            $('#total').html("R "+total);
        }
    });

});
