<?php 
$PageSecurity = 4;
$PageName = 'Purchase Bill Book';
include('includes/DefinePOClass.php');
include('includes/SQL_CommonFunctions.inc');

	$title = _('Purchase Bill Book');

$Fin1ExpS1=explode("-",$_SESSION['financialYrStart']);
$_SESSION['YearStart']=$Fin1ExpS1[0];
$Fin1ExpE1=explode("-",$_SESSION['financialYrEnd']);
$_SESSION['YearEnd']=$Fin1ExpE1[0];
?>
<?php 
/**************************************************************************************************************************/
if($_REQUEST['Save']) 
{
                   
                     $vat_cst=explode('**',$_REQUEST['vat_cst']);			        		 		
					 $data['bill_book_date']       =FormatDateForSQL($_REQUEST['voucher_date']);					
					 $data['po_no']                =$_REQUEST['po_no'];
					 $data['po_type']              =$_REQUEST['po_type']; 
					 $data['doc_type']             =$_REQUEST['doc_type'];
					 $data['bill_no']              =$_REQUEST['bill_no']; 
					 $data['bill_date']            =FormatDateForSQL($_REQUEST['bill_date']); 
					 $data['due_date']       =FormatDateForSQL($_REQUEST['bill_book_date']); 
					 $data['challan_no']           =$_REQUEST['challan_no']; 
					 $data['challan_date']         =FormatDateForSQL($_REQUEST['challan_date']);				
					 $data['remarks']              =$_REQUEST['remarks'];
					 $data['Excise_Effect']        =$_REQUEST['Excise_Effect'];

			         $data['total_item_amount']    =$_REQUEST['basic_amt'];	
			         $data['discount_per']         =$_REQUEST['discount_percent'];
					 $data['discount_amt']         =$_REQUEST['discount_amt'];	
					 $data['discounted_amt']       =$_REQUEST['discounted_amt'];
					 $data['pckg_ledger']           =$_REQUEST['pckg_ledger'];
					 $data['pkg_per']              =$_REQUEST['pkg_per'];
					 $data['pkg_charges']          =$_REQUEST['pkg_charges'];  
					 $data['insurance_ledger']     =$_REQUEST['insurance_ledger'];  
					 $data['non_tax_insurance']    =$_REQUEST['insurance'];
                     $data['total_amt']            =$_REQUEST['total_amt'];
                     $excise_id=explode('**',$_REQUEST['excise']);
					 $data['excise']               =$excise_id[0];
					 $data['excise_amt']           =$_REQUEST['excise_amt'];
					 $ecess=explode('**',$_REQUEST['ecess']);
					 $data['ecess']                =$ecess[0];
					 $data['ecess_amt']            =$_REQUEST['ecess_amt'];
					 $secess=explode('**',$_REQUEST['shecess']);
					 $data['shecess']              =$secess[0];
					 $data['shecess_amt']          =$_REQUEST['shecess_amt'];
                     $data['tot_tax_amt']          =$_REQUEST['tot_tax_amt'];  
                     $data['vat_cst']              =$vat_cst[0];
					 $data['taxvalue']             =$_REQUEST['vat_amt'];
					 $data['surcharge_ledger']     =$_REQUEST['surcharge_ledger'];
					 $data['surcharge_per']        =$vat_cst[2];
					 $data['sur_oct_amt']          =$_REQUEST['sur_amt'];
					 $data['addcharge_ledger']     =$_REQUEST['addcharge_ledger'];
					 $data['add_charges']          =$_REQUEST['entry_tax_amt'];	
					 $data['insurance']            =$_REQUEST['insr_amt']; 					
					 $data['freight_ledger']       =$_REQUEST['freight_ledger'];
					 $data['Freight']              =$_REQUEST['Freight'];
                     $data['round_ledger']         =$_REQUEST['round_ledger'];
					 $data['round_off']            =$_REQUEST['roundVal'];
					 $data['pluMin']               =$_REQUEST['pluMin'];
					 $data['GrandTotal']           =$_REQUEST['GrandTotal'];
					 $data['ledger']               =$_REQUEST['ledger'];			
					
					
					

					 if($_REQUEST['pocat']=='AT')  {
		                //************************ For Excise Duty *********************//	
		                $total_exciseant=$_REQUEST['excise_amt']/2;	
		                $exise_caption=$s->GetFieldValue("excise_tax","id='".$excise_id[0]."'","caption");
		                $exise_id2=$s->GetFieldValue("excise_tax","id!='".$excise_id[0]."' and caption='".$exise_caption."'","id");
			                $data['Excise_Duty_value1']=$total_exciseant;
			                $data['Deffered_Duty_id']=$exise_id2;
			                $data['Deffered_Duty_value']=$total_exciseant;
		               //***************** Ecess Duty Value ************************//
		                $total_ecessamt=$_REQUEST['ecess_amt']/2;	
		                $ecess_caption=$s->GetFieldValue("excise_tax","id='".$ecess[0]."'","caption");
		                $ecess_id2=$s->GetFieldValue("excise_tax","id!='".$ecess[0]."' and caption='".$ecess_caption."'","id");
			                $data['Ecess_Duty_value1']=$total_ecessamt;
			                $data['Deffered_E_Cess_id']=$ecess_id2;
			                $data['Deffered_E_Cess_value']=$total_ecessamt;
		               //****************** SHE Cess Value *************************// 
		                $total_shaecessamt=$_REQUEST['shecess_amt']/2;	
		                $ecess_caption=$s->GetFieldValue("excise_tax","id='".$secess[0]."'","caption");
		                $shaecess_id2=$s->GetFieldValue("excise_tax","id!='".$secess[0]."' and caption='".$ecess_caption."'","id");
			                $data['SHE_Cess_value1']=$total_shaecessamt;
			                $data['Deffered_SHE_id']=$shaecess_id2;
			                $data['Deffered_SHE_value']=$total_shaecessamt; 

		                $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$excise_id[0]."' and ledgertype='excisetax'","AccountsID"),"amount"=>$total_exciseant,"amount_type"=>'DR');		               
		                $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$exise_id2."' and ledgertype='excisetax'","AccountsID"),"amount"=>$total_exciseant,"amount_type"=>'DR');
                        $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$ecess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$total_ecessamt,"amount_type"=>'DR');
                        $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$ecess_id2."' and ledgertype='cess'","AccountsID"),"amount"=>$total_ecessamt,"amount_type"=>'DR');
                        $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$secess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$total_shaecessamt,"amount_type"=>'DR');
                        $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$shaecess_id2."' and ledgertype='cess'","AccountsID"),"amount"=>$total_shaecessamt,"amount_type"=>'DR');

		                 } 

		                 else if($_REQUEST['pocat']=='MT'){

			                 $data['Excise_Duty_value1']=$_REQUEST['excise_amt'];
			                 $data['Ecess_Duty_value1']=$_REQUEST['ecess_amt'];
			                 $data['SHE_Cess_value1']=$_REQUEST['shecess_amt']; 

                       $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$excise_id[0]."' and ledgertype='excisetax'","AccountsID"),"amount"=>$_REQUEST['excise_amt'],"amount_type"=>'DR');
                       $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$ecess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$_REQUEST['ecess_amt'],"amount_type"=>'DR');
                       $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$secess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$_REQUEST['shecess_amt'],"amount_type"=>'DR');
  
		             }
		              
                      $insurnace_amt=$_REQUEST['insr_amt']+$_REQUEST['insurance'];
		              $data2[]=array("ledgerid"=>$_REQUEST['insurance_ledger'],"amount"=>$insurnace_amt,"amount_type"=>'DR');
		              $data2[]=array("ledgerid"=>$_REQUEST['pckg_ledger'],"amount"=>$_REQUEST['pkg_charges'],"amount_type"=>'DR');
                      $data2[]=array("ledgerid"=>$_REQUEST['freight_ledger'],"amount"=>$_REQUEST['Freight'],"amount_type"=>'DR');
                      $data2[]=array("ledgerid"=>$_REQUEST['surcharge_ledger'],"amount"=>$_REQUEST['sur_amt'],"amount_type"=>'DR');
                      if($_REQUEST['pluMin']=='+')
                      $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['roundVal'],"amount_type"=>'DR');
                      else
			          $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['roundVal'],"amount_type"=>'CR');  
			          $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","vender_client='".$_REQUEST['vendor']."' and ledgertype='vendor'","AccountsID"),"amount"=>$_REQUEST['GrandTotal'],"amount_type"=>'CR');  
			          $data2[]=array("ledgerid"=>$_REQUEST['addcharge_ledger'],"amount"=>$_REQUEST['entry_tax_amt'],"amount_type"=>'DR');
                      $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$vat_cst[0]."' and ledgertype='salestax'","AccountsID"),"amount"=>$_REQUEST['vat_amt'],"amount_type"=>'DR'); 
                      $data2[]=array("ledgerid"=>$_REQUEST['ledger'],"amount"=>$_REQUEST['discounted_amt'],"amount_type"=>'DR'); 

						
						
						
						 $data['po_cat']               =$_REQUEST['pocat'];
						 //$data['misCharge']            =$_REQUEST['other_amt'];						
						 $data['form_type']            =$_REQUEST['form_type'];
						 $data['created_date']         =date('Y-m-d'); 
						 $data['created_by']           =$_SESSION['UserID'];
						 $data['company_id']           =$_SESSION['ACGCompanyId'];
						 			
				       $cond_purchbill="id='".$_REQUEST['editId']."'"; 
		               $insertsql=$s->RecordEdit('purchase_billbook', $data,$cond_purchbill);
                       $Lastreq_id=$_REQUEST['editId'];
              $accountid=$s->GetFieldValue("account_book","trans_type_id='".$_REQUEST['editId']."' and trans_type='PURCHASE BILL'","id");  
                $countval= count($_REQUEST['itemcode']);	
                $delete=DB_query("delete from purchase_bill_details where purch_billbookid='".$_REQUEST['editId']."'",$db);
			   	for($i=0;$i<$countval;$i++)
				{			
			
				    $data_arr['purch_billbookid']   =$Lastreq_id;
					$data_arr['mst_productid']      =$_POST['mst_itemid'][$i];				
					$data_arr['qty_as_per_bill']    =$_POST['qty_as_per_bill'][$i];
					$data_arr['quantity']           =$_REQUEST['reciveqty'][$i];
					$data_arr['short_qty']          =$_REQUEST['short_accessid'][$i];
					$data_arr['rate']               =$_REQUEST['itemrate'][$i];	
					$data_arr['total_price']        =$_REQUEST['itemamount'][$i];	
					$data_arr['discount']           =$_REQUEST['discount'][$i];
					$data_arr['discount_type']      =$_REQUEST['DiscountType'][$i];				
					$data_arr['basic_amt']          =$_REQUEST['basic'][$i];
					$data_arr['sub_total']          =$_REQUEST['basic'][$i];				
					$data_arr['remarks']            =$_REQUEST['remarks'][$i];  
			       $sql=$s->RecordInsert('purchase_bill_details', $data_arr);
		      }

	$update_mrn="Update addmrn set mrnstatus='closed' where id='".$_REQUEST['mrn_no']."'";
	$update_res=DB_query($update_mrn,$db);

       /***************************** Posting In Account ********************************/
       if($accountid!='')
       {
       $delete_account=DB_query("delete from account_book where id='".$accountid."'",$db);
       $delete_account_id=DB_query("delete from account_book_details where account_bookid='".$accountid."'",$db);
       }
        $dataArray['Branch']= $_REQUEST['site'] ;
        $dataArray['VPrefix']= '25' ;
        $dataArray['Voucher_NO']= $_REQUEST['voucher_no'];  
        $dataArray['voucher_type']='Auto';     
        $dataArray['Dates']= FormatDateForSQL($_REQUEST['voucher_date']); 
        $dataArray['conv_rate']='1' ;  
        $dataArray['posted_date']= FormatDateForSQL($_REQUEST['voucher_date']);
        $dataArray['AccountBookType']= 'voucher';   
        $dataArray['created_date']= date('Y-m-d');
        $dataArray['created_by']= $_SESSION['UserID'];   
        $dataArray['narration']=$_REQUEST['remarks'];  
        $dataArray['transation_date_and_time']=FormatDateForSQL($_REQUEST['voucher_date'])." ".date('h:i:s');
        $dataArray['trans_type_id']=$Lastreq_id;
        $dataArray['trans_type']='PURCHASE BILL';
        $s->RecordInsert('account_book', $dataArray);
        $getlastid=DB_Last_Insert_ID($db,'account_book', 'id');

        $total_credit='';
        $total_debit='';
       foreach($data2 as $key=>$value1)
       {
              if($value1[amount]!='0.00')
              {
                $data3['account_bookid']=$getlastid;
                $data3['ledgerid']=$value1[ledgerid];
                $data3['amount']=$value1[amount];
                $data3['converted_amount']=$value1[amount];
                $data3['currency']=$s->getField('currency_master','abbreviation','INR','id');
                $data3['conv_currency']=$s->getField('currency_master','abbreviation','INR','id');
                $data3['amount_type']=$value1[amount_type];
                if($value1[amount_type]=='DR') {  $total_debit[]=$value1[amount];  }
                else if($value1[amount_type]=='CR') {  $total_credit[]=$value1[amount]; }      
              $s->RecordInsert('account_book_details', $data3);
              //  echo "<pre>";
             //   print_r($data3);
             }
       }

      if(!empty($total_credit)) $credit=array_sum($total_credit); else $credit=0;
      if(!empty($total_debit)) $debit=array_sum($total_debit); else $debit=0;

        $update=DB_query("update account_book set total_cramount='".$credit."',total_dramount='".$debit."',total_cramount_conv='".$credit."',total_dramount_conv='".$debit."' ,pending_amount='".$debit."' where id='".$getlastid."'",$db);
    



       /********************************************************************************/

	$s->pageLocation("index.php?route=PurchBillBook_list".$rurl);

}
if($_REQUEST['editId'] != '')
{
   // echo "select * from addmrn where id='".$_REQUEST['id']."'";
	$sqlmrn=DB_query("select * from purchase_billbook where id='".$_REQUEST['editId']."'",$db);
	$rowmrn=DB_fetch_array($sqlmrn);
	//extract($row1);
	//print_r($rowmrn);
}
$arr_type=array("IO"=>"Import Order","DO"=>"Domestic Order");
$arr_doc=array("Challan"=>"Challan","Bill"=>"Bill");
$arr_duty=array("Consolidated"=>"Consolidated");
$arr_po_cattype=array("AT"=>"Asset","MT"=>"Material","SV"=>"Service");

