$(document).ready(function(){
add_del_row();
$( "#issdate" ).datepick();
$( "#divdate" ).datepick();
$( "#mfgyear" ).datepick();
$( "#refnodate" ).datepick();
$( "#challandate" ).datepick();

if($('#ptotal').val()!='')
{
	$('#grtotal').focus();
}
else
{
	$('#jobcode').focus();
}

	
var jobberwindow;
  $('#guesmas').click(function(e) {
	
	if($.trim($('#jobcode').val())!=''&&$.trim($('#jobbername').val())!='')
	{
   jobberwindow = positionedPopup("../../masters/mastercmpedit.php",450,700);
   setTimeout(function(){ jobberwindow.document.getElementById("compid").value = $('#jobcode').val();jobberwindow.document.getElementById("name").value = $('#jobbername').val();jobberwindow.document.getElementById("address").value = $('#adress').val();jobberwindow.document.getElementById("type").value = 'JOBBER'}, 2000);
	}
   else
   {
	jobberwindow = positionedPopup("../../masters/mastercmpedit.php",450,700);
   }
   
	//if (window.focus) {driverwindow.focus()}
});



	

	
	
	$("#pendingRawMatList .dragDown,#penrmlist").click(function()
  {
    var divHeight = 0;
    var div = $("#pendingRawMatList .dataDiv");
	var jobidval = $("#jobid").val();
    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('pendingproduct.php',
      {
        'type': 'pendingproduct','agent':$('#agentcode').val(),'jobid':jobidval
      }, function(html)
      {
        if (html == 0)
        {
          divHeight = 20;
          div.html('No data.');
        }
        else
        {
          divHeight = 200;
          div.html(html);
		   $(".dataDiv table").tablesorter({
			theme: 'default',
			widthFixed: false,
			showProcessing: true,
			//headerTemplate : '{content} {icon}', // Add icon for various themes

			widgets: ['filter',  'stickyHeaders'  ],
    		widgetOptions : {
			filter_searchDelay: 300,
			stickyHeaders_attachTo : '.dataDiv'
			}
			});
		  
        }
        div.animate(
        {
          height: divHeight
        }, 1000, function()
        {
          if (!div.hasClass('show'))
          {
            div.addClass('show');
          }
          else
          {
            div.removeClass('show');
          }
        });
      });
    }
  });
  
  
 var newsrnowin	
	 $('body').on('click', '.srno', function (e) {
	
		 var row = $(this).closest('tr');
		 	 
		 var prodcode  = row.find('.prodcode').val();
		 var orderid  = row.find('.jobid').val();
		 var entryid  = row.find('.entryid').val();
		 var recrefno  = row.find('.recrefno').val();
		 
       newsrnowin=window.open('sizeset_entry.php?prodcode='+prodcode+'&orderid='+orderid+'&entryid='+entryid+'&recrefno='+recrefno,'','height=650,width=770');
	    if (window.focus) {newsrnowin.focus()
		}
			 
     });
			
			
  
  $('body').on('click',"#form_bookdetails table .qty",function(e)
//  $("#pendingQuanList .dragDown,#form_bookdetails table .qty").dblclick(function()
  {
    var divHeight = 0;
    var div = $("#pendingQuanList .dataDiv");
	
	var left =  $(this).position().left-10;
	var top =  $(this).position().top+35;
	var row= $(this).closest('tr');
	var prodval = row.find(".prodcode").val();
	var jobidval = $("#jobid").val();
	if($.trim(prodval)=='')
	return false;
	
	$('#pendingQuanList').css({'position': 'absolute',  'left': left,    'top': top});
	//$('#pendingQuanList').show('slow');

    if (div.hasClass('show'))
    {
		$(".qnty_pv").show();
		
			var totIssuedQty = 0;
$( "#pendingQuanList .dataDiv table td textarea.issuedqty" ).each(function( i ) {
			totIssuedQty+=Number($(this).val()); 
		 });
		 $(this).val(totIssuedQty); 
    
      divHeight = 0;
      div.animate(
      {
        height: divHeight
      }, 1000, function()
      {
		  if (!div.hasClass('show'))
		  {
			div.addClass('show');
		  }
		  else
		  {
			div.removeClass('show');
		  }
      });
    }
    else
    {
      $.post('pendingproduct.php',
      {
        'type': 'pendingproductdetails','prodcode':prodval,'jobid':jobidval
      }, function(html)
      {
        if (html == 0)
        {
          divHeight = 20;
          div.html('No data.');
        }
        else
        {
			  div.html('');
          divHeight = 150;
          div.html(html);
        }
        div.animate(
        {
          height: divHeight
        }, 2000, function()
        {
          if (!div.hasClass('show'))
          {
            div.addClass('show');
          }
          else
          {
            div.removeClass('show');
          }
        });
      });
    }
  });
  


$('body').on("blur",".rate",function(e)
{
	
	var row= $(this).closest('tr');
	var rateVal = $(this).val();
	var qtyVal = row.find(".qty").val();
	if(rateVal!=''&&qtyVal!=''){
	var amount = Math.round(qtyVal*rateVal);
	row.find('.amount').val(amount);
	}
});	



$('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();
         }
     });
	 
	 

