$(document).ready(function () {
  $("body").off("click").on("click", ".remove", remove);
  $(".tbody").on("blur", ".rate", autoAddRows);
  $(".tbody").on("blur keyup change click", ".amount, .remove", calculations);
  $(".tbody").on("blur keyup change click", ".trqty, .remove", calculations2);
  $("body").on("blur click keyup change", ".formem", showcode);
  //    $("body").on("keyup focus blur", '.trqty, .rate, .amount', itemCal);
  //    $("body").on("keyup focus blur", '.qty, .rate, .amount, .subtotal .discount, .discperc, .netamt', mainbCal);
  $("body").on("keyup focus blur", ".remark", autoAddRows);
  $("body").on("keyup focus blur change", ".itemcode", GetItemFromCode);
  $("body").on("keyup focus blur change", ".memcode", GetMemDet);
  $("body").on("keyup focus blur change", ".item", showDetail);
  $("body").on(
    "change blur keyup",
    ".calby,.trqty,.rate,.yard,.meters",
    calculateRow
  );
  $("body").on("change blur keyup focus", ".retdate", Getamount);
  $("body").on("change blur keyup focus", ".advance", Maincal);

  function GetMemDet() {
    var memcode = $(".memcode").val();

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "getmemdetail.php",
      data: { memcode: memcode },
      success: function (response) {
        if (response != "") {
          var name = response.name,
            add1 = response.add1,
            add2 = response.add2,
            add3 = response.add3,
            mobile = response.mobile;

          $(".name").val(name);
          $(".add1").val(add1);
          $(".add2").val(add2);
          $(".add3").val(add3);
          $(".mob1").val(mobile);
        }
      },
      error: function (request, textStatus, errorThrown) {},
    });
  }

  function GetItemFromCode() {
    var $row = $(this).closest("tr");
    var itemcode = $row.find(".itemcode").val();
    $.post("show_item_dtl.php", { itemcode: itemcode }, function (data) {
      if (data != "") {
        $row.find(".item").html(data).trigger("change");
      }
    });
  }

  function showcode() {
    var showmem = $(".formem").val();
    if (showmem == "Member") {
      $(".hidemem").show();
    } else {
      $(".hidemem").hide();
    }
  }

  function Maincal() {
    var advance = $(".advance").val(),
      billamt = $(".billamt").val();
    var bal = billamt - advance;
    $('.bal').val(bal);
  }

  function Getamount() {
    var start = new Date($(".vouchdt").val()),
    end = new Date($(".retdate").val()),
    daysno = (end-start) / (1000 * 60 * 60 * 24);
    $('.days').val(daysno);
    var subtotal = $(".totamt").val();
    var totamt = subtotal * daysno;
    $('.billamt').val(totamt);
      var advance = Math.round((totamt / 100) * 50);
      $('.advance').val(advance);
  }

  function calculateRow() {
    var $row = $(this).closest("tr");

    var calby = $row.find(".calby").val();
    // var meters = $row.find('.meters').val();
    var rate = $row.find(".rate").val();

    var meters = parseFloat($row.find(".meters").val());
    var yard = parseFloat($row.find(".yard").val());
    var trqty = parseFloat($row.find(".trqty").val());

    // var pair = packing * carton;
    // $row.find('.pair').val(pair.toFixed(2));
    var calm = parseFloat(meters),
      caly = parseFloat(yard),
      calq = parseFloat(trqty),
      amount = 0;

    // var totdoz = pair / 12;
    if (calby == "M" || meters > 0) {
      //            var m = 'meter';
      // $row.find('.calby').val(m)
      (amount = (parseFloat(calm) * parseFloat(rate)).toFixed(2)),
        $row.find(".amount").val(amount);
    } else if (calby == "Y" || yard > 0) {
      (amount = (parseFloat(caly) * parseFloat(rate)).toFixed(2)),
        $row.find(".amount").val(amount);
    } else {
      (amount = (parseFloat(calq) * parseFloat(rate)).toFixed(2)),
        $row.find(".amount").val(amount);
    }

    // var amt =  $row.find('.amount').val("");
    //         if (isNaN(amt)) {
    //             $row.find('.amount').val("0");
    //         } else {
    //             $row.find('.amount').val(amt);
    //         }
    // calculateTot();
  }

  function calculations() {
    var totamt = 0;
    
    $(".amount").each(function () {
      if (!isNaN(this.value) && this.value.lenght !== 0) {
        totamt += parseFloat(this.value);
      }
    });
    $(".totamt").val(totamt);
  }
  
  function calculations2() {
    var totqty = 0;
    $(".trqty").each(function () {
      if (!isNaN(this.value) && this.value.lenght !== 0) {
        totqty += parseFloat(this.value);
      }
    });
    $(".totqty").val(totqty);
  }

  //getting rate from item
  function showDetail() {
    var tr = $(this).closest("tr");
    var name = tr.find(".item").val();
    $.ajax({
      type: "GET",
      dataType: "json",
      //                url         : "get_itemrate_dtl.php",
      url: "get_itemrate_dtl.php",
      data: "name=" + name + "",
      success: function (response) {
        var code = response.code;
        var rate = response.rate;
        var msp = response.msp;
        var mrp = response.mrp;
        $(tr.find(".itemcode")).val(code);
        $(tr.find(".rate")).val(rate);
        $(tr.find(".msp")).val(msp);
        $(tr.find(".mrp")).val(mrp);
      },
      error: function (request, textStatus, errorThrown) {
        alert(errorThrown);
      },
    });
  }

  $("#addnew").click(function () {
    AddRows();
  });

  function autoAddRows() {
    var ctr = $("#items").val();
    var tr = $(this).closest("tr");
    var srno = tr.find(".srno").val();
    if (srno == ctr) {
      AddRows();
    }
  }

  function remove() {
    $(this).closest("tr").remove();
  }

  function AddRows() {
    var ctr = $("#items").val();
    var hide_check = "";
    if ($("#del_all").prop("checked")) {
      hide_check = 0;
    } else {
      hide_check = 1;
    }
    var detail = ".fetchpart_" + ctr;
    $.post("rationkit_add.php", { ctr: ctr, hide: hide_check }, function (data) {
      $(data).appendTo(".tbody");
      ctr++;
      $("#items").val(ctr);
      $(detail).select2();
    });
  }
});