?>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div"> 
<h1 align="center">Process Purchase Bill Book</h1>
<form  name="purchase" action="" method="post" onsubmit="return validateFrm();">
<table width="100%" border="0" cellspacing="0" cellpadding="3">
<tr class="row1">
	<td width="13%" style="text-align:right;"><strong>Branch <font color="#FF0000">*</font></strong></td>
	<td width="20%"> 
	<?php 
  $sql = "Select loccode,locationname from locations where CompanyId='".$_SESSION['ACGCompanyId']."' 
  and loccode in ('".$_SESSION['AssignedBranch']."') and loccode='".$rowmrn['site']."'";
	$result=DB_query($sql, $db);
	?>
	<select name="site" id="site" onchange="getreqitemdataNew(this.value)"  style="width:98%;">  
	<?php
	while($myrow=DB_fetch_array($result))
	{ 
	$p='';
	if($myrow['loccode']==$rowmrn['site'])
	$p="selected";
	?>
	<option value="<?php echo $myrow['loccode']; ?>"<?php if($p!="") {echo $p;} ?>> <?php echo $myrow['locationname']; ?> </option>
	<?php } ?>
	</select></td>
	<td width="13%" style="text-align:right;"><strong>Voucher No.</strong></td>
	<td width="20%"><input name="voucher_no" type="text" value="<?php echo $rowmrn['bill_book_no']; ?>"  style="width:98%;" id="bill" readonly="true"  /></td>
	<td width="13%" style="text-align:right;"><strong>Voucher Date</strong></td>
	<td><input name="voucher_date" id="voucher_date" type="text" class="datepicker" style="width:98%;" value="<?php echo ConvertSQLDate($rowmrn['bill_book_date']); ?>" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>	
