$(document).ready(function () {
  $("#orderdate").datepick();
  $("#divdate").datepick();
  $("#dlvdate").datepick();

  var buyerwindow;
  $("#guesmas").click(function (e) {
    if (
      $.trim($("#buyercode").val()) != "" &&
      $.trim($("#buyerma").val()) != ""
    ) {
      buyerwindow = positionedPopup(
        "../../masters/mastercmpedit.php",
        450,
        700
      );
      setTimeout(function () {
        buyerwindow.document.getElementById("compid").value =
          $("#buyercode").val();
        buyerwindow.document.getElementById("name").value = $("#buyerma").val();
        buyerwindow.document.getElementById("address").value =
          $("#adress").val();
        buyerwindow.document.getElementById("city").value = $("#city").val();
        buyerwindow.document.getElementById("type").value = "CUSTOMER";
      }, 2000);
    } else {
      buyerwindow = positionedPopup(
        "../../masters/mastercmpedit.php",
        450,
        700
      );
    }

    //if (window.focus) {driverwindow.focus()}
  });

  /*$.post("type_fill.php",{},function(result){
		if(result == null)
		{
			$('#cat_new').html("")
			return;
		}
		var html = "<option selected value=''>--select--</option>";
		$.each(result, function(key,value) {
		html += "<option  value='"+value.list.option+"'>"+value.list.option+"</option>";
			
		});						
		$('#cat_new').html("").append(html);
		var row_itemline;
        $("#cat_new").on("blur", function(){
		 row_itemline = $(this).closest('tr');	
			
		
		});
 	},'json');//post ends*/

  $("body").on(
    "dblclick",
    "#pendingRawMatList div table td.prodcode",
    function (e) {
      $.ajaxSetup({ async: false });
      //console.log($(this).text());
      var prodcode = $(this).text();
      var row = $(this).closest("tr");
      var qty = row.find(".qty").text();
      var frm = row.find(".frm").text();

      $.post(
        "product_code_fill.php?mode=singleproductfill&q=dummy",
        { prodcode: prodcode },
        function (html) {
          var data = html.split("|");
          var row = [];
          row["data"] = data;
          row["value"] = prodcode;
          console.log(row);
          var tempRow = $("#form_bookdetails table tbody tr.last");
          fillProductDetails(tempRow, row);
        }
      );

      $("#form_bookdetails table tbody tr.last td textarea.prodcode").val(
        $(this).text()
      );
      $("#form_bookdetails table tbody tr.last td textarea.qty").val(qty);
      //$('#form_bookdetails table tbody tr:last td textarea.frm').val(frm);
      $.ajaxSetup({ async: true });
    }
  );

  //for focusing on next field by pressing enter

  var altDown = false;

  var n = 0;

  $select = $(
    "input:text:not(#client,#address,#callby,#contactno,#email),textarea:not(#address),select:not(#address),input:button:not(#guesmas,#bkbymas,#showva)"
  );

  $select
    .keydown(function (e) {
      $select = $("input:text,textarea,select,input:button");

      n = $select.length;

      if (e.which == 13 && !$(this).is("textarea")) {
        //Enter key

        e.preventDefault(); //to skip default behavior of the enter key

        var nextIndex = $select.index(this) + 1;

        if (nextIndex < n) $select[nextIndex].focus();
        else {
          $select[nextIndex - 1].blur();
        }
      }

      if (e.keyCode == 18 && $(this).is("textarea")) {
        altDown = true;
      }
    })
    .keyup(function (e) {
      if (e.which == 13 && altDown) {
        altDown = false;

        //Enter key

        e.preventDefault(); //to skip default behavior of the enter key

        var nextIndex = $select.index(this) + 1;

        if (nextIndex < n) $select[nextIndex].focus();
        else {
          $select[nextIndex - 1].blur();
        }
      }
    });

  $("#total").keyup(function (e) {
    var code = e.which; // recommended to use e.which, it's normalized across browsers
    if (code == 13) {
      e.preventDefault();
      $("#discount").focus();
    } // missing closing if brace
  });

  $("#discount").keyup(function (e) {
    var code = e.which; // recommended to use e.which, it's normalized across browsers
    if (code == 13) {
      e.preventDefault();
      $("#namount").focus();
    } // missing closing if brace
  });

  $("#namount").keyup(function (e) {
    var code = e.which; // recommended to use e.which, it's normalized across browsers
    if (code == 13) {
      e.preventDefault();
      $("#servicetax").focus();
    } // missing closing if brace
  });

  $("#servicetax").keyup(function (e) {
    var code = e.which; // recommended to use e.which, it's normalized across browsers
    if (code == 13) {
      e.preventDefault();
      $("#grtotal").focus();
    } // missing closing if brace
  });

  $("#grtotal").keyup(function (e) {
    var code = e.which; // recommended to use e.which, it's normalized across browsers
    if (code == 13) {
      e.preventDefault();
      $("#Update").focus();
    } // missing closing if brace
  });

  $("#date").datepick();

  $("#New").click(function () {
    window.location = "sorderentry.php";
  });

  $("#Close").click(function () {
    window.close();
  });

  $("#Update").click(function () {
    $("#message").hide();

    $("#transperent").show();

    $.post(
      "sorderentry_crud.php?mode=update",
      $("#bookingform").serialize() +
        "&" +
        $("#msview").find("textarea").serialize(),
      function (html) {
        jSuccess(html);
        //window.location.reload();
        $("#transperent").hide();
      }
    );
  });

  $("#Save").click(function () {
    if (validate_form()) {
      $("#message").hide();
      $("#transperent").show();
      //$('#guesmas').trigger('click');
      $.post(
        "sorderentry_crud.php?mode=insert",
        $("#bookingform").serialize(),
        function (html) {
          var str = html.split("###");
          jSuccess(str[0]);
          jSuccess("order ID:" + str[1]);
          window.location = "sorderentry.php?orderid=" + str[1];
          $("#process").show();
          $("#transperent").hide();
        }
      );
    }
  });

  var newwindow;
  $("#history").click(function (e) {
    newwindow = window.open(
      "history.php?vehno=" + $("#vehno").val(),
      "",
      "height=380,width=700"
    );
    if (window.focus) {
      newwindow.focus();
    }
  });

  $("body").on("click", "#sepsizentry .sizeedit", function () {
    $("#message").hide();
    var row = $(this).closest("tr");
    $("#transperent").show();

    $.post(
      "sorderdet_crud.php?mode=updatesize",
      $(".sizetable").find("textarea").serialize() +
        "&orderid=" +
        $(".orderid").val() +
        "&prodcode=" +
        $(".productname").val() +
        "&entryid=" +
        $(".entryid").val(),
      function (html) {
        jSuccess(html);
        window.opener.$("#Update").trigger("click");
        window.opener.location.reload();
        $("#transperent").hide();
      }
    );
  });

  $("body").on(
    "keydown",
    ".sizechartdiv table tbody tr td textarea.qnty_pv",
    function (e) {
      if (e.which === 13) {
        var index = $(".qnty_pv").index(this) + 1;
        $(".qnty_pv").eq(index).focus();
      }
    }
  );

  var newsrnowin;
  $("body").on("click", ".srno", function (e) {
    var row = $(this).closest("tr");

    var prodcode = row.find(".prodcode").val();
    var orderid = row.find(".orderid").val();
    var entryid = row.find(".entryid").val();

    newsrnowin = window.open(
      "sizeset_entry.php?prodcode=" +
        prodcode +
        "&orderid=" +
        orderid +
        "&entryid=" +
        entryid,
      "",
      "height=650,width=770"
    );
    if (window.focus) {
      newsrnowin.focus();
    }
  });

  $("#process").click(function () {
    var flag;

    for (i = 0; i < $("#table_prod_details  tbody  tr").length; i++) {
      var disp = $(
        "#table_prod_details tbody tr:eq(" +
          i +
          ") div .prod_save,#table_prod_details tbody tr:eq(" +
          i +
          ") div .prod_savenew"
      ).css("display");

      if (disp != "none") {
        flag = 1;

        break;
      }
    }

    $("#message").hide();

    if ($("#orderid").val() != "") {
      $("#transperent").show();
      $("#order_id").removeAttr("disabled");
      $.post(
        "sorderentry_crud.php?mode=process",
        $("#bookingform").serialize(),
        function (html) {
          console.log(html);
          var str = html.split("###");

          jSuccess(str[0]);
          $("#packinglistno").val(str[1]);
          $("#Update").trigger("click");
          $("#orderid").attr("disabled", "disabled");

          $("#transperent").hide();
          //jSuccess(html);
        }
      );
    }

    $("#process").hide();
  });

  var newwindow;

  $("body").on("click", ".productentry", function () {
    newwindow = window.open(
      "../../productreg/prodentry.php",
      "",
      "height=500,width=800"
    );

    if (window.focus) {
      newwindow.focus();
    }
  });

  $("#print").click(function () {
    var oid = $("#orderid").val();
    var veh = $("#vehno").val();
    var word = $("#tot_words").val();
    var printval = $("#printopt").val();
    
    if (oid != "") {
      $("#transperent").show();

      $.post(
        "sorderreg_export_pdf.php",
        {
          orderid: oid,
          vehno: veh,
          tword: word,
          printopt: printval,
          PrePrint: "false",
          Logo: "true",
          Stvat: $("#Stvat").prop("checked"),
        },
        function () {
          window.open("sorder_entry.pdf", "", "width=900,height=400");

          $("#transperent").hide();
        }
      );
    }
  });

  $("#total").blur(update_total);

  $("#namount").blur(update_total);

  $("#discount").blur(update_total);

  $("#grtotal").blur(update_total);

  $("body").on("blur", ".rate,.qty,.percgst,.cgst,.sgst,.igst", function (e) {
    //var perigst=0;
    //var persgst = 0;
    var percgst = 0;
    var cgst = 0;
    var sgst = 0;
    var igst = 0;
    var gtotalamt = 0;
    var row = $(this).closest("tr");

    var rate = row.find(".rate").val();
    if (!isNaN(rate)) rate = Number(rate);

    var fresh = row.find(".qty").val();
    if (!isNaN(fresh)) fresh = Number(fresh);
    var perdisc = $("#disper").val();
    if (!isNaN(perdisc)) perdisc = Number(perdisc);

    var amt = (rate * fresh).toFixed(2);
    //var category = row.find('.cat').val();
    //if(category=='PRODUCT')
    row.find(".amount").val(amt);
    var discamt = Math.round((amt * perdisc) / 100);
    row.find(".discount").val(discamt);

    //else if(category=='SERVICES')
    //row.find('.scost').val(amt);
    //gst calculation
    var cmp = "27AALCG4637M1Z1"; //$("#cmpgstin").val();
    var scode = "";
    if ($("#pos").val() == "") {
      scode = $("#gstin").val();
    } else {
      scode = $("#pos").val();
    }
    if (cmp.substr(0, 2) == scode.substr(0, 2)) {
      cgst = (Number(amt - discamt) * row.find(".percgst").val() * 0.01) / 2;
      sgst = (Number(amt - discamt) * row.find(".percgst").val() * 0.01) / 2;
    } else {
      igst = Number(amt - discamt) * row.find(".percgst").val() * 0.01;
    }
    row.find(".cgst").val(cgst.toFixed(2));
    row.find(".sgst").val(sgst.toFixed(2));
    row.find(".igst").val(igst.toFixed(2));

    gtotalamt = Number(amt - discamt) + Number(cgst) + Number(sgst) + Number(igst);
    row.find(".gtotal").val(gtotalamt.toFixed(2));
  });
/*  
  $("body").on("blur", ".rate,.qty,.percgst,.cgst,.sgst,.igst", function (e) {
    var percgst = 0;
    var cgst = 0;
    //var persgst = 0;
    var sgst = 0;
    //var perigst=0;
    var igst = 0;
    var gtotalamt = 0;
    var row = $(this).closest("tr");

    var rate = row.find(".rate").val();
    if (!isNaN(rate)) rate = Number(rate);

    var fresh = row.find(".qty").val();
    if (!isNaN(fresh)) fresh = Number(fresh);
    var perdisc = $("#pdiscount").val();
    if (!isNaN(perdisc)) perdisc = Number(perdisc);

    var amt = (rate * fresh).toFixed(2);
    //var category = row.find('.cat').val();
    //if(category=='PRODUCT')
    row.find(".amount").val(amt);
    var discamt = (amt * perdisc) / 100;
    row.find(".discount").val(discamt);

    //else if(category=='SERVICES')
    //row.find('.scost').val(amt);
    //gst calculation
    var cmp = $("#cmpgstin").val();
    var scode = "";
    if ($("#pos").val() == "") {
      scode = $("#gstin").val();
    } else {
      scode = $("#pos").val();
    }
    if (cmp.substr(0, 2) == scode.substr(0, 2)) {
      cgst = (Number(amt - discamt) * row.find(".percgst").val() * 0.01) / 2;
      sgst = (Number(amt - discamt) * row.find(".percgst").val() * 0.01) / 2;
    } else {
      igst = Number(amt - discamt) * row.find(".percgst").val() * 0.01;
    }
    row.find(".cgst").val(cgst.toFixed(2));
    row.find(".sgst").val(sgst.toFixed(2));
    row.find(".igst").val(igst.toFixed(2));

    gtotalamt =
      Number(amt - discamt) + Number(cgst) + Number(sgst) + Number(igst);
    row.find(".gtotal").val(gtotalamt.toFixed(2));
  });
*/
  /*

  function to animate upcoming duties

  */
  $("#pendingRawMatList .dragDown,#penrmlist").click(function () {
    var divHeight = 0;
    var div = $("#pendingRawMatList .dataDiv");
    if (div.hasClass("show")) {
      div.html("");
      divHeight = 0;
      div.animate(
        {
          height: divHeight,
        },
        1000,
        function () {
          if (!div.hasClass("show")) {
            div.addClass("show");
          } else {
            div.removeClass("show");
          }
        }
      );
    } else {
      $.post(
        "finishprod.php",
        {
          type: "finishproduct",
          agent: $("#agentcode").val(),
        },
        function (html) {
          if (html == 0) {
            divHeight = 20;
            div.html("No data.");
          } else {
            divHeight = 200;
            div.html(html);
          }
          div.animate(
            {
              height: divHeight,
            },
            1000,
            function () {
              if (!div.hasClass("show")) {
                div.addClass("show");
              } else {
                div.removeClass("show");
              }
            }
          );
        }
      );
    }
  });
});

