
<?php 
$PageName = 'MaterialReceiptNote';
$url_cancel= "index.php?route=Inventory/transation/material_receipt_note_index".$rurl;
$url_add= "index.php?route=Inventory/transation/material_receipt_note_add".$rurl;
//************INSERT RECORD HERE******START HERE**********14-06-2013***********AS**********************************

$sql_user_store="select hmis_storeid,StoreCode from www_users left join storetype on storetype.id=www_users.hmis_storeid where www_users.id='".$_SESSION['UserID']."'";
$result_user_store=DB_query($sql_user_store,$db);
$rs_user_store=DB_fetch_array($result_user_store);
$main_store=$rs_user_store[0];


$sql_other_store="select store_id,StoreCode from www_users_dtls left join storetype on storetype.id=www_users_dtls.store_id where user_id='".$_SESSION['UserID']."'";
$result_other_store=DB_query($sql_other_store,$db);
while($rs_other_store=DB_fetch_array($result_other_store))
{
  $store[]=$rs_other_store['store_id'];
}
if(!empty($store))
{
  $get_store_id=implode(",",$store);
}


if($_REQUEST['save'])
{
	 date_default_timezone_set('Asia/Calcutta');
	$data['Po_category']=$_REQUEST['Pocategory'];
	$data['DocumentType'] = $_REQUEST['DocumentType'];
	$data['BillNo'] = $_REQUEST['billno'];  
	$data['ReceivedFrom'] = $_REQUEST['vendor'];
	$data['MRNVoucherDate'] = FormatDateForSQL($_REQUEST['MRNVoucherDate']); 
	$data['GetPassNo'] = $_REQUEST['gatepassno']; 
	$data['gatepassdate'] = FormatDateForSQL($_REQUEST['gatepassdate']);
	$data['VehicleNo'] = $_REQUEST['vehicalno']; 
	$data['TimeIn'] = $_REQUEST['timein']; 
	$data['Timeout'] = $_REQUEST['timeout']; 
	$data['MRNDate']=FormatDateForSQL($_REQUEST['MRNdate']);
	$data['LRno'] = $_REQUEST['lrno'];
	$data['LRdate']  =FormatDateForSQL($_REQUEST['lrdate']);

	$data['form_type'] = $_REQUEST['form_type'];
	$data['form_no'] = $_REQUEST['form_no'];
	$data['Transp_name'] = $_REQUEST['transport'];
	$data['RemarksIfAny'] = $_REQUEST['RemarksIfAny']; 		
	$data['totalBillQty'] = $_REQUEST['totalBillQty'];
    $data['totalRecQty'] = $_REQUEST['totalRecQty'];
	$data['Modified_by'] =$_SESSION['UserID'];
	$data['Modified_date'] =date('Y-m-d');
	$data['totalamount']=$_REQUEST['totalitemamount'];   
	$data['transaction_time']         =FormatDateForSQL($_REQUEST['MRNdate'])." ".date('H:i:s', time());
	
	 $cond="id='".$_REQUEST['mrnid']."'";
       // echo '<pre/>';
       // print_r($data); exit;
	$s->RecordEdit('addmrn',$data,$cond);
	$Lastreq_id=$_REQUEST['mrnid'];
	
	
	$countval= count($_REQUEST['itemcode']);
	$total_basic_amount=0;
	$total_tax_amount=0;	
	$coldata1=0;
	$numdata1=0;
	
	//print_r($_REQUEST['mst_itemid']);exit;
	$delete=DB_query("delete from addmrnqty where issue_id='".$_REQUEST['mrnid']."'",$db);


	 $result = DB_query("select pending_qty,against_tra_id from stock_valuation_tbl where against_voucher_main_id = '".$_REQUEST['mrnid']."' and type='MRN'",$db);
     
     $data = DB_fetch_array($result);
     $pendingqty =  $s->getField('stock_valuation_tbl','id',$data['against_tra_id'],'pending_qty');
     $totalqty=$pendingqty+$data['pending_qty'];
     Db_query("Update stock_valuation_tbl set pending_qty='".$totalqty."',flag=0 where id='".$data['against_tra_id']."'",$db);
     DB_query("delete from stock_valuation_tbl where against_voucher_main_id='".$_REQUEST['mrnid']."' and type='MRN'",$db);
               




	
	for($i=0;$i<count($_REQUEST['mst_itemid']);$i++)
	{
		if($_REQUEST['mst_itemid'][$i]!='')
		{	 

		 $data= DB_query("SELECT pending_qty,against_tra_id FROM `stock_valuation_tbl` WHERE against_voucher_main_id='".$_REQUEST['mrnid']."' AND mst_itemid='".$_POST['mst_itemid'][$i]."'",$db);
         
         $pendigresult=  DB_fetch_array($data);
         $lastpendingqty=$pendigresult['pending_qty'];
         $againsttraid=$pendigresult['against_tra_id'];
         $pendingqty1 = $s->getField('stock_valuation_tbl','id', $againsttraid,'pending_qty');
         $newpendingqty = $pendingqty1+$lastpendingqty;
           
           DB_query("UPDATE stock_valuation_tbl SET pending_qty='".$newpendingqty."' WHERE id='".$againsttraid."'",$db);



			//$delete=DB_query("delete from stock_valuation_tbl where against_voucher_main_id='".$_REQUEST['mrnid']."' and type='MRN'",$db);


			$data_arr['issue_id']           =$Lastreq_id;
			//$data_arr['issue_qty']          =$_POST['issuebalanc'][$i];
            $data_arr['mst_unitid']         =$_REQUEST['unit'][$i];
            $data_arr['mst_sec_unitid']         =$_REQUEST['unit2'][$i];

            $data_arr['mst_itemid']         =$_POST['mst_itemid'][$i];
			$data_arr['POQty']              =$_REQUEST['poqty'][$i];
        	$data_arr['qty_as_per_bill']    =$_REQUEST['qty_as_per_bill'][$i];
            
			$data_arr['reciveqty']          =$_REQUEST['reciveqty'][$i];
            $data_arr['stock_qty2']         =$_REQUEST['reciveqty2'][$i];
           
            $data_arr['qty_type']           =$_REQUEST['qty_type'][$i]; 
			$data_arr['short_accessid']     =$_REQUEST['short_qty'][$i];
			$data_arr['batch_no']           =$_REQUEST['batch_no'][$i];    
			$data_arr['mfg']                =FormatDateForSQL($_REQUEST['mfg'][$i]);  
            $data_arr['expiry']             =FormatDateForSQL($_REQUEST['expiry'][$i]);           
            $data_arr['minSign']            =$_REQUEST['minSign'][$i];
           
            $data_arr['conv_fac']           =$_REQUEST['conv_fac'][$i];
            $data_arr['mrprate']            =$_REQUEST['mrprate'][$i];
			if($_REQUEST['receiviedagaist']=='Indent')
			$data_arr['grn_type']           ='Indent';
			else
			$data_arr['grn_type']           ='Indirect';							
			if($_REQUEST['short_qty'][$i]!=0)
			$data_arr['status']            ="N";
			else
			$data_arr['status']            ="Y";	

		    $data_arr['free_qty']            =$_REQUEST['freeqty'][$i];	
		//echo "<pre>";
		//print_r($data_arr);

			$s->RecordInsert('addmrnqty', $data_arr);		

          $dtls_Lastreq_id=DB_Last_Insert_ID($db,'addmrnqty',$ErrMsg);

	    /* ######################################### Stock Valuation ################################################### */      

	   


          
          $data_stock['site']                     =$_REQUEST['sitecode'];
          $data_stock['store']                    =$_REQUEST['storecode'];
          $data_stock['mst_itemid']               =$_POST['mst_itemid'][$i];
         
          $data_stock['primary_unit']             =$_REQUEST['unit'][$i];
          $data_stock['secondary_unit']           =$_REQUEST['unit2'][$i];
          $data_stock['against_voucher_main_id']  =$Lastreq_id;
          $data_stock['against_voucher_dtls_id']  =$dtls_Lastreq_id;
          $data_stock['type']                     ='MRN';    
          
          $data_stock['inwardqty_primary']        =$_REQUEST['reciveqty'][$i];
          $data_stock['inwardqty_secondary']      =$_REQUEST['reciveqty2'][$i];
          $data_stock['pending_qty']              =$_REQUEST['reciveqty'][$i];
          $data_stock['trasaction']               =FormatDateForSQL($_REQUEST['MRNdate'])." ".date('H:i:s', time());
          $data_stock['batch_no']                 =$_REQUEST['batch_no'][$i];
		  $data_stock['inward_rate']             = $_REQUEST['mrprate'][$i];
          $data_stock['date_of_mfg']              =FormatDateForSQL($_REQUEST['mfg'][$i]);
          $data_stock['date_of_expiry']           =FormatDateForSQL($_REQUEST['expiry'][$i]);
		  
          $s->RecordInsert('stock_valuation_tbl', $data_stock);
            
    
      
      /************************************UPDATE MRN DETAILS TBL**************************************/	
                     
                         $reciveqty_name='reciveqty' ;
                        
			
			if($_REQUEST['receiviedagaist']=='PO')
			{
                 
				if($_REQUEST[$reciveqty_name][$i]>=$_REQUEST['pending_qty'][$i])
				{
                $updatePO=DB_query("Update purchorderdetails set status='received' where 
				parantId='".$_REQUEST['PONo']."' and mst_itemid='".$_REQUEST['mst_itemid'][$i]."' and mst_unitid='".$_REQUEST['unitid'][$i]."'",$db);					
				}
				else
				{
					
				  $updatePO=DB_query("Update purchorderdetails set status='Pending' where 
				parantId='".$_REQUEST['PONo']."' and mst_itemid='".$_REQUEST['mst_itemid'][$i]."' and mst_unitid='".$_REQUEST['unitid'][$i]."'",$db);	
				}
			}
			                       
				
			
			if($_REQUEST['receiviedagaist']=='Indent')
			{
				
				if($_REQUEST[$reciveqty_name][$i]>=$_REQUEST['pending_qty'][$i])
				{
					
					$updatePO=DB_query("Update requisitionorderdetails set mrn_status='received' where 
				requsitionno='".$_REQUEST['PONo']."' and mst_itemid='".$_REQUEST['mst_itemid'][$i]."' and  uom='".$_REQUEST['unitid'][$i]."' ",$db);					
				}
				else
				{
				 $updatePO=DB_query("Update requisitionorderdetails set mrn_status='Pending' where 
				requsitionno='".$_REQUEST['PONo']."' and mst_itemid='".$_REQUEST['mst_itemid'][$i]."' and uom='".$_REQUEST['unitid'][$i]."'",$db);	
				}
			}
         
    }
   } 
 
   if($_REQUEST['receiviedagaist']=='PO')
	{
		$get_num_rows=DB_query("Select * from purchorderdetails where parantId='".$_REQUEST['PONo']."'",$db);
		$num_rows=DB_num_rows($get_num_rows);				
		$check_item_stat=DB_query("Select * from purchorderdetails where parantId='".$_REQUEST['PONo']."'
		and status='received'",$db);
		$received_num_rows=DB_num_rows($check_item_stat);
		
		if($num_rows==$received_num_rows)
		{
			$updatePOStat=DB_query("Update purchorders set Po_recive_status='Receive' where 
			id='".$_REQUEST['PONo']."'",$db);
		}
		else
		{
			
			$updatePOStat=DB_query("Update purchorders set Po_recive_status='Pending' where 
			id='".$_REQUEST['PONo']."'",$db);
		}
	}
	
	
	if($_REQUEST['receiviedagaist']=='Indent')
	{
		$get_num_rows=DB_query("Select * from requisitionorderdetails where requsitionno='".$_REQUEST['PONo']."'",$db);
		$num_rows=DB_num_rows($get_num_rows);				
		$check_item_stat=DB_query("Select * from requisitionorderdetails where requsitionno='".$_REQUEST['PONo']."'
		and mrn_status='received'",$db);
		$received_num_rows=DB_num_rows($check_item_stat);
		
		if($num_rows==$received_num_rows)
		{
			$updatePOStat=DB_query("Update materialrequisitions set MRN_Receive_status='1' where 
			requisitionno='".$_REQUEST['PONo']."'",$db);
		}
		else
		{
			$updatePOStat=DB_query("Update materialrequisitions set MRN_Receive_status='0' where 
			requisitionno='".$_REQUEST['PONo']."'",$db);

		}
	}
   
	//exit;
	$_SESSION['success_msg']="Saved Successfully";
	$s->pageLocation("index.php?route=Inventory/transation/material_receipt_note_index".$rurl);
}




//************INSERT RECORD HERE******END HERE**********14-06-2013***********AS**********************************

$mrn_query = "select * from addmrn where id='".$_REQUEST['mrnid']."'";
		$mrn_query_res = DB_query($mrn_query,$db) or die(DB_error());
		$mrn_query_result = DB_fetch_assoc($mrn_query_res);
?>

<!-------------------------------------------JS PART START HERE--------------AS---------14-06-2013----------------><div id="PickedItems" style="display:none"></div>
<script type="text/javascript">
function calculateTaxable(i1)
{
   var id=i1.split("_");
   var i=id[2];
   
		var exciseValue=document.getElementById("exciseValue_"+i).value;
		var ECessValue=document.getElementById("ECessValue_"+i).value;
		var SAHCessValue=document.getElementById("SAHCessValue_"+i).value;		
		if(exciseValue==''){exciseValue=0;}
		if(ECessValue==''){ECessValue=0;}
		if(SAHCessValue==''){SAHCessValue=0;}
		var TOTAL=parseFloat(exciseValue)+parseFloat(ECessValue)+parseFloat(SAHCessValue);
		document.getElementById("taxable_amt_"+i).value=TOTAL.toFixed(2);
}
<!--------------------------------------------INPORT ORDER CALCULATION PART---------------------------------------------------------------------->


function GetStore(str)
{
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		document.getElementById("storecode").innerHTML=xmlhttp.responseText;
	}
	}
	xmlhttp.open("GET","ajax_getstore.php?branchcode="+str,true);
	xmlhttp.send();
}

function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : event.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       } 
function ChkGRNType(str)
{
	if (str=='Indent')
	{
		//$(".sh").hide();
		document.getElementById("poname").innerHTML="";
		document.getElementById("inprno").innerHTML="";
		return;
	}
	else
	{
		//$(".sh").show();
	}
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		var data=xmlhttp.responseText.split("__");
		document.getElementById("GtT1").innerHTML=data[0];
		document.getElementById("GtT2").innerHTML=data[1];
		document.getElementById("GtT3").innerHTML=data[2];
		document.getElementById("GtT4").innerHTML=data[3];
		document.getElementById("GtT5").innerHTML=data[4];
		document.getElementById("GtT6").innerHTML=data[5];
	}
	}
	xmlhttp.open("GET","ajax_get_chechgrntype.php?GRNTYPE="+str,true);
	xmlhttp.send();
}


function GetIndentPONo(str)
{
	if (str.length==0)
	  {
	  document.getElementById("poname").innerHTML="";
		document.getElementById("inprno").innerHTML="";
	  return;
	  }
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		var data=xmlhttp.responseText.split("__");
		document.getElementById("poname").innerHTML=data[0];
		document.getElementById("inprno").innerHTML=data[1];
	}
	}
	var site=document.getElementById("sitecode").value;
	var receag=document.getElementById("receiviedagaist").value;
	var purtype=document.getElementById("PoType").value;
	xmlhttp.open("GET","ajax_get_indent_po_no.php?supplierId="+str+"&ReciveAng="+receag+"&POType="+purtype+"&Branch="+site,true);
	xmlhttp.send();
}


function GetPODetails(str)
{
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		var data=xmlhttp.responseText.split("__");
		document.getElementById("alldatadetails").innerHTML=data[0];
		document.getElementById("basicamtdetails").innerHTML=data[1];
	}
	}
	var purtype=document.getElementById("PoType").value;
	xmlhttp.open("GET","ajax_getpodetails.php?POID="+str+"&POType="+purtype,true);
	xmlhttp.send();
}




function check_bill_qty(str,id)
{
  var iddata=id1.split("_");
  var id=idata[1];
	var poqty=parseInt(document.getElementById("pending_qty_"+id).value);
	var tolerance = document.getElementById("tolerance_"+id).value;
	if(tolerance==''){tolerance=0;}
	str1=parseInt(str);
	if(poqty!='')
	{
	var qty=(poqty*tolerance)/100;
	var poqty1=parseInt(poqty)+parseInt(qty);
	//var poqty2=poqty-qty;	
	if(str1>poqty1)
	{
		var altmsg = "Quantity As Per Bill Cannot Be Greater Than "+tolerance+" % more of PO Quantity";
		alert(altmsg);
		document.getElementById("qtyasper_bill_"+id).value='';
		document.getElementById("qty_received_"+id).value='';
		document.getElementById("qtyasper_bill_"+id).focus();
		return false;
	}
	}
}



function check_po_qty1(k)
{
 var k1=k.split("_");
 var i=k[1];
	var poqty=parseInt(document.getElementById("pending_qty_"+i).value);
	var str=parseInt(document.getElementById("qty_received_"+i).value);
	var tolerance = document.getElementById("tolerance_"+i).value;
	if(tolerance==''){tolerance=0;}
	str1=parseInt(str);
	if(poqty!='')
	{
	var qty=(poqty*tolerance)/100;
	var poqty1=parseInt(poqty)+parseInt(qty);
	//var poqty2=poqty-qty;	
	if(str1>poqty1)
	{
		var altmsg = "QTY Received Cannot Be Greater Than "+tolerance+" % more of PO Quantity";
		alert(altmsg);
		document.getElementById("qty_received_"+i).value='';
		document.getElementById("qty_received_"+i).focus();
		return false;
	}
	}
}


function calculate_poshort(id1)
{	var i=id1.split("_");
var id=i[2];

	var qty_per_bill=parseInt(document.getElementById("qtyasper_bill_"+id).value);
	var reciveqty=parseInt(document.getElementById("qty_received_"+id).value);	
	if(document.getElementById("qty_received_"+id).value=='')
	{
	var reciveqty=0;	
	}
	else
	{
	var reciveqty=parseInt(document.getElementById("qty_received_"+id).value);	
	}
	var short_accessid=qty_per_bill-reciveqty;
	if(short_accessid<0){short_accessid=0;}
	document.getElementById("short_qty_"+id).value=short_accessid;
}


function calc_total_price(str1)
{
   var id=str1.split("_");
   var str=id[1];
	var item_total_rate=0;
	var reciveqty = document.getElementById("qty_received_"+str).value;
	var itemrate=document.getElementById("Rate_"+str).value;
		
	if(reciveqty!='' && itemrate!='')
	{
		document.getElementById("totalValue_"+str).value=(parseFloat(reciveqty)*parseFloat(itemrate)).toFixed(2);
	}
}

function DiscountAmount(DA,i1)
{
  var str=i1.split("_");
  var i=str[1];
		var discount_percent = document.getElementById("PerAmo_"+i).value;
		var rate = document.getElementById("Rate_"+i).value;
		var discount = document.getElementById("Discount_"+i).value;
		var quantity = document.getElementById("qty_received_"+i).value;
		var totalPrice = parseFloat(quantity)*parseFloat(rate);
		if(discount_percent=='PercentAmt')
		{
		if(discount==''){discount=0;}
		var percent = parseFloat(totalPrice) * parseFloat(discount)/100;
		var subTotal = parseFloat(totalPrice)-parseFloat(percent);
		}
		else if(discount_percent=='Amount')
		{ 
		var percent = parseFloat(document.getElementById("Discount_"+i).value);
		if(isNaN(percent)){percent=0;}
		var subTotal = totalPrice-parseFloat(percent);
		}
		document.getElementById("perc_"+i).value=percent.toFixed(2);
		document.getElementById("NetRate_"+i).value=subTotal.toFixed(2);
		//document.getElementById("basic_"+i).value=subTotal.toFixed(2);
}




function CustomDutyType(val,i)
{
		if(document.getElementById("cuntomDuty_Flag_"+i).value=='2')
		{
			document.getElementById("Custon_Duty_"+i).value=''; 
			document.getElementById("CustomDutyAmt_"+i).value=''; 
			document.getElementById("Custon_Duty_"+i).disabled=true; 
			document.getElementById("CustomDutyAmt_"+i).disabled=true; 
		}
		else
		{
			document.getElementById("Custon_Duty_"+i).value=document.getElementById("custonduty1_"+i).value; 
			document.getElementById("CustomDutyAmt_"+i).value=document.getElementById("custondutyamt1_"+i).value; 
			document.getElementById("Custon_Duty_"+i).disabled=false; 
			document.getElementById("CustomDutyAmt_"+i).disabled=false; 
		}
}




function cal_grandtotalImp(i1)
{
    var id=i1.split("_");
	var i=id[2]
	
		//var type_of_bill=document.getElementById("cuntomDuty_Flag_"+i).value;
		var basic=document.getElementById("basic_"+i).value;
		var Totaltaxable=document.getElementById("CustomDutyAmt_"+i).value;
		var Totaltaxable1=document.getElementById("TotalSpecial_"+i).value;
		var Totaltaxable2=document.getElementById("customecess_"+i).value;
		var Totaltaxable3=document.getElementById("customsececess_"+i).value;
		var Totaltaxable4=document.getElementById("adduty_"+i).value;
		
		if(basic==''){basic=0;}
		if(Totaltaxable1==''){Totaltaxable1=0;}
		if(Totaltaxable2==''){Totaltaxable2=0;}
		if(Totaltaxable3==''){Totaltaxable3=0;}
		if(Totaltaxable4==''){Totaltaxable4=0;}
		if(Totaltaxable==''){Totaltaxable=0;}
		
		var grand_tot1= parseFloat(basic)+parseFloat(Totaltaxable)+parseFloat(Totaltaxable1)+parseFloat(Totaltaxable2)
		+parseFloat(Totaltaxable3)+parseFloat(Totaltaxable4);
		var grand_tot=grand_tot1.toFixed(2);
		
		
		document.getElementById("TotalSpecial_amt_"+i).value=grand_tot;
}


function cal_totalamount_count()
{
	var total=0;
	var t=document.getElementById("conterimp").value;
	
	for(var i=0;i<t;i++)
	{   
	    if(document.getElementById("TotalSpecial_amt_"+i))
		var amt=parseFloat(document.getElementById("TotalSpecial_amt_"+i).value);
		else
		var amt=0;
		
		total=parseFloat(total)+amt;	
	}	
	var fintotal=parseFloat(total);
	document.getElementById("total_item_amount").value=fintotal.toFixed(2);	
	
	
	var hdcnt=document.getElementById("conterimp").value;
	var flag1=0;
	if(hdcnt!='')
	{
		for(var j=0;j<hdcnt;j++)
		{   
		    if(document.getElementById("cuntomDuty_Flag_"+j))
			{
			if(document.getElementById("cuntomDuty_Flag_"+j).value==1)
			{
				flag1=1;
			}
			}
		}
	}	
	if(flag1==1)
	{
		document.getElementById("CustomDuty").disabled=true;
	}
	else
	{
		document.getElementById("CustomDuty").disabled=false;
	}

}




function cal_totalamount_consoliedate()
{
	var total=0;
	var t=document.getElementById("conterimp").value;
	
	for(var i=0;i<t;i++)
	{   
	    if(document.getElementById("basic_"+i))
		var amt=parseFloat(document.getElementById("basic_"+i).value);
		else
		var amt=0;
		
		total=parseFloat(total)+amt;	
	}	
	var fintotal=parseFloat(total);
	document.getElementById("total_item_amount").value=fintotal.toFixed(2);	
	
	
	var hdcnt=document.getElementById("conterimp").value;
	var flag1=0;
	if(hdcnt!='')
	{
		for(var j=0;j<hdcnt;j++)
		{   
		    if(document.getElementById("cuntomDuty_Flag_"+j))
			{
			if(document.getElementById("cuntomDuty_Flag_"+j).value==1)
			{
				flag1=1;
			}
			}
		}
	}	
	if(flag1==1)
	{
		document.getElementById("CustomDuty").disabled=true;
	}
	else
	{
		document.getElementById("CustomDuty").disabled=false;
	}

}

function cal_totalamount()
{

   if(document.getElementById("PoType").value=='DO' && document.getElementById("dutytype").value=='Itemwise')
   {
	var total=0;
	var t=document.getElementById("conterimp").value;
	
	for(var i=0;i<t;i++)
	{   
	    if(document.getElementById("basic_"+i))
		var amt=parseFloat(document.getElementById("basic_"+i).value);
		else
		var amt=0;
		
		total=parseFloat(total)+amt;	
	}	
	var fintotal=parseFloat(total);
	document.getElementById("total_item_amount").value=fintotal.toFixed(2);	
	
	
	var hdcnt=document.getElementById("conterimp").value;
	var flag1=0;
	if(hdcnt!='')
	{
		for(var j=0;j<hdcnt;j++)
		{   
		    if(document.getElementById("cuntomDuty_Flag_"+j))
			{
			if(document.getElementById("cuntomDuty_Flag_"+j).value==1)
			{
				flag1=1;
			}
			}
		}
	}	
	if(flag1==1)
	{
		document.getElementById("CustomDuty").disabled=true;
	}
	else
	{
		document.getElementById("CustomDuty").disabled=false;
	}
	
	
	}
	
	else
	{
	
	var total=0;
	var t=document.getElementById("conterimp").value;
	
	for(var i=0;i<t;i++)
	{   
	    if(document.getElementById("TotalSpecial_"+i))
		var amt=parseFloat(document.getElementById("TotalSpecial_"+i).value);
		else
		var amt=0;
		
		total=parseFloat(total)+amt;	
	}	
	var fintotal=parseFloat(total);
	document.getElementById("total_item_amount").value=fintotal.toFixed(2);	
	
	
	var hdcnt=document.getElementById("conterimp").value;
	var flag1=0;
	if(hdcnt!='')
	{
		for(var j=0;j<hdcnt;j++)
		{   
		    if(document.getElementById("cuntomDuty_Flag_"+j))
			{
			if(document.getElementById("cuntomDuty_Flag_"+j).value==1)
			{
				flag1=1;
			}
			}
		}
	}	
	if(flag1==1)
	{
		document.getElementById("CustomDuty").disabled=true;
	}
	else
	{
		document.getElementById("CustomDuty").disabled=false;
	}
	
	
	}

}


function CalculateCustomDuty(id,val)
{
	
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		var data=xmlhttp.responseText.split("__");
		var k=data[0];
		document.getElementById("CustomDutyAmt_"+k).value=data[1];
	}
	}
	var id1=id.split("_");
	var i=id1[2];
	var basicamt=document.getElementById("basic_"+i).value;
	xmlhttp.open("GET","ajax_get_cutom_duty.php?ids="+id+"&vls="+val+"&bamt="+basicamt,true);
	xmlhttp.send();
}