</tr>
<tr class="row1">
    <td style="text-align:right;"><strong>Vendor</strong></td>
	<td><div id="vender">
	<select name="vendor" id="vendor" onchange="showmrn(this.value)" style="width:98%;">
        <?php
        $sql_supplier = "select id,vendor_code, vendor_name from suppliers where id='".$rowmrn['vendor']."'";
	$result_supplier=DB_query($sql_supplier, $db);
	while($mysupplier=DB_fetch_array($result_supplier))
	{ 
	
	?>
	<option value="<?php echo $mysupplier['id']; ?>"> <?php echo $mysupplier['vendor_name']; ?> </option>
	<?php } ?>
        </select>
	</div></td>
	<td style="text-align:right;"><strong>MRN No.</strong></td>
	<td><?php 
	$sql_m =DB_query("select id, MRNNo from addmrn where id='".$rowmrn['mrn_no']."'", $db);
	$result_m=DB_fetch_array($sql_m);
	?>
	<div id="getmrn">
	<select name="mrn_no" id="mrn_no"  onchange="get_mrn_details(this.value)" style="width:98%;">
	<option value="<?php echo $result_m['id']; ?>"> <?php echo $result_m['MRNNo']; ?> </option>
	</select>
	</div></td>
	<?php  $mrndate=$s->getField('addmrn','id',$rowmrn['mrn_no'],'MRNDate');
	        $ReceivedAgainst=$s->getField('addmrn','id',$rowmrn['mrn_no'],'ReceivedAgainst'); 
	        $orderno=$s->getField('addmrn','id',$rowmrn['mrn_no'],'order_no');
	        $podate=$s->getField('purchorders','id',$orderno,'po_date'); 
	?> 
    <td style="text-align:right;"><strong>MRN Date</strong></td>
	<td><input type="text" name="mrn_date" id="mrnDate" style="width:98%;" readonly value="<?php echo	 ConvertSQLDate($mrndate); ?>" /></td> 
</tr>
<input type="hidden" name="" id="against_type" value="<?php echo $ReceivedAgainst; ?>">

<tr class="row1">
	<td style="text-align:right;"><strong>PO No.</strong></td>
	<td><input name="po_no" id="poNO" type="text"  style="width:98%;" readonly value="<?php echo $s->getField('purchorders','id',$orderno,'purchase_ordNo')?>"/></td>
    <td style="text-align:right;"><strong>PO Date</strong></td>
	<td><input type="text" name="po_date" id="po_date" readonly style="width:98%;" value="<?php echo  ConvertSQLDate($podate);?>" /></td>
    <td style="text-align:right;"><strong>Due Date</strong></td>
	<td><input type="text" name="bill_book_date" id="bill_book_date" class="datepicker" value="<?php echo ($due_date!="")?ConvertSQLDate($due_date):date('d/m/Y'); ?>"  style="width:98%;" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>  
</tr>
<tr class="row1">
	<td style="text-align:right;"><strong>PO Type</strong></td>
	<td>
	<?php 
		 $po_purch_type=$s->GetFieldValue("addmrn","id='".$rowmrn['mrn_no']."'","type");
		 echo $arr_type[$po_purch_type];
	?>
	<input type="hidden" name="po_type" value="<?php echo $po_purch_type; ?>">
	</td>	
	<td style="text-align:right;"><strong>Document Type</strong></td>
	<td id="doc_type_data">
    <select name="doc_type" id="doc_type" style="width:98%;">
    <option value="<?php echo $rowmrn['DocumentType'];?>" ><?php echo $arr_doc[$rowmrn['doc_type']];?></option>
    </select>
	</td>
    <td style="text-align:right;"><strong>Duty Type</strong></td>
	<td id="doc_type_data">	
            <select name="duty_type" id="duty_type" style="width:98%;" onchange="showitemdetails(this.value)" >        
        
        <?php
        foreach($arr_duty as $key=>$value)
        { 
        $t='';
        if($key==$rowmrn['duty_type'])
        $t="selected";       
        ?>             
    <option value="<?php echo $key;?>" <?php echo $t; ?>><?php echo $value;?></option>
        <?php } ?>
    </select>
	</td>
</tr>

<tr class="row1">
	<td style="text-align:right;"><strong>Bill No.</strong></td>
	<td><input type="text" name="bill_no" id="bill_no"  style="width:98%;" value="<?php  echo  $rowmrn['bill_no']; ?>"  /></td>	
	<td style="text-align:right;"><strong>Bill Date</strong></td>
	<td id="doc_type_data">
   <input type="text" name="bill_date" id="bill_date"  style="width:98%;" value="<?php 
   echo  ConvertSQLDate($rowmrn['bill_date']);  ?>" class="datepicker" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)"
  />
	</td>
	<?php if($rowmrn['po_type']=='IO' ) { ?>
	<td style="text-align:right;"><strong>CHA Ledger</strong></td>
	<td id="doc_type_data"><select   name="cha_ledger" id="cha_ledger" style="width:98%" onchange="showrate_ex(this.value)"  >
     <option value="0">Select</option>
     <?php
     $id=$s->getField('category_master','code','CHA','id');
     $sql=DB_query("select * from suppliers where CompanyId='".$_SESSION['ACGCompanyId']."' and category='".$id."' ",$db);
     while($row1=DB_fetch_array($sql))
     {  ?>
   <option value="<?php echo $row1['id']; ?>"><?php echo $row1['vendor_name']; ?></option>
     <?php } ?>
    </select>   
   </td>   
   <input type="hidden" name="" id="tds1" value="">
   <input type="hidden" name="" id="tds2" value="">
   <input type="hidden" name="" id="tds3" value="">
   <input type="hidden" name="" id="tds4" value="">
	<?php } else { ?>
	<td colspan="2"></td>
	<?php } ?>