//document ends

function run() {
  $("textarea").click(function () {
    row_u = $(this).parents("tr");
    curr_u = $(this);
    undo_u = $(row_u).clone();

    //undo.appendTo("body");
  });
}

function inline_edit() {
  var tableid = "#msview ";

  $(tableid + "tbody textarea," + tableid + " tbody .pwd").click(function (
    event
  ) {
    if ($("#inline_edit").val() == 0) {
      $(tableid + " tbody tr input:button").hide();

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

      row_u = $(this).closest("tr");

      curr_u = $(this);

      undo_u = $(row_u).clone(true);

      row.find("input:button").show();
    } else
      $("#message")
        .html("Please Save the changes made OR press ESC to UNDO")
        .show();
  });

  $(tableid + " tbody textarea," + tableid + " tbody .pwd").keyup(function (
    event
  ) {
    if (
      (event.keyCode == 67 && event.ctrlKey) ||
      event.ctrlKey ||
      event.keyCode == 9
    )
      return;

    if (event.keyCode == 222) {
      //event.preventdefault();

      $(this).val(
        $(this)
          .val()
          .substring(0, $(this).val().length - 1) + "`"
      );
    }

    if ($("#inline_edit").val() == 0) {
      var row = $(this).closest("tr");

      $(tableid + " tbody tr  textarea").attr("readonly", "readonly");

      row.find("textarea").removeAttr("readonly");

      row.find("textarea").css("background-color", "#E0B99F");

      row.find("input:button").show();

      $("#inline_edit").val("1");
    }
  });
}

