// this function displays the "please wait" screen for when a form is loaded
function showLoading(){
  Element.show('loading_background');
  Element.show('loading_message');
}

// this function is called once the page is loaded and recalculates all of the fields in case of a page reload
function calculatePage(){
  setTimeout("runCalculatePage()", 0);
}

function runCalculatePage(){
  // get the first row of input fields from each form group
  var subtotal = $$("#customer_invoice_lines input");
  for (var i = 0; i < form_inputs.length; i++){
    // update the group for each field 
  	update_totals(form_inputs[i]);
  }
  pageLoaded = true;
  
  Element.hide("loading_message");
  Element.hide("loading_background");
}

function updateTotals(){
  var subtotal = 0;
  var rows = $$("#customer_invoice_lines tbody tr");
  rows.each(
    function(row){
      subtotal += update_total_for_row(row.id);
    }
  );
  var shipping = shippingHandlingSubtotal();
  
  $("subtotal").innerHTML = subtotal;
  $("host_credit_total").innerHTML = subtotal - (shipping + parseFloat($("customer_invoice_art_certificate_total").value || 0));
  $("shipping_handling_total").innerHTML = shipping;
  var total = display((parseFloat($("subtotal").innerHTML || 0) + 
      parseFloat($("customer_invoice_separate_shipping_charge").value || 0)) * 
      (1 + (parseFloat($("customer_invoice_tax_rate").value || 0) / 100)));
  $("total").innerHTML = total;
}

function update_total_for_row(invoice_row){
	var subtotal = parseFloat($(invoice_row + "_artwork_price").value || 0) + parseFloat($(invoice_row + "_frame_charge").value || 0);
  // alert("subtotal: " + subtotal);
	$(invoice_row + "_art_frame_subtotal").innerHTML = subtotal;
	var total = subtotal + parseFloat($(invoice_row + "_shipping_handling").value || 0);
	$(invoice_row + "_total").innerHTML = total;
	return total;
}

function shippingHandlingSubtotal(){
  var subtotal = 0;
  var rows = $$("#customer_invoice_lines tbody tr input.shipping_handling");
  // alert(rows.size());
  rows.each(
    function(input){
      subtotal += parseFloat(input.value || 0);
    }
  );
  return subtotal;
}