</tr>
<tr class="row1">
	<td style="text-align:right;"><strong>Challan No.</strong></td>
	<td><input type="text" name="Challan_no" id="challan_no" readonly style="width:98%;" value="<?php echo  $rowmrn['challan_no']; ?> " /></td>	
	<td style="text-align:right;"><strong>Challan Date</strong></td>
	<td id="doc_type_data">
     <input type="text" name="challan_date" id="challan_date" readonly style="width:98%;" 
          value="<?php  echo  ConvertSQLDate($rowmrn['challan_date']);?>" />
	</td>
	<td style="text-align:right;"><strong>PO Category</strong></td><td>
	<?php
		  $po_type_code=$s->GetFieldValue("addmrn","id='".$rowmrn['mrn_no']."'","Po_category");
		echo $arr_po_cattype[$po_type_code];
	 ?>
	 <input type="hidden" value="<?php echo $po_type_code; ?>" name="pocat"/>
	</td>
</tr>
</table>
 <div id="itemdata" >
  <?php { ?>
<br>
<div align="right" id="charges1">
  <div id="importPo3" style="width:100%; margin:auto;">
    <table width="100%" border="1" cellspacing="0" cellpadding="3" style="border:1px solid #808080;">
      <tr class="row1">
        <td colspan="14" style="text-align:center;"><strong>Against :</strong>
            <input type="radio" name="calc_total_against" id="bill_id" value="bill" <?php if($rowmrn['against_type']=='bill') { ?> checked="checked" <?php } ?> onclick="calculateAgainst3(this.value)" />
            <strong>Bill Qty</strong>
            <input type="radio" name="calc_total_against" id="received_id" value="received" <?php if($rowmrn['against_type']=='received') { ?> checked="checked" <?php } ?> onclick="calculateAgainst3(this.value)"/>
            <strong>Received Qty</strong></td>
            <input type="hidden" id="against_purch" value="<?php echo $rowmrn['against_type']; ?>" />
            </tr>
       <tr>
        <th width="4%">S. No.</th>
        <th width="10%">Item Code</th>
        <th>Description</th>
        <th width="10%">UOM</th>
        <th width="6%">PO QTY</th>
        <th width="6%">Bill QTY</th>
        <th width="6%">Recieved QTY</th>
        <th width="6%">Short Quantity</th>
        <th width="6%">Rate</th>
        <th width="6%">Amount</th>
        <th colspan="2" width="12%">Discount</th>
        <th width="6%">Basic<br /> Amt.</th>
      </tr>
    <?php 
	$mrntype=$s->getField('addmrn','id',$rowmrn['mrn_no'],'ReceivedAgainst');
	$i=0;
	$sql=DB_query("select * from purchase_bill_details where purch_billbookid='".$_REQUEST['editId']."'",$db);
	while($row=DB_fetch_array($sql))
	{
		$itemcode=$s->getField('item_master','id',$row['mst_productid'],'StockID');
		$itemname=$s->getField('item_master','id',$row['mst_productid'],'item_name');
		$unit=$s->getField('item_master','id',$row['mst_productid'],'mst_unitid');	

	    $oldCur =$row['currency'];
	
	  if($mrntype=='PO')
	   {	   
	   $order_no=$s->getField('addmrn','id',$rowmrn['mrn_no'],'order_no');
	   $poqty=$s->GetFieldValue("purchorderdetails","parantId='".$order_no."' and mst_itemid='".$row['mst_productid']."'","Quantity");
	   $pendingqty=$poqty-$row['quantity'];
	   }
	
?>
      <tr bgcolor="#fff">
       <td><?php echo $i+1;?><input type="hidden" name="pur_det_id[]" value="<?php echo $row['id'];?>"></td>
       <td><?php echo $itemcode;?>        
      <input type="hidden" readonly="" id="mst_itemid[]" name="mst_itemid[]" size="15" value="<?php echo $row['mst_productid']; ?>" />
        <input type="hidden" readonly="" id="itemcode[]" name="itemcode[]" size="15"  value="<?php echo $itemcode; ?>" />
        <input type="hidden" readonly="" id="tolrancees[]" name="tolrancees[]" size="15"  value="<?php echo $tolerance; ?>" />
        <input type="hidden" readonly="" id="pending[]" name="pending[]" size="15"  value="<?php echo $pending_qty; ?>" /></td>
        <td><?php echo $itemname ?></td>
        <td><?php $unitname=$s->getField('unitsofmeasure','unitid',$unit,'unitname');	echo $unitname;?></td>
        <td><?php   echo $poqty; ?>
        <input name="poqty[]" type="hidden" id="poqty[]" value="<?php echo $poqty;?>" size="10"/></td>
        <td><input name="qty_as_per_bill[]" type="text" id="qty_as_per_bill_<?php echo $i; ?>" value="<?php echo $row['qty_as_per_bill'];?>"  size="8" readonly oonblur="check_bill_qty(this.value,<?php echo $i;?>)" style="width:98%;" />
        </td>
        <td><input name="reciveqty[]" readonly type="text" id="reciveqty_<?php echo $i; ?>" value="<?php echo $row['quantity'];?>" size="8" style="width:98%;" /></td>
        <td><input name="short_accessid[]" type="text" id="short_accessid[]" value="<?php echo $row['short_qty'];?>" size="8" readonly="true" oonfocus="calculate_poshort(<?php echo $i ?>);" style="width:98%;" /></td>
        <!--<td><input name="itemrate[]" type="text" id="itemrate_<?php echo $i; ?>" value="<?php echo $ratVal=$row['rate']; ?>"  size="8"   <?php //if($ratVal!='') { ?>  readonly="true" <?php// } ?>  onkeyup="caltotalamt(this.value,<?php echo $i; ?>)" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' />
        </td> -->
        <td><input name="itemrate[]" type="text" id="itemrate_<?php echo $i; ?>" value="<?php echo $ratVal=$row['rate']; ?>"  size="8"  onkeyup="calculatetotalrate('<?php echo $i; ?>')" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' style="width:98%;" /></td>
        <td><input name="itemamount[]" readonly type="text" id="itemamount_<?php echo $i; ?>" value="<?php echo $row['total_price']; ?>" onfocus="calculateAmuunt(<?php echo $i; ?>)"  size="8" style="width:98%;" /></td> 
        <td width="6%"><input type="text" value="<?php echo $row['discount']; ?>" name="discount[]" onkeyup="calculateAgainst_per()" size="8" id="Discount1_<?php echo $i; ?>" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' style="width:98%;" /></td>
        <td width="6%"><input name="DiscountType1[]" type="hidden" id="PerAmo_<?php echo $i; ?>" value="<?php echo $row['discount_type']; ?>" size="8" readonly />
		<input name="DiscountType[]" type="text"  id="PerAmo_<?php echo $i; ?>" value="<?php if($row['discount_type']=='Amount') { echo 'Amt'; } else { echo '%'; }
		?>" size="8" readonly style="width:98%;" /></td>
       <td><input type="text" style="width:98%;" id="basic_<?php echo $i; ?>" value="<?php echo $row['sub_total'];   ?>" name="basic[]" readonly/></td>       
      </tr>
      <?php $i++; }	 ?> <input type="hidden" name="countval2" value="<?php echo $i; ?>"  id="count"/>
    </table>
  </div>
<br />			
<table width="100%" cellpadding="3" cellspacing="0" border="0">
			<tr>
				<td valign="top" width="70%">
				<table width="100%" cellpadding="3" cellspacing="0" border="0">
				<tr class="row1">
				<td width="13%" style="text-align:right;"><strong>Ledger</strong></td>
				<td>
				<select name="ledger" id="ledger" style="width:98%;">
				<option value="000">---Select Ledger---</option>
				<?php				
				$ledger_sql=DB_query("select AccountsID, AccountName from accountledger  where ledgertype='purchase'
									 ORDER BY AccountName ASC",$db);
				while($ledger_row=DB_fetch_array($ledger_sql))
				{
				?>
				<option value="<?php echo $ledger_row['AccountsID'];?>"<?php echo ($ledger_row['AccountsID']==$rowmrn['ledger']?'selected':'')?>><?php echo $ledger_row['AccountName'];?></option>
				<?php } ?>
				</select></td>
				</tr>
				<tr class="row1">
				<td style="text-align:right;"><strong>Remarks If Any</strong></td>
				<td>
				<textarea name="remarks" id="remarks" style="width:98%; height:60px;"><?php echo $rowmrn['remarks'];?></textarea></td>
				</tr>
				  <tr class="row1">
					<td style="text-align:right;"><strong>Excise Effect</strong></td>
					<td><select name='Excise_Effect' style="width:98%;">
					<option value="0">---</option>
					<option value="RG-23A"<?php echo ( $rowmrn['Excise_Effect']=='RG-23A')?'selected':''?>  >RG 23A &Iota; &Iota;nd</option>
						<option value="RG-23C"<?php echo ( $rowmrn['Excise_Effect']=='RG-23C')?'selected':''?>  >RG 23C &Iota; &Iota;nd</option>
						<option value="RG-23D"<?php echo ( $rowmrn['Excise_Effect']=='RG-23D')?'selected':''?>  >RG 23D &Iota; &Iota;nd</option>
						<option value="Non Modvat"<?php echo ( $rowmrn['Excise_Effect']=='Non Modvat')?'selected':''?>  >Non Modvat</option>
					</select>&nbsp;</td>
				  </tr>
				  <tr class="row1">
				  <td style="text-align:right;"><strong>Form Type</strong></td>
				  <td><select  name="form_type" id="form_type" style="width:98%; height:20px;">
				  <option value="">Select</option>
				  <?php $formSql=DB_query("Select * from form_type_master",$db);
				     while($formRow=DB_fetch_array($formSql)) {	?>
				  <option value="<?php  echo $formRow['id']?>"<?php echo ($rowmrn['form_type']==$formRow['id']?'selected':'')?>><?php  echo $formRow['form_name']?></option> <?php }?>	</select></td>
				  </tr>
				  </table>
				  </td>
		<td valign="top">
		<table width='100%' border='0' cellspacing='0' cellpadding='3'>
		<tr class='row1'>
		<td width="40%" style="text-align:right;"><strong>Basic Amount</strong> </td>
		<td><input type='text' readonly value='<?php echo $rowmrn['total_item_amount']; ?>'  name='basic_amt' id='total_item_amount' style='width:98%;' readonly  /></td>
		</tr>
		<tr class='row1'>
	    <td style="text-align:right;"><strong>Discount</strong></td>
	    <td>	 
	     <input type='text'  name='discount_percent' placeholder='Percent' id='discount_percent' value='<?php echo $rowmrn['discount_per']; ?>' onkeyup='cal_po_charges(this)' style='width:48%; float:left; margin-right:3px;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' >
	     <input type='text'  name='discount_amt' value='<?php echo $rowmrn['discount_amt']; ?>' id='discount_amt' placeholder='Amount' onkeyup='cal_po_charges(this)'  style='width:48%; float:left;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' ></td>
	    </tr>
        <tr class='row1'>
		<td style="text-align:right;"><strong>Discounted Amount</strong></td>
		<td><input type='text' readonly name='discounted_amt' value='<?php echo $rowmrn['discounted_amt']; ?>' id='discnted_amt' style='width:98%;' ></td>
		</tr>
		<?php 	   
		$excise=DB_query("select * from excise_tax where ledgertype like '%excisetax%' 
			and form_type='Purchase' group by caption ",$db);
        
		//$option="<option value=''>Select</option>";
		while($excise_res=DB_fetch_assoc($excise))
		{
		$p='';
		if($excise_res['id']==$rowmrn['excise'])
			$p='selected';
		else
			$p='';
		$option.="<option ".$p." value='".$excise_res['id']."**".$excise_res['def_rate']."'>".$excise_res['caption']."</option>";
	    }
	   $cess=DB_query("select * from excise_tax where ledgertype='cess'  group by caption limit 0,1 ",$db);	
	   while($cess_res=DB_fetch_assoc($cess)){
		$p1='';
		if($cess_res['id']==$rowmrn['ecess'])
			$p1='selected';
		else
			$p1='';
		$option1.="<option ".$p1." value='".$cess_res['id']."**".$cess_res['def_rate']."'>".$cess_res['caption']."</option>";
	}
	$scess=DB_query("select * from excise_tax where ledgertype='cess'  group by caption limit 1,1 ",$db);
	
	while($scess_res=DB_fetch_assoc($scess)){
		$p2='';
		if($scess_res['id']==$rowmrn['shecess'])
			$p2='selected';
		else
			$p2='';
		$option2.="<option ".$p2." value='".$scess_res['id']."**".$scess_res['def_rate']."'>".$scess_res['caption']."</option>";
	}
	?>
	
	    <tr class='row1'>
        <td style="text-align:right;"><strong>Pkg Charges</strong> </td>
        <td><select name="pckg_ledger" style="width:48%; float:left; margin-right:3px;"><?php  $pckLedger=DB_query("Select * from accountledger where ledgertype='pckcharge'",$db);
				  while($pckLedgerRow=DB_fetch_array($pckLedger)) {?>
				  <option value="<?php echo $pckLedgerRow['AccountsID'];?>"><?php echo $pckLedgerRow['AccountName'];?></option>
				  <?php  }  ?> </select>
		<input type='text'  name='pkg_per' placeholder='percent' value='<?php echo $rowmrn['pkg_per']; ?>' id='pkg_perc' onkeyup='cal_po_charges(this)' style='width:48%; float:left;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'  />												        
		<input name='pkg_charges'  id='pkg_charges' placeholder='Amount' value='<?php echo $rowmrn['pkg_charges'];?>' onkeyup='cal_po_charges(this)' style='width:98%' type='text' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' readonly/></td>
        </tr>        
		<tr class='row1'>
        <td style="text-align:right;"><strong>Taxable Insurance</strong> </td>
        <td>
		<input type='text'  name='insurance' placeholder='' value='<?php echo $rowmrn['non_tax_insurance']; ?>'  id='insurance_non_taxable' onkeyup='cal_po_charges(this)' style='width:98%' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
        </tr>
        <tr class='row1'>
	    <td style="text-align:right;"><strong>Total Amt</strong></td>
	    <td><input type='text' readonly name='total_amt' readonly id='total_amt' value='<?php echo $rowmrn['total_amt']; ?>' style='width:98%;' ></td>
	    </tr>
        <tr class='row1'>
        <td style="text-align:right;"><strong>Excise Duty </strong> </td>
        <td>
		<select id='excise' readonly  name='excise' onchange='cal_po_charges(this)' style="width:48%; float:left; margin-right:3px;">
            
			<?php echo $option; ?></select>													        
		<input name='excise_amt' readonly  value='<?php echo $rowmrn['excise_amt']; ?>' readonly id='excise_amt' style='width:48%; float:left;' type='text'/></td>
        </tr>
        <tr class='row1'>
        <td style="text-align:right;"><strong>E Cess</strong></td>
        <td><select  name='ecess' id='ecess' style="width:48%; float:left; margin-right:3px;" onchange='cal_po_charges(this)'>        	
        	 <?php echo $option1; ?></select>												
		<input name='ecess_amt' readonly id='ecess_amt'  value='<?php echo $rowmrn['ecess_amt']; ?>' style='width:48%; float:left;' type='text'/></td>
        </tr>
        <tr class='row1'>
        <td style="text-align:right;"><strong>SHE Cess</strong></td>
        <td><select name='shecess' id='shecess' style="width:48%; float:left; margin-right:3px;" onchange='cal_po_charges(this)'>         	
        	<?php echo $option2; ?></select>												
		<input name='shecess_amt' readonly id='shecess_amt'  value='<?php echo $rowmrn['shecess_amt']; ?>' style='width:48%; float:left;' type='text'/></td>
        </tr>
		<tr class='row1'>
        <td style="text-align:right;"><strong>Total Taxable Amount</strong></td>
        <td><input name='tot_tax_amt' readonly id='tot_tax_amt' value='<?php echo $rowmrn['tot_tax_amt']; ?>' style='width:98%' type='text'/></td>
        </tr>
        <tr class='row1'>
        <td style="text-align:right;"><strong>Input Tax</strong></td>
        <?php
	 	$Taxsql="SELECT salestax_id,tax_code, taxrate,surcharge_rate FROM sales_tax_master
	 	 where account_group in('VI','VO')";
		$Taxresult=DB_query($Taxsql,$db);
		?>
        <td><select id='vat_cst' name='vat_cst' onchange='cal_po_charges(this)' style='width:48%; float:left; margin-right:3px;'>
	    <option value=''>---Select---</option>
	    <?php 
		while($Taxmyrow=DB_fetch_array($Taxresult)){
			$p4='';
			if($Taxmyrow['salestax_id']==$rowmrn['vat_cst'])
			$p4='selected';
		    else
			$p4='';
		?>
        <option <?php echo $p4; ?>  value='<?php echo $Taxmyrow['salestax_id']."**".$Taxmyrow['taxrate']."**".$Taxmyrow['surcharge_rate']; ?>'><?php echo $Taxmyrow['tax_code'].' --- '.$Taxmyrow['taxrate'].'%'; ?></option>
        <?php } ?>
        </select> <input name='vat_amt' value='<?php echo $rowmrn['taxvalue']; ?>' readonly id='vat_amt' style='width:48%; float:left;' type='text'/></td>
        </tr>      
     	<tr class='row1'>
        <td style="text-align:right;"><strong>Surcharge Tax</strong></td>
        <td><select name="surcharge_ledger" id="sur_oct_per3" style="width:48%; float:left; margin-right:3px;" >
				  <?php 
				  $surLedger=DB_query("Select * from accountledger where ledgertype='surcharge'",$db);
				  while($surLedgerRow=DB_fetch_array($surLedger))
				  {?>
				  <option value="<?php echo $surLedgerRow['AccountsID'];?>"><?php echo $surLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				  </select><input type='text' readonly  name='sur_per' value='<?php echo $rowmrn['surcharge_per']; ?>' id='sur_per' style='width:22%; float:left; margin-right:3px;'/><input type='text' readonly value='<?php echo $rowmrn['sur_oct_amt']; ?>' name='sur_amt' id='sur_amt' style='width:24%; float:left;'/></td>
        </tr>
        <tr class='row1'>
        <td style="text-align:right;"><strong>Entry Tax</strong></td>
        <td><select name="addcharge_ledger" style="width:48%; float:left; margin-right:3px;">
				  <?php 
				  $pckLedger=DB_query("Select * from accountledger where ledgertype='addcharge'",$db);
				  while($pckLedgerRow=DB_fetch_array($pckLedger))
				  {?>
				  <option value="<?php echo $pckLedgerRow['AccountsID'];?>"><?php echo $pckLedgerRow['AccountName'];?></option>
				  <?php  }  ?>
				  </select>	
        	<input type='text' name='entry_tax_amt' value='<?php echo $rowmrn['add_charges']; ?>' onkeyup='cal_po_charges(this)' id='entry_amt' style='width:48%; float:left;'/></td>
        </tr>
        <tr class='row1'>
        <td style="text-align:right;"><strong>Insurance</strong> </td>
        <td><select name="insurance_ledger" style="width:48%; float:left; margin-right:3px;" >
				  <?php 
				  $pckLedger1=DB_query("Select * from accountledger where ledgertype='insurance'",$db);
				  while($pckLedgerRow1=DB_fetch_array($pckLedger1))
				  {?>
				  <option value="<?php echo $pckLedgerRow1['AccountsID'];?>"><?php echo $pckLedgerRow1['AccountName'];?></option>
				  <?php  }  ?>
				  </select>	<input type='text'  name='insr_amt' value='<?php echo $rowmrn['insurance']; ?>' onkeyup='cal_po_charges(this)' id='insr_amt' style='width:48%; float:left;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'/>
				  <input type='hidden' readonly name='other_amt' value='' onkeyup='cal_po_charges(this)'
         id='other_amt' style='width:98%;' /></td>
        </tr>
        <tr class='row1'>
        <td style="text-align:right;"><strong>Freight</strong></td>
        <td><select name="freight_ledger" id="TotalCharge" style="width:48%; float:left; margin-right:3px;" >
				  	<?php 
				  $frLedger=DB_query("Select * from accountledger where ledgertype='freight'",$db);
				  while($frLedgerRow=DB_fetch_array($frLedger))
				  {?>
				  <option value="<?php echo $frLedgerRow['AccountsID'];?>"><?php echo $frLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				  </select>
		<input type='text'  name='Freight' value='<?php echo $rowmrn['freight']; ?>' onkeyup='cal_po_charges(this)' id='freight_amt' style='width:48%; float:left;' /> </td>
        </tr>
      
     	<tr class="row1">
		<td style="text-align:right;"><strong>Round Off</strong></td>
        <td><select name="round_ledger" id="round_ledger" style="width:48%; float:left; margin-right:3px;">
                   			<?php 
				  $frLedger=DB_query("Select * from accountledger where ledgertype='round'",$db);
				  while($frLedgerRow=DB_fetch_array($frLedger))
				  {?>
				  <option value="<?php echo $frLedgerRow['AccountsID'];?>"><?php echo $frLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				 
				  </select><input type="text" readonly name="pluMin" readonly value='<?php echo $rowmrn['pluMin']; ?>' id="pluMin" style="width:22%; float:left; margin-right:3px;" />
        <input type="text" readonly name="roundVal" readonly  id="roundVal" value='<?php echo $rowmrn['round_off']; ?>' style="width:24%; float:left;"/>
        </td>
        </tr>          
        <tr class="row1">
        <td style="text-align:right;"><strong>Grand Total</strong></td>
        <td><input type="text" readonly name="GrandTotal" readonly id="GrandTotal" value='<?php echo $rowmrn['GrandTotal']; ?>' style="width:98%;" />       
        </td>
        </tr>
                
	</table>
				  
		    </td>
		</tr></table>
		
</div>
<?php } 
if($_REQUEST["action"]!="viewReport"){
?>
<p align="center"><input type="submit" name="Save" class="search" value="Save"/></p>
<?php } ?>
 </div>
</form>
</div>
</div>
<script type="text/javascript" src="POModule/po_calculation.js"></script>
<script>
 $(function() {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' ,changeMonth: true,
		changeYear: true,
		yearRange: '-80:+20'});
});


</script>

<script>
  $("#bill_date").datepicker(
      {  inlue: true } );
</script>

<script>
function validateFrm()
{


	if(document.getElementById("site").value=='000')
	{
	    alert("Must Select Site");
		document.getElementById("site").focus();
		return false;
	}
	if(document.getElementById("ledger").value=='000')
    {
        alert("Must Select Ledger First");
			document.getElementById("ledger").focus();
			return false;

    }


 if(document.getElementById("radio").checked==false && document.getElementById("radio2").checked==false)
 {
     alert("Must Select Against Bill");			
	 return false;

 }

	if(document.getElementById("doc_type").value=='Challan')
	{
		if(document.getElementById("bill_no").value=='')
		{
			alert("Must Enter Bill No");
			document.getElementById("bill_no").focus();
			return false;
		}
		if(document.getElementById("bill_date").value == '')
		{
			alert("Enter Bill Date");
			document.getElementById("bill_date").focus();
			return false;
		}
	}
	
	else
	{
		if(document.getElementById("challan_no").value=='')
		{
			alert("Must Enter Challan No");
			document.getElementById("challan_no").focus();
			return false;
		}
		if(document.getElementById("challan_date").value == '')
		{
			alert("Enter Challan Date");
			document.getElementById("challan_date").focus();
			return false;
		}
		
	}



}

 function isNumberKey(sender, evt) {
    var txt = sender.value;
    //alert(evt.which);
    var dotcontainer = txt.split('.');
    var charCode = (evt.which) ? evt.which : event.keyCode;
    //alert(event.keyCode);
    if (!(dotcontainer.length == 1 && charCode == 46) && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}
function validate_floating(val,id)
{
   var data=id.split("_");
   var val1=parseFloat(val);
 
   if(val=="" || val1==0)
       {   //document.getElementById(id).value="";
           //document.getElementById(id).focus();
       }else{   
         document.getElementById(id).value=val1.toFixed(2); 
         //document.getElementById(id).value=Math.floor(val1 * 100) / 100;   /* Fixing decimal two points*/ 
       }   
}
 
 function calculateAgainst3(str)
 {
$("#against_purch").val(str);
	var totAmount=0;
	var count =document.getElementById("count").value;
if(str=='bill')
{
   
	var flag=0;
	for(var h=0; h<count;h++)
		{
		if(document.getElementById("itemrate_"+h).value!='')
		{
		flag=flag+1;
		}
		}
	
	if(flag!=count)
	{
	alert("Must Fill Item Rate First");
	document.getElementById("bill_id").checked=false;
	}
	else
	{
		for(var h=0; h<count;h++)
		{
				if(billQty==''){billQty=0;}
				if(itemRate==''){itemRate=0;}
				var billQty=document.getElementById("qty_as_per_bill_"+h).value;
				var itemRate=document.getElementById("itemrate_"+h).value;
				var amtVal=parseFloat(billQty)*parseFloat(itemRate);
				document.getElementById("itemamount_"+h).value = amtVal;
				var discount = document.getElementById("Discount1_"+h).value;
				if(discount==''){discount=0;}
				var discount_type = document.getElementById("PerAmo_"+h).value;
				if(discount_type=='Amount')
				{
					if(parseFloat(amtVal)>parseFloat(discount))
					{
						var basicAmt = parseFloat(amtVal)-parseFloat(discount);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
					
				}
				else 
				{
					var midRes= (discount*amtVal)/100;
					if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
						
						
				}
			}

			if(totAmount==''){totAmount=0;}
			document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
				
				
		}
}
else
{
		var flag=0;
		for(var h=0; h<count;h++)
			{
				if(document.getElementById("itemrate_"+h).value!='')
				{
					flag=flag+1;
				}
			}

		if(flag!=count)
		{
			alert("Must Fill Item Rate First");
			document.getElementById("received_id").checked=false;
		}
		else
		{
				for(var h=0; h<count;h++)
				{
					var recQty=document.getElementById("reciveqty_"+h).value;
					var itemRate=document.getElementById("itemrate_"+h).value;
					var amtVal=parseFloat(recQty)*parseFloat(itemRate);
					document.getElementById("itemamount_"+h).value = amtVal;
					var discount = document.getElementById("Discount1_"+h).value;
					if(discount==''){discount=0;}
					var discount_type = document.getElementById("PerAmo_"+h).value;
					if(discount_type=='Amount')
					{
						 	if(parseFloat(amtVal)>parseFloat(discount))
							{
								var basicAmt = parseFloat(amtVal)-parseFloat(discount);
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
							}else{
								alert("Discount Amount cannot be greater than Basic Amount");
								var basicAmt = parseFloat(amtVal)-0;
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
								document.getElementById("Discount1_"+h).value=0;
							}
					}
					else 
					{
						var midRes= (discount*amtVal)/100;
						if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						}else{
							alert("Discount Amount cannot be greater than Basic Amount");
							var basicAmt = parseFloat(amtVal)-0;
							document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
							var totAmount =  totAmount+parseFloat(basicAmt);
							document.getElementById("Discount1_"+h).value=0;
						}
					}
				}
			
				document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
		   }
}

    cal_po_charges_billbook('');
		//calculate_taxable_totalamt();
 }
 function calculateAgainst_per()
 {
 var str=$("#against_purch").val();
	var totAmount=0;
	var count =document.getElementById("count").value;
if(str=='bill')
{
   
	var flag=0;
	for(var h=0; h<count;h++)
		{
		if(document.getElementById("itemrate_"+h).value!='')
		{
		flag=flag+1;
		}
		}
	
	if(flag!=count)
	{
	alert("Must Fill Item Rate First");
	document.getElementById("bill_id").checked=false;
	}
	else
	{
		for(var h=0; h<count;h++)
		{
				if(billQty==''){billQty=0;}
				if(itemRate==''){itemRate=0;}
				var billQty=document.getElementById("qty_as_per_bill_"+h).value;
				var itemRate=document.getElementById("itemrate_"+h).value;
				var amtVal=parseFloat(billQty)*parseFloat(itemRate);
				document.getElementById("itemamount_"+h).value = amtVal;
				var discount = document.getElementById("Discount1_"+h).value;
				if(discount==''){discount=0;}
				var discount_type = document.getElementById("PerAmo_"+h).value;
				if(discount_type=='Amount')
				{
					if(parseFloat(amtVal)>parseFloat(discount))
					{
						var basicAmt = parseFloat(amtVal)-parseFloat(discount);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
					
				}
				else 
				{
					var midRes= (discount*amtVal)/100;
					if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
						
						
				}
			}

			if(totAmount==''){totAmount=0;}
			document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
				
				
		}
}
else
{
		var flag=0;
		for(var h=0; h<count;h++)
			{
				if(document.getElementById("itemrate_"+h).value!='')
				{
					flag=flag+1;
				}
			}

		if(flag!=count)
		{
			alert("Must Fill Item Rate First");
			document.getElementById("received_id").checked=false;
		}
		else
		{
				for(var h=0; h<count;h++)
				{
					var recQty=document.getElementById("reciveqty_"+h).value;
					var itemRate=document.getElementById("itemrate_"+h).value;
					var amtVal=parseFloat(recQty)*parseFloat(itemRate);
					document.getElementById("itemamount_"+h).value = amtVal;
					var discount = document.getElementById("Discount1_"+h).value;
					if(discount==''){discount=0;}
					var discount_type = document.getElementById("PerAmo_"+h).value;
					if(discount_type=='Amount')
					{
						 	if(parseFloat(amtVal)>parseFloat(discount))
							{
								var basicAmt = parseFloat(amtVal)-parseFloat(discount);
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
							}else{
								alert("Discount Amount cannot be greater than Basic Amount");
								var basicAmt = parseFloat(amtVal)-0;
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
								document.getElementById("Discount1_"+h).value=0;
							}
					}
					else 
					{
						var midRes= (discount*amtVal)/100;
						if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						}else{
							alert("Discount Amount cannot be greater than Basic Amount");
							var basicAmt = parseFloat(amtVal)-0;
							document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
							var totAmount =  totAmount+parseFloat(basicAmt);
							document.getElementById("Discount1_"+h).value=0;
						}
					}
				}
			
				document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
		   }
}

    cal_po_charges_billbook('');
		//calculate_taxable_totalamt();
 }
function chkdteformat(obj){
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
  var input=$(obj).val();
  if(!pattern.test(input))
  {
      alert("Date should be in dd/mm/yyyy Format");
      $(obj).val("");
  }
}
function calculatetotalrate(i)
{
 	if(document.getElementById("bill_id").checked==true || document.getElementById("received_id").checked==true)
 	{
 		   if(document.getElementById("received_id").checked==true)
		 	var recQty=document.getElementById("reciveqty_"+i).value;
		  else  if(document.getElementById("bill_id").checked==true)
		 	var recQty=document.getElementById("qty_as_per_bill_"+i).value;

			var itemRate=document.getElementById("itemrate_"+i).value;
			if(itemRate==""){
				var itemRate=0;
			}
			var amtVal=parseFloat(recQty)*parseFloat(itemRate);
			document.getElementById("itemamount_"+i).value = amtVal.toFixed(2);
			var dis=document.getElementById("Discount1_"+i).value;

	      DiscountAmounts(dis,i);
	  }
 }
function DiscountAmounts(val,i)
 {

 	if(document.getElementById("bill_id").checked==true || document.getElementById("received_id").checked==true)
 	{

	var itemAmt=document.getElementById("itemamount_"+i).value;
	if(val==''){val=0;}
	if(itemAmt==''){itemAmt=0;}
	var distype=document.getElementById("PerAmo_"+i).value;
	if(distype=='Amount')
	{
	var subTotal = parseFloat(itemAmt)-parseFloat(val);
   }
   else
   {
   	var subTotal = parseFloat(itemAmt)-(parseFloat(itemAmt)*parseFloat(val)/100);
   }

	document.getElementById("basic_"+i).value = subTotal.toFixed(2);
	
	var count =document.getElementById("count").value;
	var totAmount=0;
	for(var h=0; h<count;h++)
	{
		var subTotal1 = document.getElementById("basic_"+h).value;
		totAmount=parseFloat(totAmount)+parseFloat(subTotal1);
	}
	document.getElementById("total_item_amount").value = totAmount.toFixed(2);

	 cal_po_charges_billbook('');
  }
 }
 function DiscountAmountNew(val,i)
{
	var disAmt = document.getElementById("Discount1_"+i).value;
	var itemAmt=document.getElementById("itemamount_"+i).value;
	var totAmount=0;
	if(disAmt==''){disAmt=0;}
	if(itemAmt==''){itemAmt=0;}
	if(val=='%')
	{
		var percent = parseFloat(itemAmt) * parseFloat(disAmt)/100;
		var subTotal = parseFloat(itemAmt)-parseFloat(percent);
		document.getElementById("basic_"+i).value = subTotal.toFixed(2);
		var count =document.getElementById("count").value;
		for(var h=0; h<count;h++)
		{
			var subTotal1 = document.getElementById("basic_"+h).value;
           if(subTotal1=='') { subTotal1=0;}

			totAmount=parseFloat(totAmount)+parseFloat(subTotal1);
		}
		document.getElementById("total_item_amount").value = totAmount.toFixed(2);
	}
	else
	{
		var count =document.getElementById("count").value;
	var subTotal = parseFloat(itemAmt)-parseFloat(disAmt);
	document.getElementById("basic_"+i).value = subTotal.toFixed(2);
	for(var h=0; h<count;h++)
		{
			var subTotal1 = document.getElementById("basic_"+h).value;
			  if(subTotal1=='') { subTotal1=0;}
			totAmount=parseFloat(totAmount)+parseFloat(subTotal1);
		}
		document.getElementById("total_item_amount").value = totAmount.toFixed(2);
	}
	calculate_taxable_totalamt();
}
function calculate_taxable_totalamt()
{
 	
var pkg=document.getElementById("pkg_charges").value;
if(pkg=='') {pkg=0;}
/*var addcharge=document.getElementById("additionalCharges1").value;
if(addcharge==''){ addcharge=0;}*/
var addcharge=0;
var basic=document.getElementById("total_item_amount").value;
var diss_out=document.getElementById("discount_amt").value;
var diss_out=parseFloat(diss_out).toFixed(2);
if(diss_out==''){ diss_out=0;}
cal_po_charges(diss_out);
//if(basic==''){ basic=0;}
//var totalamt=parseFloat(pkg)+parseFloat(addcharge)+parseFloat(basic);
//document.getElementById("tot_taxable_amt3").value=totalamt.toFixed(2);
//var taxrate=document.getElementById("taxname1").value;
//tax_rate3(taxrate);


 }

</script>