function jobentry_rel() {
  $("#jobdet_container table td textarea").autoCap();

  //for focusing on next field by pressing enter

  var n = 0;

  $select = null;

  $("#jobdet_container table td textarea").keydown(function (e) {
    $select = $("#jobdet_container table td textarea");
    n = $select.length;

    if (e.which == 13) {
      //Enter key

      e.preventDefault(); //to skip default behavior of the enter key

      var nextIndex = $select.index(this) + 1;

      if (nextIndex < n) $select[nextIndex].focus();
      else {
        $select[nextIndex - 1].blur();
      }

      e.preventDefault(); //to skip default behavior of the enter key

      var nextIndex = $select.index(this) + 1;

      if (nextIndex < n) $select[nextIndex].focus();
      else {
        $select[nextIndex - 1].blur();
      }
    }
  });

  $("body").keydown(function (e) {
    if (e.keyCode == 27) {
      //reload page
    }
  });

  $("body").on("click", "#jobdet_container td .edit", function () {
    $("#message").hide();

    $("#jobdet_container td .edit").hide();
    $("#msview tbody tr textarea").css("background-color", "");
    $("#msview tbody textarea").removeAttr("disabled");

    var row = $(this).closest("tr");
    var sizeSet = row.find(".sizeset");
    var sizeChart = sizeSet.attr("sizeChartId");

    $("#transperent").show();

    $.post(
      "sorderdet_crud.php?mode=update",
      row.find("select,textarea").serialize() +
        "&" +
        $(".calc").serialize() +
        "&" +
        $("#" + sizeChart + " table")
          .find("textarea")
          .serialize() +
        "&" +
        $(".sizetable").serialize() +
        "&ordertype=" +
        $("#ordertype").val(),
      function (html) {
        jSuccess(html);
        $("#Update").trigger("click");
        window.location.reload();
        $("#transperent").hide();
      }
    );
  });

  $("#jobdet_container td .deletedet").click(function () {
    $("#message").hide();
    $("#jobdet_container td .deletedet").hide();
    $("#msview tbody tr textarea").css("background-color", "");
    $("#msview tbody textarea").removeAttr("disabled");

    var row = $(this).closest("tr");
    row.remove();
    $("#transperent").show();

    $.post(
      "sorderdet_crud.php?mode=delete",
      row.find("select,textarea").serialize() + "&" + $(".calc").serialize(),
      function (html) {
        jSuccess(html);
        //$.when( update_total()).done($('#Update').trigger('click'));

        window.location.reload();
        $("#transperent").hide();
      }
    );
  });

  $("#jobdet_container td .addnew").click(function () {
    $("#message").hide();

    $("#jobdet_container td .addnew").hide();

    $("#msview tbody tr textarea").css("background-color", "");

    $("#msview tbody textarea").removeAttr("disabled");

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

    var sizeSet = row.find(".sizeset");
    var sizeChart = sizeSet.attr("sizeChartId");

    $("#transperent").show();
    $.post(
      "sorderdet_crud.php?mode=insert",
      row.find("select,textarea").serialize() +
        "&" +
        $(".calc").serialize() +
        "&" +
        $("#" + sizeChart + " table")
          .find("textarea")
          .serialize(),
      function (html) {
        jSuccess(html);
        console.log(html);
        //return false;
        $("#Update").trigger("click");
        window.location.reload();
        $("#transperent").hide();
      }
    );
  });

  $(".pcost,.calc,.scost").blur(update_total);

  $(".code").autocomplete("product_code_fill.php?", {
    delay: 10,
    minChars: 1,
    matchSubset: 1,
    matchContains: 1,
    mustMatch: 0,
    cacheLength: 10,
    sortResults: false,
    showResult: function (row, data) {
      return row + "|" + data[0];
    },
    autoFill: false,
  });

  $(".sizeset, .set").dblclick(function (e) {
    var sizeChart = $(this).attr("sizeChartId");
    var pos = $(this).position();
    $(".sizechartdiv").hide();
    if ($("#" + sizeChart).is(":visible")) {
      $("#" + sizeChart).slideUp();
    } else {
      $("#" + sizeChart)
        .css({ left: pos.left - 200, top: pos.top + 25 })
        .slideDown();
    }

    var freshTotal = 0;
    var seconds = 0;
    var qtyTotal = 0;
    var currBlur = $(".qnty_pv, .fresh_pv, .reprocess_pv");
    var tr = currBlur.closest("tr");
    var thistable = currBlur.closest("#" + sizeChart + " table");

    thistable.find(".fresh_pv").each(function (index) {
      freshTotal += Number($(this).val());
    });

    thistable.find(".reprocess_pv").each(function (index) {
      seconds += Number($(this).val());
    });

    thistable.find(".qnty_pv").each(function (index) {
      qtyTotal += Number($(this).val());
    });

    thistable.find(".tqnty_pv").val(qtyTotal);
    thistable.find(".tfresh_pv").val(freshTotal);
    thistable.find(".treprocess_pv").val(seconds);
  });

  $(".sizechartdiv table th, .closediv").click(function (e) {
    $(this).closest(".sizechartdiv").hide();
  });

  $(".prodcode").autocomplete("product_code_fill.php?", {
    delay: 200,
    minChars: 1,
    matchSubset: 1,
    matchContains: 1,
    cacheLength: 10,
    autoFill: false,
    onItemSelect: function (row) {
      console.log(row);
      var tempRow = $("*:focus").closest("tr");

      if (row.data[0] != "undefined") tempRow.find(".cat").val(row.data[0]);
      if (row.data[1] != "undefined")
        tempRow.find(".colorcode").val(row.data[1]);
      if (row.data[2] != "undefined")
        tempRow.find(".shortdesc").val(row.data[2]);
      /*	
			if(row.data[3]!='undefined')
			{
			var sizeSet = tempRow.find('.sizeset');
			
			sizeSet.val(row.data[3]);
			
			var sizeChart = sizeSet.attr('sizeChartId');
			}*/
      if (row.data[3] != "undefined") tempRow.find(".hsncode").val(row.data[3]);
      if (row.data[4] != "undefined") tempRow.find(".rate").val(row.data[4]);

      if (row.data[5] != "undefined") tempRow.find(".percgst").val(row.data[5]);

      if (row.data[12] != "undefined")
        tempRow.find(".sordmrp").val(row.data[12]);
      if (row.data[13] != "undefined")
        tempRow.find(".sorddisc").val(row.data[13]);

      /*var sizeArray = sizeSet.val().split(',');
			var tr
			$.each(sizeArray, function( index, value ) {
  			console.log( index + ": " + value );
			
			 tr+= "<tr><td>"+(index+1)+"</td><td><textarea style='height: 32px;' name='size_pv[]' class='size_pv' >"+value+"</textarea></td> <td><textarea name='qnty_pv[]'  class='qnty_pv' style='height: 32px;'></textarea></td><td><textarea name='fresh_pv[]' class='fresh_pv' style='height: 32px;'></textarea></td><td><textarea style='height: 32px;' name='reprocess_pv[]' class='reprocess_pv'></textarea></td></tr>";
			
			
			});		
			 
			 
			$('#'+sizeChart+' table').append(tr);
										
			},
			
			showResult:function(row,data) {
			return row+"|"+data[6];		*/
    },
  });

  $("body").on("change", ".qnty_pv, .fresh_pv, .reprocess_pv", function (e) {
    var currBlur = $(this);
    var tr = currBlur.closest("tr");

    var freshTotal = 0;
    var reprocessTotal = 0;
    var damageTotal = 0;
    var qtyTotal = 0;

    var table = currBlur.closest("table");

    var fresh = Number(tr.find(".fresh_pv").val());
    var seconds = Number(tr.find(".reprocess_pv").val());

    table.find(".fresh_pv").each(function (index) {
      freshTotal += Number($(this).val());
    });

    table.find(".reprocess_pv").each(function (index) {
      seconds += Number($(this).val());
    });

    table.find(".qnty_pv").each(function (index) {
      qtyTotal += Number($(this).val());
    });

    table.find(".tqnty_pv").val(qtyTotal);
    table.find(".tfresh_pv").val(freshTotal);
    table.find(".treprocess_pv").val(seconds);

    var sizechartid = table.closest("div").attr("id");

    $("#msview .sizeset").each(function (index) {
      if ($(this).attr("sizechartid") == sizechartid) {
        var tr = $(this).closest("tr");

        tr.find(".qty").val(qtyTotal);
        //tr.find('.fresh').val(freshTotal);
        //tr.find('.reprocess_pv').val(seconds);
      }
    });

    //console.log(total);
  });
}

