$(document).ready(function() {
  $('.invoice_table tr.clickable').mouseover(function() {
    $(this).addClass("invoice_row_over");
  });
  $('.invoice_table tr.clickable').mouseout(function() {
    $(this).removeClass("invoice_row_over");
  });
  // $('.invoice_table tr:even').addClass('invoice_row_alt');
  // Client default send invoice message
  $('#chk_default_send_message').click(function() {
    if (this.checked) {
      $('#send_invoice_subject').attr('disabled','disabled');
      $('#send_invoice_msg').attr('disabled','disabled');
    } else {
      $('#send_invoice_subject').removeAttr('disabled');
      $('#send_invoice_msg').removeAttr('disabled');
    }
  })
  // Client default thank-you message
  $('#chk_default_thank_you_message').click(function() {
    if (this.checked) {
      $('#thank_you_subject').attr('disabled','disabled');
      $('#thank_you_msg').attr('disabled','disabled');
    } else {
      $('#thank_you_subject').removeAttr('disabled');
      $('#thank_you_msg').removeAttr('disabled');
    }
  })
});
/*------------------------------------
  Add/remove form rows
------------------------------------*/
/**
 * Add a row to a form by cloning the last row.
 *
 * Requires rows to be enclosed in a tbody tag with id="tbody_"+id_prefix
 * If the row has an id attribute of the form "row_"+id_prefix+id_value, the id_value is parsed out and incremented in the new row
 * If an array of update_attr_classes is provided, each element in the row with one of those class names will have the id incremented in its "name" and "id" attributes (if present). If there is a hidden form variable with id var_default_{classname}_val, the value of the field will be set to that default. If there is a hidden form variable with id var_default_{classname}_html, the innerHtml of the element will be set to that default.
 */