$('body').on("click","#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;
			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="jobentry.php";
		
		}); 
		
		$("#Close").click(function() {
		
		
		
		window.close();
		
		
		
		});

	

$('#Update').click(function(){
		
		$('#message').hide();
		
		$('#transperent').show();
	
		$.post("jobentry_crud.php?mode=update",$("#bookingform").serialize(),function(html){
			
/*						
$( "#jobdet_container td .edit, #jobdet_container td .addnew" ).each(function( index ) {
		  
		 $('#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("jobdet_crud.php?mode=update",row.find('select,textarea').serialize()+'&refno='+$('#refno').val()+'&jobid='+$('#jobid').val()+'&'+$('#'+sizeChart+' table').find('textarea').serialize(),function(html){
	 

		console.log(html);
	 	jSuccess(html);
  		});
});	*/
		
		jSuccess(html);
		
		$('#transperent').hide();
		});	
		
		
});

	

		$('#Save').click(function(){
		if(validate_form())
		{
		$('#message').hide();
		$('#transperent').show();
		 console.log($("#bookingform").serialize());
		$.post("jobentry_crud.php?mode=insert",$("#bookingform").serialize()+'&'+$('#msview').serialize(),function(html){
         console.log(html);
		var str=html.split('###');		
		jSuccess(str[0]);		
		jSuccess('Rec Refno:'+str[1]);
		window.location="jobentry.php?jobid="+str[1];		
		$('#refno').val(str[1]);
		$('#process').show();
		$('#Save').hide();
		$('#Update').show();
		
		/*******************************/
		
		$( "#jobdet_container td .edit" ).each(function( index ) { 
		 
		$("#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("jobdet_crud.php?mode=insert",row.find('select,textarea').serialize()+'&refno='+$('#refno').val()+'&jobid='+$('#jobid').val()+'&'+$('#'+sizeChart+' table').find('textarea').serialize(),function(html){
		console.log(html);
	 	jSuccess(html);
		
 		});
	});
		
		/*******************************/
		
		$('#transperent').hide();		
  	});	
 }
});
	
	
	

	

$('#process').click(function(){

	var flag=0;
	var disp = '';
	for(i=0;i<$("#form_bookdetails table  tbody  tr").length;i++)
	{		
		var disp=$('#form_bookdetails table  tbody tr:eq('+i+')  .edit,#form_bookdetails table  tbody tr:eq('+i+')  .addnew').css('display'); 	
		
		if(disp!="none")
		{
		flag=1;
		break;
		}

	}


if(flag==1)

	jNotify('Please save the record before Processing!!');

else
{
	$.post("jobentry_crud.php?mode=process",$("#bookingform").serialize(),function(html){
		console.log(html);
		var tojobid = html.split('###');
		$('#jobidfrom').val(tojobid[1]);
		jSuccess(html);
		$('#Update').trigger('click');
		//window.location.reload();
		$('#transperent').hide();
		});	
}
//$('#process').hide();


//}

});