function fillProductDetails(tempRow, row) {
  if (row.data[0] != "undefined") tempRow.find(".cat").val(row.data[0]);
  if (row.data[1] != "undefined") tempRow.find(".colorcode").val(row.data[1]);
  if (row.data[2] != "undefined") tempRow.find(".shortdesc").val(row.data[2]);
  if (row.data[4] != "undefined") {
    var sizeSet = tempRow.find(".sizeset");

    sizeSet.val(row.data[4]);

    var sizeChart = sizeSet.attr("sizeChartId");
  }
  if (row.data[5] != "undefined") tempRow.find(".set").val(row.data[5]);
  if (row.data[6] != "undefined") tempRow.find(".qty").val(row.data[6]);
  if (row.data[7] != "undefined") tempRow.find(".fresh").val(row.data[7]);
  if (row.data[8] != "undefined") tempRow.find(".reprocess").val(row.data[8]);
  if (row.data[9] != "undefined") tempRow.find(".demage").val(row.data[9]);

  var sizeArray = sizeSet.val().split(",");
  var qtyArray = row.data[12].split(",");
  var qtyval = qtyArray;

  var tr;
  var seen = {};
  var sizeQty = "0";
  console.log(sizeArray);
  $.each(sizeArray, function (temp, value) {
    if ($.trim(qtyArray[temp]) == "") {
      qtyArray[temp] = "0-0";
    }
    var value_index = qtyArray.find((a) => a.includes(value + "-"));
    sizeQty = 0;
    if (value_index) {
      var qtyval = value_index.split("-");
      if ($.trim(value) == $.trim(qtyval[0])) {
        sizeQty = qtyval[1];
      }
    }
    tr +=
      "<tr><td>" +
      (temp + 1) +
      "</td><td><textarea style='height: 32px;' name='size_pv[]' class='size_pv' >" +
      value +
      "</textarea></td> <td><textarea name='qnty_pv[]'  class='qnty_pv' style='height: 32px;'>" +
      sizeQty +
      "</textarea></td><td><textarea name='fresh_pv[]' class='fresh_pv' style='height: 32px;'></textarea></td><td><textarea style='height: 32px;' name='reprocess_pv[]' class='reprocess_pv'></textarea></td><td><textarea style='height: 32px;' name='demage_pv[]' class='demage_pv'></textarea></td></tr>";
  });

  $("#" + sizeChart + " table").append(tr);
}

