$(document).ready(function(){
var shipping = 0;
var shippingCharges= 0;

function roundNumber(number,decimals) {
  var newString;// The new rounded number
  decimals = Number(decimals);
  if (decimals < 1) {
    newString = (Math.round(number)).toString();
  } else {
    var numString = number.toString();
    if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
      numString += ".";// give it one at the end
    }
    var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
    var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
    var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
    if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
      if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
        while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
          if (d1 != ".") {
            cutoff -= 1;
            d1 = Number(numString.substring(cutoff,cutoff+1));
          } else {
            cutoff -= 1;
          }
        }
      }
      d1 += 1;
    } 
    if (d1 == 10) {
      numString = numString.substring(0, numString.lastIndexOf("."));
      var roundedNum = Number(numString) + 1;
      newString = roundedNum.toString() + '.';
    } else {
      newString = numString.substring(0,cutoff) + d1.toString();
    }
  }
  if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
    newString += ".";
  }
  var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
  for(var i=0;i<decimals-decs;i++) newString += "0";
  //var newNumber = Number(newString);// make it a number if you like
  return newString; // Output the result to the form field (change for your purposes)
}

function update_total() {
  var total = 0;
  $('.price').each(function(i){
    price = $(this).html().replace("$","");
    if (!isNaN(price)) total += Number(price);
  });

  total = roundNumber(total,2);

  
  $('#total').html("$"+total);
  
  
}



function update_price() {
  var row = $(this).parents('.item-row');
  var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
  price = roundNumber(price,2);
  isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);
  
  update_total();
}

function bind() {
  $(".cost").blur(update_price);
  $(".qty").blur(update_price);
}

 
  
  $('#add_new_quotation input').on('keyup',function(){
  var val1=$('#product_price').val().replace(/[\₹]/g, '');
    var val2=$('#product_quantity').val().replace(/[\₹]/g, '');

    var val3=val1*val2;
    $('#product_total').val("₹"+val3.toFixed(2));
  });
  
  $('#add_new_invoice_without_pi input').on('keyup',function(){
  var val1=$('#product_price').val().replace(/[\₹]/g, '');
    var val2=$('#product_quantity').val().replace(/[\₹]/g, '');

    var val3=val1*val2;
    $('#product_total').val("₹"+val3.toFixed(2));
  });
  $(document.body).on("change",".Product_select",function(){
  
    inlinetotal(); 
      
});
  

  


$('#product_price').change(function(){
    var unitcost=$('#product_price').val();
    var productid=$('#Product_select').val();
    var valueofcost=$('#product_price').data("value");
    
  /*  
    $.ajaxSetup({

      headers: {

      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

      }

    });  
    $.ajax({

         url:url_checkunitcost,
  
        type:"POST",
  
          data:{
                productid:productid,
                unitcost:unitcost
              },
  
         success:function(result){
         
            if(result == 'allow')
   
            {
                
            }

            else

            {
               var r=confirm("are you sure for chanenging price");
               
               if (r == true) {
                 
                inlinetotal();
                taxtotal();

               
              } else {    */            
                
                //$('#product_price').val("₹"+valueofcost);
                
                inlinetotal(); 
                taxtotal();
               
             /*  }
            }

          
         }
        });*/
  }); 
	
	$(document).on('change','.shipping-charge-custom',function(){
		shipping = parseFloat($(this).val());
		shippingCharges = (shipping*18)/100;
		subtotal();
        taxtotal();
        updatetotal();
	});
  