$('#print').click(function () {

var oid=$('#jobid').val();
var veh=$('#vehno').val();
var word=$('#tot_words').val();

if(oid!='')
{
	$("#transperent").show();

	$.post('jobreg_export_pdf.php', {jobid:oid,vehno:veh,tword:word,PrePrint:'false',Logo:'true',Stvat:$('#Stvat').prop('checked')},function (data) {
     console.log(data);
	window.open("job_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('change','.rmchartdiv table textarea.rmissued_pv',function(){
	
	$(this).data("old", $(this).data("new") || $(this).html());
    $(this).data("new", $(this).val());
    });

});

//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 fillProductDetails(tempRow,row)
{
			if(row.data[1]!='undefined')
			tempRow.find('.cat').val(row.data[1]);	
			if(row.data[2]!='undefined')
			tempRow.find('.colorcode').val(row.data[2]);	
			if(row.data[3]!='undefined')
			tempRow.find('.shortdesc').val(row.data[3]);	
			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]);
			if(row.data[10]!='undefined')
			tempRow.find('.ratiotota').val(row.data[10]);
			if(row.data[11]!='undefined')
			tempRow.find('.gencode').val(row.data[11]);
			
			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>";
			
		if (seen[temp])
        $(this).remove();
        else
        seen[temp] = true;
			});		
			
			$('#'+sizeChart+' table').append(tr);	
}




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	 

	 

	}	

});