function update_total() {
  var price = 0;
  var p_total = 0;
  var s_total = 0;
  var disper = 0;
  var discamt = 0;
  var pdiscount = 0;
  var sdiscount = 0;
  var pnetamount = 0;
  var snetamount = 0;
  var total = 0;
  var vat = 0;
  var servicetax = 0;

  $(".amount").each(function (i) {
    price = $(this).val();

    if (!isNaN(price))
      //p_total += Number(price);
      p_total = Number(price);
  });

  $(".scost").each(function (i) {
    price = $(this).val();

    if (!isNaN(price))
      //	s_total += Number(price);
      s_total = Number(price);
  });

  total = Number(p_total) + Number(s_total);

  $(".tpcost").val(p_total.toFixed(2));
  $(".tscost").val(s_total.toFixed(2));
  $("#ptotal").val(p_total.toFixed(2));
  $("#stotal").val(s_total.toFixed(2));

  if ($("#disper").val() > 0) {
    discamt = Math.round(
      Number($("#ptotal").val()) * Number($("#disper").val() / 100)
    );

    pnetamount = Math.round(Number($("#ptotal").val()) - Number(discamt));

    $("#pdiscount").val(discamt.toFixed(2));
    $("#pnamount").val(pnetamount.toFixed(2));
  } else {
    pnetamount = p_total.toFixed(2);

    $("#pnamount").val(pnetamount);
  }

  if ($("#pdiscount").val() > 0) {
    pnetamount = Math.round(
      Number($("#ptotal").val()) - Number($("#pdiscount").val())
    );

    $("#pnamount").val(pnetamount.toFixed(2));
  } else {
    pnetamount = p_total.toFixed(2);

    $("#pnamount").val(pnetamount);
  }

  if ($("#sdiscount").val() > 0) {
    snetamount = Math.round(
      Number($("#stotal").val()) - Number($("#sdiscount").val())
    );

    $("#snamount").val(snetamount.toFixed(2));
  } else {
    snetamount = s_total.toFixed(2);

    $("#snamount").val(snetamount);
  }

  //--by partha as discussed on 3rd sept 2014.
/*
  vat = Number(pnetamount) * Number($("#pervat").val() * 0.01);

  vat = Math.round(vat);

  $("#vat").val(vat.toFixed(2));

  servicetax = 4.8 * Number(snetamount) * 0.01;

  servicetax = Math.round(servicetax);

  $("#servicetax").val(servicetax.toFixed(2));
*/
  //$('#servicetax').val('0.00');
  
  var totcgst = $("#totcgst").val();
  var totsgst = $("#totsgst").val();
  var totigst = $("#totigst").val();

//  var grtotal =     Number(pnetamount) + Number(snetamount) + Number(vat) + Number(servicetax);
  var grtotal =     Number(pnetamount) + Number(totcgst) + Number(totsgst) + Number(totigst);
  grtotal = Math.round(grtotal);

  $("#grtotal").val(grtotal.toFixed(2));
  //$('#grtotal').trigger('blur');
}

function validate_form() {
  /*if($.trim($('#compid').val())=="")
		{
			jSuccess("Blank Name");
			$('#compid').focus();
			return false;
		}*/
  /*else if($.trim($('#address').val())=="")
		{
			jSuccess("Blank Address");
			$('#address').focus();
			return false;
		}*/
  /*
		else if($.trim($('#callby').val())=="")
		{
			jSuccess("Blank Contact name");
			$('#callby').focus();
			return false;
		}*/
  /*else if($.trim($('#telephone').val())=="")
		{
			jSuccess("Blank Contact No");
			$('#telephone').focus();
			return false;
		}
		*/

  //else

  return true;
}

var winPop;

function positionedPopup(url, height, width) {
  if (!width) width = 300;

  if (winPop && !winPop.closed && winPop.document.location.href != url) {
    //checks to see if window is open
    winPop.close();
  }
  winPop = window.open(
    url,
    "mywindow1",
    "menubar=1,resizable=1,width=" +
      width +
      ",height=" +
      height +
      ",left=250,top=0"
  );

  if (winPop && winPop.document.location.href == url) winPop.focus();

  return winPop;
}