function claculateExcisetotal(id,str)
{  
		var b=document.getElementById("total_item_amount").value;	 
	 
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
				var data=xmlhttp.responseText.split("__"); 
			 	document.getElementById("rateval").value=data[0];
				document.getElementById("custondutyval").value=data[1];
    		}
  		}
		xmlhttp.open("GET","ajax_calculate_customduty.php?quotTaxId="+str+"&data="+b,true);
		xmlhttp.send();


}


function cal_totalamountwithduty()
{
	var hdcnt=document.getElementById("conterimp").value;
	var chka=document.getElementById("CustomDuty").value;
	if(chka==0)
	{
		var total=0;
		for(var j=0;j<hdcnt;j++)
		{
			if(document.getElementById("CustomDutyAmt_"+j).value!='')
			{
				var amt=parseFloat(document.getElementById("CustomDutyAmt_"+j).value);
				total=parseFloat(total)+amt;	
			}
			else
			{
				total=0;
			}
		}
		total=total;
		document.getElementById("custondutyval").value=total.toFixed(2);		
	}
	else
	{
		var basic=document.getElementById("total_item_amount").value;
		var rate=document.getElementById("rateval").value;
		if(basic==''){basic=0;}
		var calexc=(basic*rate)/100;
		document.getElementById("custondutyval").value=calexc.toFixed(2);	
		
	}
}