$('#jobdet_container td .edit').click(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();
 
		console.log($('#'+sizeChart+' table').find('textarea').serialize());
		
 $.post("jobdet_crud.php?mode=update",row.find('select,textarea').serialize()+'&'+$('#'+sizeChart+' table').find('textarea').serialize()+'&refno='+$('#refno').val()+'&jobid='+$('#jobid').val(),function(html){

	console.log(html);
	 jSuccess(html);
	
	  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();
		var sizeSet = row.find('.sizeset');		
	    var sizeChart = sizeSet.attr('sizeChartId');
        $('#transperent').show();

 			$.post("jobdet_crud.php?mode=delete",row.find('select,textarea').serialize()+'&'+$(".calc").serialize()+'&'+$('#'+sizeChart+' table').find('textarea').serialize(),function(html){

	  jSuccess(html); 
	  $.when( update_total()).done($('#Update').trigger('click'));
	  $('#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("jobdet_crud.php?mode=insert",row.find('select,textarea').serialize()+'&'+$(".calc").serialize()+'&'+$('#'+sizeChart+' table').find('textarea').serialize()+'&'+$('#pendingQuanList table').find('textarea').serialize(),function(html){
		 $.post("jobdet_crud.php?mode=insert",row.find('select,textarea').serialize()+'&refno='+$('#refno').val()+'&jobid='+$('#jobid').val()+'&'+$('#'+sizeChart+' table').find('textarea').serialize(),function(html){
	jSuccess(html);
	console.log(html+'test');
	 $('#Update').trigger('click');
	 window.location.reload();
	 $('#transperent').hide();
  });

});	



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


	
	
/*	$('.sizeset').tooltipster({
    contentCloning: true,
	 trigger: 'click'
});*/


$('.sizeset').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();
	}
	
		$('.foot td textarea').attr('readonly','readonly');
	
	var freshTotal = 0;
			var seconds = 0;
			var qtyTotal = 0;
			var demage_pv = 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('.demage_pv').each(function( index ) {
				demage_pv+=Number($(this).val());
			  });
			  
			 thistable.find('.tqnty_pv').val(qtyTotal);
			 thistable.find('.tfresh_pv').val(freshTotal);
			 thistable.find('.treprocess_pv').val(seconds);
			 thistable.find('.tdemage_pv').val(demage_pv);
	
});

$(".sizechartdiv tbody tr th,.pendingQuanList tbody tr th, .closediv").on("click", function(e){
	e.preventDefault();
	$('.sizechartdiv, .rmchartdiv, .pendingQuanList').hide();
});	


$('.rmset').dblclick(function(e) {
	
    var rmChart = $(this).attr('rmChartId');
	var pos = $(this).position();
	$('.rmchartdiv').hide();
	if($('#'+rmChart).is(':visible'))
	{
		$('#'+rmChart).slideUp();
	}
	else
	{	
	$('#'+rmChart).css({'left':pos.left-50,'top':pos.top+25}).slideDown();
	}
	
});

$('.rmchartdiv table th').click(function(e) {
	$(this).closest('.rmchartdiv').hide();
});



		
		/*$('body').on('blur','.fresh_pv',function(){
			var currBlur = $(this);
			var tr = currBlur.closest('tr');
			if(tr.find('.fresh_pv').val()>0){
			var reprocess_pv =  Number(tr.find('.qnty_pv').val()) - $(this).val() ;
			tr.find('.reprocess_pv').val(reprocess_pv);
			}
			});*/
			
			/*$('body').on('blur','.reprocess_pv',function(){
			var currBlur = $(this);
			var tr = currBlur.closest('tr');
			if(tr.find('.fresh_pv').val()>0){
			var demage_pv =  Number(tr.find('.qnty_pv').val()) - Number(tr.find('.fresh_pv').val()) - $(this).val() ;
			tr.find('.demage_pv').val(demage_pv);
			}
			});*/
		
		
		$('body').on('change','.qnty_pv,.fresh_pv,.reprocess_pv,.demage_pv', function() {
			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 reprocess = Number(tr.find('.reprocess_pv').val());
			var damage = Number(tr.find('.demage_pv').val());
			var total = Number(tr.find('.qnty_pv').val());
			
			total = fresh + reprocess + damage;
			
			tr.find('.qnty_pv').val(total);
			
			table.find('.fresh_pv').each(function( index ) {
				freshTotal+=Number($(this).val());
			  });
			  
			  table.find('.reprocess_pv').each(function( index ) {
				reprocessTotal+=Number($(this).val());
			  });
			  
			  table.find('.demage_pv').each(function( index ) {
				damageTotal+=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(reprocessTotal);
			  table.find('.tdemage_pv').val(damageTotal);
			  
			  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').val(reprocessTotal);
					tr.find('.demage').val(damageTotal);
				}
			  });
			
		});

}



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 totcgst=0;
var totsgst=0;
var vat=0;
var servicetax=0;




    $('.amount').each(function(i){

        price = $(this).val();

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

    });	

	

	$('.scost').each(function(i){

        price = $(this).val();

        if (!isNaN(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.
	
	var cmp = $('#cmpgstin').val();
	var scode = $('#gstin').val();
	if (((cmp.substr(0,2))==(scode.substr(0,2))) || (scode == ''))
	{
	totcgst=(Number(pnetamount)* Number($('#tpercgst').val()*0.01));

	totcgst=Math.round(totcgst);

	$('#totcgst').val(totcgst.toFixed(2));
	
	
	totsgst=(Number(pnetamount)* Number($('#tpersgst').val()*0.01));

	totsgst=Math.round(totsgst);

	$('#totsgst').val(totsgst.toFixed(2));
	}
	else
	{

	vat=(Number(pnetamount)* Number($('#pervat').val()*0.01));

	vat=Math.round(vat);

	$('#vat').val(vat.toFixed(2));
	}

	

	servicetax=4.8*Number(snetamount)*.01;

	servicetax=Math.round(servicetax);

	$('#servicetax').val(servicetax.toFixed(2));

       

	//$('#servicetax').val('0.00');



	var grtotal=Number(pnetamount)+Number(vat)+Number(totcgst)+Number(totsgst);

	grtotal=Math.round(grtotal);

	$('#grtotal').val(grtotal.toFixed(2));

}



function validate_form()

{

	if($.trim($('#refnodate').val())=="")
		{
			jSuccess("Blank Ref Date");
			$('#refnodate').focus();
			return false;
		}
		else if($.trim($('#challan').val())=="")
		{
			jSuccess("Blank Challan no");
			$('#challan').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;

		

	}


function add_del_row(){
			


		$('body').on('keydown','table#msview  tbody tr textarea',function(e)
		{
			var tr = $(this).closest('tr');
			 if(e.altKey &&  e.which == 65)
			 {
				e.preventDefault();
				  var prot = $("#prototype").clone();
				  prot.attr("id", "")
				  tr.after(prot);	
			 }
		  });

			


		$('body').on('keydown','table#msview  tbody tr textarea',function(e)
		{
			var tr = $(this).closest('tr');
		  if(e.altKey &&  e.which == 88)
		  {
			e.preventDefault();
			tr.remove();
			
		  }
  			});

		}





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;

}