<?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']) 
{                     		        		 		
					    $data['bill_book_date']       =FormatDateForSQL($_REQUEST['voucher_date']);					
					    $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['surcharge_ledger']                      =$_REQUEST['surcharge_ledger'];
						$data['sur_oct_amt']                           =$_REQUEST['surcharge_amt'];
						$data['freight_ledger']                        =$_REQUEST['freight_ledger'];
						$data['freight']                               =$_REQUEST['Freight'];
						$data['pckg_ledger']                           =$_REQUEST['pckg_ledger'];
						$data['pkg_charges']                           =$_REQUEST['pkg_charges'];
						$data['round_ledger']                          =$_REQUEST['round_ledger'];
						$data['round_off']                             =$_REQUEST['round_off_value'];
						$data['round_off_sign']                        =$_REQUEST['sign'];
						$data['addcharge_ledger']                      =$_REQUEST['other_ledger'];
						$data['add_chargess']                          =$_REQUEST['add_chargess'];		
						$data['taxvalue']                              =$_REQUEST['vat_amt'];
				        $data['ledger']                                =$_REQUEST['ledger'];
				        $data['educess_value']                         =$_REQUEST['ecess_amt'];
				        $data['excise_value']                          =$_REQUEST['excise_amt'];
				        $data['she_ecess_value']                       =$_REQUEST['shecess_amt'];
				        $data['total_item_amount']                     =$_REQUEST['basic_amt'];
				        $data['modified_date']                          =date('Y-m-d');         
						$data['modified_by']                            =$_SESSION['UserID'];	
						$data['against_type']                           =$_REQUEST['calc_total_against'];		
						$data['GrandTotal']                            =$_REQUEST['GrandTotal'];
						$data['insurance_ledger']                      =$_REQUEST['insurance_ledger'];
				        $data['insurance']                             =$_REQUEST['insr_amt'];
				        $data['form_type']                             =$_REQUEST['form_type'];
				        $data['ledger_id']                             =$_REQUEST['ledger'];
                        $data['remarks']                               =$_REQUEST['remarks'];
                        $data['Excise_Effect']                         =$_REQUEST['Excise_Effect'];		
						date_default_timezone_set('Asia/Calcutta');
						$data['transation_date_and_time']			   = date('y-m-d- h:i:s');
			        			
					       $cond="id='".$_REQUEST['editId']."'";
				    	   $s->RecordEdit('purchase_billbook',$data,$cond);

				    	   $purchaseledger=$s->GetFieldValue("accountledger","vender_client='".$_REQUEST['vendor']."' and ledgertype='vendor'","AccountsID");
             $data2[]=array("ledgerid"=>$purchaseledger,"amount"=>$_REQUEST['GrandTotal'],"amount_type"=>'CR');     
       $amount[$purchaseledger][]=$_REQUEST['GrandTotal'];         
             $data2[]=array("ledgerid"=>$_REQUEST['ledger'],"amount"=>$_REQUEST['basic_amt'],"amount_type"=>'DR'); 
             $amount[$_REQUEST['ledger']][]=$_REQUEST['basic_amt']; 
             $data2[]=array("ledgerid"=>$_REQUEST['pckg_ledger'],"amount"=>$_REQUEST['pkg_charges'],"amount_type"=>'DR');
             $amount[$_REQUEST['pckg_ledger']][]=$_REQUEST['pkg_charges'];
         $data2[]=array("ledgerid"=>$_REQUEST['insurance_ledger'],"amount"=>$_REQUEST['insr_amt'],"amount_type"=>'DR');
         $amount[$_REQUEST['insurance_ledger']][]=$_REQUEST['insr_amt'];
             $data2[]=array("ledgerid"=>$_REQUEST['freight_ledger'],"amount"=>$_REQUEST['Freight'],"amount_type"=>'DR');
              $amount[$_REQUEST['freight_ledger']][]=$_REQUEST['Freight'];
             $data2[]=array("ledgerid"=>$_REQUEST['surcharge_ledger'],"amount"=>$_REQUEST['surcharge_amt'],"amount_type"=>'DR');
             $amount[$_REQUEST['surcharge_ledger']][]=$_REQUEST['surcharge_amt'];
             $data2[]=array("ledgerid"=>$_REQUEST['other_ledger'],"amount"=>$_REQUEST['other_amt'],"amount_type"=>'DR');
             $amount[$_REQUEST['other_ledger']][]=$_REQUEST['other_amt'];
             if($_REQUEST['sign']=='+'){
             $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['round_off_value'],"amount_type"=>'DR'); 
             $amount[$_REQUEST['round_ledger']][]=$_REQUEST['round_off_value']; }
             else{
       $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['round_off_value'],"amount_type"=>'CR');
       $amount[$_REQUEST['round_ledger']][]=$_REQUEST['round_off_value'];
      }
     

      

				     
				           // $Lastreq_id=DB_Last_Insert_ID($db,'purchase_billbook',$ErrMsg);
				    	    $Lastreq_id=$_REQUEST['editId'];
					 $sql_delete="delete from purchase_bill_details where purch_billbookid='".$_REQUEST['editId']."'";
	 $result_delete=DB_query($sql_delete,$db);

	  $accout_id=$s->GetFieldValue("account_book","trans_type_id='".$_REQUEST['editId']."' and trans_type='PURCHASE BILL'",'id');
	  $accountid="id='".$accout_id."'";
	 // $s->DeleteRecord('account_book',$accountid);
	  $condition_acc="account_bookid='".$accout_id."'";
	  $s->DeleteRecord('account_book_details',$condition_acc);
	
 	$countval= count($_REQUEST['mst_itemid']);	
	
	   	for($i=0;$i<$countval;$i++)
		   {
		     	if($_POST['qty_as_per_bill'][$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['rate']                   = $_REQUEST['Rate'][$i];	
				$data_arr['total_price']            = $_REQUEST['totalPrice'][$i];	
				$data_arr['discount']               = $_REQUEST['Discount'][$i];
				$data_arr['discount_type']          = $_REQUEST['DiscountType'][$i];
				$data_arr['discount_amount']        =$_REQUEST['discounted_amount[]'][$i]; 
				$data_arr['basic_amt']              = $_REQUEST['basic_Amt'][$i];
				$data_arr['pkg_amt']                = $_REQUEST['pkg_Amt'][$i];

				$data_arr['tax_type']               = $_REQUEST['Excise_type'][$i];
				$excise=explode("#",$_REQUEST['Excise_Duty'][$i]);
				$data_arr['Excise_Duty']            = $excise[0];

				$data_arr['Excise_Duty_value']      = $_REQUEST['exciseValue'][$i];		
                $ecess=explode("#",$_REQUEST['Cess_ID'][$i]);
				$data_arr['ecess_id']               = $ecess[0];	
				$data_arr['Edu_Cess']               = $_REQUEST['ECessValue'][$i];
				$shecess=explode("#",$_REQUEST['SHECess_ID'][$i]);	
				$data_arr['s_ecess_id']             = $shecess[0];	
				$data_arr['SHE_Cess']               = $_REQUEST['SAHCessValue'][$i];
				$data_arr['fright_amt']             =$_REQUEST['freightItem'][$i];	

                $data_arr['vat_id']                 = $_REQUEST['inputVat'][$i];	
                $data_arr['vat_amt']                = $_REQUEST['taxvalue1'][$i];	

				$data_arr['sur_per']                = $_REQUEST['surchargeper'][$i];
				$data_arr['sur_amt']                = $_REQUEST['surchargeamt'][$i];	
				$data_arr['val_after_disc']         = $_REQUEST['TotalAmount'][$i];				
				//$data_arr['remarks']                = $_REQUEST['remarks'][$i];  

		       $sql=$s->RecordInsert('purchase_bill_details', $data_arr);
				 //echo "<pre>";
				               // print_r($data_arr);

		       /****************** Preparing Records for Account Posting *******************************/

		             if($excise[0]!='')  
		             {
		             $exciseledger=$s->GetFieldValue("accountledger","taxid='".$excise[0]."' and ledgertype='excisetax'","AccountsID");
		              $data2[$exciseledger]=array("ledgerid"=>$exciseledger,"amount"=>$_REQUEST['exciseValue'][$i],"amount_type"=>'DR');
		              $amount[$exciseledger][]=$_REQUEST['exciseValue'][$i]; 
		             }
		           if($ecess[0]!='')  
		           {
		             $ecessledger=$s->GetFieldValue("accountledger","taxid='".$ecess[0]."' and ledgertype='cess'","AccountsID"); 
		             $data2[$ecessledger]=array("ledgerid"=>$ecessledger,"amount"=>$_REQUEST['ECessValue'][$i],"amount_type"=>'DR'); 
		              $amount[$ecessledger][]=$_REQUEST['ECessValue'][$i];
		            }
		              if($shecess[0]!='') 
		               {
		              $shecessledger=$s->GetFieldValue("accountledger","taxid='".$shecess[0]."' and ledgertype='cess'","AccountsID");	
		              $data2[$shecessledger]=array("ledgerid"=>$shecessledger,"amount"=>$_REQUEST['SAHCessValue'][$i],"amount_type"=>'DR'); 
		              $amount[$shecessledger][]=$_REQUEST['SAHCessValue'][$i];    
		          }
		              if($_REQUEST['inputVat'][$i]!=''){
		              $vatledger=$s->GetFieldValue("accountledger","taxid='".$_REQUEST['inputVat'][$i]."' and ledgertype='salestax'","AccountsID");	
		              	 $data2[$vatledger]=array("ledgerid"=>$vatledger,"amount"=>$_REQUEST['taxvalue1'][$i],"amount_type"=>'DR'); 
		              	 $amount[$vatledger][]=$_REQUEST['taxvalue1'][$i];  
		              }
		               
		       /****************************************************************************************/
                    
              }
            
		  }
		  /***************************  Preparing Records Phase 2 *****************************************/
         /*    $data2[]=array("ledgerid"=>$_REQUEST['pckg_ledger'],"amount"=>$_REQUEST['pkg_charges'],"amount_type"=>'DR');
             $amount[$_REQUEST['pckg_ledger']][]=$_REQUEST['pkg_charges'];
		     $data2[]=array("ledgerid"=>$_REQUEST['insurance_ledger'],"amount"=>$_REQUEST['insr_amt'],"amount_type"=>'DR');
		     $amount[$_REQUEST['insurance_ledger']][]=$_REQUEST['insr_amt'];
             $data2[]=array("ledgerid"=>$_REQUEST['freight_ledger'],"amount"=>$_REQUEST['Freight'],"amount_type"=>'DR');
              $amount[$_REQUEST['freight_ledger']][]=$_REQUEST['Freight'];
             $data2[]=array("ledgerid"=>$_REQUEST['surcharge_ledger'],"amount"=>$_REQUEST['surcharge_amt'],"amount_type"=>'DR');
             $amount[$_REQUEST['surcharge_ledger']][]=$_REQUEST['surcharge_amt'];
             $data2[]=array("ledgerid"=>$_REQUEST['other_ledger'],"amount"=>$_REQUEST['other_amt'],"amount_type"=>'DR');
             $amount[$_REQUEST['other_ledger']][]=$_REQUEST['other_amt'];
             if($_REQUEST['sign']=='+'){
             $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['round_off_value'],"amount_type"=>'DR'); 
             $amount[$_REQUEST['round_ledger']][]=$_REQUEST['round_off_value']; }
             else{
			 $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['round_off_value'],"amount_type"=>'CR');
			 $amount[$_REQUEST['round_ledger']][]=$_REQUEST['round_off_value'];
			}
			$purchaseledger=$s->GetFieldValue("accountledger","vender_client='".$_REQUEST['vendor']."' and ledgertype='vendor'","AccountsID");

			 $data2[]=array("ledgerid"=>$purchaseledger,"amount"=>$_REQUEST['GrandTotal'],"amount_type"=>'CR');  		
			 $amount[$purchaseledger][]=$_REQUEST['GrandTotal'];	       
             $data2[]=array("ledgerid"=>$_REQUEST['ledger'],"amount"=>$_REQUEST['basic_amt'],"amount_type"=>'DR'); 
             $amount[$_REQUEST['ledger']][]=$_REQUEST['basic_amt'];	                     
 */
		  /************************************************************************************************/

		 //echo "<pre>";
				          //      print_r($data2);
		   /***************************** Posting In Account ********************************/
				        $dataArray['Branch']= $_REQUEST['site'] ;
				        $dataArray['VPrefix']= 25;
				        //$dataArray['Voucher_NO']= $strBothFinal;  
				        $dataArray['voucher_type']='Auto';     
				        $dataArray['Dates']= FormatDateForSQL($_REQUEST['voucher_date']); 
				        $dataArray['conv_rate']='1' ;  
				        $dataArray['posted_date']= date('Y-m-d');
				        $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';
				        $condition="id='".$accout_id."'";
				        $s->RecordEdit('account_book', $dataArray,$condition);
                         

				        //$getlastid=DB_Last_Insert_ID($db,'account_book', 'id');

				         $getaccountid=$s->GetFieldValue("account_book","trans_type_id='".$_REQUEST['editId']."' and trans_type='PURCHASE BILL'","id"); 

				        $total_credit='';
				        $total_debit='';
				       foreach($data2 as $key=>$value1)
				       {
				              if($value1[amount]!='0.00')
				              {
				                $data3['account_bookid']=$getaccountid;
				                $data3['ledgerid']=$value1[ledgerid];
				                $data3['amount']=array_sum($amount[$value1[ledgerid]]);
				                $data3['converted_amount']=array_sum($amount[$value1[ledgerid]]);
				                $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[]=array_sum($amount[$value1[ledgerid]]);  }
				                else if($value1[amount_type]=='CR') {  $total_credit[]=array_sum($amount[$value1[ledgerid]]); }      
				             $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($rowmrn);
	//echo $against_type;
	//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%" 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)">  
	<?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%" align="right"><strong>Voucher No.:</strong></td>
	<td width="20%"><input name="voucher_no" type="text" value="<?php echo $rowmrn['bill_book_no']; ?>"   id="bill" readonly="true"  /></td>
	<td width="13%" align="right"><strong>Voucher Date:</strong></td>
	<td><input name="voucher_date" id="voucher_date" type="text" class="datepicker"  value="<?php echo ConvertSQLDate($rowmrn['bill_book_date']); ?>" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>	
</tr>
<tr class="row1">
	<td align="right"><strong>Vendor:</strong></td>
	<td><div id="vender">
	<select name="vendor" id="vendor" onchange="showmrn(this.value)">
        <?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 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)"   >
	<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 align="right"><strong>MRN Date:</strong></td>
	<td><input type="text" name="mrn_date" id="mrnDate"  readonly value="<?php echo	 ConvertSQLDate($mrndate); ?>" /></td> 
</tr>
<input type="hidden" name="" id="against_type" value="<?php echo $ReceivedAgainst; ?>">

<tr class="row1">
	<td align="right"><strong>PO No.:</strong></td>
	<td><input name="po_no" id="poNO" type="text" readonly value="<?php echo $s->getField('purchorders','id',$orderno,'purchase_ordNo')?>"/></td>
    <td align="right"><strong>PO Date:</strong></td>
	<td><input type="text" name="po_date" id="po_date" readonly  value="<?php echo  ConvertSQLDate($podate);?>" /></td>
    <td 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'); ?>"   placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>  
</tr>
<tr class="row1">
	<td 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 align="right"><strong>Document Type:</strong></td>
	<td id="doc_type_data"><select name="doc_type" id="doc_type" >
    <option value="<?php echo $rowmrn['DocumentType'];?>" ><?php echo $arr_doc[$rowmrn['doc_type']];?></option>
    </select></td>
    <td align="right"><strong>Duty Type:</strong></td>
	<td id="doc_type_data"><select name="duty_type" id="duty_type"  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 align="right"><strong>Bill No.:</strong></td>
	<td><input type="text" name="bill_no" id="bill_no"   value="<?php  echo  $rowmrn['bill_no']; ?>"  /></td>	
	<td align="right"><strong>Bill Date:</strong></td>
	<td id="doc_type_data"><input type="text" name="bill_date" id="bill_date" value="<?php echo  ConvertSQLDate($rowmrn['bill_date']);  ?>" class="datepicker" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>
	<?php if($rowmrn['po_type']=='IO' ) { ?>
	<td align="right"><strong>CHA Ledger:</strong></td>
	<td id="doc_type_data"><select name="cha_ledger" id="cha_ledger" style="width:200px" 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 align="right"><strong>Challan No.:</strong></td>
	<td><input type="text" name="Challan_no" id="challan_no" readonly  value="<?php echo $rowmrn['challan_no']; ?> " /></td>	
	<td align="right"><strong>Challan Date:</strong></td>
	<td id="doc_type_data">
   <input type="text" name="challan_date" id="challan_date" readonly  
          value="<?php  echo  ConvertSQLDate($rowmrn['challan_date']);?>" />
	</td>
	<td 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 { ?>

<div align="right" id="charges1">
  <div id="importPo2" style="width:100%; overflow:auto;">
  <p align="center"><strong>Against :</strong>
	<input type="radio" name="calc_total_against" id="bill_id" <?php if($against_type=='bill') { ?> checked <?php } ?> value="bill" onclick="calculateAgainst3(this.value)" />
	<strong>Bill Qty.</strong> 
	<input type="radio" name="calc_total_against" <?php if($against_type=='received') { ?> checked <?php } ?> id="received_id"  value="received" onclick="calculateAgainst3(this.value)"/><strong>Received Qty.</strong></p>
   <table width="160%" cellpadding="3" cellspacing="0" id='tableDataProduction' border="1" style="border-collapse:collapse; border:#808080 1px solid;">
   	<tr>                                        
       <th>S. No.</th>
       <th>&nbsp;</th>
       <th>Item Code</th>
       <th>Item Name</th>
       <th>UOM</th>                                     
       <th colspan="2" style="text-align:center">Qty.</th>
       <th>Quoted Rate </th>
       <th>Total Price</th>
       <th colspan="2" >Discount</th>  
       <th>Discount Amount</th>  
       <th>Basic Amount</th>
       <th>Pkg Charges</th>
       <th>Excise flag</th>
       <th>Excise</th>
       <th>Excise Value</th>
       <th>E-Cess</th>
       <th>E-Cess Value</th>
       <th>SAH-E Cess</th>
       <th>SAH-E Cess Value</th>
       <th>Excise Amt.</th>
       <th>Freight and P&S</th>
       <th colspan="2">Input Vat/Cst</th>
       <th>Value</th>
       <th>Surcharge %</th>
       <th>Surcharge Amt</th>
       <th>Total Amt.</th>						  
    </tr>   
         <?php 
         $i=0;
        $sql_item_details="select * from purchase_bill_details where purch_billbookid='".$_REQUEST['editId']."'";
        $result_item_details=DB_query($sql_item_details,$db);
        while($rs_item_details=DB_fetch_array($result_item_details))
        {
        	$item_code=$s->getField('item_master','id',$rs_item_details['mst_productid'],'StockID');
        	$item_name=$s->getField('item_master','id',$rs_item_details['mst_productid'],'item_name');

        	$unit_id=$s->getField('item_master','id',$rs_item_details['mst_productid'],'mst_unitid');
        	$unit=$s->getField('unitsofmeasure','unitid',$unit_id,'unitname');
             ?>			
<tr bgcolor="#fff">
<td id='first_row'><?php echo ($i+1); ?></td>
<td><input type='hidden'  name='mst_itemid[]' value='<?php echo $rs_item_details['mst_productid']; ?>' id='itemid_<?php echo $i; ?>'  /></td>
<td><input type='text' value='<?php echo $item_code; ?>'   id='itemcode_<?php echo $i; ?>' style='width:100%;' readonly='' /></td>
<td><input type='text' value='<?php echo $item_name; ?>'  id='itemname_<?php echo $i; ?>' style='width:100%;' readonly='' /></td>
<td><input type='text' value='<?php echo $unit; ?>'  id='itemunit_<?php echo $i; ?>' style='width:100%;' readonly='' /></td>
<td ><input style='width:100%;' onkeyup='calculateFull_itemwise_pur(this);' autocomplete='off' type='text' name='qty_as_per_bill[]' id='Quantity_<?php echo $i; ?>' value='<?php echo $rs_item_details['qty_as_per_bill'];?>' onkeypress='return isNumberKey(event)'  class='get_tot' /></td>          
<td><input name="reciveqty[]" readonly type="text" id="reciveqty_<?php echo $i; ?>" value="<?php echo $rs_item_details['quantity'];?>" size="8"/></td>       
<td><input style='width:100%;' value='<?php echo $rs_item_details['rate']; ?>' autocomplete='off' onkeyup='calculateFull_itemwise_pur(this);'  onkeypress='return isNumberKey(event)' type='text' name='Rate[]' id='Rate_<?php echo $i; ?>' class='' /></td>
<td><input style='width:100%;' value='<?php echo $rs_item_details['rate']*$rs_item_details['quantity']; ?>' type='text' name='totalPrice[]' id='totalValue_<?php echo $i; ?>' readonly='true' class='tot_price'/></td>				
<td width='5%'><select style='width:100%;' name='DiscountType[]' id='PerAmo_<?php echo $i; ?>' class='item_PerAmo' onchange='calculateFull_itemwise_pur(this);' >
             	<?php $data5='';
				       $s1="";$s2="";
                    	if($rs_item_details['discount_type']=='Amount')
                    	{
                    		$s1='selected';
                    		$s2="";
                    	}
                    	elseif($rs_item_details['discount_type']=='PercentAmt')
                    	{
                    		$s2='selected';
                    		$s1='';
                    	}
					$data5.="<option ".$s1." value='Amount'>Amt</option>";
					$data5.="<option ".$s2." value='PercentAmt'>%</option>";
					echo $data5;
					?>
			 </select></td>
			
<td width='5%'><input type='text' style='width:100%;' value='<?php echo $curId =$rs_item_details['discount']; ?>' onkeyup='calculateFull_itemwise_pur(this);' autocomplete='off' name='Discount[]' onkeypress='return isNumberKey(event)' id='Discount_<?php echo $i; ?>' class='discount_item' /></td>		
<td><input type='text' name='discounted_amount[]' value='<?php echo $rs_item_details['discount_amount']; ?>' id='discounted_amount_<?php echo $i; ?>'   class='discounted_item_price' style='width:100%;' readonly/></td>
<td><input type='text' id='basic_<?php echo $i; ?>' name='basic_Amt[]' class='basic' style='width:100%;' readonly  value='<?php echo $rs_item_details['basic_amt']; ?>' class='total_item_amount'/></td>
<td><input type='text' id='pkgamt_<?php echo $i; ?>' name='pkg_Amt[]'  style='width:100%;'  value='<?php echo $rs_item_details['pkg_amt'];?>'  class='pkgamt'/></td>
<td><select name='Excise_type[]' style='width:100%;' id='hid_billing_type_<?php echo $i; ?>' onchange='calculateFull_itemwise_pur(this)'>
       <option value=''>Select</option>
       <?php 
       $data2='';
        $s2="";$s3="";
if($rs_item_details['tax_type']=='Excisable')
{
	$s2='selected';
	$s4='';
	$s3='';
}
elseif($rs_item_details['tax_type']=='NonExcisable' || $rs_item_details['tax_type']=='')
{
	$s3='selected';
	$s2='';
	$s4='';
}
elseif($rs_item_details['tax_type']=='IncludeTax')
{
	$s4='selected';
	$s2='';
	$s3='';
}
$data2.="<option ".$s2." value='NonExcisable'>NonExcisable</option>";
$data2.="<option ".$s2." value='Excisable'>Excisable</option>";
$data2.="<option ".$s4." value='IncludeTax'>IncludeTax</option>";
echo $data2;
?>						
	  </select></td>
<?php
$ExcisePercentage=$s->getField('excise_tax','id',$rs_item_details['Excise_Duty'],'def_rate');
$ECessPercentage=$s->getField('excise_tax','id',$rs_item_details['ecess_id'],'def_rate');
$SAHCessPercentage=$s->getField('excise_tax','id',$rs_item_details['s_ecess_id'],'def_rate');
if($rs_item_details['vat_id']!=''){
$vat_id=$rs_item_details['vat_id'];
$vat_per=$s->getField('sales_tax_master','salestax_id',$vat_id,'taxrate');
$sur_per=$s->getField('sales_tax_master','salestax_id',$vat_id,'surcharge_rate');
}
else {
if($vendor_state==$location_state)
$vat_id=$s->GetFieldValue("item_master","id='".$row['mst_itemid']."'","vat_purchase");
else
$vat_id=$s->GetFieldValue("item_master","id='".$row['mst_itemid']."'","cst_purchase");	
$vat_per=$s->getField('sales_tax_master','salestax_id',$vat_id,'taxrate');
$sur_per=$s->getField('sales_tax_master','salestax_id',$vat_id,'surcharge_rate');
}
?>
<td><select name='Excise_Duty[]' id='exciseDuty_<?php echo $i; ?>' style='width:100%;' onchange='calculateFull_itemwise_pur(this)'>
         <option value=''>Select</option>
<?php           
      $excise_sql=DB_query("select * from excise_tax where ledgertype like'%excisetax%' and form_type='Purchase' group by caption",$db); 
      while($excise_row=DB_fetch_array($excise_sql))
      {
      $g=''; $data12='';
      if($rs_item_details['Excise_Duty']==$excise_row['id'])
      {$g='selected';} 
        $data12.="<option value='".$excise_row['id'].'#'.$excise_row['def_rate']."' ".$g.">".$excise_row['caption']."</option>";
      }  
      echo $data12;
      ?>
        </select></td>
<td><input name='exciseValue[]' class='excise' id='exciseValue_<?php echo $i; ?>' value='<?php echo $rs_item_details['Excise_Duty_value']; ?>' type='text' style='width:100%;' /></td>
	  <?php
	    $cessLedgerSql1=DB_query("Select * from excise_tax where ledgertype like '%cess%' group by caption   ",$db);   
	    $cessLedgerSql2=DB_query("Select * from excise_tax where ledgertype like'%scess%' group by caption ",$db);  ?>
<td><select name='Cess_ID[]' id='cess_ID1_<?php echo $i; ?>' onchange='calEcessonchange(this.id,this.value)' style='width:100%;'>
	 	<?php
	 	$data3='';
	  $cessLedger1=DB_fetch_array($cessLedgerSql1);
	  if(DB_num_rows($cessLedgerSql1)>0)
	  $data3.="<option value=".$cessLedger1['id'].'#'.$cessLedger1['def_rate'].">".$cessLedger1['caption']."</option>"; 
	  else
	  $data3.="<option value=''></option>"; 
	echo $data3;
	  ?>	
	  </select></td>
<td><input name='ECessValue[]' class='ecess' readonly value='<?php echo $rs_item_details['Edu_Cess']; ?>' id='ECessValue_<?php echo $i; ?>' type='text' style='width:100%;' readonly /></td>
<td><select name='SHECess_ID[]' id='cess_ID2_<?php echo $i; ?>' style='width:100%;' onchange='calSHEcessonchange(this.id,this.value)'>
	  	<?php
	  $cessLedger2=DB_fetch_array($cessLedgerSql2);
	  if(DB_num_rows($cessLedgerSql2)>0)
	  $data1.="<option value=".$cessLedger2['id'].'#'.$cessLedger2['def_rate'].">".$cessLedger2['caption']."</option>";
	  else
       $data1.="<option value=''></option>"; 
   echo $data1;
   ?></select></td>
<td><input name='SAHCessValue[]' class='shecess' value='<?php echo $rs_item_details['SHE_Cess']; ?>' id='SAHCessValue_<?php echo $i; ?>' type='text' style='width:100%;' readonly /></td>
<?php $totalexcise=$rs_item_details['SHE_Cess']+$rs_item_details['Edu_Cess']+$rs_item_details['Excise_Duty_value']; ?>
<td><input type='text' name='taxable_amt[]' value='<?php echo $totalexcise; ?>' id='taxable_amt_<?php echo $i; ?>' style='width:100%;' onfocus='calculateTaxable(this.id)'
	   readonly/></td>
<td><input type='text' name='freightItem[]' value='<?php echo $rs_item_details['fright_amt']; ?>' class='freight' id='freightItem_<?php echo $i; ?>' style='width:100%;' 
	   onkeyup='calculateFull_itemwise_pur(this)' /></td>
	   <?php
	   $vatdesc=$s->getField('sales_tax_master','salestax_id',$vat_id,'taxrate');
	   ?>
<td><input type='text' name='' value='<?php echo $vatdesc; ?>' id='vatdes_<?php echo $i; ?>' style='width:100%;' readonly > </td>
<td><input type='hidden' value='<?php echo $vat_id; ?>' name='inputVat[]' id='inputVat_<?php echo $i; ?>'></td>
<td><input type='text' name='taxvalue1[]' class='vat' id='taxvalue_<?php echo $i; ?>' style='width:100%;' value='<?php echo $rs_item_details['vat_amt'];?>' readonly='true'/></td>
<td><input type='text' name='surchargeper[]'  id='surchargeper_<?php echo $i; ?>' style='width:100%;' value='<?php echo $sur_per; ?>' readonly='true'/></td>
<td><input type='text' name='surchargeamt[]' class='surcharge' id='surchargeamt_<?php echo $i; ?>' style='width:100%;' value='<?php echo $rs_item_details['sur_amt']; ?>'readonly='true'/></td>
<td><input type='text' id='TotalSpecial_<?php echo $i; ?>' name='TotalAmount[]' style='width:100%;' readonly 
	   class='TotalSpecial' value="<?php echo $rs_item_details['val_after_disc']; ?>" /></td>
</tr>
<?php $i++; } ?> 
<input type="hidden" name="countval2" value="<?php echo $i; ?>"  id="count"/>

 </table>
  </div>

		<table width="100%" cellpadding="3" cellspacing="0" border="0">
			<tr>
				<td valign="top" width="66%">
				<table width="100%" cellpadding="3" cellspacing="0" border="0">
				<tr class="row1">
				<td width="13%" align="right"><strong>Ledger:</strong></td>
				<td>
				<select name="ledger" id="ledger" >
				<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 align="right"><strong>Remarks If Any:</strong></td>
				<td><textarea name="remarks" id="remarks" ><?php echo $rowmrn['remarks'];?></textarea></td>
				</tr>
				  <tr class="row1">
					<td align="right"><strong>Excise Effect:</strong></td>
					<td><select name='Excise_Effect' >
					<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 align="right"><strong>Form Type:</strong></td>
				  <td><select  name="form_type" id="form_type" style="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="34%" align="right"><strong>TOTAL AMOUNT:</strong></td>
                  <td ><input type='text' name='basic_amt' readonly id='total_item_amount' value='<?php echo $total_item_amount; ?>' /></td>
               </tr>  
                <tr class='row1'>
                  <td align="right"><strong>Pkg Charges:</strong></td>
                  <td><select name="pckg_ledger" id="pkg_perc" style="width:48%; float:left;">
				  	<?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 name="pkg_charges" readonly id="pkg_charges" type="text" value="<?php echo $pkg_charges; ?>" style="width:48%; float:left;" />
				 </td>

                </tr>         
        <tr class='row1'>
        <td align="right"><strong>Excise Duty:</strong></td>
        <td><input type='text' name='excise_amt' id='excise_duty_val' value='<?php echo $excise_value; ?>'  readonly='true'/></td>
         </tr>
        <tr class='row1'>
         <td align="right"><strong>Ecess:</strong></td>
         <td><input type='text' name='ecess_amt' id='ecess_val' value='<?php echo $educess_value;?>'  readonly='true'/></td>
         </tr>
         <tr class='row1'>
         <td align="right"><strong>SHEcess:</strong></td>
          <td><input type='text' name='shecess_amt' id='shecess_val' value="<?php echo $she_ecess_value; ?>"  readonly='true'/></td>
          </tr>
          <tr class='row1'>
        <td align="right"><strong>Freight And P&amp;S:</strong></td>
        <td><select name="freight_ledger" id="TotalCharge1" style="width:48%; float:left;">	
        		  	<?php 
				  $frLedger=DB_query("Select * from accountledger where ledgertype like'%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' id='TotalCharge' value='<?php echo $freight; ?>'  readonly='true' style="width:48%; float:left;" /></td>
        </tr>
        <tr class='row1'>
        <td align="right"><strong>Vat/Cst Tax Value:</strong></td>
        <td><div id='taxval'><input type='text' name='vat_amt' id='taxvalue' value='<?php echo $taxvalue; ?>'   onkeyup="cal_grandtotal();"/></div></td>
        </tr>
         <tr class='row1'>
        <td align="right"><strong>Surcharge:</strong></td>
        <td><select name="surcharge_ledger"  id="surcharge_ledger" style="width:48%; float:left;">	
        		  	<?php 
				  $frLedger=DB_query("Select * from accountledger where ledgertype like'%surcharge%'",$db);
				  while($frLedgerRow=DB_fetch_array($frLedger))
				  {?>
				  <option value="<?php echo $frLedgerRow['AccountsID'];?>"><?php echo $frLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				  </select>	<input type='text' name='surcharge_amt' id='surcharge_amt' value='<?php echo $sur_oct_amt; ?>' onkeyup="cal_grandtotal();" style="width:48%; float:left;" /></td>
        </tr>
        <tr class='row1'>
        <td align="right"><strong>Insurance:</strong></td>
        <td><select name="insurance_ledger" id="insurance_ledger" style="width:48%; float:left;">
				  	<?php 
				  $pckLedger=DB_query("Select * from accountledger where ledgertype='insurance'",$db);
				  while($pckLedgerRow=DB_fetch_array($pckLedger))
				  {?>
				  <option value="<?php echo $pckLedgerRow['AccountsID'];?>"><?php echo $pckLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				  </select>	
        	<input name='insr_amt' id='insurance' type='text' value='<?php echo $insurance; ?>'  onkeyup='cal_grandtotal()' style="width:48%; float:left;" /></td>
      </tr>
       <tr class='row1'>
       <td align="right"><strong>Miscellaneous:</strong></td>
       <td><select name="other_ledger" id="other_ledger" style="width:48%; float:left;">
				  	<?php 
				 // $pckLedger=DB_query("Select * from accountledger where ledgertype='addcharge'",$db);
				  //	echo "Select * from accountledger where ledgertype='Other Charges'";
				  	$pckLedger=DB_query("Select * from accountledger where ledgertype='Other Charges'",$db);
				  while($pckLedgerRow=DB_fetch_array($pckLedger))
				  {?>
				  <option value="<?php echo $pckLedgerRow['AccountsID'];?>"><?php echo $pckLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				  </select>	
       	<input type='text'  name='other_amt' id='miscellaneous' value='<?php echo $add_chargess; ?>'  onkeyup='cal_grandtotal()' style="width:48%; float:left;" /></td>
       </tr>	
        <tr class='row1'>
                <td align="right"><strong>Round Off:</strong>&nbsp;</td>
                <td> <select name="round_ledger" id="" style="width:47%; float:left;">
					<?php 
					$roundLedger=DB_query("Select * from accountledger where ledgertype='round'",$db);
					while($roundLedgerRow=DB_fetch_array($roundLedger)){
					?>
					<option value="<?php echo $roundLedgerRow['AccountsID'];?>"><?php echo $roundLedgerRow['AccountName'];?></option><?php 	
				  }
				  ?></select>
				  <input type="text" name="sign" id="sign" value='<?php echo $round_off_sign; ?>' style="width:10%;float:left;">
				  <input type="text" name="round_off_value" id="round_off_value" value='<?php echo $round_off; ?>' style="width:41%;float:left;" readonly=""  ></td>
				  </tr>             
     <tr class='row1'>
	<td align="right"><strong>Grand Total:</strong></td>
    <td><input type='text' name='GrandTotal' readonly id='GrandTotal'  value='<?php echo $GrandTotal; ?>'/>
		</td></tr></table>
				  
		    </td>
		</tr></table>
		
</div>
<?php } 
if($_REQUEST["action"]!="viewReport"){
?>
<div align="center">
   <input type="submit" name="Save" class="search" value="Save"/>
   </div>
<?php } ?>
 </div>
</form>
<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)
 {
	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("Rate_"+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("Quantity_"+h).value;
				var itemRate=document.getElementById("Rate_"+h).value;
				var amtVal=parseFloat(billQty)*parseFloat(itemRate);
				document.getElementById("totalValue_"+h).value = amtVal;
				var discount = document.getElementById("Discount_"+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);
						document.getElementById("discounted_amount_"+h).value = discount;
						
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						
						document.getElementById("discounted_amount_"+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);
						document.getElementById("discounted_amount_"+h).value=midRes.toFixed(2);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
					
						document.getElementById("discounted_amount_"+h).value=0;
					}
						
						
				}

               var exciseflag=document.getElementById("hid_billing_type_"+h).value;
                if(exciseflag=='' || exciseflag=='NonExcisable')
                {
                	document.getElementById("exciseValue_"+h).value=0;
                	document.getElementById("ECessValue_"+h).value=0;
                	document.getElementById("SAHCessValue_"+h).value=0;
                	document.getElementById("taxable_amt_"+h).value=0;
                	var basic=document.getElementById("basic_"+h).value;
                	var pkg=document.getElementById("pkgamt_"+h).value;
                	var freight=document.getElementById("freightItem_"+h).value;
                	if(basic=='') basic=0;
                	if(pkg=='') pkg=0;
                	if(freight=='') freight=0;
                	var vatper=document.getElementById("vatdes_"+h).value;
                	var surper=document.getElementById("surchargeper_"+h).value;
                	var totalamt=parseFloat(basic)+parseFloat(pkg)+parseFloat(freight);
                	var vatamt=parseFloat(totalamt)*parseFloat(vatper)/100;
                	var suramt=parseFloat(vatamt)*parseFloat(surper)/100;
                	document.getElementById("taxvalue_"+h).value=vatamt.toFixed(2);
                	document.getElementById("surchargeamt_"+h).value=suramt.toFixed(2);
                	var totalamt=parseFloat(basic)+parseFloat(freight)+parseFloat(pkg)+parseFloat(vatamt)+parseFloat(suramt)+parseFloat(totalexciseamt);
                	document.getElementById("TotalSpecial_"+h).value=totalamt.toFixed(2);


                }	
                else
                {
                  var basic=document.getElementById("basic_"+h).value;
                 var pkg=document.getElementById("pkgamt_"+h).value;	
               //   alert(basic);
                 if(basic=='') basic=0;
                	if(pkg=='') pkg=0;
                  var exsiceper=document.getElementById("exciseDuty_"+h).value;
                  if(exsiceper!='')
                  {
                  	var exciseper_val=exsiceper.split("#");
                  	var totalbasic=parseFloat(basic)+parseFloat(pkg);
                  	var exciseval=parseFloat(totalbasic)*exciseper_val[1]/100;
                  	//alert(exciseval);
                  	var ecessper=document.getElementById("cess_ID1_"+h).value;
                  	if(ecessper!='')
                  	{
                  		//alert(ecessper);
                  		var eper=ecessper.split("#");
                  		var ecessamt=parseFloat(exciseval)*eper[1]/100;

                  	}	
                  	else
                  	{
                  		ecessamt=0;
                  	}
                  	var sheecessper=document.getElementById("cess_ID2_"+h).value;
                  	if(sheecessper!='')
                  	{
                  		var seper=sheecessper.split("#");
                  		var secessamt=parseFloat(exciseval)*seper[1]/100;

                  	}	
                  	else
                  	{
                  		secessamt=0;
                  	}
                  // alert(exciseval);
                	
                }
                else
                {
                  exciseval=0;	
                  ecessamt=0;	
                  secessamt=0;

                }
                var totalexciseamt=parseFloat(exciseval)+parseFloat(ecessamt)+parseFloat(secessamt);
               // alert(exciseval);
                    document.getElementById("exciseValue_"+h).value=exciseval.toFixed(2);
                	document.getElementById("ECessValue_"+h).value=ecessamt.toFixed(2);
                	document.getElementById("SAHCessValue_"+h).value=secessamt.toFixed(2);
                	document.getElementById("taxable_amt_"+h).value=totalexciseamt.toFixed(2);
                	
                	var freight=document.getElementById("freightItem_"+h).value;
                	 
                	if(freight=='') freight=0;
                	var vatper=document.getElementById("vatdes_"+h).value;
                	var surper=document.getElementById("surchargeper_"+h).value;
                	var totalamt=parseFloat(basic)+parseFloat(pkg)+parseFloat(freight)+parseFloat(totalexciseamt);
                	var vatamt=parseFloat(totalamt)*parseFloat(vatper)/100;
                	var suramt=parseFloat(vatamt)*parseFloat(surper)/100;
                	//alert(vatamt);
                	document.getElementById("taxvalue_"+h).value=vatamt.toFixed(2);
                	document.getElementById("surchargeamt_"+h).value=suramt.toFixed(2);
                	var totalamt=parseFloat(basic)+parseFloat(freight)+parseFloat(pkg)+parseFloat(vatamt)+parseFloat(suramt)+parseFloat(totalexciseamt);
                	document.getElementById("TotalSpecial_"+h).value=totalamt.toFixed(2);

                }
			}

			
				
				
				
		}
}
else
{
	// alert("hi");
		var flag=0;
	for(var h=0; h<count;h++)
		{
		if(document.getElementById("Rate_"+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("reciveqty_"+h).value;
				var itemRate=document.getElementById("Rate_"+h).value;
				var amtVal=parseFloat(billQty)*parseFloat(itemRate);
				document.getElementById("totalValue_"+h).value = amtVal;
				var discount = document.getElementById("Discount_"+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);
						document.getElementById("discounted_amount_"+h).value=discount;
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);						
						document.getElementById("discounted_amount_"+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);
					     document.getElementById("discounted_amount_"+h).value=midRes.toFixed(2);
					}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("discounted_amount_"+h).value=0;
					}
						
						
				}
               var exciseflag=document.getElementById("hid_billing_type_"+h).value;
                if(exciseflag=='' || exciseflag=='NonExcisable')
                {
                	document.getElementById("exciseValue_"+h).value=0;
                	document.getElementById("ECessValue_"+h).value=0;
                	document.getElementById("SAHCessValue_"+h).value=0;
                	document.getElementById("taxable_amt_"+h).value=0;
                	var basic=document.getElementById("basic_"+h).value;
                	var pkg=document.getElementById("pkgamt_"+h).value;
                	var freight=document.getElementById("freightItem_"+h).value;
                	if(basic=='') basic=0;
                	if(pkg=='') pkg=0;
                	if(freight=='') freight=0;
                	var vatper=document.getElementById("vatdes_"+h).value;
                	var surper=document.getElementById("surchargeper_"+h).value;
                	var totalamt=parseFloat(basic)+parseFloat(pkg)+parseFloat(freight);
                	var vatamt=parseFloat(totalamt)*parseFloat(vatper)/100;
                	var suramt=parseFloat(vatamt)*parseFloat(surper)/100;
                	document.getElementById("taxvalue_"+h).value=vatamt.toFixed(2);
                	document.getElementById("surchargeamt_"+h).value=suramt.toFixed(2);
                	var totalamt=parseFloat(basic)+parseFloat(freight)+parseFloat(pkg)+parseFloat(vatamt)+parseFloat(suramt)+parseFloat(totalexciseamt);
                	document.getElementById("TotalSpecial_"+h).value=totalamt.toFixed(2);
                }	
                else
                {
                  var basic=document.getElementById("basic_"+h).value;
                 var pkg=document.getElementById("pkgamt_"+h).value;	
                 if(basic=='') basic=0;
                	if(pkg=='') pkg=0;
                  var exsiceper=document.getElementById("exciseDuty_"+h).value;
                  
                  if(exsiceper!='')
                  {
                  	var exciseper_val=exsiceper.split("#");
                  	var totalbasic=parseFloat(basic)+parseFloat(pkg);
                  	var exciseval=parseFloat(totalbasic)*exciseper_val[1]/100;
                  //	alert(exciseval);
                  	var ecessper=document.getElementById("cess_ID1_"+h).value;
                  	if(ecessper!='')
                  	{
                  		var eper=ecessper.split("#");
                  		var ecessamt=parseFloat(exciseval)*eper[1]/100;

                  	}	
                  	else
                  	{
                  		ecessamt=0;
                  	}
                  	var sheecessper=document.getElementById("cess_ID2_"+h).value;
                  	if(sheecessper!='')
                  	{
                  		//alert("hello");
                  		//alert(exciseval);
                  		var seper=sheecessper.split("#");
                  		var secessamt=parseFloat(exciseval)*seper[1]/100;

                  	}	
                  	else
                  	{
                  		secessamt=0;
                  	}

                	 //alert(exciseval);
                }
                else
                {
                  exciseval=0;	
                  ecessamt=0;	
                  secessamt=0;

                }
               // alert(exciseval);
                var totalexciseamt=parseFloat(exciseval)+parseFloat(ecessamt)+parseFloat(secessamt);
                    document.getElementById("exciseValue_"+h).value=exciseval.toFixed(2);
                	document.getElementById("ECessValue_"+h).value=ecessamt.toFixed(2);
                	document.getElementById("SAHCessValue_"+h).value=secessamt.toFixed(2);
                	document.getElementById("taxable_amt_"+h).value=totalexciseamt.toFixed(2);
                	
                	var freight=document.getElementById("freightItem_"+h).value;
                	
                	if(freight=='') freight=0;
                	var vatper=document.getElementById("vatdes_"+h).value;
                	var surper=document.getElementById("surchargeper_"+h).value;
                	var totalamt=parseFloat(basic)+parseFloat(pkg)+parseFloat(freight)+parseFloat(totalexciseamt);
                	var vatamt=parseFloat(totalamt)*parseFloat(vatper)/100;
                	var suramt=parseFloat(vatamt)*parseFloat(surper)/100;
                	document.getElementById("taxvalue_"+h).value=vatamt.toFixed(2);
                	document.getElementById("surchargeamt_"+h).value=suramt.toFixed(2);
                	var totalamt=parseFloat(basic)+parseFloat(freight)+parseFloat(pkg)+parseFloat(vatamt)+parseFloat(suramt)+parseFloat(totalexciseamt);
                	document.getElementById("TotalSpecial_"+h).value=totalamt.toFixed(2);

                }
			}

			
				
				
		}
	}

    basic_calculation('');
		//calculate_taxable_totalamt();
 }
 function cal_grandtotal()
    {
     
     var basic_amt=document.getElementById("total_item_amount").value;
     var excise_amt=document.getElementById("excise_duty_val").value;
     var ecess_amt=document.getElementById("ecess_val").value;
     var shecess_amt=document.getElementById("shecess_val").value;
     var TotalCharge=document.getElementById("TotalCharge").value;
     var taxvalue=document.getElementById("taxvalue").value;

     var insurance=document.getElementById("insurance").value;
     var miscellaneous=document.getElementById("miscellaneous").value;
     var pkgamt=document.getElementById("pkg_charges").value;
     var surcharge_amt=document.getElementById("surcharge_amt").value;
      if(basic_amt=='') basic_amt=0;
      if(insurance=='') insurance=0;
      if(miscellaneous=='') miscellaneous=0;
       if(excise_amt=='') excise_amt=0;
        if(ecess_amt=='') ecess_amt=0;
          if(shecess_amt=='') shecess_amt=0;
            if(TotalCharge=='') TotalCharge=0;
               if(taxvalue=='') taxvalue=0;
                if(pkgamt=='') pkgamt=0;
               if(surcharge_amt=='') surcharge_amt=0;
            

      var total=(parseFloat(basic_amt)+parseFloat(insurance)+parseFloat(miscellaneous)+parseFloat(excise_amt)+parseFloat(ecess_amt)+parseFloat(shecess_amt)+parseFloat(TotalCharge)+parseFloat(taxvalue)+parseFloat(pkgamt)+parseFloat(surcharge_amt)).toFixed(2);
      
      var grand_total=total.split(".");
     // alert(grand_total);

//
       //if(grand_total[1]<10)
	   // { 
	    	//var first_digit=parseFloat(grand_total[1])*10;
	   // }
     //  else
       //	{ 
       		var first_digit=grand_total[1];
        //}
   // echo $first_digit;
 //echo "fd=".$round1[1];exit;

		/*  if(first_digit>=50)
		  {
		  var rov=100-parseFloat(first_digit);
		  var tot=parseFloat(grand_total[0])+1;
		  var sign="+";
          var roundval1=rov; 
          var roundval=parseFloat(rov)/100;
		  var grand1=tot;
		  	
		  }
		  else if(first_digit<50){
		    var sign="-";
		    var roundval1=grand_total[1]; 
           var roundval=parseFloat(first_digit)/100;
		  var grand1=grand_total[0];
		} */
		 if(first_digit>=50)
		  {
		  var rov=100-parseFloat(first_digit);
		  var tot=parseFloat(grand_total[0])+1;
		  var sign="+";
          var roundval1=rov; 
          var roundval=parseFloat(rov)/100;
		  var grand1=tot;
		  	
		  }
		  else if(first_digit<50){
		    var sign="-";
		    var roundval1=grand_total[1]; 
           var roundval=parseFloat(first_digit)/100;
		  var grand1=grand_total[0];
		}
		//alert(grand1);
      document.getElementById("sign").value=sign;
      document.getElementById("round_off_value").value=roundval.toFixed(2);
      document.getElementById("GrandTotal").value=grand1;
     

    }
</script>