function calsuroctamtipm(str)
{
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var amount=(amt*str)/100;
document.getElementById("insurancecharges_amt").value=amount.toFixed(2);	
}

function reversecalsuroctamt(str)
{ 
var amt=parseFloat(document.getElementById("total_item_amount").value); 
 var amount=(100*str)/amt;
 document.getElementById("insurancecharges").value=amount.toFixed(2);	
}
 
function caloverfreight(str)
{
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var amount=(amt*str)/100;
document.getElementById("overseasfrieght_amt").value=amount.toFixed(2);	
}

function reversecaloverfreight(str)
{ 
var amt=parseFloat(document.getElementById("total_item_amount").value);  
var amount=(100*str)/amt;
document.getElementById("overseasfrieght").value=amount.toFixed(2);	
}

function callocalfreight(str)
{
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var amount=(amt*str)/100;
document.getElementById("localfreight_amt").value=amount.toFixed(2);	
}

function reversecallocalfreight(str)
{ 
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var per=parseFloat(document.getElementById("localfreight").value); 
var amount=(100*str)/amt;
 document.getElementById("localfreight").value=amount.toFixed(2);	
}


function calclearingforwarding(str)
{
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var amount=(amt*str)/100;
document.getElementById("calclearingforwarding_amt").value=amount.toFixed(2);	
}

function reversecalclearingforwarding(str)
{ 
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var per=parseFloat(document.getElementById("clearingforwarding").value); 
var amount=(100*str)/amt;
 document.getElementById("clearingforwarding").value=amount.toFixed(2);	
}

function caldetetioncharges(str)
{
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var amount=(amt*str)/100;
document.getElementById("detetioncharges_amt").value=amount.toFixed(2);	
}

function reversecaldetetioncharges(str)
{ 
var amt=parseFloat(document.getElementById("total_item_amount").value); 
var per=parseFloat(document.getElementById("detetioncharges").value); 
var amount=(100*str)/amt;
 document.getElementById("detetioncharges").value=amount.toFixed(2);	
}




function cal_grandamountimp()
{
	
	var total=document.getElementById("total_item_amount").value;
	if(document.getElementById("custondutyval"))
	var cdis_amt=document.getElementById("custondutyval").value;
	else 
	var cdis_amt=0;
	var insurancecharges_amt=document.getElementById("insurancecharges_amt").value;
	var overseasfrieght_amt=document.getElementById("overseasfrieght_amt").value;
	var localfreight_amt=document.getElementById("localfreight_amt").value;
	var calclearingforwarding_amt=document.getElementById("calclearingforwarding_amt").value;	
	var detetioncharges_amt=document.getElementById("detetioncharges_amt").value;	
	var othercharges=document.getElementById("othercharges").value;	
	
	if(total==''){total=0;}
	if(cdis_amt==''){cdis_amt=0;}
	if(insurancecharges_amt==''){insurancecharges_amt=0;}
	if(overseasfrieght_amt==''){overseasfrieght_amt=0;}
	if(localfreight_amt==''){localfreight_amt=0;}
	if(calclearingforwarding_amt==''){calclearingforwarding_amt=0;}
	if(detetioncharges_amt==''){detetioncharges_amt=0;}	if(othercharges==''){othercharges=0;}
	 
	var grand=document.getElementById("GrandTotal").value;
	
	grandtotal=parseFloat(total)+parseFloat(cdis_amt)+parseFloat(insurancecharges_amt)+parseFloat(overseasfrieght_amt)+parseFloat(localfreight_amt)+parseFloat(calclearingforwarding_amt)+parseFloat(detetioncharges_amt)+parseFloat(othercharges);
document.getElementById("GrandTotal").value=grandtotal.toFixed(2);	
document.getElementById("orig_grand_tot").value=grandtotal.toFixed(2);	

}



function checkCustomtype(i)
{
	if(document.getElementById("cuntomDuty_Flag_"+i).value=='')
	{
		alert("please Select The Custom Duty Flag First !");
		return false;
	}
}


<!--------------------------------------------INPORT ORDER CALCULATION PART---------------------------------------------------------------------->




<!--------------------------------------------DOMESTIC ORDER CALCULATION PART---------------------------------------------------------------------->


function checkExcisable(str,i1)
{
 var t=i1.split("_");
 var i=t[2];
	if(str=='NonExcisable')
	{
		document.getElementById("exciseDuty_"+i).disabled=true;
		document.getElementById("exciseValue_"+i).disabled=true;
		document.getElementById("cess_ID1_"+i).disabled=true;
		document.getElementById("ECessValue_"+i).disabled=true;
		document.getElementById("cess_ID2_"+i).disabled=true;
		document.getElementById("SAHCessValue_"+i).disabled=true;
		document.getElementById("taxable_amt_"+i).disabled=true;
		
		
		document.getElementById("exciseDuty_"+i).value='0';
		document.getElementById("exciseValue_"+i).value='';
		document.getElementById("cess_ID1_"+i).value='';
		document.getElementById("ECessValue_"+i).value='';
		document.getElementById("cess_ID2_"+i).value='';
		document.getElementById("SAHCessValue_"+i).value='';
		document.getElementById("taxable_amt_"+i).value='';
	}
	else if(str=='Excisable' || str==0)
	{
	   
		document.getElementById("exciseDuty_"+i).disabled=false;
		document.getElementById("exciseValue_"+i).disabled=false;
		document.getElementById("cess_ID1_"+i).disabled=false;
		document.getElementById("ECessValue_"+i).disabled=false;
		document.getElementById("cess_ID2_"+i).disabled=false;
		document.getElementById("SAHCessValue_"+i).disabled=false;
		document.getElementById("taxable_amt_"+i).disabled=false;	
	}
	else
	{
		document.getElementById("exciseDuty_"+i).disabled=true;
		document.getElementById("exciseValue_"+i).disabled=true;
		document.getElementById("cess_ID1_"+i).disabled=true;
		document.getElementById("ECessValue_"+i).disabled=true;
		document.getElementById("cess_ID2_"+i).disabled=true;
		document.getElementById("SAHCessValue_"+i).disabled=true;
		document.getElementById("taxable_amt_"+i).disabled=true;
		
		
		document.getElementById("exciseDuty_"+i).value='0';
		document.getElementById("exciseValue_"+i).value='';
		document.getElementById("cess_ID1_"+i).value='';
		document.getElementById("ECessValue_"+i).value='';
		document.getElementById("cess_ID2_"+i).value='';
		document.getElementById("SAHCessValue_"+i).value='';
		document.getElementById("taxable_amt_"+i).value='';
	}
	document.getElementById(i1).value=str;
}



function claculateExcise(id,val)
{
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		var data=xmlhttp.responseText.split("__");
		var k=data[0];
		document.getElementById("exciseValue_"+k).value=data[1];
	}
	}
	var id1=id.split("_");
	var i=id1[1];
	var basicamt=document.getElementById("basic_"+i).value;
	xmlhttp.open("GET","ajax_getexcisevalue.php?ids="+id+"&vls="+val+"&bamt="+basicamt,true);
	xmlhttp.send();
}


function checkexiseflag(i1)
{
   var t=i1.split("_");
   var i=t[1];
		if(document.getElementById("hid_billingtype_"+i).value=='')
		{
			alert("Select Tax Type");
			document.getElementById("hid_billingtype_"+i).focus();
		}	
}



function calEcessonchange(id,val)
{
	
	
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		var data=xmlhttp.responseText.split("__");
		var k=data[0];
		document.getElementById("ECessValue_"+k).value=data[1];
	}
	}
	var id1=id.split("_");
	var i=id1[2];
	var ecessval=document.getElementById("exciseValue_"+i).value;
	xmlhttp.open("GET","ajax_ecesscalculation.php?ids="+id+"&vls="+val+"&Ecessval="+ecessval,true);
	xmlhttp.send();
}