$(document).on('click', 'a.delete', function () {

  var popup=confirm("Are you sure!!!");
    if(popup==true)
		{
      $(this).closest('tr').remove();
      empty();
      subtotal();
      taxtotal();
      updatetotal();
      return false;
    }  
}); 



  $('#c_s_gsttype').change(function()
  {
    var price=$('#product_price').val().replace(/[\₹]/g, '');
    var valueofcsgst=$('#c_s_gsttype').val().replace(/[\*\^\'\!\%\+\₹]/g, '').split(' ')[0];
    var quantity=$('#product_quantity').val();
    var outcome=((((price/100)*(valueofcsgst*2))*quantity));
    $(document).find('#gst_rowtotal').val("₹"+outcome.toFixed(2));  
    $(document).find('#testing').val("₹"+outcome.toFixed(2));  
  });

  $('#i_gsttype').change(function()
  {
    var price=$('#product_price').val().replace(/[\₹]/g, '');
    var valueofigst=$('#i_gsttype').val().replace(/[^a-z0-9\s]/gi, '');
    var quantity=$('#product_quantity').val();
    var outcome=(((price/100)*valueofigst)*quantity);
    $(document).find('#gst_rowtotal').val("₹"+outcome.toFixed(2)); 
    $(document).find('#testing').val("₹"+outcome.toFixed(2)); 
  });

  $("#addrows").click(function(){
    var listproduct_id=$('#Product_select').val();
    var listproduct_name=$('#Product_select').find(":selected").text();
    var listproduct_HSN=$('#product_HSN').val();
    var listproduct_SKU=$('#product_SKU').val();
    var listproduct_unitcost=$('#product_price').val().replace(/[\₹]/g, '');
    var listproduct_quantity=$('#product_quantity').val();
    var listproduct_csgst=$('#c_s_gsttype').val();
    var listproduct_igst=$('#i_gsttype').val();
    var taxvalue=$('#testing').val();
    var listproduct_total=$('#product_total').val();
   
      if(listproduct_name==null || listproduct_quantity==0 ||listproduct_total==0||listproduct_HSN==''||listproduct_csgst==null&&listproduct_igst==null)
      {
        alert("please Enter All Value Properly!!!");
      }   
      else if(listproduct_csgst==null)
      { 
        var valueofigst=$('#i_gsttype').val().replace(/[^a-z0-9\s]/gi, '');
        $("#qwe").css("display", "block");
        $("#maintable").append('<tr class="itemrow"><td><label class="listcol1 control-label  finallistname" id="finallistname" data-id="'+listproduct_id+'" > '+listproduct_name+'</label><td><label class="listcol3 control-label  finallistSKU" id="finallistSKU" > '+listproduct_SKU+'</label></td><td><label class="listcol2 control-label  finallistHSN" id="finallistHSN" > '+listproduct_HSN+'</label></td><td><input type="text" id="finallistunitcost" class="listcol4  finallistunitcost" value="₹'+listproduct_unitcost+'" ></td><td><input type="number" id="finallistquantity" class="listcol5 finallistquantity" min="0" value='+listproduct_quantity+' ></td><td style="display:none;"><input type="text" id="finallistcsgst" class="listcol6 finallistcsgst" value='+listproduct_csgst+'></td><td><input type="text" id="finallistigst" class="listcol7  finallistigst" value='+listproduct_igst+' ></td><td><input type="text" class="listcol8 taxfield  gstperc'+valueofigst+'"  value="'+taxvalue+'" readonly></td><td><input type="text" id="finallisttotal" class="listcol9  total finallisttotal" value="'+listproduct_total+'" readonly></td><td><a class="delete" id="delete"><i class="fa fa-minus orange"></i></a></td></tr>');
        
        $('#product_HSN').val("");
        $('#product_SKU').val("");
        $('#product_price').val('0');
        $('#product_total').val('₹00.00');
        $('#testing').val('₹00.00');
        $('#gst_rowtotal').val('₹00.00');
        $('#product_quantity').val('0');
        $('#i_gsttype').val("");
        $(document).find('#product_price').attr("data-name"," ");
        $(document).find('#product_price').attr("data-id"," ");
        $("#Product_select").empty();
              
        igst(valueofigst);
        subtotal();
        taxtotal();
        updatetotal();

        
      }
      else if(listproduct_igst==null)
      { 
        var valueofcsgst=$('#c_s_gsttype').val().replace(/[\*\^\'\!\%\+\.]/g, '').split(' ')[0];
        $("#qwe").css("display", "block");
        $("#maintable").append('<tr class="itemrow"><td><label class="listcol1 control-label  finallistname" id="finallistname" for="inputSuccess" data-id="'+listproduct_id+'" > '+listproduct_name+'</label><td><label class="listcol2 control-label  finallistSKU" id="finallistSKU" > '+listproduct_SKU+'</label></td><td><label class="listcol3 control-label  finallistHSN" id="finallistHSN" > '+listproduct_HSN+'</label></td><td><input type="text" id="finallistunitcost" class="listcol4  finallistunitcost" value="₹'+listproduct_unitcost+'" ></td><td><input type="number" id="finallistquantity" class="listcol5  finallistquantity" min="0" value="'+listproduct_quantity+'" ></td><td><input type="text" id="finallistcsgst" class="listcol6  finallistcsgst" value="'+listproduct_csgst+'" ></td><td style="display:none;"><input type="text" id="finallistigst" class="listcol7  finallistigst" value="'+listproduct_igst+'" ></td><td><input type="text" class="listcol8 taxfield  gstperc'+valueofcsgst+'" value="'+taxvalue+'" readonly></td><td><input type="text" id="finallisttotal" class="listcol9  total finallisttotal" value="'+listproduct_total+'" readonly></td><td><a class="delete" id="delete"><i class="fa fa-minus orange"></i></a></td></tr>');
                                                                                                                                                                                                                                        
        $('#product_HSN').val("");
        $('#product_SKU').val("");
        $('#product_price').val('0');
        $('#product_total').val('₹00.00');
        $('#testing').val('₹00.00');
        $('#gst_rowtotal').val('₹00.00');
        $('#product_quantity').val('0');
        $('#c_s_gsttype').val("");
        $(document).find('#product_price').attr("data-name"," ");
        $(document).find('#product_price').attr("data-id"," ");
        $("#Product_select").empty();
     
        
        csgst(valueofcsgst);
        subtotal();
        taxtotal();
        updatetotal();
      }

  });







    function inlinetotal()
    {
      var val1=$('#product_price').val().replace(/[\₹]/g, '');
      var val2=$('#product_quantity').val().replace(/[\₹]/g, '');

      var val3=val1*val2;
      $('#product_total').val("₹"+val3.toFixed(2));

    };
 
    function updatetotal(){

      var grandTotal = 0;
      
      var stval = parseFloat($('.subtot').val().replace(/[\₹]/g, ''));
      var taxval = parseFloat($('.taxtot').val().replace(/[\₹]/g, ''));
      grandTotal = stval+taxval;
      console.log(shipping);
      console.log(shippingCharges);
      console.log(grandTotal);
      console.log(grandTotal);
      $('.grdtot').val("₹"+grandTotal.toFixed(2));
    };

    function subtotal(){

      var subTotal = 0;
      $(".total").each(function () {

      var stval = parseFloat($(this).val().replace(/[\₹]/g, ''));
      subTotal += isNaN(stval) ? 0 : stval;
      });
      $('.subtot').val("₹"+subTotal.toFixed(2));
    };

    function taxtotal()
    {
      var tax=0;
      $(".taxfield").each(function(){
        var taxval = parseFloat($(this).val().replace(/[\₹]/g, ''));
        tax +=isNaN(taxval) ? 0: taxval;
      });
	  
	  tax = tax + shippingCharges;
      $('.taxtot').val("₹"+tax.toFixed(2));

    };

    function igst(valueofigst)
    {

      if(valueofigst==5){
        var tax=0;
        $(document).find('.gstperc5').each(function(){
          var taxval = parseFloat($(this).val().replace(/[\₹]/g, ''));
          tax +=isNaN(taxval) ? 0: taxval;
        });
        $(document).find('.gst5').val("₹"+tax.toFixed(2));
      }
      if(valueofigst==12){
        var tax=0;
        $(document).find('.gstperc12').each(function(){
          var taxval = parseFloat($(this).val().replace(/[\₹]/g, ''));
          tax +=isNaN(taxval) ? 0: taxval;
        });
        $(document).find('.gst12').val("₹"+tax.toFixed(2));
        
      }
      if(valueofigst==18){
        var tax=0;
        $(document).find('.gstperc18').each(function(){
          var taxval = parseFloat($(this).val().replace(/[\₹]/g, ''));
          tax +=isNaN(taxval) ? 0: taxval;
        });
        $(document).find('.gst18').val("₹"+tax.toFixed(2));
      }
      if(valueofigst==28){
        var tax=0;
        $(document).find('.gstperc28').each(function(){
          var taxval = parseFloat($(this).val().replace(/[\₹]/g, ''));
          tax +=isNaN(taxval) ? 0: taxval;
        });
        $(document).find('.gst28').val("₹"+tax.toFixed(2));
      }

    };

    function empty()
    {
      
        var tax5=0;
          $(document).find('.gstperc5').each(function(){
            var taxval5 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax5 +=isNaN(taxval5) ? 0: taxval5;
          });
        $(document).find('.gst5').val("₹"+tax5.toFixed(2));
      
      
        var tax12=0;
          $(document).find('.gstperc12').each(function(){
            var taxval12 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax12 +=isNaN(taxval12) ? 0: taxval12;
          });
        $(document).find('.gst12').val("₹"+tax12.toFixed(2));
      
      
        var tax18=0;
          $(document).find('.gstperc18').each(function(){
            var taxval18 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax18 +=isNaN(taxval18) ? 0: taxval18;
          });
        $(document).find('.gst18').val("₹"+tax18.toFixed(2));
      
      
        var tax28=0;
          $(document).find('.gstperc28').each(function(){
            var taxval28 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax28 +=isNaN(taxval28) ? 0: taxval28;
          });
        $(document).find('.gst28').val("₹"+tax28.toFixed(2));


        var tax25=0;
          $(document).find('.gstperc25').each(function(){
            var taxval25 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax25 +=isNaN(taxval25) ? 0: taxval25;
          });
        $(document).find('.gst25').val("₹"+tax25.toFixed(2));
    
        var tax6=0;
          $(document).find('.gstperc6').each(function(){
            var taxval6 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax6 +=isNaN(taxval6) ? 0: taxval6;
          });
        $(document).find('.gst6').val("₹"+tax6.toFixed(2));
    
        var tax9=0;
          $(document).find('.gstperc9').each(function(){
            var taxval9 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax9 +=isNaN(taxval9) ? 0: taxval9;
          });
        $(document).find('.gst9').val("₹"+tax9.toFixed(2));
    
        var tax14=0;
          $(document).find('.gstperc14').each(function(){
            var taxval14 = parseFloat($(this).val().replace(/[\₹]/g, ''));
            tax14 +=isNaN(taxval14) ? 0: taxval14;
          });
        $(document).find('.gst14').val("₹"+tax14.toFixed(2));
      
    }

    function csgst(valueofcsgst)
  {
    if(valueofcsgst==25){
      var tax25=0;
      $(document).find('.gstperc25').each(function(){
        var taxval25 = parseFloat($(this).val().replace(/[\₹]/g, ''));
        tax25 +=isNaN(taxval25) ? 0: taxval25;
      });
      $(document).find('.gst25').val("₹"+tax25.toFixed(2));
    }
    if(valueofcsgst==6){
      var tax6=0;
      $(document).find('.gstperc6').each(function(){
        var taxval6 = parseFloat($(this).val().replace(/[\₹]/g, ''));
        tax6 +=isNaN(taxval6) ? 0: taxval6;
      });
      $(document).find('.gst6').val("₹"+tax6.toFixed(2));
    }
    if(valueofcsgst==9){
      var tax9=0;
      $(document).find('.gstperc9').each(function(){
        var taxval9 = parseFloat($(this).val().replace(/[\₹]/g, ''));
        tax9 +=isNaN(taxval9) ? 0: taxval9;
      });
      $(document).find('.gst9').val("₹"+tax9.toFixed(2));
    }
    if(valueofcsgst==14){
      var tax14=0;
      $(document).find('.gstperc14').each(function(){
        var taxval14 = parseFloat($(this).val().replace(/[\₹]/g, ''));
        tax14 +=isNaN(taxval14) ? 0: taxval14;
      });
      $(document).find('.gst14').val("₹"+tax14.toFixed(2));
    }

    };

 });