function addFormRow(id_prefix, update_attr_classes) {
  if (update_attr_classes == null) update_attr_classes = [];
  if (id_prefix == null) return false;
  // Clone the last row
  var cloned_row = $("#tbody_"+id_prefix+" tr:first").clone(); // Clone the first row--note that IE7 behaves inexplicably when cloning a row that was already cloned, so we explicitly clone the first row, not the last.
  // Parse out the ID of the cloned row
  var old_row_id = cloned_row.attr("id");
  var match_regex = new RegExp("row_"+id_prefix+"(\\d+)");
  var matches = old_row_id.match(match_regex);
  var old_id = 0;
  if (matches != null) old_id = parseInt(matches[1]);
  // Parse out the ID of the last row, to determine the new ID to use
  var last_row_id = $("#tbody_"+id_prefix+" tr:last").attr("id");
  var matches = last_row_id.match(match_regex);
  var last_id = 0;
  if (matches != null) last_id = parseInt(matches[1]);
  new_id = last_id + 1;
  // alert("old: "+old_id+", last:"+last_id+", new:"+new_id); // *** debug
  // Update the row ID
  $("#row_"+id_prefix+old_id, cloned_row).attr("id", "row_"+id_prefix+new_id);
  // Loop over each field, and replace "id_prefix+old_id" with "id_prefix+new_id" in the name and id attributes, and set default values
  var default_value;
  $.each(
    update_attr_classes,
    function(i, update_class) {
      // Update id attribute
      if ($("."+update_class, cloned_row).attr("id")) $("."+update_class, cloned_row).attr("id", $("."+update_class, cloned_row).attr("id").replace(id_prefix+old_id, id_prefix+new_id));
      // Update name attribute
      if ($("."+update_class, cloned_row).attr("name")) {
        // if (update_class == "item_description") alert("Original:"+$("."+update_class, cloned_row).attr("name")+"="+$("."+update_class, cloned_row).val()); // *** debug
	$("."+update_class, cloned_row).attr("name", $("."+update_class, cloned_row).attr("name").replace(id_prefix+old_id, id_prefix+new_id));
        // if (update_class == "item_description") alert("New:"+$("."+update_class, cloned_row).attr("name")+"="+$("."+update_class, cloned_row).val()); // *** debug
      }
      // Set default values
      default_value = $("#var_default_"+update_class+"_val").val();
      if (default_value != null) $("."+update_class, cloned_row).val(default_value);
      default_html = $("#var_default_"+update_class+"_html").val();
      if (default_html != null) $("."+update_class, cloned_row).html(default_html);
      $("."+update_class, cloned_row).removeAttr("disabled");
    }
  );
  // Add the row back to the table
  $("#tbody_"+id_prefix).append(cloned_row);
  // Change the ID of the new row--for some reason it doesn\'t work right before the append
  $("#tbody_"+id_prefix+" tr:last").attr("id", "row_"+id_prefix+new_id);
}
// Delete a form row. Assumes del link has id attribute "del_link_"+id_prefix+id, and row to delete has id attribute "row_"+id_prefix+id.
function delFormRow(id_prefix, del_link_id) {
  var row_id = del_link_id.replace("del_link_", "row_");
  if ($.browser.msie && row_id == "row_item1") alert("The first line item cannot be removed."); // Hackaround because IE doesn't properly support cloning rows that are themselves cloned--so we need to keep this first row as originally rendered, for use as a clone template. Not ideal but this will prevent bizarre bugs in rare cases.
  else if ($("#tbody_"+id_prefix+" tr").length > 1) $("#tbody_"+id_prefix+" #"+row_id).remove();
  else alert("At least one row is required");
}
// Add an invoice item
function addItemRow() {
  addFormRow("item", ["item_del_row", "item_description", "item_volume", "item_unit", "item_rate", "item_tax_1", "item_tax_2", "item_tax_3", "item_adjustment_amount", "item_adjustment_type", "item_amount", "item_reusable"]);
}
// Delete an invoice item
function delItemRow(del_link_id) {
  delFormRow("item", del_link_id);
  // Re-compute invoice values
  calculateInvoiceAmounts();
}
/*-----------------------------------
  Calculate invoice totals in edit invoice form
-----------------------------------*/
function calculateInvoiceAmounts() {
  var volume, rate, item_amount, row_id, matches, item_id;
  var subtotal, total;
  subtotal = total = 0;
  var whole_number_currencies = ["jpy"];
  var tax_amounts = [];
  var currency = $("#select_currency").val();
  // Whole number currency
  is_whole_number_currency = false;
  if (in_array(currency,whole_number_currencies,'') == true) {
    is_whole_number_currency = true;
  }
  // Iterate over each invoice item
  $("#tbody_item tr").each(function(i, item_row) {
    // Parse out the item ID
    row_id = $(item_row).attr("id");
    matches = row_id.match(/row_item(\d+)/);
    if (matches) {
      item_id = matches[1];
      // Calculate item amount
      volume = $(".item_volume", item_row).val();
      rate = $(".item_rate", item_row).val();
      adjustment_amount = $(".item_adjustment_amount", item_row).val();
      adjustment_type = $(".item_adjustment_type", item_row).val();
      if (isNaN(volume) || isNaN(rate)) item_amount = 0;
      else item_amount = rate * volume;
      // Apply adjustments
      if (!isNaN(adjustment_amount) && adjustment_amount > 0 && item_amount) {
        if (adjustment_type == 'discount_amt') item_amount = item_amount - adjustment_amount;
        else if (adjustment_type == 'discount_pct') item_amount = item_amount * (1 - adjustment_amount/100);
        else if (adjustment_type == 'surcharge_amt') item_amount = item_amount + (adjustment_amount * 1);
        else if (adjustment_type == 'surcharge_pct') item_amount = item_amount * (1 + adjustment_amount/100);
      }
      // Round item amount if currency requires
      if (is_whole_number_currency == true) item_amount = Math.round(item_amount);
      // Show item amount
      if (is_whole_number_currency == true) $("#span_item_amount_item"+item_id).html(item_amount.toFixed(0));
      else $("#span_item_amount_item"+item_id).html(item_amount.toFixed(2));
      // Compile totals
      if (item_amount > 0 || item_amount < 0) {
        // Add to subtotal
        subtotal += item_amount;
        // Add up taxes
        var tax_id, tax_pct, tax_1_amount;
        // Tax 1
        tax_id = $(".item_tax_1", item_row).val();
        if (tax_id) tax_pct = $("#var_tax_" + tax_id + "_percent").val();
        if (tax_pct) {
          tax_pct = parseFloat(tax_pct);
          if (is_whole_number_currency == true) {
            tax_1_amount = Math.round((tax_pct/100) * item_amount);
          } else {
            tax_1_amount = (tax_pct/100) * item_amount;
          }
          if (tax_amounts[tax_id] != null) tax_amounts[tax_id] += tax_1_amount;
          else tax_amounts[tax_id] = tax_1_amount;
        }
        // Tax 2
        tax_pct = 0;
        tax_id = $(".item_tax_2", item_row).val();
        if (tax_id) tax_pct = $("#var_tax_" + tax_id + "_percent").val();
        if (tax_pct) {
          tax_pct = parseFloat(tax_pct);
          var is_compound = ($("#var_tax_" + tax_id + "_applies_to").val() == "amount_plus_tax_1");
          if (is_compound && tax_1_amount) {
            if (is_whole_number_currency == true) {
              tax_2_amount = Math.round((tax_pct/100) * (item_amount + tax_1_amount));
            } else {
              tax_2_amount = (tax_pct/100) * (item_amount + tax_1_amount);
            }
          } else {
            if (is_whole_number_currency == true) {
              tax_2_amount = Math.round(tax_2_amount = (tax_pct/100) * item_amount);
            } else {
              tax_2_amount = (tax_pct/100) * item_amount;
            }
          }
          if (tax_amounts[tax_id] != null) tax_amounts[tax_id] += tax_2_amount;
          else tax_amounts[tax_id] = tax_2_amount;
        }
        // Tax 3
        tax_pct = 0;
        tax_id = $(".item_tax_3", item_row).val();
        if (tax_id) tax_pct = $("#var_tax_" + tax_id + "_percent").val();
        if (tax_pct) {
          tax_pct = parseFloat(tax_pct);
          var is_compound = ($("#var_tax_" + tax_id + "_applies_to").val() == "amount_plus_tax_1");
          if (is_compound && tax_1_amount) {
            if (is_whole_number_currency == true) {
              tax_3_amount = Math.round((tax_pct/100) * (item_amount + tax_1_amount));
            } else {
              tax_3_amount = (tax_pct/100) * (item_amount + tax_1_amount);
            }
          } else {
            if (is_whole_number_currency == true) {
              tax_3_amount = Math.round((tax_pct/100) * item_amount);
            } else {
              tax_3_amount = (tax_pct/100) * item_amount;
            }
          }
          if (tax_amounts[tax_id] != null) tax_amounts[tax_id] += tax_3_amount;
          else tax_amounts[tax_id] = tax_3_amount;
        }
      }
    }
  }); // End iteration over each row
  // Show subtotal
  if (is_whole_number_currency == true) {
    $("#span_subtotal").html(subtotal.toFixed(0));
  } else {
    $("#span_subtotal").html(subtotal.toFixed(2));
  }
  var total = subtotal;
  // Show taxes
  var tax_ids_str = $("#var_tax_ids").val();
  var tax_ids = tax_ids_str.split("|");
  for (var i in tax_ids) {
    var tax_id = tax_ids[i];
    var tax_amount = tax_amounts[tax_id];
    if (isNaN(tax_amount)) tax_amount = 0;
     if (is_whole_number_currency == true) {
      $("#span_tax_amount_"+tax_id).html(tax_amount.toFixed(0));
     } else {
      $("#span_tax_amount_"+tax_id).html(tax_amount.toFixed(2));
     }
    total += tax_amount;
  }
  // Show total
  if (is_whole_number_currency == true) {
    $("#span_total").html(total.toFixed(0));
    $("#total_amount").val(total.toFixed(0));
  } else {
    $("#span_total").html(total.toFixed(2));
    $("#total_amount").val(total.toFixed(2));
  }
}
/*------------------------------------
  Checking decimals commas
------------------------------------*/
function checkForDecimalCommas(name, number) {
  var received_number = number;
  if (number.match(",") != null) {
    $("#div_dlg_format_number").modal({
      containerCss: {
        height: "auto",
        width: "550",
        padding: "20px",
        backgroundColor: "#fff",
        border: "3px solid #ccc"
      }});
      // remove more than one comma
      while (number.match(",") != null) {
        number = number.replace(",",".");
      }
      // restore value
      if (name == "rate") {
        $(".item_rate[value=\'"+received_number+"\']").val(number);
      } else if (name == "adjustment") {
        $(".item_adjustment_amount[value=\'"+received_number+"\']").val(number);
      } else if (name == "payment_amount") {
        $("#payment_amount[value=\'"+received_number+"\']").val(number);
      }
      $("#close_modal").focus();
  }
}
/*-----------------------------------
  Utility functions
-----------------------------------*/