function calSHEcessonchange(id,val)
{
	
	
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		var data=xmlhttp.responseText.split("__");
		var k=data[0];
		document.getElementById("SAHCessValue_"+k).value=data[1];
	}
	}
	var id1=id.split("_");
	var i=id1[2];
	var ecessval=document.getElementById("exciseValue_"+i).value;
	xmlhttp.open("GET","ajax_ecesscalculation.php?ids="+id+"&vls="+val+"&Ecessval="+ecessval,true);
	xmlhttp.send();
}





function cal_grandtotal(i1)
{
   var t=i1.split("_");
   var i=t[1];
		var type_of_bill=document.getElementById("hid_billingtype_"+i).value;
		var basic=document.getElementById("basic_"+i).value;
		var Totaltaxable=document.getElementById("taxable_amt_"+i).value;
		if(basic==''){basic=0;}
		if(Totaltaxable==''){Totaltaxable=0;}
		if(document.getElementById("hid_billingtype_"+i).value=='NonExcisable')
		{
		var grand_tot1=parseFloat(basic);
		var grand_tot=grand_tot1.toFixed(2);
		}	
		else if(document.getElementById("hid_billingtype_"+i).value=='IncludeTax'){
		var grand_tot1= parseFloat(basic) ;
		var grand_tot=grand_tot1.toFixed(2);
		}
		else
		{
		var grand_tot1= parseFloat(basic)+parseFloat(Totaltaxable);
		var grand_tot=grand_tot1.toFixed(2);
		}
		document.getElementById("TotalSpecial_"+i).value=grand_tot;
}



function calcPackaging(str)
{
	if(str!='')
	{
		var tota_amt=document.getElementById("total_item_amount").value;
		var pckgng_val=(str/100)*tota_amt;
		document.getElementById("pkg_charges1").value=pckgng_val.toFixed(2);
	}
}



function tax_rate1(str)
{
	var taxableAmount=document.getElementById("total_item_amount").value;
	var taxableAmount1=document.getElementById("pkg_charges1").value;
	if(taxableAmount1==''){taxableAmount1=0;}
	var taxableAmount2=parseFloat(taxableAmount)+parseFloat(taxableAmount1);
	if (str.length==0)
	{
	document.getElementById("taxval").innerHTML="";
	return;
	}
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
	document.getElementById("taxval").innerHTML=xmlhttp.responseText;
	}
	}
	xmlhttp.open("GET","get_tax_valdata.php?taxid="+str+"&amt="+taxableAmount2,true);
	xmlhttp.send();
}


function calsuroctamt(str)
{
var amt=parseFloat(document.getElementById("taxvalue").value);
var	suroctper=parseFloat(document.getElementById("sur_oct_per").value);
var amount=(amt*suroctper)/100;
document.getElementById("sur_oct_amt").value=amount.toFixed(2);	
}


function cal_grandamount()
{
	
	var total=document.getElementById("total_item_amount").value;
	var sur_oct_amt=document.getElementById("sur_oct_amt").value;
	var TotalCharge=document.getElementById("TotalCharge").value;
	var taxamt=document.getElementById("taxvalue").value;
	var packagingCharges=document.getElementById("pkg_charges1").value;
	var additionalCharges=document.getElementById("additionalCharges").value;	
	if(total==''){total=0;}
	if(sur_oct_amt==''){sur_oct_amt=0;}
	if(TotalCharge==''){TotalCharge=0;}
	if(packagingCharges==''){packagingCharges=0;}
	if(additionalCharges==''){additionalCharges=0;}
	if(taxamt==''){taxamt=0;}
	var grand=document.getElementById("GrandTotal").value;
	grandtotal=parseFloat(total)+parseFloat(sur_oct_amt)+parseFloat(TotalCharge)+parseFloat(packagingCharges)+parseFloat(additionalCharges)+parseFloat(taxamt);
	document.getElementById("GrandTotal").value=grandtotal.toFixed(2);	
	document.getElementById("orig_grand_tot").value=grandtotal.toFixed(2);	
}
function showResult(str)
{ 
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {  
    var data=xmlhttp.responseText.split("__");	
	//alert(data);
    document.getElementById("storecode").innerHTML=data['0'];
    document.getElementById("vendor").innerHTML=data['1'];
	
    }
  }

