(function ($) {
  Drupal.behaviors.plwOrderCopyDetails = {
    attach: function (context, settings) {
      var updateGrandTotal = function() {
        var i, tbl = $('order-wine-list'),
          qtyFields = $('input[name^="qty\\["]'),
          qtyValue = 0,
          qtyTotal = $('input[name="qty\\[totalCount\\]"]'),
          totalFields = $('input[name^="total\\["]'),
          totalValue = 0,
          grandTotal = $('input[name="total\\[total\\]"]'),
          len = qtyFields.length;

        for(i = 0; i < len; i++) {
          if ('qty[totalCount]' == qtyFields[i].name) {
            continue;
          }
          qtyValue += parseInt(qtyFields[i].value);
          totalValue += parseFloat(totalFields[i].value);
        }
        qtyTotal.val(qtyValue);
        grandTotal.val(totalValue.toFixed(2));
      }
      /**
       * Copy address details to delivery fields.
       */
      $('#plw-order-copy-details', context).click(function() {
        $('#edit-delivery-name').val($('#edit-contact-name').val());
        $('#edit-delivery-address').val($('#edit-billing-address').val());
        $('#edit-delivery-state').val($('#edit-billing-state').val());
        $('#edit-delivery-suburb').val($('#edit-billing-suburb').val());
        $('#edit-delivery-postcode').val($('#edit-billing-postcode').val());
        return false;
      });
      $('#order-wine-list input.order-qty', context).keyup(function() {
        var elm = $(this),
          id = elm.attr('name').match(/qty\[(\d+)\]/)[1],
          qty = parseInt(elm.val()),
          price = $('input[name="price\\[' + id + '\\]"]').val(),
          total = $('input[name="total\\[' + id + '\\]"]');
        if (isNaN(qty)) {
          qty = 0;
        }
        elm.val(qty);
        total.val((qty * price).toFixed(2));
        updateGrandTotal();
      });
    }
  };
}(jQuery));
;