function alertArr(a) {
  var str="";
  for (var i in a) str += a[i] + "\n";
  alert(str);
}
function alertOb(o) {
  var str="";
  for (var i in o) str += i + " : " + o[i] + "\n";
  alert("Object: "+str)
}
function in_array(needle, stack, strict) {
  var found = false, key, strict = !!strict;
  for (key in stack) {
    if ((strict && stack[key] === needle) || (!strict && stack[key] == needle)) {
      found = true;
      break;
    }
  }
  return found;
}
function changeClientContact(e) {
  var client_id = $(e).val();
  if (client_id == "__new__") {
    $('.input_other_email').show();
  } else {
    $('.input_other_email').val('');
    $('.input_other_email').hide();
  }
}
function checkVolumeContent(e) {
  // Get the parent row
  var unit_item_id = $(e).val();
  if (unit_item_id <= 0) return;
  // Get the parent row
  var select_id = $(e).attr("id");
  var item_id = 0;
  var item_row;
  matches = select_id.match(/unit_item(\d+)/);
  if (matches) item_id = matches[1];
  item_row = $("#row_item"+item_id);
  if (!item_row) return;
  if ($(e).val() == "total") {
    $(".item_volume", item_row).val(1);
    if (item_id > 0) calculateInvoiceAmounts();
    $(".item_volume", item_row).attr("disabled",true);
  } else {
    $(".item_volume", item_row).removeAttr("disabled");
    if (item_id > 0) calculateInvoiceAmounts();
  }
}