xmlhttp.open("GET","check_data_fin.php?section=showVendorMRN&site="+str,true);
xmlhttp.send();
}
function calculateBillQty(id)
{
    
    var total= 0;
    
    jQuery('input[id^=qtyasperbill]').each(function(){
         var amount = parseFloat(jQuery(this).val());
         if(!isNaN(amount))
            total+=parseFloat(amount);
    });
   document.getElementById(id).value=total.toFixed(2);
}
function calculateRecQty(id)
{
    
    var total= 0;
    
    jQuery('input[id^=reciveqty_]').each(function(){
         var amount = parseFloat(jQuery(this).val());
         if(!isNaN(amount))
            total+=parseFloat(amount);
    });
   document.getElementById(id).value=total.toFixed(2);
}
function calTotalQtyDirect(val,idd,obj)
{
    id1=idd.split("_");
    id=id1[1];
       //alert(id);
       var totalamt1=0;
        if(id==undefined)
           {
             //var qtyRec = document.getElementById("reciveqty").value;
             var qtyRec=$(obj).closest('tr').find('input[id=reciveqty]').val();
                
            // var qtyBill = document.getElementById("qtyasperbill").value;
             var qtyBill=$(obj).closest('tr').find('input[id=qtyasperbill]').val();
            
             if(qtyRec==''){qtyRec=0;}
             var confac=$(obj).closest('tr').find('input[id=convfac]').val();

             if(confac=='') confac=0;
             var secondaryqty=parseFloat(qtyRec)*parseFloat(confac);
             $(obj).closest('tr').find('input[id=reciveqty2]').val(secondaryqty.toFixed(2));

             if(parseFloat(qtyBill)>parseFloat(qtyRec))
             {
                var diff = parseFloat(qtyBill)-parseFloat(qtyRec);
                $(obj).closest('tr').find('input[id=shortaccessid]').val(diff.toFixed(2));
                //document.getElementById('minSign_'+id).style.display="block";
                 $(obj).closest('tr').find('input[id=minSign]').val('-');
                
             }
             if(parseFloat(qtyBill)<=parseFloat(qtyRec))
             { 
                var diff = parseFloat(qtyRec)-parseFloat(qtyBill);
                $(obj).closest('tr').find('input[id=shortaccessid]').val(diff.toFixed(2));
                 $(obj).closest('tr').find('input[id=minSign]').val('+');
                
             }
             
             var firstRow=$(obj).closest('tr').find('input[id=qtyasperbill]').val();
             if(firstRow=='') { firstRow=0; }
               var firstRow1= $(obj).closest('tr').find('input[id=reciveqty]').val();


             if(firstRow1=='') { firstRow1=0; }
             var totalamt=0;
              calculateBillQty('shortDirect');
              calculateRecQty('short1Direct');
            
            
             
              

             
             /*var poqty=parseInt($(obj).closest('tr').find('input[id=poqty').val());

             var tolerance= $(obj).closest('tr').find('input[id=tolerances').val()
             if(tolerance==''){tolerance=0;}
             if(poqty==''){poqty=0;}
             str1=parseInt(val);
             if(str1==''){str1=0;}
             if(tolerance=='')
             {
                 if(parseInt(poqty)<parseInt(str1))
                 {
                      alert('Bill Quantity Cannot Be Greater Than poqty Quantity');
                      $(obj).closest('tr').find('input[id=qtyasperbill').focus();
                      $(obj).closest('tr').find('input[id=qtyasperbill').val('');
                      return false;
                 }
             }
             else
             {
                var p1 = (tolerance*poqty)/100;
                var p2 = parseFloat(poqty)+parseFloat(p1);
                if(parseInt(p2)<parseInt(str1))
                {

                    alert('Bill Quantity Cannot Be Greater Then PO Quantity');
                    $(obj).closest('tr').find('input[id=qtyasperbill').focus();
                    $(obj).closest('tr').find('input[id=qtyasperbill').val('');
                    return false;
                 }
             }*/
        }
        else
            {
                    //var qtyRec = document.getElementById("reciveqty").value;
             var qtyRec=$(obj).closest('tr').find('input[id=reciveqty_'+id+"]").val();
                
            // var qtyBill = document.getElementById("qtyasperbill").value;
             var qtyBill=$(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").val();

               if(parseFloat(qtyRec)>parseFloat(qtyBill))
             {
                alert("Receive Quantity cannot be greater than Bill Quantity");
                $(obj).closest('tr').find('input[id=reciveqty_'+id+"]").val('0');
                //return false;
             }
            
             if(qtyRec==''){qtyRec=0;}
             var confac=$(obj).closest('tr').find('input[id=convfac_'+id+"]").val();

             if(confac=='') confac=0;
             var secondaryqty=parseFloat(qtyRec)*parseFloat(confac);
             $(obj).closest('tr').find('input[id=reciveqty2_'+id+"]").val(secondaryqty.toFixed(2));

             if(parseFloat(qtyBill)>parseFloat(qtyRec))
             {
                var diff = parseFloat(qtyBill)-parseFloat(qtyRec);
                $(obj).closest('tr').find('input[id=shortaccessid_'+id+"]").val(diff.toFixed(2));
                //document.getElementById('minSign_'+id).style.display="block";
                 $(obj).closest('tr').find('input[id=minSign_'+id+"]").val('-');
                
             }
             if(parseFloat(qtyBill)<=parseFloat(qtyRec))
             { 
                var diff = parseFloat(qtyRec)-parseFloat(qtyBill);
                $(obj).closest('tr').find('input[id=shortaccessid_'+id+"]").val(diff.toFixed(2));
                 $(obj).closest('tr').find('input[id=minSign_'+id+"]").val('+');
                
             }
             
             var firstRow=$(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").val();
             if(firstRow=='') { firstRow=0; }
               var firstRow1= $(obj).closest('tr').find('input[id=reciveqty_'+id+"]").val();


             if(firstRow1=='') { firstRow1=0; }
             var totalamt=0;
             //var countcharges =$(obj).closest('tr').find('input[id=hiditemcount_'+id+"]").val();
            calculateBillQty('shortDirect');
              calculateRecQty('short1Direct');
              

             
           //  var poqty=parseInt($(obj).closest('tr').find('input[id=poqty_'+id+"]").val());

            // var tolerance= $(obj).closest('tr').find('input[id=tolerances_'+id+"]").val()
           //  if(tolerance==''){tolerance=0;}
            // if(poqty==''){poqty=0;}
           // str1=parseInt(val);
           //  if(str1==''){str1=0;}
            
              //   if(parseInt(poqty)<parseInt(str1))
              //   {
                     // alert('Bill Quantity Cannot Be Greater Then PO Quantity');
                     // $(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").focus();
                     // $(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").val('');
                    // return false;
                // }
             
             

            }
}
function countPendingQty()
{
    var total= 0;
   
    jQuery('input[id^=qtyasperbill_]').each(function(){
         var amount = parseFloat(jQuery(this).val());
            total+=parseFloat(amount);
    });
    return total;
}
function calTotalQty1Direct(val,idd,obj)
{
    id1=idd.split("_");
    id=id1[1];
       //alert(id);
       var totalamt1=0;
        if(id==undefined)
           {
           	var count=countPendingQty();
             var pendings=document.getElementById('poqty1').value;
             if(count>pendings)
             {
                alert("Bill qty cannot greater then PO qty");
                return false;

             }
             //var qtyRec = document.getElementById("reciveqty").value;
             var qtyRec=$(obj).closest('tr').find('input[id=reciveqty]').val();
                
            // var qtyBill = document.getElementById("qtyasperbill").value;
             var qtyBill=$(obj).closest('tr').find('input[id=qtyasperbill]').val();
            
             if(qtyRec==''){qtyRec=0;}
             var confac=$(obj).closest('tr').find('input[id=convfac]').val();

             if(confac=='') confac=0;
             var secondaryqty=parseFloat(qtyRec)*parseFloat(confac);
             $(obj).closest('tr').find('input[id=reciveqty2]').val(secondaryqty.toFixed(2));

             if(parseFloat(qtyBill)>parseFloat(qtyRec))
             {
                var diff = parseFloat(qtyBill)-parseFloat(qtyRec);
                $(obj).closest('tr').find('input[id=shortaccessid]').val(diff.toFixed(2));
                //document.getElementById('minSign_'+id).style.display="block";
                 $(obj).closest('tr').find('input[id=minSign]').val('-');
                
             }
             if(parseFloat(qtyBill)<=parseFloat(qtyRec))
             { 
                var diff = parseFloat(qtyRec)-parseFloat(qtyBill);
                $(obj).closest('tr').find('input[id=shortaccessid]').val(diff.toFixed(2));
                 $(obj).closest('tr').find('input[id=minSign]').val('+');
                
             }
             
             var firstRow=$(obj).closest('tr').find('input[id=qtyasperbill]').val();
             if(firstRow=='') { firstRow=0; }
               var firstRow1= $(obj).closest('tr').find('input[id=reciveqty]').val();


             if(firstRow1=='') { firstRow1=0; }
             var totalamt=0;
              calculateBillQty('shortDirect');
              calculateRecQty('short1Direct');
            
            
             
              

             
             var poqty=parseInt($(obj).closest('tr').find('input[id=poqty').val());
             var freeqty=parseInt($(obj).closest('tr').find('input[id=freeqty').val());
             if(freeqty=='') { freeqty=0; }
             poqty=parseFloat(poqty)+parseFloat(freeqty);

             var tolerance= $(obj).closest('tr').find('input[id=tolerances').val()
             if(tolerance==''){tolerance=0;}
             if(poqty==''){poqty=0;}
             str1=parseInt(val);
             if(str1==''){str1=0;}
             if(tolerance=='')
             {
                 if(parseInt(poqty)<parseInt(str1))
                 {  

                      alert('Bill Quantity Cannot Be Greater Than poqty Quantity');
                      $(obj).closest('tr').find('input[id=qtyasperbill').focus();
                      $(obj).closest('tr').find('input[id=qtyasperbill').val('');
                      return false;
                 }
             }
             else
             {
                var p1 = (tolerance*poqty)/100;
                var p2 = parseFloat(poqty)+parseFloat(p1);
                if(parseInt(p2)<parseInt(str1))
                {
                    
                    alert('Bill Quantity Cannot Be Greater Then PO Quantity');
                    $(obj).closest('tr').find('input[id=qtyasperbill').focus();
                    $(obj).closest('tr').find('input[id=qtyasperbill').val('');
                    return false;
                 }
             }
        }
        else
            {
            	//var count=countPendingQty();
            	var count=val;
             var pendings=document.getElementById('poqty_'+id).value;
             var free=document.getElementById('freeqty_'+id).value;
             if(free=='') {free=0; }
             pendings=parseFloat(pendings)+parseFloat(free);

             if(parseFloat(val)>parseFloat(pendings))
             {
                alert("Bill qty cannot greater then PO qty");
                var qtyBill=$(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").val(0);
                var count=countPendingQty();
                document.getElementById('shortDirect').value=count.toFixed(2);
                return false;

             }
                    //var qtyRec = document.getElementById("reciveqty").value;
             var qtyRec=$(obj).closest('tr').find('input[id=reciveqty_'+id+"]").val();
                
            // var qtyBill = document.getElementById("qtyasperbill").value;
             var qtyBill=$(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").val();
            
             if(qtyRec==''){qtyRec=0;}
             var confac=$(obj).closest('tr').find('input[id=convfac_'+id+"]").val();

             if(confac=='') confac=0;
             var secondaryqty=parseFloat(qtyRec)*parseFloat(confac);
             $(obj).closest('tr').find('input[id=reciveqty2_'+id+"]").val(secondaryqty.toFixed(2));

             if(parseFloat(qtyBill)>parseFloat(qtyRec))
             {
                var diff = parseFloat(qtyBill)-parseFloat(qtyRec);
                $(obj).closest('tr').find('input[id=shortaccessid_'+id+"]").val(diff.toFixed(2));
                //document.getElementById('minSign_'+id).style.display="block";
                 $(obj).closest('tr').find('input[id=minSign_'+id+"]").val('-');
                
             }
             if(parseFloat(qtyBill)<=parseFloat(qtyRec))
             { 
                var diff = parseFloat(qtyRec)-parseFloat(qtyBill);
                $(obj).closest('tr').find('input[id=shortaccessid_'+id+"]").val(diff.toFixed(2));
                 $(obj).closest('tr').find('input[id=minSign_'+id+"]").val('+');
                
             }
             
             var firstRow=$(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").val();
             if(firstRow=='') { firstRow=0; }
               var firstRow1= $(obj).closest('tr').find('input[id=reciveqty_'+id+"]").val();


             if(firstRow1=='') { firstRow1=0; }
             var totalamt=0;
             //var countcharges =$(obj).closest('tr').find('input[id=hiditemcount_'+id+"]").val();
            calculateBillQty('shortDirect');
              calculateRecQty('short1Direct');
              

             
             var poqty=parseInt($(obj).closest('tr').find('input[id=poqty_'+id+"]").val());

             /*var tolerance= $(obj).closest('tr').find('input[id=tolerances_'+id+"]").val()
             if(tolerance==''){tolerance=0;}
             if(poqty==''){poqty=0;}
             str1=parseInt(val);
             if(str1==''){str1=0;}
            
                 if(parseInt(poqty)<parseInt(str1))
                 {
                      alert('Bill Quantity Cannot Be Greater Then PO Quantity');
                      $(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").focus();
                      $(obj).closest('tr').find('input[id=qtyasperbill_'+id+"]").val('');
                      return false;
                 }*/
             
             

            }
}


function deactivate1(str)
{ 
	 var confirmText = "Are you sure you want to delete the Document?";
    if(confirm(confirmText))
	{
		//var qty=document.getElementById("hrdqty1A_"+str).value;
		//var n=qty.split(",");
//		var count=n.length;
//		for(var j=0;j<count;j++)
//		{
//			var fin=parseFloat(n[j]);
//			var hrdqty=parseFloat(document.getElementById("hrdstock_qty2_"+j).value);
//			var diff=hrdqty-fin;
//			document.getElementById("hrdstock_qty2_"+j).value=diff;
//		}
		//document.getElementById("itemid1_"+str).value='';
		//document.getElementById("active_"+str).style.display='block';
		
                document.getElementById("itemid_"+str).value='';
                 document.getElementById("qtyasperbill_"+str).value='';
                 document.getElementById("reciveqty_"+str).value='';
		document.getElementById("deactive_"+str).style.display='none';
		document.getElementById("hide_"+str).style.display='none';
                var totalamt=0;
                var totalamt1=0;
                var countcharges = document.getElementById("count3").value;
                
                for(var i=1;i<countcharges;i++)
                {
                var qtyBill1 = document.getElementById("qtyasperbill_"+i).value;
                var qtyRec1 = document.getElementById("reciveqty_"+i).value;
                
                if(qtyBill1==''){qtyBill1=0;}
                if(qtyRec1==''){qtyRec1=0;}
                
                var totalamt=parseFloat(totalamt)+parseFloat(qtyBill1);
                var totalamt1=parseFloat(totalamt1)+parseFloat(qtyRec1);
                }
                
                //var finalRes=parseFloat(totalamt)+parseFloat(firstRow);
                document.getElementById("shortDirect").value=totalamt.toFixed(2);
                document.getElementById("short1Direct").value=totalamt1.toFixed(2);
		//alert('Item removed');
		//calqty(str);
		//caltotal(str);
		
	}
}

<!--------------------------------------------DOMESTIC ORDER CALCULATION PART---------------------------------------------------------------------->
</script>


<!-------------------------------------------JS PART END HERE--------------AS---------14-06-2013---------------->
<input type="hidden" name="mrnid" value="<?php echo $_REQUEST['mrnid']; ?>" />
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div">
<h1><?php echo $s->getField('modules_form','id',$_REQUEST['frmid'],'description'); ?></h1>
<form action="" method="post">
 <table width="100%" border="0" cellspacing="0" cellpadding="3">
  <tr class="row1">
    <td width="13%" align="right"><strong>Branch:</strong><font color="#FF0000">*</font></strong></td>
    <td width="20%"><?php $SQLSite=DB_query("Select loccode,locationname from locations where CompanyId='".$_SESSION['ACGCompanyId']."' and loccode in ('".$_SESSION['AssignedBranch']."')",$db); ?>
     <select name="sitecode" id="sitecode" onchange="showResult(this.value)">
      <?php 
	  	while($site_row=DB_fetch_array($SQLSite))
	  	{
			$p = "";
		if($mrn_query_result['site'] == $site_row['loccode'])
				$p = "selected";
	  ?>
      <option value="<?php echo $site_row['loccode'];?>" <?php echo $p; ?>><?php echo $site_row['locationname'];?></option>
      <?php } ?>
    </select><input type="hidden" name="grntypedata" value="<?php echo $mrn_query_result['Grn_Type']; ?>" /></td>
    <td width="13%" align="right"><strong>GRN No.:</strong></td>
    <td width="20%"><input type="text" value="<?php echo $mrn_query_result['MRNNo'];?>" name="MRNNo" readonly="true"></td>
    <td width="13%" align="right"><strong>GRN Date:</strong></td>
    <td><input type="text" name="MRNdate" value="<?php if(isset($mrn_query_result['MRNDate']))
    echo ConvertSQLDate($mrn_query_result['MRNDate']); else echo date('d/m/Y');?>" id="MRNdate" class="datepicker"></td>
  </tr>
  
  <tr class="row1">
    <td align="right"><strong>Store:<font color="#FF0000">*</font></strong></td>
    <td><select id="storecode" name="storecode"  onfocus="check_po()">
	<?php
	if($get_store_id!='' && $main_store!='')
	{	
	$sql_store=DB_query("SELECT id, StoreName,storecode FROM storetype where Store_Site IN ('".$_SESSION['AssignedBranch']."') and CompanyId='".$_SESSION['ACGCompanyId']."' and id in(".$main_store.",".$get_store_id.")",$db); 
   }
   else if($get_store_id=='' && $main_store!='')
   {
   	 $sql_store=DB_query("SELECT id, StoreName,storecode FROM storetype where Store_Site IN ('".$_SESSION['AssignedBranch']."') and CompanyId='".$_SESSION['ACGCompanyId']."' and id in(".$main_store.")",$db); 
   }
   else
   {
   	 $sql_store=DB_query("SELECT id, StoreName,storecode FROM storetype",$db); 
   }	
	while($row_store=DB_fetch_array($sql_store))
	{
	$p1='';
	if($mrn_query_result['StoreCode'] == $row_store['id'])
	$p1="selected";
	?>
	<option value="<?php echo $row_store['id']; ?>"<?php echo $p1; ?>><?php echo $row_store['StoreName']; ?></option>
	<?php } ?>
	
		</select></td>
    <td align="right"><strong>Recieve Against: <font color="#FF0000">*</font></strong></td>
    <td><input type="text" name="receiviedagaist" value="<?php echo $mrn_query_result['ReceivedAgainst']; ?>" />
	<?php if($mrn_query_result['ReceivedAgainst'] == "PO"){ $received_flag = 1 ; }?></td>
    <td align="right"><strong>Recevied From:</strong></td>
    <td>
    	<?php 
    		if($mrn_query_result['ReceivedAgainst']=='stock_transfer'){?>
    			<select name="vendor" id="vendor" >
					<option value="" >Select</option>
					<?php 
						$sql="Select * from clientmaster where CompanyId='".$_SESSION['ACGCompanyId']."'";
						$result = DB_query($sql, $db);
						while($myrow = DB_fetch_array($result))
						{ 
							$p = "";
							if($mrn_query_result['ReceivedFrom'] == $myrow['id'])
								$p = "selected";					
						?>
		 					<option  value="<?php echo $myrow['id']; ?>" <?php echo $p; ?>><?php echo $myrow['c_name']; ?></option>
					<?php }	?>
					</select>
				<?php 
    		}else{
    	?>
    		<select name="vendor" id="vendor" >
			<option value="" >Select</option>
			<?php 
				$sql="Select id,vendor_name from suppliers where CompanyId='".$_SESSION['ACGCompanyId']."'";
				$result = DB_query($sql, $db);
				while($myrow = DB_fetch_array($result))
				{ 
					$p = "";
					if($mrn_query_result['ReceivedFrom'] == $myrow['id'])
						$p = "selected";					
			?>
		 <option  value="<?php echo $myrow['id']; ?>" <?php echo $p;?>><?php echo  str_replace(array("M/s ","M/S"),'',$myrow['vendor_name']); ?></option>
		<?php }	?></select>
		<?php } ?>
		</td>

  </tr>
  <?php 
  if($mrn_query_result['ReceivedAgainst']=='PO')
   {
	$SQLPo=DB_query("SELECT id ,purchase_ordNo FROM purchorders where id='".$mrn_query_result['order_no']."'",$db);
   }
   else if($mrn_query_result['ReceivedAgainst']=='Indent')
   {
   	$SQLPo=DB_query("SELECT requisitionno ,Reqno FROM materialrequisitions where requisitionno='".$mrn_query_result['order_no']."'",$db);
   }
   else if($mrn_query_result['ReceivedAgainst']=='stock_transfer')
   {
   	$SQLPo=DB_query("SELECT * FROM invoice where invoice_id='".$mrn_query_result['order_no']."'",$db);
   }

?>
  
  <tr class="row1">
    <td align="right"><strong>
    	<?php 
    	 if($mrn_query_result['ReceivedAgainst']=='Indent')
    	 { echo "Indent/PR No<?php ";
    	 }
    	 if($mrn_query_result['ReceivedAgainst']=='stock_transfer')
    	 {
    	 	echo "Invoice No.";
    	 }
    	 else { echo "PO No."; } ?>:
    	 </strong>
   	</td>
    <td>
	    <select name="PONo" id="indentprno">
		<?php 
		while($FetchPodata=DB_fetch_array($SQLPo))
		{
		   if($mrn_query_result['ReceivedAgainst']=='Indent')
			{ ?>
				<option value="<?php echo $FetchPodata['requisitionno'];  ?>"><?php echo $FetchPodata['Reqno']; ?></option>
				<?php } else  if($mrn_query_result['ReceivedAgainst']=='PO') { ?>
				<option value="<?php echo $FetchPodata['id'];  ?>"><?php echo $FetchPodata['purchase_ordNo']; ?></option>
				<?php } else  if($mrn_query_result['ReceivedAgainst']=='stock_transfer') { ?>
				<option value="<?php echo $FetchPodata['invoice_id'];  ?>"><?php echo $FetchPodata['invoiceNo']; ?></option>


		<?php }	
		} ?>
		</select>
	</td>
    <td align="right"><strong>Type:</strong></td>
    <td>
        <input type="text" readonly name="poType" id="poType"
         value="<?php if($mrn_query_result['Type'] == 'DO'){ echo "Domestic Order"; } elseif($mrn_query_result['Type'] == 'IO') { echo 'Import Order' ;}?>" style='width:98%;'/>
      
        
    </td>
    <td align="right"><strong>PO Category:</strong></td>
    <td><select name='Pocategory' id='Pocategory' style='width:98%;'>
      <option value=''>Select</option>
      <option value='AT' <?php if($mrn_query_result['Po_category'] == "AT"){ echo "selected";}?> >Asset</option>
      <option value='MT' <?php if($mrn_query_result['Po_category'] == "MT"){ echo "selected" ;}?> >Material</option>
      <option value='SV' <?php if($mrn_query_result['Po_category'] == "SV"){ echo "selected" ;}?> >Service</option>
    </select></td>
  </tr>
  <tr class="row1">
    <td align="right"><strong>Document Type:</strong></td>
    <td><select name="DocumentType" id="DocumentType">
	<option value="Challan" <?php if($mrn_query_result['DocumentType'] == "Challan"){ echo "selected";}?> >Challan</option>
	<option value="Bill" <?php if($mrn_query_result['DocumentType'] == "Bill"){ echo "selected";}?> >Bill</option>
	</select></td>
    <td align="right"><strong>Document No.:</strong></td>
    <td><input name="billno" type="text" id="billno" value="<?php echo $mrn_query_result['BillNo']; ?>" /></td>
    <td align="right"><strong>Challan / Bill Date:</strong></td>
    <td><input type="text" name="MRNVoucherDate" class="datepicker"  onblur="valdate();"  value="<?php echo ConvertSQLDate($mrn_query_result['MRNVoucherDate']);?>"/></td>
  </tr>
  <tr class="row1">
    <td align="right"><strong>Gate Entry No.:<font color="#FF0000">*</font></strong></td>
    <td><input type="text" name="gatepassno"  id="gatepassno"  value="<?php echo $mrn_query_result['GetPassNo']; ?>"
	onkeyup="checkgatentyno(this.value)"; />
	<div id="entrycheck1"><input type="hidden" name="entrycheck" id="entrycheck"  value="<?php echo $entrycheck; ?>" /></div></td>
    <td align="right"><strong>Gate Entry Date:<font color="#FF0000">*</font></strong></td>
    <td><input type="text" name="gatepassdate" id="gatepassdate" class="datepicker" value="<?php echo ConvertSQLDate($mrn_query_result['gatepassdate']);?>"/></td>
    <td align="right"><strong>Vehicle No.:</strong></td>
    <td><input name="vehicalno" type="text" id="vehicalno" value="<?php echo $mrn_query_result['VehicleNo']; ?>"/></td>
  </tr>
  <tr class="row1">
    <td align="right"><strong>Receiving Time:</strong></td>
    <td><select name="timein" id="timein" style="width:49%">
	<option value="Day" <?php if($mrn_query_result['TimeIn'] == "Day"){echo "selected";}?>>Day</option>
	<option value="Night" <?php if($mrn_query_result['TimeIn'] == "Night"){echo "selected";} ?>>Night</option>
	</select><input type="text" name="timeout" value="<?php if(isset($mrn_query_result['Timeout'])) echo $mrn_query_result['Timeout']; else echo date("h:i:s",time());?>" style="width:49%"></td>
    <td align="right"><strong>L R No.:</strong></td>
    <td><input name="lrno" type="text" id="lrno"  value="<?php echo $mrn_query_result['LRno']; ?>"/></td>
    <td align="right"><strong>L R Date:</strong></td>
    <td><input name="lrdate" type="text" id="lrdate" value="<?php if(isset($_SESSION['lrdate'])) echo $lrdate; else echo date('d/m/Y'); ?>"  onblur="LRdate();" class="datepicker"/></td>
  </tr>
  <tr class="row1">
    <td align="right"><strong>Form Type:</strong></td>
    <td><input type="text" name="form_type" id="form_type"  value="<?php echo $mrn_query_result['form_type']; ?>"/></td>
    <td align="right"><strong>Form No.:</strong></td>
    <td><input type="text" name="form_no" id="form_no"  value="<?php echo $mrn_query_result['form_no']; ?>"/></td>
    <td align="right"><strong>Transporter Name:</strong></td>
    <td><select name="transport" id="transport" >
     <option value="0">Select</option>
     <?php
     $trans=DB_query("select * from transport_master where CompanyId='".$_SESSION['ACGCompanyId']."'",$db);
     while($trow=DB_fetch_array($trans))
     {
     	$p='';
     	if($trow['id']==$mrn_query_result['Transp_name'])
     		$p="selected";
     ?>
     <option value="<?php echo $trow['id']; ?>" <?php echo $p; ?>><?php echo $trow['TransportName']; ?></option>
     <?php } ?>
</select></td>
  </tr>
  <tr class="row1">
    <td align="right"><strong>Remarks:</strong></td>
    <td colspan="5"><textarea name="RemarksIfAny"  id="RemarksIfAny"  style="width:99%;"><?php echo $mrn_query_result['RemarksIfAny'];?></textarea></td>
    </tr>
</table>

<h3>Items Details <input type='button' value='Delete' onclick='deleteItems()' class="search" /></h3>
                
	<table width='100%' cellpadding='3' cellspacing='0' border='1' style="border:#808080 1px solid;">
        <tr>
          <th width="5%">Select</th>
          <th width="1"></th>
          <th width="8%">Item Code</th>
          <th>Item Name</th>
          <th width="5%">PO Qty.</th>
           <th width="5%">Free Qty.</th>
          <th width="5%">Pending Qty.</th>
          <th width="8%">Batch No.</th>
          <th width="5%">Date of MFG.</th>
          <th width="5%">Date of Exp.</th>
          <th width="5%">Bill Qty.</th>
          <th colspan="5" style="text-align:center">Rec. Qty.</th>       
          <th colspan="3">Short Qty.</th> 
          <th width="5%">MRP</th>        
        </tr>
        <tbody id="dataTable">
          <?php       			 
				$sqlPoRec=DB_query("SELECT * FROM addmrnqty where issue_id='".$_REQUEST['mrnid']."' order by id  ",$db);
				$i=1;
				while($PORecDetails=DB_fetch_array($sqlPoRec))
				{
					$pending_qty='';
				
					$ItemCode=$s->GetFieldValue('item_master',"id='".$PORecDetails['mst_itemid']."'",'StockID');
					$Itemname=$s->GetFieldValue('item_master',"id='".$PORecDetails['mst_itemid']."'",'item_name');
					$Tolrance=$s->GetFieldValue('item_master',"id='".$PORecDetails['mst_itemid']."'",'item_mst_form_rate');
				
				
					if($mrn_query_result['ReceivedAgainst']=='Indent')
					{
                 		$check_last_mrn="Select sum(reciveqty),POQty,sum(stock_qty2) as stock_qty2,sum(free_qty) as free_qty from addmrnqty 
                 		inner join  addmrn on addmrn.id=addmrnqty.issue_id  where addmrn.id='".$mrn_query_result['id']."'
                 		and addmrnqty.mst_itemid='".$PORecDetails['mst_itemid']."'     and ReceivedAgainst='Indent' and mst_unitid='".$PORecDetails['mst_unitid']."'";
                 	}
                 	if($mrn_query_result['ReceivedAgainst']=='stock_transfer'){
                 		$check_last_mrn="Select sum(reciveqty),POQty,sum(stock_qty2) as stock_qty2,sum(free_qty) as free_qty from addmrnqty inner join addmrn  on addmrn.id=addmrnqty.issue_id where addmrn.order_no='".$mrn_query_result['order_no']."' and addmrnqty.mst_itemid='".$PORecDetails['mst_itemid']."' and ReceivedAgainst='PO' and mst_unitid='".$PORecDetails['mst_unitid']."'";
                 	}
				 	else
				 	{
                   		$check_last_mrn="Select sum(reciveqty),POQty,sum(stock_qty2) as stock_qty2,sum(free_qty) as free_qty from addmrnqty inner join addmrn  on addmrn.id=addmrnqty.issue_id where addmrn.order_no='".$mrn_query_result['order_no']."' and addmrnqty.mst_itemid='".$PORecDetails['mst_itemid']."' and ReceivedAgainst='PO' and mst_unitid='".$PORecDetails['mst_unitid']."'";
                  	}
				 
                  	//echo $check_last_mrn;

				$last_mrn_res=DB_query($check_last_mrn,$db);
				
				$last_mrn_row=DB_fetch_array($last_mrn_res);

				/* if($PORecDetails['qty_type']=='P')
				{
					if($last_mrn_row['POQty']!='' && $last_mrn_row['sum(reciveqty)']!='' )
					{
						$pending_qty=$last_mrn_row['POQty']-($last_mrn_row['sum(reciveqty)']);
					}
					else
					{
						$pending_qty=$PORecDetails['Quantity'];
					}
					$primary_qty=$PORecDetails['reciveqty'];
					$secondary_qty=$PORecDetails['stock_qty2'];
					
				}
				else if($PORecDetails['qty_type']=='S')
				{

                   if($last_mrn_row['POQty']!='' && $last_mrn_row['stock_qty2']!='' )
						{
						//$pending_qty=$last_mrn_row['POQty']-($last_mrn_row['stock_qty2']);
						}
						else
						{
						//$pending_qty=$PORecDetails['Quantity'];
						}
						$primary_qty=$PORecDetails['stock_qty2'];
						$secondary_qty=$PORecDetails['reciveqty'];
				} */
				if($PORecDetails['qty_type']=='P')
				{
					if($last_mrn_row['POQty']!='' && $last_mrn_row['sum(reciveqty)']!='' )
					{
						$pending_qty=$last_mrn_row['POQty']+$last_mrn_row['free_qty']-($last_mrn_row['sum(reciveqty)']);
					}
					else
					{
						$pending_qty=$PORecDetails['Quantity'];
					}
					$primary_qty=$PORecDetails['reciveqty'];
					$secondary_qty=$PORecDetails['stock_qty2'];
					
				}
				else if($PORecDetails['qty_type']=='S')
				{

                   if($last_mrn_row['POQty']!='' && $last_mrn_row['stock_qty2']!='' )
						{
						//$pending_qty=$last_mrn_row['POQty']-($last_mrn_row['stock_qty2']);
						}
						else
						{
						//$pending_qty=$PORecDetails['Quantity'];
						}
						$primary_qty=$PORecDetails['stock_qty2'];
						$secondary_qty=$PORecDetails['reciveqty'];
				}
				 	
	 	$unitname1=$s->GetFieldValue('unitsofmeasure',"unitid='".$PORecDetails['mst_unitid']."'",'unitname');
	 	$unitname2=$s->GetFieldValue('unitsofmeasure',"unitid='".$PORecDetails['mst_sec_unitid']."'",'unitname');

	?>
            
          <tr id='hide_<?php echo $i; ?>' bgcolor="#fff">
            <td>
            <?php 
            	if($mrn_query_result['ReceivedAgainst']=='stock_transfer'){
            		echo $i;
            	}else{
            ?>
            	<input type="checkbox" name='rec[]' id="rec_<?php echo $i; ?>"><input type='button' value='+'  id="add_<?php echo $i; ?>" onclick='javascript:addBatch(this,this.id);'>
            	<?php } ?>
            </td>
            <td><input type='hidden' name='mst_itemid[]' id='itemid_<?php echo $i; ?>' value='<?php echo $PORecDetails['mst_itemid'] ?>' readonly="true" />
            	</td>
            <td><input type='text' name='itemcode[]' id='itemcode_<?php echo $i; ?>' value='<?php echo $ItemCode ?>' readonly="true" style="width:100%;" />
            <input type='hidden' readonly='' id='tolerances_<?php echo $i; ?>' name='tolrancees[]' size='15'  value='<?php echo $tolerance; ?>' />
			</td>
            <td><input name="text" type="text"  id="itemname_<?php echo $i; ?>"
			 value="<?php echo $Itemname; ?>" readonly="true" style="width:100%;"/></td>
              <?php if($mrn_query_result['ReceivedAgainst']=='Without PO'){ $readonly=""; } else { $readonly="readonly"; } ?>			
            <td><input type='text' name='poqty[]' id='poqty_<?php echo $i; ?>' 
			value='<?php echo $PORecDetails['POQty'] ?>' style="width:100%;" <?php echo $readonly; ?> /></td>
			  <td><input type='text' name='freeqty[]' id='freeqty_<?php echo $i; ?>' 
			value='<?php echo $PORecDetails['free_qty'] ?>' style="width:100%;" <?php echo $readonly; ?> /></td>
             <?php if($mrn_query_result['Grn_Type']=='Indirect') { $colspan='5';  ?>
            

            <td>
            <?php 
            	if($Tolrance!='')
            	{

            		$x = round(($pending_qty+$primary_qty),2);
            		$y = round(($x*$Tolrance)/100);
            		$newpendingqty = round(($x+$y),2);
				}
				else
				{ 
					$newpendingqty = round(($pending_qty+$primary_qty),2);
				}
            ?>
            	<input type='text' name='pending_qty[]' id='pending_<?php echo $i; ?>' value='<?php echo round($newpendingqty,2); ?>' readonly="true" style="width:100%;" />
            	
            	 <input type='hidden' name='pending_qty1[]' id='pending1_<?php echo $i; ?>'
			 value='<?php echo round($newpendingqty,2); ?>' readonly="true" style="width:100%;" />
			 </td>
             <?php }  ?>
            <td><input style='width:100%;'  type='text' name='batch_no[]' id='batch_no_<?php echo $i; ?>' 
			value='<?php echo $PORecDetails['batch_no'] ?>'/></td>
			<td><input type='text' name='mfg[]'value="<?php echo ConvertSQLDate($PORecDetails['mfg']); ?>" id='mfg_<?php echo $i ?>'  class='datepicker' style="width:100%;" readonly  /></td>
			<td><input type='text' id="expiry_<?php echo $i; ?>" name='expiry[]' value="<?php echo ConvertSQLDate($PORecDetails['expiry']); ?>" id='expiry_<?php echo $i ?>'  class='datepicker' style="width:100%;" readonly  /></td>
            <td width="5%"><input style='width:100%;'  type='text' name='qty_as_per_bill[]' id='qtyasperbill_<?php echo $i; ?>'
				 onkeyup='calTotalQty1Direct(this.value,this.id,this)' onkeypress="return isNumberKey(event)" value="<?php echo round($PORecDetails['qty_as_per_bill'],2); ?>"/></td>
            <td width="5%"><input style='width:100%;'  type='text' name='reciveqty[]' id='reciveqty_<?php echo $i; ?>'onkeyup='calTotalQtyDirect(this.value,this.id,this);' onkeypress="return isNumberKey(event)"  value="<?php echo round($primary_qty) ?>"/></td> 
			<td width="5%"><select name='unit[]' style='width:100%;'><option value="<?php echo $PORecDetails['mst_unitid']; ?>"><?php echo $unitname1;?></option></select></td>  
			<td width="1"><input  name="conv_fac[]" type="hidden" id="convfac_<?php echo $i; ?>" autocomplete="off"   size="8" value="<?php echo $PORecDetails['conv_fac']; ?>" /></td>
			<td width="5%"><input name="reciveqty2[]" readonly="" type="text" id="reciveqty2_<?php echo $i; ?>" autocomplete="off"   size="8" value="<?php echo $secondary_qty; ?>" style="width:100%;"/></td>   
			<td width="5%"><select name='unit2[]' style='width:100%;'><option value="<?php echo $PORecDetails['mst_sec_unitid']; ?>"><?php echo $unitname2;?></option></select></td>
            <td width="2%"><input style='width:100%;'  type='text' name='minSign[]' readonly='' id='minSign_<?php echo $i; ?>'
			  readonly="true"  value="<?php echo $PORecDetails['minSign'] ?>"/></td>
            <td width="5%"><input style='width:100%;'  type='text' name='short_qty[]' readonly="" id='shortaccessid_<?php echo $i; ?>' onfocus='calculate_poshort(this.id);'  value="<?php echo $PORecDetails['short_accessid']; ?>"/></td>
			 <td width="1"><input type="hidden" name="qty_type[]" value="<?php echo $PORecDetails['qty_type']; ?>" id="qtytype_<?php echo $i; ?>">
			 <input type="hidden" id="actualqty_<?php echo $i; ?>" value="<?php echo $primary_qty ?>"> 
			 <input type="hidden" id="actualsecqty_<?php echo $i; ?>" value="<?php echo $secondary_qty ?>">
             <input type="hidden" id="billqty_<?php echo $i; ?>" value="<?php echo $PORecDetails['qty_as_per_bill'] ?>">
			</td>
			<td><input name="mrprate[]" type="text" id="mrprate_<?php echo $i; ?>" autocomplete="off"   size="8" value="<?php echo $PORecDetails['mrprate']; ?>" style="width:100%;"/></td>			
           </tr>
          <?php $i++; }	 ?>
        </tbody>
        <input type="hidden" name="Input" id="count3"  value="<?php echo $i; ?>" />
        <input type="hidden" name="Input" id="edit_cnt"  value="<?php echo $i; ?>" />
        <input name="hidden" type='hidden' id='conterimp' value="<?php echo $i; ?>" />
        <input name="hidden" type='hidden' id='hiditemcount' value="<?php echo $i; ?>" />
        <?php 
        $data2.="<tr bgcolor='#fff'>";
        if($mrn_query_result['Grn_Type']=='Indirect') { $colspan='5'; } else { $colspan='5'; }
        //$data2.="<td colspan='7' style='text-align:right;'><strong>Total Quantity</strong></td>";
$data2.="<td colspan='8'>&nbsp;</td>";
$data2.="<td><strong>Total Qty.</strong></td>";
$data2.="<td><input readonly name='totalBillQty' readonly type='text' id='shortDirect'  size='8' value='".$mrn_query_result['totalBillQty']."'/></td>";
$data2.="<td><input readonly name='totalRecQty' type='text' readonly id='short1Direct'  size='8' value='".$mrn_query_result['totalRecQty']."'/></td>";
$data2.="<td colspan='6'></td>";
$data2.="</tr>";
echo $data2;
        ?>
      </table>

 
<p style="text-align:center;">
	<input type="submit" name="save" value="Save" class="search" onclick="return confirmPost()" />
    <!--<input type="submit" name="reset" value="Reset" class="search" />-->&nbsp;<input type="button" class="search" value="Cancel" name="Back" onclick="history.back();" /></a>
	</p>
</form>

<script type="text/javascript">
function confirmPost()
{
	var check=0;
	jQuery('input[id^=qtyasperbill_]').each(function(){
         var amount = jQuery(this).val();
            if(amount=='0' || amount=='')
            	check=1;
    });
	if(check==1)
	{
		alert("Bill Qty cannot be 0");
		return false;	
	}
	

	
}
function checkItemdelete()
{
	var check=0;
	jQuery('input[id^=itemid_]').each(function(){
         	check+=1;
    });
	return check;
}
function deleteItems()
{
	var x=checkItemdelete();
	
	if(checkItemdelete()==1)
	{
		 alert("You cannot delete all the items");
		return false;
	}
       $("input[name='rec[]']:checked").each(function(i) {
        var rec_id = this.id;
        var val=document.getElementById(rec_id).value;
       	var x=rec_id.split('_');
       var val1= $(this).closest('tr').find('input[id=qtyasperbill_'+x[1]+']').val();

       var shortDirect= document.getElementById('shortDirect').value;
       var total=parseFloat(shortDirect)-parseFloat(val1);
       document.getElementById('shortDirect').value=total.toFixed(2);
      

        var val2= $(this).closest('tr').find('input[id=reciveqty2_'+x[1]+']').val();

        var short1Direct= document.getElementById('short1Direct').value;
        var total1=parseFloat(short1Direct)-parseFloat(val2);
      
      	 document.getElementById('short1Direct').value=total1.toFixed(2);
      
       
        $(this).closest('tr').remove();

        });
}
function addBatch(obj,id)
{

	var data1=id.split("_");

    var thisRow = $(obj).closest( 'tr' )[0];
    $( thisRow ).clone().insertBefore( thisRow ).find( 'input:text' );
    
    var qty=$(obj).closest('tr').find('input[id=qtyasperbill_'+data1[1]+']').val();

     var pen=$(obj).closest('tr').find('input[id=pending1_'+data1[1]+']').val();


      /* -------------- Code for add button to remove duplicacy of po Quantity Starts here-------------------------------------------------------  */
   
     $(obj).closest('tr').find('input[id=add_'+data1[1]+']').hide();
     $(obj).closest('tr').find('input[id=itemcode_'+data1[1]+']').hide();
     $(obj).closest('tr').find('input[id=itemname_'+data1[1]+']').hide('');
     $(obj).closest('tr').find('input[id=poqty_'+data1[1]+']').hide().val('');

     $(obj).closest('tr').find('input[id=pending_'+data1[1]+']').hide();
     $(obj).closest('tr').find('input[id=batch_no_'+data1[1]+']').val('');
     $(obj).closest('tr').find('input[id=mfg_'+data1[1]+']').val('').addClass("datepicker");
     $(obj).closest('tr').find('input[id=expiry_'+data1[1]+']').val('').addClass("datepicker");
     $(obj).closest('tr').find('input[id=qtyasperbill_'+data1[1]+']').val('');
     $(obj).closest('tr').find('input[id=reciveqty_'+data1[1]+']').val('');
     $(obj).closest('tr').find('input[id=reciveqty2_'+data1[1]+']').val('');
     $(obj).closest('tr').find('input[id=minSign_'+data1[1]+']').val('');
     $(obj).closest('tr').find('input[id=shortaccessid_'+data1[1]+']').val('');

  /* -------------- Code for add button to remove duplicacy of po Quantity Ends here -------------------------------------------------------  */
   
   
    var countqty=countPendingQty();
    //alert(pen);
    if(countqty>parseFloat(pen))
    {
       
        $(obj).closest('tr').find('input[id=qtyasperbill_'+data1[1]+']').val(0);
        qty=0;
         //var countqty=countPendingQty();
    }


    var shortDirect=document.getElementById('shortDirect').value;
    //alert(qty+" "+shortDirect);
    if(qty=="")
        qty=0;
    if(shortDirect=="")
        shortDirect=0;
    var total=parseFloat(qty)+parseFloat(shortDirect);
    document.getElementById('shortDirect').value=total.toFixed();
     var secqty=$(obj).closest('tr').find('input[id=reciveqty2_'+data1[1]+']').val();
    var shortDirect1=document.getElementById('short1Direct').value;

     if(secqty=="")
        secqty=0;
    if(shortDirect1=="")
        shortDirect1=0;
    var total1=parseFloat(secqty)+parseFloat(shortDirect1);

    document.getElementById('short1Direct').value=parseFloat(total1.toFixed(2));
	var i=parseInt(data1[1]+1);
    $(obj).closest('tr').find('input[id=mfg_'+data1[1]+']').attr('id','mfg_'+i);
    $(obj).closest('tr').find('input[id=expiry_'+data1[1]+']').attr('id','expiry_'+i);
    $('.datepicker').removeClass('hasDatepicker').datepicker({ dateFormat: 'dd/mm/yy',changeMonth: true, changeYear: true,yearRange: '-80:+20'});
        
   
    
}



function ajax_cur_rate(str,id1)
 {
 var i=id1.split("_");
var id=i[1];
alert(id);
 	var basicAmt = document.getElementById("NetRate_"+id).value;
	var oldid=document.getElementById("itemCurrency_"+id).value;
	if (str==''){
  		document.getElementById("conv_rate_"+id).value="";
 	 	return;
  	}
	
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  		xmlhttp=new XMLHttpRequest();
  	}else{// code for IE6, IE5
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}
	xmlhttp.onreadystatechange=function(){
   	if(xmlhttp.readyState==4 && xmlhttp.status==200){
	
		var data=xmlhttp.responseText.split("__");
		if(data[0]=="")
		{
		alert('Conversion Rate is Empty');
			document.getElementById("conv_curr_"+id).focus();
		return false;
		}
		else
		{
    	document.getElementById("conv_rate_"+id).value=data[0];
		}
		document.getElementById("basic_"+id).value=data[1];
   }
 }
xmlhttp.open("GET","ajax_get_rate.php?oldCur="+oldid+"&newCur="+str+"&basicAmount="+basicAmt,true);
xmlhttp.send();
 }


function cal_cvd_total_amount(str)
{
var id_brk=str.split('_');
	var i=id_brk[1];
		var basic=document.getElementById("basic_"+i).value;	 
		 var Totaltaxable=document.getElementById("CustomDutyAmt_"+i).value;
		if(basic==''){basic=0;}
		if(Totaltaxable==''){Totaltaxable=0;}
	  
 	 
		var grand_tot1= parseFloat(basic)+parseFloat(Totaltaxable); 
		var cvdPer = document.getElementById("cvd_percentage_"+i).value;
		var cvd = grand_tot1*(cvdPer/100);
		var grand_tot=cvd.toFixed(2);
		
		 
		 document.getElementById("TotalSpecial_"+i).value=grand_tot ;	
	
	




}
function calculate_amt(id,str)
{

var id1=id.split("_");
var i=id1[1];
     
var totalamt=0;
 if(i==undefined)
	{
             var qtyRec = document.getElementById("reciveqty").value;
             var rate=document.getElementById("rate").value;
             if(rate=='') { rate=0;}
             if(qtyRec==''){qtyRec=0;}
             var amount=parseFloat(rate)*parseFloat(qtyRec);
             document.getElementById("totalValue").value=amount.toFixed(2);
             var countcharges = document.getElementById("hiditemcount").value;
               // alert(countcharges);
                if(document.getElementById("totalValue"))
               var firstRow= document.getElementById("totalValue").value;
           else
           	var firstRow=0;
                if(firstRow=='') { firstRow=0; }
                for(var j=1;j<countcharges;j++)
                {
                var qtyBill1 = document.getElementById("totalValue_"+j).value;
              
                if(qtyBill1==''){qtyBill1=0;}         
                
                var totalamt=parseFloat(totalamt)+parseFloat(qtyBill1);              
                }


             var finalRes=parseFloat(totalamt)+parseFloat(firstRow);
               
                document.getElementById("totalitemamount").value=finalRes.toFixed(2);
               
        }
        else
            {
             var qtyRec = document.getElementById("reciveqty_"+i).value;    
           
             var rate=document.getElementById("rate_"+i).value;
             if(rate=='') { rate=0;}
             if(qtyRec==''){qtyRec=0;}
             var amount=parseFloat(rate)*parseFloat(qtyRec);
             document.getElementById("totalValue_"+i).value=amount.toFixed(2);
                var countcharges = document.getElementById("hiditemcount").value;
               
                if(document.getElementById("totalValue"))
                var firstRow= document.getElementById("totalValue").value;
                else
             	var firstRow=0;
                if(firstRow=='') { firstRow=0; }
                for(var j=1;j<countcharges;j++)
                {
                var qtyBill1 = document.getElementById("totalValue_"+j).value;
              
                if(qtyBill1==''){qtyBill1=0;}         
                
                var totalamt=parseFloat(totalamt)+parseFloat(qtyBill1);              
                }
            

             var finalRes=parseFloat(totalamt)+parseFloat(firstRow);
               
                document.getElementById("totalitemamount").value=finalRes.toFixed(2);
           }





}
function cal_e_cess1(id)
{
	var id_brk=id.split('_');
	var i=id_brk[1];
	var b = document.getElementById("CustomDutyAmt_"+i).value; 
	var c = document.getElementById("TotalSpecial_"+i).value; 
	var tot1= parseFloat(b)+parseFloat(c);
	var ecessPer = document.getElementById("ecess_percentage_"+i).value;
	var tot = tot1*(ecessPer/100);
	var final_eces=tot.toFixed(2);
	document.getElementById("customecess_"+i).value=final_eces;	
}

function cal_esec_cess1(id)
{
var id_brk=id.split('_');
	var i=id_brk[1];
	var b = document.getElementById("CustomDutyAmt_"+i).value; 
	var c = document.getElementById("TotalSpecial_"+i).value; 
	var tot1= parseFloat(b)+parseFloat(c);
	var secEcessPer = document.getElementById("secess_percentage_"+i).value; 
	var tot = tot1*(secEcessPer/100);
	var final_eces1=tot.toFixed(2);
	 document.getElementById("customsececess_"+i).value=final_eces1;	
}

function cal_add_duty1(id)
{
var id_brk=id.split('_');
	var i=id_brk[1];
	var a = document.getElementById("basic_"+i).value; 
	var b = document.getElementById("CustomDutyAmt_"+i).value;
	var c = document.getElementById("TotalSpecial_"+i).value; 
	var d = document.getElementById("customecess_"+i).value; 
	var e = document.getElementById("customsececess_"+i).value; 
		var tot12= parseFloat(a)+parseFloat(b)+parseFloat(c)+parseFloat(d)+parseFloat(e);
	var addPer = document.getElementById("add_percentage_"+i).value; 
	var tot1 = tot12*(addPer/100);
	var final_eces2=tot1.toFixed(2);
	 document.getElementById("adduty_"+i).value=final_eces2 ;	
	
}



function addRow_mrn(tableID) 
{

	if(document)
	var table = document.getElementById(tableID);
	var rowCount = table.rows.length;
	var rowCount = table.rows.length;
	if(document.getElementById("hiditemcount").value=='')
	r =rowCount+1;
	else
	{
	var t=document.getElementById("edit_cnt").value;
	var t1=document.getElementById("hiditemcount").value;
	r=parseInt(t1);
	
	r1=parseInt(t1)+1;
	}
	var row = table.insertRow(rowCount);
	document.getElementById("hiditemcount").value=r1;
	document.getElementById("edit_cnt").value=r1;
	document.getElementById("conterimp").value=r1;
	var colCount = table.rows[0].cells.length;
	for(var i=0; i<colCount; i++) {		
	var newcell = row.insertCell(i);
	//newcell.style.background='#e7e7e7';
	
		newcell.innerHTML = table.rows[0].cells[i].innerHTML;
	//alert(newcell.childNodes[0].type);
	switch(newcell.childNodes[0].type) 
	{
	case "text":
	newcell.childNodes[0].value = "";
	var nod_id = newcell.childNodes[0].id.split("_");
	if(!isNaN(nod_id[1]))
	newcell.childNodes[0].id = nod_id[0]+'_'+r;
	else
	newcell.childNodes[0].id = nod_id[0]+'_'+nod_id[1]+'_'+r;
	break;		
	case "hidden":
	newcell.childNodes[0].value = "";
	var nod_id = newcell.childNodes[0].id.split("_");
	if(!isNaN(nod_id[1]))
	newcell.childNodes[0].id = nod_id[0]+'_'+r;
	else
	newcell.childNodes[0].id = nod_id[0]+'_'+nod_id[1]+'_'+r;
	break;
	case "button":
	var nod_id = newcell.childNodes[0].id.split("_");
	if(!isNaN(nod_id[1]))
	newcell.childNodes[0].id = nod_id[0]+'_'+r;
	else
	newcell.childNodes[0].id = nod_id[0]+'_'+nod_id[1]+'_'+r;
	break;
	case "checkbox":
	newcell.childNodes[0].checked = false;
	var nod_id = newcell.childNodes[0].id.split("_");
	if(!isNaN(nod_id[1]))
	newcell.childNodes[0].id = nod_id[0]+'_'+r;
	else
	newcell.childNodes[0].id = nod_id[0]+'_'+nod_id[1]+'_'+r;
	break;
	case "select-one":
	newcell.childNodes[0].selectedIndex = 0;
	var nod_id = newcell.childNodes[0].id.split("_");
	if(!isNaN(nod_id[1]))
	newcell.childNodes[0].id = nod_id[0]+'_'+r;
	else
	newcell.childNodes[0].id = nod_id[0]+'_'+nod_id[1]+'_'+r;
	break;	
	}
		//document.getElementById("stock_perunit_"+rowCount).value=1;
	}
		//document.getElementById(countid).innerHTML=rowCount;
$('.datepicker').removeClass('hasDatepicker').datepicker({ dateFormat: 'dd/mm/yy',changeMonth: true, changeYear: true,yearRange: '-80:+20'});
	}
	

function deleteRow2_grn(tableID) 
{
		try 
		{
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;
			//alert(rowCount);
			for(var i=0; i<rowCount; i++) 
				{
					var row = table.rows[i];
					var chkbox = row.cells[0].childNodes[0];
					if(null != chkbox && true == chkbox.checked) 
					{
						if(rowCount <= 1) 
						{
							alert("Cannot delete all the rows.");
							break;
						}
					table.deleteRow(i);
					rowCount--;
					i--;
					}
					
				}
				
		document.getElementById("hiditemcount").value=parseInt(rowCount);	
		document.getElementById("edit_cnt").value=parseInt(rowCount);	
				
		}
		catch(e) 
		{
			alert(e);
		}

}
</script>





