<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

 
include("config.inc.php");
include("Functions_Purchase.php");
include("Forms_DataGrid_Purchases.php");
//echo "hello";
$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

$querylog="SELECT FI_Purchases as loginaccess, ifNull(Login_location,0) As Login_location from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");

	
$querylog=" select ifNull(FI_PurchaseCategory,0) As FI_PurchaseCategory, ifNull(FI_PurchasesApp,0) As FI_PurchasesApp, ifNull(Login_FastPrint,0) As Login_FastPrint, ".
		  " ifNull(FI_PurchasesVATMod,0) As FI_PurchasesVATMod,ifNull(FI_PurchasesVAT,0) FI_PurchasesVAT ".
		  " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}
	

$querycostcent=" select costcent_applyvat ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   "";
			   
$costcentres = mysql_query($querycostcent,$connection) or die(mysql_error());
$rows=mysql_fetch_array($costcentres);
$costcent_applyvat = $rows[0];
if($costcent_applyvat=='')	$costcent_applyvat = 1;
	
//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


//Read From Module Table
$querymodule=" Select ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
			 " ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_Grn,0) As Module_Grn, ifNull(Module_DownPayment,0) As Module_DownPayment, ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_ExpireDate,0) As Module_ExpireDate, ".
			 " ifNull(Module_Unit1Method,0) As Module_Unit1Method ".
			 " ,ifNull(Module_ImportExcell,0) As Module_ImportExcell ".
			 " ,ifNull(Module_Heatno,0) As Module_Heatno, ifNull(Module_Purchase_Pending,0) As Module_Purchase_Pending, ifNull(module_locationPurchases,0) As module_locationPurchases ".
			" , ifNull(Module_PurchasesJvWHT,0) As Module_PurchasesJvWHT, ifNull(Module_ChargesPurchase,0) As Module_ChargesPurchase, ifNull(Module_sizes, 0) as Module_sizes, ".
			"  ifNull(Module_Color, 0) as Module_Color , ifNull(module_randomesupplier,0) as Module_RandomeSupplier ".	
			" From Module "; 
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

//Read From PurchaseSetup Table
$queryPurchaseSetup="Select PurchaseTTC, SupplierCur, Warehouse As SetupDftWareHouse, ifNull(ShowCostCentLayout,0) As ShowCostCentLayout,Barcode,ifNull(ShowItemSellingPrice,0) As ShowItemSellingPrice,
					ifnull(purchase_doubleunit,0) as purchase_doubleunit, ifnull(auto_paymentrqst,0) as auto_paymentrqst, ifnull(showCIF,0) as showCIF, ifnull(ShowInvoiceDate,0) as ShowInvoiceDate,
					ifnull(HeatNo_Required,0) as HeatNo_Required, ifnull(ps_restrictCurrency,0) as ps_restrictCurrency , ifnull(restrictPrice,0) as PS_restrictPrice
					From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}

$querydflwh="select default_warehouse_code as defaultwarehouse from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_warehouse_code != '' ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}

//Projects List
$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectrows   = mysql_num_rows($projectresult);
if ($projectrows == 0)
    $queryproject=" select distinct project_code, project_name from project order by project_code ";
			  
//$resultfromproject=mysql_query($queryproject,$connection) or die(mysql_error());

//Costcenter List
$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   " order by costcent.costcent_code";
			  
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentrows   = mysql_num_rows($costcentresult);
if ($costcentrows == 0)
    $querycostcent=" select distinct costcent_code, costcent_name from costcent order by costcent_code ";			  
//$resultcostcent=mysql_query($querycostcent,$connection) or die(mysql_error());



//Warehouse List
$querywarehouse=" select distinct warehouse.warehouse_code, warehouse_name ".
				" from warehouse where warehouse_code in (select warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."') ".
				" order by warehouse.warehouse_code";
$resultwh = mysql_query($querywarehouse,$connection) or die(mysql_error());
$whexist   = mysql_num_rows($resultwh);
if ($whexist == 0)
	$querywarehouse="select warehouse_code,warehouse_name from warehouse order by warehouse_code";
	
$resultwarehouse=mysql_query($querywarehouse,$connection) or die(mysql_error());


$querycurrency="select Currency_code from currency order by currency_code";
$resultcurrency=mysql_query($querycurrency,$connection) or die(mysql_error());

$querypendingtype=" select Login_Purchase_Pending ".
				" from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' ";
$resultpt = mysql_query($querypendingtype,$connection) or die(mysql_error());
$rowpt   = mysql_fetch_row($resultpt);
$Login_Purchase_Pending = $rowpt[0];



$actionmode = $_POST["actionmode"]; if ($actionmode == ""){$actionmode = $_GET["actionmode"];}   
$mainaction = $_POST["mainaction"]; if ($mainaction == ""){$mainaction = $_GET["mainaction"];} 
$mainmode   = $_POST["mainmode"]; if ($mainmode == ""){$mainmode = $_GET["mainmode"];} 
$message 	= $_POST["message"]; if ($message == ""){$message = $_GET["message"];}   
$PrPurId 	= $_POST["PrPurId"]; if ($PrPurId == ""){$PrPurId = $_GET["PrPurId"];}
$QtySerNo 	= $_POST["QtySerNo"]; if ($QtySerNo == ""){$QtySerNo = $_GET["QtySerNo"];}
$txtPaymentCondidions	= $_POST["txtPaymentCondidions"]; if ($txtPaymentCondidions == ""){$txtPaymentCondidions = $_GET["txtPaymentCondidions"];} 
$txtPurCountDetail 	= $_POST["txtPurCountDetail"]; if ($txtPurCountDetail == ""){$txtPurCountDetail = $_GET["txtPurCountDetail"];} 
$txtPurId    		= $_POST["txtPurId"]; if ($txtPurId == ""){$txtPurId = $_GET["txtPurId"];} 
$txtRef 			= $_POST["txtRef"]; if ($txtRef == ""){$txtRef = $_GET["txtRef"];} 
$txtDate 			= $_POST["txtDate"]; if ($txtDate == ""){$txtDate = $_GET["txtDate"];} 
$txtJvRef 			= $_POST["txtJvRef"]; if ($txtJvRef == ""){$txtJvRef = $_GET["txtJvRef"];} 
$txtJvFolio 		= $_POST["txtJvFolio"]; if ($txtJvFolio == ""){$txtJvFolio = $_GET["txtJvFolio"];} 
$txtMaturityDate   	= $_POST["txtMaturityDate"]; if ($txtMaturityDate == ""){$txtMaturityDate = $_GET["txtMaturityDate"];} 
$txtSupplier 	   	= $_POST["txtSupplier"]; if ($txtSupplier == ""){$txtSupplier = $_GET["txtSupplier"];} 
$txtSupplierName 	= $_POST["txtSupplierName"]; if ($txtSupplierName == ""){$txtSupplierName = $_GET["txtSupplierName"];} 
$txtSupplier1 	   	= $_POST["txtSupplier1"]; if ($txtSupplier1 == ""){$txtSupplier1 = $_GET["txtSupplier1"];} 
$txtSupplierName1 	= $_POST["txtSupplierName1"]; if ($txtSupplierName1 == ""){$txtSupplierName1 = $_GET["txtSupplierName1"];} 
$txtSupplierVat 	= $_POST["txtSupplierVat"]; if ($txtSupplierVat == ""){$txtSupplierVat = $_GET["txtSupplierVat"];} 
$txtPaymentTerms	= $_POST["txtPaymentTerms"]; if ($txtPaymentTerms == ""){$txtPaymentTerms = $_GET["txtPaymentTerms"];} 
$txtCurr   			= $_POST["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_GET["txtCurr"];} 
$txtPurCategory   	= $_POST["txtPurCategory"]; if ($txtPurCategory == ""){$txtPurCategory = $_GET["txtPurCategory"];} 
$txtRemark  		= $_POST["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_GET["txtRemark"];} 
$txtProjectCode 	= $_POST["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_GET["txtProjectCode"];} 
$txtCostCentCode	= $_POST["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_GET["txtCostCentCode"];} 
$txtInvoiceNo		= $_POST["txtInvoiceNo"]; if ($txtInvoiceNo == ""){$txtInvoiceNo = $_GET["txtInvoiceNo"];} 
$txtSrvNo			= $_POST["txtSrvNo"]; if ($txtSrvNo == ""){$txtSrvNo = $_GET["txtSrvNo"];} 
$txtWaybillNo		= $_POST["txtWaybillNo"]; if ($txtWaybillNo == ""){$txtWaybillNo = $_GET["txtWaybillNo"];} 
$txtTotalAmount		= $_POST["txtTotalAmount"]; if ($txtTotalAmount == ""){$txtTotalAmount = $_GET["txtTotalAmount"];} 
$txtPurDiscountAmt	= $_POST["txtPurDiscountAmt"]; if ($txtPurDiscountAmt == ""){$txtPurDiscountAmt = $_GET["txtPurDiscountAmt"];} 
$txtPurDiscount		= $_POST["txtPurDiscount"]; if ($txtPurDiscount == ""){$txtPurDiscount = $_GET["txtPurDiscount"];} 
$txtPurVatChk		= $_POST["txtPurVatChk"]; if ($txtPurVatChk == ""){$txtPurVatChk = $_GET["txtPurVatChk"];} 
$txtPurVatBase1		= $_POST["txtPurVatBase1"]; if ($txtPurVatBase1 == ""){$txtPurVatBase1 = $_GET["txtPurVatBase1"];} 
 
 

if (empty($mainaction))	$mainaction = 'insert';
$message = ereg_replace("'"," ",$message);

print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">

<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">
<script type="text/javascript" src="js/grid/UI_DataGrid.js"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>


<link type="text/css" href="js/calendar/jquery.datepick.css" rel="stylesheet">
<script type="text/javascript" src="js/calendar/jquery.datepick.js"></script>

<link type="text/css" href="js/grid/scripts/jquery-ui.css" rel="stylesheet">
<script type="text/javascript" src="js/grid/scripts/jquery-ui.min.js"></script>

<script type="text/javascript" language="javascript">
	$(document).ready(function() { 
		
		$(document).on('focus', '.date', function() {
			$('.date').datepick({showTrigger: '#calImg'});
		});
		
		$(document).on('focusin', '.table-focus-g1', function() {
			AutoSaveRecordGrid(this.id,'SelectedRec','ModRec_G1','imgSubmit');
			selRecordColor(this,'SelectedRec','SelectedRecColor');
		});
		
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
		//Set Cursor Position After Page Reload
		var NextElement = readCookie('pur-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('pur-nextcell');
		
		
		
	});
	
	
</script>
<script type="text/javascript" language="javascript">


function checkduplicate(PItem) {


x = document.purchase;
	
		var xmlhttp = getXMLHttpRequest();	
		var SaId  = x.txtPurId.value;
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = xmlhttp.responseText;
					 
					if(data==1)
						alert('Duplicate Item');
				
			}
		}
	    
		xmlhttp.open("GET","Form_Purchase_Actions.php?mode=checkduplicate&PItem="+PItem+"&SSaId="+SaId);
		xmlhttp.send();


}

function getItemImage(index){

	var item_code = document.getElementById('itemcode['+index+']').value;
	if(item_code != ''){
		
		if (window.XMLHttpRequest)
			{// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp=new XMLHttpRequest();
			}
		else
			{// code for IE6, IE5
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = xmlhttp.responseText.split("[BRK]");
				if(data[1] != ''){
					document.getElementById('imgholder['+index+']').innerHTML = "<img src='uploads/"+data[1]+"' height='20px' width = '20px' onclick=\"Showimage('"+item_code+"');\">";
				}
				data  = '';			
			}
		}
		
		xmlhttp.open("GET","Form_Purchase_Actions.php?actionmode=getItemImage"+"&item_code="+item_code,true);
		xmlhttp.send();
	}
}

function getItemLocation(index){

	var item_code = document.getElementById('itemcode['+index+']').value;
	if(item_code != ''){
		
		if (window.XMLHttpRequest)
			{// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp=new XMLHttpRequest();
			}
		else
			{// code for IE6, IE5
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = xmlhttp.responseText.split("[BRK]");
				if(data[1] != ''){
					document.getElementById('item_location['+index+']').value =  data[1] ;
				}
				data  = '';			
			}
		}
		 
		
		xmlhttp.open("GET","Form_Purchase_Actions.php?actionmode=getItemLocation"+"&item_code="+item_code,true);
		xmlhttp.send();
	}
}

function Showimage(vitemcode){

	win = window.open('List_Items_Picture.php?item_code='+vitemcode, 'History', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	win.creator = self;
	win.focus();	

}

function kdClient(choice,e)
{   
	 x = document.purchase;
	
	 if(choice==0)
		var suppliercode = x.txtSupplier.value;
		else
		var suppliercode = x.txtSupplierName.value;
		
    var intKey = (window.Event) ? e.which : e.keyCode;
	
		
    if (intKey == 13) { //enter key
	
	
		var xmlhttp = getXMLHttpRequest();	
		
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{ 
				var data = xmlhttp.responseText.split("[BRK]");
				  
					if(data[1]!=''){
							 
							if(choice==0)
								x.txtSupplierName.value = data[2];
							else
							x.txtSupplier.value = data[1];
								
					
						if(x.txtSupplierName.value!='')
							{
								x.submit();	
							} 
							
						
						
					}else {
					 
					document.getElementById('lstSupplierNameH').click();
				}
			}
		}
	    
		xmlhttp.open("GET","Form_Purchase_Actions.php?mode=getsuppliername&suppliercode="+suppliercode+"&choice="+choice);
		xmlhttp.send();
	
      
			
			
    }
	
	
  


}

function showlistHeatNo(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vHeatNoCode = encodeURIComponent(document.getElementById('purchasedt_heatno['+PIndex+']').value);
	
	window.open('List_HeatNo.php?frm=3&index='+PIndex+'&PHeatNoCode='+vHeatNoCode,'List_HeatNo','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}


function openhistory(vitemcode){

win = window.open('Form_ItemHistory.php?PItem_Code='+vitemcode, 'History', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	win.creator = self;
	win.focus();	

}
function UploadDocuments(vform){

var txtPurId = document.purchase.txtPurId.value;

win = window.open('UploadDocuments.php?vform='+vform+'&prqstid='+txtPurId, 'Upload', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	win.creator = self;
	win.focus();	

}



function CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, Module_PurchasesJvWHT){
  
    x = document.purchase;
	
	var PurDate = x.txtDate.value;
	var PurMaturityDate = x.txtMaturityDate.value;
	var PurSupplier = x.txtSupplier.value;
	var PurCurr = x.txtCurr.value;
	var PurProject = x.txtProjectCode.value;
	var PurCostCenter = x.txtCostCentCode.value;
	
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	if (PurDate=='' )
	{
		alert("Date Column is mandatory!");
		x.txtDate.focus();
		return 0;
	}
	else if (PurMaturityDate=='')
	{
		alert("MaturityDate Column is mandatory!");
		x.txtMaturityDate.focus();
		return 0;
	}
	else if (PurSupplier=='' )
	{
		alert("Supplier Column is mandatory!");
		x.txtSupplier.focus();
		return 0;
	}
	else if (PurCurr=='' )
	{
		alert("Currency Column is mandatory!");
		x.txtCurr.focus();
		return 0;
	}
	else if (PurProject=='' && ModuleRestProj==1 && ModuleProj==1)
	{
		alert("Project is mandatory!");
		x.txtProjectCode.focus();
		return 0;
	}
	else if (PurCostCenter=='' && ModuleRestCost==1 && ModuleCost==1 && document.getElementById('txtCostCentCode').type == 'text')
	{
		alert("CostCenter is mandatory!");
		x.txtCostCentCode.focus();
		return 0;
	}
	else if(Module_PurchasesJvWHT == 1){if (document.getElementById('txtWHTPer')) { 
		var vWHTPer = x.txtWHTPer.value;
		var vWHTAmt = x.txtWHTAmt.value;
		
		if (vWHTPer != "" && (vWHTPer*1 != vWHTPer/1 || vWHTPer < 0) ) {
			alert('WHT Percentage should be a NUMERIC and POSITIVE value.');
			x.txtWHTPer.focus();
			return 0;
		}
		else if (vWHTAmt != "" && (vWHTAmt*1 != vWHTAmt/1 || vWHTAmt < 0) ) {
			alert('WHT Amount should be a NUMERIC and POSITIVE value.');
			x.txtWHTAmt.focus();
			return 0;
		}
		
		return 1 ;
}	}	
	
	else
	return 1 ;	
}



function CheckFieldsDt(PIndex,ItemExpire,ModuleExpireDate,ItemWithSerial,ModuleSerialNo){
  
    x = document.purchase;
	
	var PurDtItem 	   = document.getElementById('itemcode['+PIndex+']').value;
	var PurDtWarehouse = document.getElementById('warehousecode['+PIndex+']').value;
	var PurDtQty       = document.getElementById('purdtquantity['+PIndex+']').value;
	var PurDtQty2	   = document.getElementById('unit2qty['+PIndex+']').value;
	var PurDtPrice     = document.getElementById('price['+PIndex+']').value;
	var PurDtDisc      = document.getElementById('purdtdiscount['+PIndex+']').value;
	var AvailableQty   = document.getElementById('porderqty['+PIndex+']').value;
	var PorderRef      = document.getElementById('porderref['+PIndex+']').value;
	
	var PurDtExpireDate = document.getElementById('expiredate['+PIndex+']').value;
	var PurDtBatchNo    = document.getElementById('batchno['+PIndex+']').value;
	var PurDtHeatNo    = document.getElementById('purchasedt_heatno['+PIndex+']').value;
	
	var vmode = x.actionmode.value;
	var HeatNo_Required = x.HeatNo_Required.value;
	
	if (PurDtPrice == '')   PurDtPrice = 0;
	if (PurDtQty2 == '')    PurDtQty2 = 0;
	if (PurDtQty == '')     PurDtQty = 0;
	if (PurDtDisc == '')    PurDtDisc = 0;
	if (AvailableQty == '') AvailableQty = 0;
	
	PurDtQty     = parseFloat(PurDtQty);	
	AvailableQty = parseFloat(AvailableQty);
	
	
	if (PurDtItem=='')
	{
		alert("Item is mandatory!");
		document.getElementById('itemcode['+PIndex+']').focus();
		return 0;
	}	
	else if (PurDtWarehouse=='')
	{
		alert("Warehouse is mandatory!");
		document.getElementById('warehousecode['+PIndex+']').focus();
		return 0;
	}
	else if (PurDtQty*1 != PurDtQty/1 || PurDtQty <= 0  ) {
		alert('Quantity ('+PurDtQty+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('purdtquantity['+PIndex+']').focus();
		return 0;
	}
	else if (PurDtQty > AvailableQty && AvailableQty >= 0 && PorderRef != "") {
		alert('Quantity entered not allowed. Qty must be <= Remaining Ordered Qty ['+AvailableQty+'].');
		document.getElementById('purdtquantity['+PIndex+']').focus();
		return 0;
	}
	else if ((PurDtPrice*1 != PurDtPrice/1 || PurDtPrice < 0) ) {
		alert('Price should be a NUMERIC and POSITIVE value');
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((PurDtDisc != '' && PurDtDisc*1 != PurDtDisc/1) ) {
		alert('Discount should be a NUMERIC value');
		document.getElementById('purdtdiscount['+PIndex+']').focus();
		return 0;
	}
	else if ((PurDtQty2 != '' && PurDtQty2*1 != PurDtQty2/1) ) {
		alert('Item Qty2 should be a NUMERIC value.');
		document.getElementById('unit2qty['+PIndex+']').focus();
		return 0;
	}
	else if (ItemExpire == 1 && ModuleExpireDate==1 && PurDtExpireDate == '' ) {
		alert('Item Expire Date is mandatory.');
		document.getElementById('expiredate['+PIndex+']').focus();
		return 0;
	}
	else if (ItemExpire == 1 && ModuleExpireDate==1 && PurDtBatchNo == '' ) {
		alert('Item Batch No is mandatory.');
		document.getElementById('batchno['+PIndex+']').focus();
		return 0;
	} 
	else if( HeatNo_Required == 1 && PurDtHeatNo == ''){
		alert('Heat No is mandatory.');
		document.getElementById('purchasedt_heatno['+PIndex+']').focus();
		return 0;
	} 
	else if( $PS_restrictPrice == 1 && PurDtPrice <= 0){
		alert('Price should be greater than ['+PurDtPrice+'].');
		document.getElementById('purchasedt_heatno['+PIndex+']').focus();
		return 0;
	}
	
	else
	return 1 ;	
}

function ClearPage(){
	if (confirm ( "Are you sure you want to Clear Page?"))
	{
		ClearForm('All');
		x = document.purchase;
		x.mainaction.value='insert';
		x.actionmode.value='';
		//x.txtPurchaseType.value='';
		x.action='Form_Purchase.php';
		x.submit();
	}	
}

function ClearPage1(){
	x = document.purchase;
	var msg = x.message.value;
	
	ClearForm('All');
	
	x.mainaction.value='insert';
	x.actionmode.value='';
	x.message.value=msg;
	x.action='Form_Purchase.php';
	x.submit();
}


function CancelRecord(){
	x = document.purchase;
	var vmode   = x.mainaction.value;
	var vmode1  = x.actionmode.value;
	var PurId   = x.txtPurId.value;
		
	if (confirm ( "Are you sure you want to Delete current pending purchase permenantly?"))
	{
		x.action="Form_Purchase_Actions.php?mode=cancel&mainmode=&SPurId="+PurId;
		x.submit();
	}
    
}

function PostChanges(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost) {
	var x = document.purchase;
	var PurId  = x.txtPurId.value;
	var vMainMode = x.mainaction.value;
	
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	var vPurVatChkbx = 0;
	if (x.chkPurVat.checked)
		vPurVatChkbx = 1;	
	
	if (x.QtySerNo.value == 1){
		alert('Please check quantity for items.');
	}	
	else if (x.txtPurCountDetail.value == 0 || x.txtPurCountDetail.value == '') {
		alert('Save not allowed. Please add items.');
	}
	else
	{
		if (result == 1) {
			if (confirm ( "Are you sure you want to Save current purchase?"))
			{
				//Save Grid Before Posting	
				var vModRec  = document.getElementById('ModRec_G1').value;
				if (vModRec != "") {
					var Obj = document.getElementById('CurRec'+vModRec);
					Obj.style.backgroundColor='#F13A3A';
					alert("Please Submit changes before.");
					
				} else {
					
					if (document.getElementById('btnPost'))
						x.btnPost.disabled = true;
					if (document.getElementById('btnCancel'))
						x.btnCancel.disabled = true;	
					if (document.getElementById('btnClear'))
						x.btnClear.disabled = true;
					if (document.getElementById('btnAddCharges'))
						x.btnAddCharges.disabled = true;	
					if (document.getElementById('btnAddItem'))
						x.btnAddItem.disabled = true;
					if (document.getElementById('btnLoadGRN'))
						x.btnLoadGRN.disabled = true;
					
					if (document.getElementById('chkpaymentrqst')){
						if(document.getElementById('chkpaymentrqst').checked)
							var autopaymentrqst = 1;
						else var autopaymentrqst = 0;
					} 
					else var autopaymentrqst = 0;
					
					x.actionmode.value='post';
					x.action="Form_Purchase_Actions.php?mode=post&mainmode="+vMainMode+"&SPurId="+PurId+"&SPurVatChkbx="+vPurVatChkbx+"&autopaymentrqst="+autopaymentrqst;
					x.submit();
				}	
			}
		}	
	}
}
	
function DeletePurDt(PurDtId, ItemPackCode, ItemCode) {
	x = document.purchase;
	var PurId  = x.txtPurId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = '';
	
	var vPurVatChkbx = 0;
	if (x.chkPurVat.checked)
		vPurVatChkbx = 1;	
	
	if (ItemPackCode != '')
	   vDelMsg = "Are you sure you want to Delete Pack Item "+ItemPackCode+" ?";
	else  
	   vDelMsg = "Are you sure you want to Delete Item "+ItemCode+" ?";
	   
	if (confirm ( vDelMsg ))
	{
		x.action="Form_Purchase_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SPurId="+PurId+"&SPurDtId="+PurDtId+"&SPurVatChkbx="+vPurVatChkbx;
		x.submit();
	}

}

function UpdatePurDt(PurDtId,PorRemQty) {
    x = document.purchase;
	var vPurId = x.txtPurId.value;
	var vPurDate = x.txtDate.value;
	var vPurVatChkbx = 0;
	if (x.chkPurVat.checked)
		vPurVatChkbx = 1;	
		
	var vMainMode = x.mainaction.value;
	
	win = window.open('Form_PurchaseDetail.php?mainaction='+vMainMode+'&actionmode=&PPurId='+vPurId+'&PPurDate='+vPurDate+'&PPurDtId='+PurDtId+'&PPurVatChkbx='+vPurVatChkbx+'&txtRemainQty='+PorRemQty, 'Form_PurchaseDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=830,height=340,top=100');		
	win.creator = self;
	win.focus();		

}

function EditPurDtQty(PurDtId, ItemCode, PorRemQty) {
	x = document.purchase;
	var PurId = x.txtPurId.value;
	
	XPos = (screen.availHeight - 150) / 2;
	YPos = (screen.availWidth - 370) / 2;
    win = window.open('Form_PurchaseEditQty.php?QItemCode='+ItemCode+'&QPurId='+PurId+'&QPurDtId='+PurDtId+'&QRemainQty='+PorRemQty, 'Form_PurchaseEditQty', 'titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,directories=no,width=370,height=150,left='+YPos+',top='+XPos);		
	win.creator = self;
	win.focus();		
}

function AddSerialNo(PurDtId, ItemCode, PurDtQty, WhCode, PorRemQty) {
	x = document.purchase;
	var PurId = x.txtPurId.value;
	
	WhCode = WhCode.replace('&','%26');
	WhCode = WhCode.replace('#','%23');
	
	XPos = (screen.availHeight - 450) / 2;
	YPos = (screen.availWidth - 550) / 2;
    win = window.open('Form_PurchaseSerialNo.php?SRItemCode='+ItemCode+'&SRItemQty='+PurDtQty+'&SRWhCode='+WhCode+'&SRPurDtId='+PurDtId+'&SRPurId='+PurId+'&SRRemainQty='+PorRemQty, 'Form_PurchaseSerialNo', 'titlebar=no,toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,directories=no, width=580,height=450,left='+YPos+',top='+XPos);
	//win.creator = self;
	//win.focus();		
	
}


function AddCharges() {
	x = document.purchase;
	var PurId  = x.txtPurId.value;
	
	if (PurId != '') {
		if (x.txtPurCategory) {
			for (var i=0; i < x.txtPurCategory.length; i++)
			{
				if (x.txtPurCategory[i].checked)
				{
				  var vPurCategory = x.txtPurCategory[i].value;
				}
			}
		} else {
			var vPurCategory = x.txtPurCategory.value;
		}
	if(document.getElementById("txtInvoiceDate"))
		var vInvoiceDate = document.getElementById("txtInvoiceDate").value;
	else var vInvoiceDate = '';
					
		var xmlhttp = getXMLHttpRequest();
			if(xmlhttp ) {
			
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200) 
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message;
					
					if (msg != "") {
						alert(decodeURIComponent(msg));
					} else {	
						win = window.open('Form_PurchaseCharges.php?txtChgPurId='+PurId, 'Form_PurchaseCharges', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=780,height=400,top=100');		
						win.creator = self;
						win.focus();													
					}
				}
			}
				
			var  the_data = 'mode=editheader&mainmode='+x.mainaction.value+
					'&SPurId='+x.txtPurId.value+'&PPurId='+x.txtPurId.value+'&txtPaymentCondidions='+x.txtPaymentCondidions.value+
					'&PPurDate='+x.txtDate.value+'&PPurCurr='+x.txtCurr.value+'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+'&PPurDiscount='+x.txtPurDiscount.value+'&PPurDiscountAmt='+x.txtPurDiscountAmt.value+
					'&PPurVatBase1='+x.txtPurVatBase1.value+'&PPurVatChkbx='+x.txtPurVatChk.value+'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+'&PPurCostCentCode='+x.txtCostCentCode.value+'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+'&PPurSrvNo='+encodeURIComponent(x.txtSrvNo.value)+
					'&PPurWaybillNo='+encodeURIComponent(x.txtWaybillNo.value)+'&PPurTotalAmount='+x.txtTotalAmount.value+'&txtInvoiceDate='+vInvoiceDate+
					'&lstWarehouse='+x.txtItemWarehouse.value+'&txtItemBarcode='+x.txtItemBarcode.value+'&txtPurDtQty='+x.txtItemQty.value;		
			xmlhttp.open("GET","Form_Purchase_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
				
	} else
	{
		alert('Please enter at least one item first.');
	}
}

//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.purchase;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtPurId.value='';
		x.txtRef.value='';
		//x.txtDate.value='';
		x.txtJvRef.value='';
		x.txtJvFolio.value='';
		//x.txtMaturityDate.value='';
		x.txtSupplier.value='';
		x.txtSupplierName.value='';
		x.txtSupplier1.value='';
		x.txtSupplierName1.value='';
		x.txtSupplierVat.value='';
		x.txtPaymentTerms.value='';
		x.txtRemark.value='';
		x.txtCurr.value='';
		x.txtProjectCode.value='';
		x.txtCostCentCode.value='';
		x.txtInvoiceNo.value='';
		x.txtSrvNo.value='';
		x.txtWaybillNo.value='';
		x.txtPaymentCondidions.value='';
		x.txtPurTaxable.value='';
		x.txtPurNoneTaxable.value='';
		x.txtPurGrossTotal.value='';
		x.txtPurDiscount.value='';
		x.txtPurDiscountAmt.value='';
		x.txtPurVat.value='';
		x.txtPurNetTotal.value='';
		x.txtPurTotalTaxes.value='';
		x.txtPurChgAmt.value='';
		x.txtPurChgAmtB1.value='';
		x.txtPurChgAmtB2.value='';
		x.txtNetTotalWithCharges.value='';
		
				
		x.message.value='';
		x.QtySerNo.value='';
		x.txtPurCountDetail.value='';
		
		x.actionmode.value = '';
		x.mainaction.value = '';
	} 
}

function AddItems(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, FIPurchaseCategory) {
	x = document.purchase;
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);

	var vPurId = x.txtPurId.value;
	var vPurDate = x.txtDate.value;
	var vPurMaturityDate = x.txtMaturityDate.value;
	var vPurSupplier = x.txtSupplier.value;
	var vPurRemark = x.txtRemark.value;
	var vPurCurr = x.txtCurr.value;
	var vPurProjectCode = x.txtProjectCode.value;
	var vPurCostCentCode = x.txtCostCentCode.value;
	var vPurInvoiceNo = x.txtInvoiceNo.value;
	var vPurSrvNo = x.txtSrvNo.value;
	var vPurWaybillNo = x.txtWaybillNo.value;
	var vPurDiscount = x.txtPurDiscount.value;
	var vPurDiscountAmt = x.txtPurDiscountAmt.value;
	var vPurVatBase1 = x.txtPurVatBase1.value;
	var txtPaymentCondidions = x.txtPaymentCondidions.value;
	
	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPurCategory.length; i++)
		{
			if (x.txtPurCategory[i].checked)
			{
			  var vPurCategory = x.txtPurCategory[i].value;
			}
		}
	} else {
		var vPurCategory = x.txtPurCategory.value;
	}	
	
	var vPurVatChkbx = 0;
	if (x.chkPurVat.checked)
		vPurVatChkbx = 1;	
	
	var vMainMode = x.mainaction.value;
	
	vPurRemark = vPurRemark.replace('&','%26');
	vPurInvoiceNo = vPurInvoiceNo.replace('&','%26');
	vPurSrvNo	  = vPurSrvNo.replace('&','%26');
	vPurWaybillNo = vPurWaybillNo.replace('&','%26');
	
	vPurRemark    = vPurRemark.replace('#','%23');
	vPurInvoiceNo = vPurInvoiceNo.replace('#','%23');
	vPurSrvNo 	  = vPurSrvNo.replace('#','%23');
	vPurWaybillNo = vPurWaybillNo.replace('#','%23');
	
	if (result == 1) {
		win = window.open('Form_PurchaseDetail.php?mainaction='+vMainMode+'&actionmode=&PPurId='+vPurId+'&PPurDate='+vPurDate+'&PPurMaturityDate='+vPurMaturityDate+
		                  '&PPurSupplier='+vPurSupplier+'&PPurCurr='+vPurCurr+'&PPurProjectCode='+vPurProjectCode+'&PPurCostCentCode='+vPurCostCentCode+'&txtPaymentCondidions='+txtPaymentCondidions+
						  '&PPurInvoiceNo='+vPurInvoiceNo+'&PPurCategory='+vPurCategory+'&PPurDiscount='+vPurDiscount+'&PPurDiscountAmt='+vPurDiscountAmt+
						  '&PPurVatBase1='+vPurVatBase1+'&PPurVatChkbx='+vPurVatChkbx+'&PPurSrvNo='+vPurSrvNo+'&PPurWaybillNo='+vPurWaybillNo+'&PPurRemark='+vPurRemark	, 
						  'Form_PurchaseDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=830,height=340,top=100');		
		win.creator = self;
		win.focus();		
	}	
	
    
}


function DeleteRecordGrid(filepath,formname,transid,PurDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	x = document.purchase;
	var vPurId    = x.txtPurId.value;
	var vPurCurr  = x.txtCurr.value;
	var vPurDate  = x.txtDate.value;
	var vPurDiscount = x.txtPurDiscount.value;
	var vMainMode = x.mainaction.value;
	var vVatChkbx = x.txtPurVatChk.value;
	var vDelMsg = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = $.parseJSON(xmlhttp.responseText);
					
				var msg = data[0].message;
					
				if (msg != "") {
					$("#Loader").removeClass("ajaxsaving");
					alert(decodeURIComponent(msg));
				} else { 
					$("#Loader").removeClass("ajaxsaving");
					ReloadGrid(filepath,formname,transid,'datagrid',index,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);			
					ReloadGridDt(filepath,'PI-TOT','TOTALS','totals',transid,-1);
				}
			}
		}

		xmlhttp.open("GET","Form_Purchase_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SPurId="+vPurId+"&SPurDtId="+PurDtId+"&SPurVatChkbx="+vVatChkbx+"&txtCurr="+vPurCurr+"&txtDate="+vPurDate+"&txtPurDiscount="+vPurDiscount);
		xmlhttp.send();
	}	

}


function SubmitRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction,ModuleRestProj,ModuleRestCost,ModuleProj,ModuleCost,ModuleExpireDate,ModuleSerialNo, FIPurchaseCategory, module_locationPurchases, Module_PurchasesJvWHT) 
{
	
	x = document.purchase;
	
	document.getElementById('imgSubmit['+PIndex+']').disabled = true;
	var itemcode  = document.getElementById('itemcode['+PIndex+']').value;
	var notallowedtoadditemduetocostcenter = false;
	 
	
	$.get( "Get_AutocompleteQuery.php?tablename=items&term="+itemcode, function( data ) {
				//  used to restrice user to add an item that belong to another cost center  , nb: will only fire  in case user have access to only specific cost center in loginstk NB cost center filtered in Get_AutocompleteQuery tablename:items
   
 
 if (parseInt(data.length) == parseInt(0) )
 {
	 alert('not allowed to add this item!');
		document.getElementById('itemcode['+PIndex+']').focus();
 }
 
	
     else
	 {
		 	
	var ItemExpire     = document.getElementById('itemexpire['+PIndex+']').value;
	var ItemWithSerial = document.getElementById('itemwithserial['+PIndex+']').value;
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	if (result == 1) {
		result = CheckFieldsDt(PIndex,ItemExpire,ModuleExpireDate,ItemWithSerial,ModuleSerialNo);
	}
	
	var PurDtId   = document.getElementById('purdtid['+PIndex+']').value;
	if (PurDtId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPurCategory.length; i++)
		{
			if (x.txtPurCategory[i].checked)
			{
			  var vPurCategory = x.txtPurCategory[i].value;
			}
		}
	} else {
		var vPurCategory = x.txtPurCategory.value;
	}	
	if(Module_PurchasesJvWHT == 1){
		
		var vPWHTAcctt = x.txtWHTAcc.value;  
		var vPWHTChk = x.txtWHTChk.value;
		var vPWHTPer = x.txtWHTPer.value;
		var vPWHTAmt = x.txtWHTAmt.value;
		
	}  else{
		var vPWHTAcctt = '';
		var vPWHTChk = 0;
		var vPWHTPer = 0;
		var vPWHTAmt = 0;
	}  
	var txtPaymentCondidions = x.txtPaymentCondidions.value;
	if(module_locationPurchases == 1)	var loc =  document.getElementById('locationcode['+PIndex+']').value;	
	
	if (document.getElementById("purdtunitprice["+PIndex+"]"))
	var vUnitprice = document.getElementById("purdtunitprice["+PIndex+"]").value;
	else var vUnitprice = 0;
	if (document.getElementById("purdtfreight["+PIndex+"]"))
	var vFreight = document.getElementById("purdtfreight["+PIndex+"]").value; 
	else var vFreight = 0;
	
	var autopaymentrqst = 0;
	
		if (document.getElementById('chkpaymentrqst')){
			if(document.getElementById('chkpaymentrqst').checked)
				autopaymentrqst = 1;
			else autopaymentrqst = 0;
		} 
		
	if(document.getElementById("txtPurDtCost["+PIndex+"]"))
		var porcost = document.getElementById("txtPurDtCost["+PIndex+"]").value;
	else var porcost = 0;
	if( porcost == '') porcost = 0;
	
	if(document.getElementById("txtPurDtFreight["+PIndex+"]"))
		var porfreight = document.getElementById("txtPurDtFreight["+PIndex+"]").value;
	else var porfreight = 0;
	if( porfreight == '') porfreight = 0;
	
	if(document.getElementById("txtInvoiceDate"))
		var vInvoiceDate = document.getElementById("txtInvoiceDate").value;
	else var vInvoiceDate = '';
	
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SPurId='+x.txtPurId.value+
					'&PPurId='+x.txtPurId.value+
					'&PPurDate='+x.txtDate.value+
					'&PPurCurr='+x.txtCurr.value+
					'&txtPaymentCondidions='+txtPaymentCondidions+
					'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+
					'&PPurSupplier1='+x.txtSupplier1.value+
					'&PPurDiscount='+x.txtPurDiscount.value+
					'&PPurDiscountAmt='+x.txtPurDiscountAmt.value+
					'&PPurVatBase1='+x.txtPurVatBase1.value+
					'&PPurVatChkbx='+x.txtPurVatChk.value+
					'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+
					'&PPurCostCentCode='+x.txtCostCentCode.value+
					'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PPurSrvNo='+encodeURIComponent(x.txtSrvNo.value)+
					'&PPurWaybillNo='+encodeURIComponent(x.txtWaybillNo.value)+
					'&PPurTotalAmount='+x.txtTotalAmount.value+
					'&SPurDtId='+document.getElementById('purdtid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecode['+PIndex+']').value+
					'&lstLocation='+loc+'&txtInvoiceDate='+vInvoiceDate+
					'&txtItemCode='+encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value)+
					'&txtPurDtRemark='+document.getElementById('remarkdt['+PIndex+']').value+
					'&txtPurDtQty='+document.getElementById('purdtquantity['+PIndex+']').value+
					'&txtPurDtQty2='+document.getElementById('unit2qty['+PIndex+']').value+
					'&txtPurDtVolume='+document.getElementById('purdtvolume['+PIndex+']').value+
					'&txtPurDtPrice='+document.getElementById('price['+PIndex+']').value+
					'&txtPurDtDiscount='+document.getElementById('purdtdiscount['+PIndex+']').value+
					'&txtPurDtBatchNo='+document.getElementById('batchno['+PIndex+']').value+
					'&txtPurDtExpireDate='+document.getElementById('expiredate['+PIndex+']').value+
					'&txtProjectCodeDt='+document.getElementById('projectcodedt['+PIndex+']').value+
					'&purchasedt_heatno='+document.getElementById('purchasedt_heatno['+PIndex+']').value+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value+
					'&txtUnitPrice='+vUnitprice+'&txtFreight='+porfreight+'&autopaymentrqst='+autopaymentrqst+
					'&txtporcost='+porcost+'&PPurShippedIn='+x.txtShippedIn.value;
		
	the_data = the_data+'&PWHTChk='+vPWHTChk+'&PWHTPer='+vPWHTPer+'&PWHTAmt='+vPWHTAmt+'&PWHTAcct='+vPWHTAcctt; 
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader").addClass("ajaxsaving");
		//$('#datagrid :input').attr('disabled', true);
		
		var SubBtnID = 'imgSubmit['+PIndex+']';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
		
		
		if(xmlhttp) {
			//xmlhttp.open("POST", "Form_Purchase_Actions.php", true);
		
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					var data = $.parseJSON(xmlhttp.responseText);
					var msg = data[0].message;
					var msgquery = data[0].messagequery;
					//alert(msgquery);
					if (msg != "") {
						$("#Loader").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtPurId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'itemcode['+index+']';
						
						createCookie('pur-nextcell',nextcell);
						
						ReloadGrid(filepath,formname,transid,'datagrid',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
							ReloadGridDt(filepath,'PI-TOT','TOTALS','totals',transid,-1);
							document.getElementById('ModRec_G1').value = "";
						});
						
						
					}
				}
			}
			
			// adds  a header to tell the PHP script to recognize the data as is sent via POST
			//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			//xmlhttp.send(the_data);
			
			xmlhttp.open("GET","Form_Purchase_Actions.php?"+the_data);
			xmlhttp.send();
		}
	}
	 }
	 
});

}

function downloadExcel(){
	var str = "Exp_ImportExcelDownload.php?transType=PI";
	window.open(str,'Import Excel Download');
}


function ImportExcell(transid,ModuleRestProj,ModuleRestCost,ModuleProj,ModuleCost,FIPurchaseCategory) {
	
	x = document.purchase;
		
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	

	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPurCategory.length; i++)
		{
			if (x.txtPurCategory[i].checked)
			{
			  var vPurCategory = x.txtPurCategory[i].value;
			}
		}
	} else {
		var vPurCategory = x.txtPurCategory.value;
	}	
	
	var vMode = 'import';
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SPurId='+x.txtPurId.value+
					'&PPurDate='+x.txtDate.value+
					'&PPurCurr='+x.txtCurr.value+
					'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+
					'&PPurDiscount='+x.txtPurDiscount.value+
					'&PPurDiscountAmt='+x.txtPurDiscountAmt.value+
					'&PPurVatBase1='+x.txtPurVatBase1.value+
					'&PPurVatChkbx='+x.txtPurVatChk.value+
					'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+
					'&PPurCostCentCode='+x.txtCostCentCode.value+
					'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PPurSrvNo='+encodeURIComponent(x.txtSrvNo.value)+
					'&PPurWaybillNo='+encodeURIComponent(x.txtWaybillNo.value)+
					'&PPurTotalAmount='+x.txtTotalAmount.value;			
	
	if (result == 1) {
			
		
		x.action="Form_Purchase_Actions.php?"+the_data;
		x.submit();	
		
	}
}

function SubmitItemBarcode(ModuleRestProj,ModuleRestCost,ModuleProj,ModuleCost,FIPurchaseCategory) {
	x = document.purchase;
	
	var vMode = 'submitbarcode';
	var transid = x.txtPurId.value;
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	if (result == 1) {
		if (x.txtItemBarcode.value=='')
		{
			result = 0;
			alert("Barcode is mandatory!");
			x.txtItemBarcode.focus();
		}
		else if (x.txtItemWarehouse.value=='')
		{
			result = 0;
			alert("Item warehouse is mandatory!");
			x.txtItemWarehouse.focus();
		}
	}
	
	
	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPurCategory.length; i++)
		{
			if (x.txtPurCategory[i].checked)
			{
			  var vPurCategory = x.txtPurCategory[i].value;
			}
		}
	} else {
		var vPurCategory = x.txtPurCategory.value;
	}	
	
	
		
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SPurId='+x.txtPurId.value+
					'&PPurId='+x.txtPurId.value+
					'&PPurDate='+x.txtDate.value+
					'&PPurCurr='+x.txtCurr.value+
					'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+
					'&PPurDiscount='+x.txtPurDiscount.value+
					'&PPurDiscountAmt='+x.txtPurDiscountAmt.value+
					'&PPurVatBase1='+x.txtPurVatBase1.value+
					'&PPurVatChkbx='+x.txtPurVatChk.value+
					'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+
					'&PPurCostCentCode='+x.txtCostCentCode.value+
					'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PPurSrvNo='+encodeURIComponent(x.txtSrvNo.value)+
					'&PPurWaybillNo='+encodeURIComponent(x.txtWaybillNo.value)+
					'&PPurTotalAmount='+x.txtTotalAmount.value+
					'&lstWarehouse='+x.txtItemWarehouse.value+
					'&txtItemBarcode='+x.txtItemBarcode.value+
					'&txtPurDtQty='+x.txtItemQty.value;
		
	
	if (result == 1) { 
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader").addClass("ajaxsaving");
		//$('#datagrid :input').attr('disabled', true);
		
		var SubBtnID = 'btnSubmitBar';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
		
		
		if(xmlhttp) {
			
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message;
					
					if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
					
					if (msg != "") {
						$("#Loader").removeClass("ajaxsaving");
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtItemBarcode.value='';
							x.txtPurId.value = transid;
							x.submit();
						} 
							
						
						ReloadGrid('Forms_DataGrid.php','PI',transid,'datagrid',0,'','ADD','PurchasesDt.PurchaseDt_ID',1,0,'',0,'',function() {
							ReloadGridDt('Forms_DataGrid.php','PI-TOT','TOTALS','totals',transid,-1);
							x.txtItemBarcode.value='';
							x.txtItemBarcode.focus();
						});
						
						
					}
				}
			}
					
			xmlhttp.open("GET","Form_Purchase_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}


}

function ShowRateParity() {
	x = document.purchase;
	
	var vPurId = x.txtPurId.value;
	
		if (vPurId != "") {
			
		if (x.txtPurCategory) {
			for (var i=0; i < x.txtPurCategory.length; i++)
			{
				if (x.txtPurCategory[i].checked)
				{
				  var vPurCategory = x.txtPurCategory[i].value;
				}
			}
		} else {
			var vPurCategory = x.txtPurCategory.value;
		}
	if(document.getElementById("txtInvoiceDate"))
		var vInvoiceDate = document.getElementById("txtInvoiceDate").value;
	else var vInvoiceDate = '';
					
		var xmlhttp = getXMLHttpRequest();
			if(xmlhttp ) {
			
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200) 
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message;
					
					if (msg != "") {
						alert(decodeURIComponent(msg));
					} else {	
						win = window.open('Form_PurchaseRates.php?PPurId='+vPurId, 'Form_PurchaseRates', 'toolbar=no,titlebar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=260,height=180,top=100,left=200');
						win.creator = self;
						win.focus();													
					}
				}
			}
				
			var  the_data = 'mode=editheader&mainmode='+x.mainaction.value+ 
					'&SPurId='+x.txtPurId.value+'&PPurId='+x.txtPurId.value+'&txtPaymentCondidions='+x.txtPaymentCondidions.value+
					'&PPurDate='+x.txtDate.value+'&PPurCurr='+x.txtCurr.value+'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+'&PPurDiscount='+x.txtPurDiscount.value+'&PPurDiscountAmt='+x.txtPurDiscountAmt.value+
					'&PPurVatBase1='+x.txtPurVatBase1.value+'&PPurVatChkbx='+x.txtPurVatChk.value+'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+'&PPurCostCentCode='+x.txtCostCentCode.value+'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+'&PPurSrvNo='+encodeURIComponent(x.txtSrvNo.value)+
					'&PPurWaybillNo='+encodeURIComponent(x.txtWaybillNo.value)+'&PPurTotalAmount='+x.txtTotalAmount.value+'&txtInvoiceDate='+vInvoiceDate+
					'&lstWarehouse='+x.txtItemWarehouse.value+'&txtItemBarcode='+x.txtItemBarcode.value+'&txtPurDtQty='+x.txtItemQty.value;		
			xmlhttp.open("GET","Form_Purchase_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
			
	} else {
		alert('Please do a purchase first !.');
	}

}

function ShowItems(){
	x = document.purchase;
	
	var vPurId = x.txtPurId.value;
	if (x.txtPurCategory) {
		for (var i=0; i < x.txtPurCategory.length; i++)
		{
			if (x.txtPurCategory[i].checked)
			{
			  var vPurCategory = x.txtPurCategory[i].value;
			}
		}
	} else {
		var vPurCategory = x.txtPurCategory.value;
	}
	if(document.getElementById("txtInvoiceDate"))
		var vInvoiceDate = document.getElementById("txtInvoiceDate").value;
	else var vInvoiceDate = '';
					
		var xmlhttp = getXMLHttpRequest();
			if(xmlhttp ) {
			
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200) 
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message;
					
					if (msg != "") {
						alert(decodeURIComponent(msg));
					} else {	
						win = window.open('Form_purchase_itemprice.php?PPurId='+vPurId, 'Form_purchase_itemprice', 'toolbar=no,titlebar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=860,height=400,top=100,left=200');
						win.creator = self;
						win.focus();													
					}
				}
			}
				
			var  the_data = 'mode=editheader&mainmode='+x.mainaction.value+ 
					'&SPurId='+x.txtPurId.value+'&PPurId='+x.txtPurId.value+'&txtPaymentCondidions='+x.txtPaymentCondidions.value+
					'&PPurDate='+x.txtDate.value+'&PPurCurr='+x.txtCurr.value+'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+'&PPurDiscount='+x.txtPurDiscount.value+'&PPurDiscountAmt='+x.txtPurDiscountAmt.value+
					'&PPurVatBase1='+x.txtPurVatBase1.value+'&PPurVatChkbx='+x.txtPurVatChk.value+'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+'&PPurCostCentCode='+x.txtCostCentCode.value+'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+'&PPurSrvNo='+encodeURIComponent(x.txtSrvNo.value)+
					'&PPurWaybillNo='+encodeURIComponent(x.txtWaybillNo.value)+'&PPurTotalAmount='+x.txtTotalAmount.value+'&txtInvoiceDate='+vInvoiceDate+
					'&lstWarehouse='+x.txtItemWarehouse.value+'&txtItemBarcode='+x.txtItemBarcode.value+'&txtPurDtQty='+x.txtItemQty.value;		
			xmlhttp.open("GET","Form_Purchase_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
		
	
}

function SearchForRef(){
    //ClearForm('All');
    x = document.purchase;
    win = window.open('Form_PurchaseSearch.php', 'Form_PurchaseSearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=1060,height=600,top=100');		
	win.creator = self;
	win.focus();		
			
}

function SearchForPending(){
    //ClearForm('All');
    x = document.purchase;
    win = window.open('Form_PurchaseSearchPending.php', 'Form_PurchaseSearchPending', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=900,height=600,top=100');		
	win.creator = self;
	win.focus();		
			
}


function LoadGRN(){
    //ClearForm('All');
    x = document.purchase;
	var vPurId = x.txtPurId.value;
	var txtSupplier = x.txtSupplier.value;
	
    win = window.open('Form_Purchase_LoadGRN.php?vPurId='+vPurId+'&txtSupplier='+txtSupplier, 'Form_Purchase_LoadGRN', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=900,height=600,top=100,left=0');		
	win.creator = self;
	win.focus();		
			
}

function SearchConfirmedPorder(FIPurchaseCategory){
	x = document.purchase;
	var vPurSupplier = x.txtSupplier.value;
	var vPurId = x.txtPurId.value;
	
	
	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPurCategory.length; i++)
		{
			if (x.txtPurCategory[i].checked)
			{
			  var vPurCategory = x.txtPurCategory[i].value;
			}
		}
	} else {
		var vPurCategory = x.txtPurCategory.value;
	}	
	
	
		var  the_data = 'mainmode='+x.mainaction.value+
					'&SPurId='+x.txtPurId.value+
					'&PPurId='+x.txtPurId.value+
					'&PPurDate='+x.txtDate.value+
					'&PPurCurr='+x.txtCurr.value+
					'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+
					'&PPurDiscount='+x.txtPurDiscount.value+
					'&PPurDiscountAmt='+x.txtPurDiscountAmt.value+
					'&PPurVatBase1='+x.txtPurVatBase1.value+
					'&PPurVatChkbx='+x.txtPurVatChk.value+
					'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+
					'&PPurCostCentCode='+x.txtCostCentCode.value+
					'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PPurSrvNo='+encodeURIComponent(x.txtSrvNo.value)+
					'&PPurWaybillNo='+encodeURIComponent(x.txtWaybillNo.value);
	
	
	win = window.open('Form_Purchase_LoadPorder.php?'+the_data, 'Form_Purchase_LoadPorder', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=1100,height=580,top=50,left=50');		
	win.creator = self;
	win.focus();		
	
}



function ChangeMaturityDate(){
	var x = document.purchase;
	var vPaymentTerms   = document.getElementById('txtPaymentTerms').value;
	var vInvoiceDate   = document.getElementById('txtInvoiceDate').value;
	var xmlhttp = getXMLHttpRequest();	
	
  
	if(xmlhttp) {
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = xmlhttp.responseText;
				x.txtMaturityDate.value = data;
				
			}
		}
				
		xmlhttp.open("GET","Form_Purchase_Actions.php?mode=changedate&mainmode=&txtPaymentTerms="+vPaymentTerms+"&txtInvoiceDate="+vInvoiceDate);
		xmlhttp.send();
		
	}
}

function ChangeDate(sdate){
	var idate = new String;
	idate = sdate;
      
    dt_array = idate.split("/");
      
    if ((dt_array[0] < 10) && (dt_array[0].length == 1))
		dt_array[0] = "0" + dt_array[0];
        
	if ((dt_array[1] < 10) && (dt_array[1].length == 1))
		dt_array[1] = "0" + dt_array[1];
   	
	// "mm/dd/yyyy"
	fdate = dt_array[1] + "/" + dt_array[0] + "/" + dt_array[2];
	
	return fdate;
}



function CalcPurDiscount(option, dec, vatapplied, vatperc) {
	x = document.purchase;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var TaxAmt = x.txtPurTaxable.value;
	var GrossTotal = x.txtPurGrossTotal.value;
	var DisPer = x.txtPurDiscount.value;
	var DisAmt = x.txtPurDiscountAmt.value;
	var VatAmt = x.txtPurVat.value;
	var TaxesAmt   = x.txtPurTotalTaxes.value;
	var ChargesAmt = x.txtPurChgAmt.value;
	
	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
		alert('Discount Amount should be a NUMERIC value');
		x.txtPurDiscountAmt.focus();
		return 0;
	}
	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
		alert('Discount Percentage should be a NUMERIC value');
		x.txtPurDiscount.focus();
		return 0;
	}
	
	
	if (TaxAmt == '') TaxAmt = 0;
	if (GrossTotal == '') GrossTotal = 0;
	if (DisPer == '') DisPer = 0;
	if (DisAmt == '') DisAmt = 0;
	if (TaxesAmt == '') TaxesAmt = 0;
	if (ChargesAmt == '') ChargesAmt = 0;
	
	TaxAmt = parseFloat(TaxAmt);
	GrossTotal = parseFloat(GrossTotal);
	DisPer = parseFloat(DisPer);
	DisAmt = parseFloat(DisAmt);
	VatAmt = parseFloat(VatAmt);
	TaxesAmt = parseFloat(TaxesAmt);
	ChargesAmt = parseFloat(ChargesAmt);
	
	if (GrossTotal > 0 && (DisPer > 0 || DisAmt > 0)) {
		if (option == 1 )  //Option by Percentage Get The Amount
			x.txtPurDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
		else if (option == 2 ){  //Option by Amount Get The Per
		    x.txtPurDiscount.value = roundNumber(((DisAmt/GrossTotal)*100),dec);
			
			if (DisAmt > 0)	x.txtPurDiscount.readOnly = true; 
			else  x.txtPurDiscount.readOnly = false;
		}

		// Calculation of Vat Amount and Net Total
		DisAmt = x.txtPurDiscountAmt.value;
		if (DisAmt == '') DisAmt = 0;
		DisAmt = parseFloat(DisAmt);
		
		VatAmt = 0;
		if (vatapplied == 1) {
			if (TaxAmt > 0)
				VatAmt = roundNumber(((TaxAmt - (DisAmt*TaxAmt/GrossTotal))*vatperc/100),dec);
		} 
		
		VatAmt = parseFloat(VatAmt);		
		x.txtPurVat.value      = formatNumber(VatAmt,dec);
		x.txtPurNetTotal.value = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);
		x.txtNetTotalWithCharges.value = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt + ChargesAmt),dec),dec);
	}   
	
	
	
}

function SetPurVat(dec, vatapplied, vatperc, PurchaseTTC) {
	x = document.purchase;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var vAmount = 0;
	
	var TaxAmt = x.txtPurTaxable.value;
	var GrossTotal = x.txtPurGrossTotal.value;
	var VatAmt = x.txtPurVat.value;
	var DisAmt = x.txtPurDiscountAmt.value;
	var NetTotal = x.txtPurNetTotal.value;
	var TaxesAmt = x.txtPurTotalTaxes.value;
	var ChargesAmt = x.txtPurChgAmt.value;
	var othercharges = x.txtPur_Othercharges.value;
	
	if (TaxAmt == '') TaxAmt = 0;
	if (GrossTotal == '') GrossTotal = 0;
	if (VatAmt == '') VatAmt = 0;
	if (DisAmt == '') DisAmt = 0;
	if (NetTotal == '') NetTotal = 0;
	if (TaxesAmt == '') TaxesAmt = 0;
	if (ChargesAmt == '') ChargesAmt = 0;
	if(othercharges == '') othercharges = 0;
	
	VatAmt = parseFloat(VatAmt);
	NetTotal = parseFloat(NetTotal);
	DisAmt = parseFloat(DisAmt);
	TaxAmt = parseFloat(TaxAmt);
	GrossTotal = parseFloat(GrossTotal);
	TaxesAmt = parseFloat(TaxesAmt);
	ChargesAmt = parseFloat(ChargesAmt);
	
	if (x.chkPurVat.checked) {
		x.txtPurVatChk.value = 1;
		
		// Calculation of Vat Amount and Net Total
		if (PurchaseTTC == 1) {	
			if (vatapplied == 1) {
				if (TaxAmt > 0) {
					vAmount = roundNumber((1 + (1 - (DisAmt/GrossTotal))*vatperc/100),20);
					GrossTotal = GrossTotal - TaxAmt;
					TaxAmt = roundNumber((TaxAmt/vAmount),dec);
					GrossTotal = GrossTotal + TaxAmt;
					VatAmt = roundNumber((((TaxAmt ) - (DisAmt*TaxAmt/GrossTotal))*vatperc/100),dec);
				}	
			}
		}
		else {
			VatAmt = 0;
			
			if (vatapplied == 1) {
				if (TaxAmt > 0)
					VatAmt = roundNumber((((TaxAmt) - (DisAmt*(TaxAmt)/GrossTotal))*vatperc/100),dec);
			}
		}
		
		VatAmt = parseFloat(VatAmt);
		TaxAmt = parseFloat(TaxAmt);
		GrossTotal = parseFloat(GrossTotal);
		
		x.txtPurTaxable.value    = formatNumber(TaxAmt,dec);
		x.txtPurGrossTotal.value = formatNumber(GrossTotal,dec);
		x.txtPurVat.value        = formatNumber(VatAmt,dec);
		x.txtPurNetTotal.value   = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);	
		x.txtNetTotalWithCharges.value   = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt + ChargesAmt),dec),dec);	
	}
	else
	{
		x.txtPurVatChk.value = 0;
		
		if (PurchaseTTC == 1) {
			x.txtPurVat.value        = formatNumber(0,dec);
			x.txtPurTaxable.value    = formatNumber(TaxAmt + VatAmt,dec);
			x.txtPurGrossTotal.value = formatNumber(GrossTotal + VatAmt,dec);
		}
		else {
			x.txtPurVat.value      = formatNumber(0,dec);
			x.txtPurNetTotal.value = formatNumber(roundNumber((NetTotal - VatAmt),dec),dec);
			x.txtNetTotalWithCharges.value = formatNumber(roundNumber((NetTotal - VatAmt + ChargesAmt),dec),dec);
		}
	   
	}  


}

function ChangeCurrency() {
	x = document.purchase;
	var PurId = x.txtPurId.value;
	
	if (PurId != '') {
		var vPurVatChkbx = 0;
		if (x.chkPurVat.checked) vPurVatChkbx = 1;
		
		x.action="Form_Purchase_Actions.php?mode=changecurrency&SPurId="+PurId+"&SPurVatChkbx="+vPurVatChkbx;
		x.submit();
	} else {
		x.submit();
	}
}

function PrintPurchase(PurId, PurRef) {
	var str = '';
	//var PurId = document.purchase.txtPurId.value;
	if (confirm ( "Do you want to Print current Purchase with reference "+PurRef+" ?"))
	{
		str = 'Form_PurchasePreview.php?PurchaseId='+PurId;
		window.open(str);
	}	
}

function PrintBarcode(PurId, PurRef, temp) {
	var c = confirm("Do you want to print the items' barcode ?");
	if(c){
		var str = "Rep_ItemBarcodeList.php?PurId="+PurId+"&temp="+temp;
		window.open(str,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
	}
}

function showlistSupplier(str){
	var vdate, vcode;
	vdate=document.purchase.txtDate.value;
	 
	if(str != 55)
		vcode=encodeURIComponent(document.purchase.txtSupplier.value);
	else if(str == 55)
		vcode=encodeURIComponent(document.purchase.txtSupplier1.value);

	window.open('List_Supplier.php?frm=3&item='+str+'&PLedger_number='+vcode+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}
function showlistSupplierName(str) {
	var vdate, vcode;
	vdate=document.purchase.txtDate.value;
	
  
	if(str != 55){
		vcode=encodeURIComponent(document.purchase.txtSupplier.value);
		vname=encodeURIComponent(document.purchase.txtSupplierName.value);
	}
	else if(str == 55){
		vcode=encodeURIComponent(document.purchase.txtSupplier1.value);
		vname=encodeURIComponent(document.purchase.txtSupplierName1.value);
	}

	window.open('List_Supplier.php?frm=3&item='+str+'&PLedger_number='+vcode+'&PLedger_name='+vname+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}


function showlistProject(str){

	vProjectCode = encodeURIComponent(document.getElementById('txtProjectCode').value);
	window.open('List_Project.php?item='+str+'&PProject_Code='+vProjectCode,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(str){

	vCostcentCode = encodeURIComponent(document.getElementById('txtCostCentCode').value);
	window.open('List_Costcenter.php?item='+str+'&PCostcent_Code='+vCostcentCode,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}


function showlistProjectDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vProjectCode = encodeURIComponent(document.getElementById('projectcodedt['+PIndex+']').value);
	
	window.open('List_SorProject.php?frm=25&index='+PIndex+'&item='+str+'&PProject_Code='+vProjectCode,'List_SorProject','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistCostcenterDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vCostcentCode = encodeURIComponent(document.getElementById('costcentcodedt['+PIndex+']').value);
	
	window.open('List_SorCostcenter.php?frm=25&index='+PIndex+'&item='+str+'&PCostcent_Code='+vCostcentCode,'List_SorCostcenter','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}


function showlistItems(str,PIndex,vcurr){
	var vDate, vItemCode;
	x = document.purchase;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemCode  = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
  
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&PItem_Code='+vItemCode+'&ItemType=All&TransDate='+vDate+'&vcurr='+vcurr,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistItemsDesc(str,PIndex){
	var vDate, vItemCode;
	x = document.purchase;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemDesc  = encodeURIComponent(document.getElementById('itemdescription['+PIndex+']').value);
	
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&PItem_Description='+vItemDesc+'&ItemType=All&TransDate='+vDate,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

/* function showlistWarehouse(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_SorWarehouse.php?frm=2&index='+PIndex+'&PWarehouse_Code='+vWarehouseCode,'List_SorWarehouse','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
} */

function showlistWarehouse(PIndex, type) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	if(type=='shelf') {
		if(encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value) == '') {
			alert('Please Select a Warehouse!');
			return 0;
		}
	}
	
	if(type=='warehouse')
	var vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	else var vWarehouseCode = encodeURIComponent(document.getElementById('locationcode['+PIndex+']').value);
	pwh=encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_SorWarehouse.php?frm=2&index='+PIndex+'&PWarehouse_Code='+vWarehouseCode+'&warehouse_type='+type+'&parentWh='+pwh,'List_SorWarehouse','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistWarehouse1() {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('txtItemWarehouse').value);
	
	window.open('List_SorWarehouse.php?frm=5&PWarehouse_Code='+vWarehouseCode,'List_SorWarehouse','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}


function CalcPurDtTotal(option,dec,PIndex) {
	x = document.purchase;
	var vmode = x.actionmode.value;
	var Qty      = document.getElementById('purdtquantity['+PIndex+']').value;
	var Price    = document.getElementById('price['+PIndex+']').value;
	var Discount = document.getElementById('purdtdiscount['+PIndex+']').value;
	var Total    = document.getElementById('purdttotal['+PIndex+']').value;
	
	if (Qty == '') 		Qty = 0;
	if (Price == '') 	Price = 0;
	if (Discount == '') Discount = 0;
	if (Total == '')    Total = 0;
	
	Qty      = parseFloat(Qty);
	Price    = parseFloat(Price);
	Discount = parseFloat(Discount);
	Total    = parseFloat(Total);
	
	if (Qty > 0 && Price >= 0 && option == 1) {
	   document.getElementById('purdttotal['+PIndex+']').value = roundNumber(((Qty*Price) - roundNumber((Qty*Price*Discount/100),0)),dec);
	}  
	else if (Qty > 0 && Total > 0 && option == 2)  { 
		document.getElementById('price['+PIndex+']').value = (Total/roundNumber((Qty*(1-Discount/100)),2));
	}
}

function CalcDtPrice(option,dec,PIndex){ 
	
	var purcost = document.getElementById("txtPurDtCost["+PIndex+"]").value;
	var purfreight = document.getElementById("txtPurDtFreight["+PIndex+"]").value;
	var qty = document.getElementById("purdtquantity["+PIndex+"]").value;
	if(purcost == '') purcost = 0;
	if(purfreight == '') purfreight = 0;
	if(qty == '') qty = 0;
	
	var purprice = parseFloat(purcost) + parseFloat(purfreight); 
	document.getElementById("price["+PIndex+"]").value = roundNumber(purprice,dec);
	document.getElementById("purdttotal["+PIndex+"]").value = qty*roundNumber(purprice,dec);
}


function CalcQty2(ModuleUnit1Method,Option,PIndex) { 
	x = document.purchase;
	var Qty  = document.getElementById('purdtquantity['+PIndex+']').value; 
	var Qty2 = document.getElementById('unit2qty['+PIndex+']').value;
	var UnitCoef = document.getElementById('itemunitcoef['+PIndex+']').value;
	
	if (Qty == '')  Qty = 0;
	if (Qty2 == '') Qty2 = 0;
	
	if(ModuleUnit1Method == 1) {
		if (Qty > 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty*UnitCoef;
		}	
		else if (Qty == 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty and Qty2 Should Be Empty
	else if(ModuleUnit1Method == 0 && Option == 1 && Qty2 == 0) {
		if (Qty > 0 && UnitCoef != 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty/UnitCoef;
		}	
		else if (Qty == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty2 Get Qty
	else if(ModuleUnit1Method == 0 && Option == 2) {
		if (Qty2 > 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('purdtquantity['+PIndex+']').value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('purdtquantity['+PIndex+']').value = '';
		}
	}
}

function ShowSlidingDiv(PDivID) {
	$(PDivID).slideToggle();
}


function kd(e)
{
	x=document.purchase;
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { //enter key
        //x.btnSubmitRecord.click();
		return false;
    }
    return true;
}



function Barcodekd(e)
{ 
	x=document.purchase;
    var intKey = (window.Event) ? e.which : e.keyCode;
			
    if (intKey == 13) { //enter key
        x.btnSubmitBar.click();
		return false;
    }
	
    return true;
}
function showlistLedgers(str){
	x = document.purchase;
	var vTransType = 'JP';
	
	window.open('Form_Trans_ListLedgers.php?str=9&PTransType='+vTransType+'&PAccountType=WHT','mywindow','width=650,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');

}
function SetWHT(dec) {
	var x = document.purchase;
	
	if (x.chkWHT.checked) {
		x.txtWHTChk.value = 1;

	} else {
		x.txtWHTChk.value = 0;
		x.txtWHTPer.value = '';
		x.txtWHTAmt.value = '';
		x.txtWHTAcc.value='';
	}

}
function CalcWHTAmount(dec) {
	var x = document.purchase;
	
	var WHTPer       = x.txtWHTPer.value;
	var NetTotal     = x.txtNetTotalWithCharges.value;
	var vat = x.txtPurVat.value;
	if (vat == '') vat = 0;
	
	if (WHTPer == '') 		WHTPer = 0;
	if (NetTotal == '') 	NetTotal = 0;
	
	WHTPer		 = parseFloat(WHTPer);
	NetTotal	 = parseFloat(NetTotal) - parseFloat(vat);
	
	if (x.chkWHT.checked) {
		x.txtWHTChk.value = 1;
		
		if(WHTPer > 0 && NetTotal > 0) {
			x.txtWHTAmt.value = formatNumber(roundNumber((NetTotal * WHTPer/100),dec),dec);
		
		}
	}
}

function CalcNetTotal(option, dec, vatapplied, vatperc) {
	x = document.purchase;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var TaxAmt = x.txtPurTaxable.value;
	var GrossTotal = x.txtPurGrossTotal.value;
	var DisPer = x.txtPurDiscount.value;
	var DisAmt = x.txtPurDiscountAmt.value;
	var VatAmt = x.txtPurVat.value;
	var TaxesAmt = x.txtPurTotalTaxes.value;
	var Othercharges = x.txtPur_Othercharges.value;
	
	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
		alert('Discount Amount should be a NUMERIC value');
		x.txtPurDiscountAmt.focus();
		return 0;
	}
	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
		alert('Discount Percentage should be a NUMERIC value');
		x.txtPurDiscount.focus();
		return 0;
	}
	
	
	if (TaxAmt == '') TaxAmt = 0;
	if (GrossTotal == '') GrossTotal = 0;
	if (Othercharges == '') Othercharges = 0;
	if (DisPer == '') DisPer = 0;
	if (DisAmt == '') DisAmt = 0;
	if (TaxesAmt == '') TaxesAmt = 0;
	
	TaxAmt = parseFloat(TaxAmt);
	GrossTotal = parseFloat(GrossTotal) ;
	Othercharges = parseFloat(Othercharges)
	DisPer = parseFloat(DisPer);
	DisAmt = parseFloat(DisAmt);
	VatAmt = parseFloat(VatAmt);
	TaxesAmt = parseFloat(TaxesAmt);
	 
	if (GrossTotal > 0 ) 
	{
		if (option == 1 )  //Option by Percentage Get The Amount
			x.txtPurDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
		else if (option == 2 ){  //Option by Amount Get The Per
		    x.txtPurDiscount.value = roundNumber(((DisAmt/GrossTotal)*100),dec);
				
			if (DisAmt > 0) x.txtPurDiscount.readOnly = true; 
			else x.txtPurDiscount.readOnly = false;
					
		}

		// Calculation of Vat Amount and Net Total
		DisAmt = x.txtPurDiscount.value;
		if (DisAmt == '') DisAmt = 0;
		DisAmt = parseFloat(DisAmt);
		//GrossTotal=GrossTotal+Othercharges;
		VatAmt = 0;
		if (vatapplied == 1) {
			if (TaxAmt > 0)
				VatAmt = roundNumber(((TaxAmt - (DisAmt*TaxAmt/GrossTotal))*vatperc/100),dec);
		} 
		
		VatAmt = parseFloat(VatAmt);		
		x.txtPurVat.value      = formatNumber(VatAmt,dec);
		x.txtPurNetTotal.value = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);
		
	}   
	
	update_netcharges();	
}
function update_netcharges(){
x = document.purchase;

var vnet = x.txtPurNetTotal.value;
vnet=parseFloat(vnet);
if(vnet=='') vnet=0;

var vCharges = x.txtPur_Othercharges.value;
vCharges=parseFloat(vCharges);
if(vCharges=='') vCharges=0;

x.txtNetTotalWithCharges.value = vCharges+vnet;
}

function changeQty2(vuniteQty,index){
	var vUnit2 = document.getElementById("itemunit2["+index+"]").value;
	
	if(vUnit2 == '') vUnit2 =0;
	if(vuniteQty == '') vuniteQty=0;
	document.getElementById("purdtquantity["+index+"]").value = vuniteQty/vUnit2;
	var newqty = document.getElementById("purdtquantity["+index+"]").value;
	if(document.getElementById("purdttotal["+index+"]"))
	 document.getElementById("purdttotal["+index+"]").value = parseFloat(newqty)*parseFloat(document.getElementById("price["+index+"]").value);
	
	
}

function CalcPurDtPrice(decimalbase,index){
	var unitprice = document.getElementById("purdtunitprice["+index+"]").value;
	var freight = document.getElementById("purdtfreight["+index+"]").value; 
	if(unitprice != '' && freight!= ''){
		document.getElementById("price["+index+"]").value = parseFloat(unitprice)+parseFloat(freight);
		CalcPurDtTotal(1,decimalbase,index);
	}
}
function showlistBatchNo(str,PIndex) {
	x = document.sales;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 580) / 2;
	
	vItemCode = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
	vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_BatchNo.php?frm=2&index='+PIndex+'&PItem_Code='+vItemCode+'&PWarehouseCode='+vWarehouseCode,'List_BatchNo','width=580,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}


function SetMaturityDate() {

	x = document.purchase;
	
	   var str   = document.getElementById('txtPaymentTerms').value;
		var str1 = '';
		
		if (str == '') str = 0;
		var sdays = parseInt(str);	
		var sdate = document.getElementById('txtDate').value;
		sdate = ChangeDate(sdate);
		var d = new Date(sdate); 
		
		d.setDate(d.getDate() + sdays); 
		
		str = d.getDate();
		str1 = str.toString();
		
		if (str1.length == 1)
     		str1 = "0"+str1;
			
		str = d.getMonth()+1;
		str2 = str.toString();
		
		if (str2.length == 1)
     		str2 = "0"+str2;	
		
		
		x.txtMaturityDate.value=(str1 + "/" + str2 + "/" + d.getFullYear()); 
		
  
		
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Purchases</title>



<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>

</head>
<body >
<form name='purchase' method='post'  enctype='multipart/form-data'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='QtySerNo' value='$QtySerNo'>
<input type='hidden' name='message' value='$message' size='200'>
<input type='hidden' name='HeatNo_Required' value='$HeatNo_Required' size='1'>
HERE;

//$message='';

	
//Initializations

$PriceLabel = 'Price';	
if ($PurchaseTTC == 1) 	
	$PriceLabel = 'Price TTC';	


//Get Default Project from salessetup
$querydflproject="select project as defaultprojectpurchasesetup from purchasesetup ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}
 
 
 
	
//Get Default Project
$querydflproject="select project_code as defaultproject from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_project=1 ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}
 

 if ( empty($defaultproject))
 {
	 $defaultproject =  $defaultprojectpurchasesetup;
 }
 
 
	
//Get Default Coscenter
$querydflcostcent="select costcent_code as defaultcostcent from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_costcenter=1 ";
$resultdflcostcent=mysql_query($querydflcostcent,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflcostcent)){
	extract($rows);
}

	
if ((empty($txtProjectCode)) && $Module_Project == 1)
	$txtProjectCode = $defaultproject;
if ((empty($txtCostCentCode)) && $Module_CostCenter == 1)
	$txtCostCentCode = $defaultcostcent;	
if (empty($txtCurr)) {
	if ($SupplierCur != '')
		$txtCurr = $SupplierCur;
	else
		$txtCurr = $base1;
}
	
if (empty($txtDate))	
	$txtDate = displayToday();
if (empty($txtMaturityDate))	
	$txtMaturityDate = displayToday();
if (empty($txtInvoiceDate))	
	$txtInvoiceDate = displayToday();



if ($FI_PurchaseCategory == 0 || $FI_PurchaseCategory == 1) $txtPurCategory = 0;
else if ($FI_PurchaseCategory == 2) $txtPurCategory = 1;	


if (empty($txtItemWarehouse)) {
	if (!empty($SetupDftWareHouse))
		$txtItemWarehouse = $SetupDftWareHouse;
	else	
		$txtItemWarehouse = $defaultwarehouse;
}

if (empty($txtItemQty)) $txtItemQty = 1;


if ($txtPurId != '') {
	// Read From Temp Tables For Selected Record				 
	$query = " Select Purchase_ID, Purchase_Reference, Date_Format(Purchase_Date,'%d/%m/%Y') As Purchase_Date, ".
	         " Date_Format(Journaldt_valuedate,'%d/%m/%Y') As Maturity_Date, Purchases.Currency_code, ".
			 " Purchases.Supplier_code As SupplierCode,	Suppliers.Ledger_name As SupplierName, Suppliers.Supplier_PaymentTerms,  ".
			 " Purchase_Remark, Purchase_InvoiceNo, Purchases.Project_Code, Purchases.Costcent_code,  ".
			 " Round(Purchase_Taxable, ".$DecimalBase."), Round(Purchase_NoneTaxable, ".$DecimalBase."), ".
			 " Round(Purchase_Total, ".$DecimalBase.") As GrossTotal, ".
			 " Round(Purchase_DiscountPer, ".$DecimalBase."), Round(Purchase_DiscountAmount, ".$DecimalBase."),  ".
			 " Round(Purchase_VAT, ".$DecimalBase.") As Purchase_VAT, Round(Purchase_VATBase1, ".$DecimalBase.") As Purchase_VATBase1, ".
			 " Round((Purchase_Total + IfNull(Purchase_VAT,0) - IfNull(Purchase_DiscountAmount,0) + (ifNull(Purchase_Tax1,0) + ifNull(Purchase_Tax2,0) + ifNull(Purchase_Tax3,0) + ifNull(Purchase_Tax4,0) + ifNull(Purchase_Tax5,0))), ".$DecimalBase.") As Purchase_NetTotal,  ".
			 " Suppliers.Supplier_VAT, Round(ifNull(Purchase_Charges,0), ".$DecimalBase."), Round(ifNull(Purchase_ChargesBase1,0), ".$DecimalBase."), Round(ifNull(Purchase_ChargesBase2,0), ".$DecimalBase."), ".
			 " ifNull(Purchase_VatChkbx,0) As Purchase_VatChkbx, ".
			 " Round((ifNull(Purchase_Tax1,0) + ifNull(Purchase_Tax2,0) + ifNull(Purchase_Tax3,0) + ifNull(Purchase_Tax4,0) + ifNull(Purchase_Tax5,0)), ".$DecimalBase.") As TotalTaxes,  ".
			 " Journal.Journal_folio, Journal.Journal_refgovernment, ifNull(Purchase_Import,0), Purchases.SrvNo, Purchases.WaybillNo, Purchases.Purchase_TotalAmount, purchase_paymentcondition ".
			 " , purchase_type, Purchase_WHTChk, Purchase_WHTAccount, Purchase_WHTPer,Purchase_WHTAmt, ifnull(auto_paymentrqst,0), Purchase_shippedIn,Date_Format(InvoiceDate,'%d/%m/%Y') as InvoiceDate, ".
			 " ifnull(Purchase_Grn,0) , ".
			 " Supplier_Code1 As SupplierCode1, s2.Ledger_name As SupplierName1".
			 " From Temp_Purchases As Purchases ". 
			 " Left Join Suppliers on Purchases.Supplier_code = Suppliers.Ledger_Number ".
			 " Left Join Suppliers s2 on Purchases.Supplier_code1 = s2.Ledger_Number ".
			 " Left Join Journal on Purchases.Journal_ID = Journal.Journal_ID ".
	         " Where Purchase_ID = ".$txtPurId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
			 
//	echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	
	$txtPurId = $rows[0];
	$txtRef = $rows[1];
	$txtDate = $rows[2];
	$txtMaturityDate = $rows[3];
	
	if ($txtSupplier == '') {
		$txtSupplier = $rows[5];
		$txtSupplierName = $rows[6];
		$txtSupplier1 = $rows[42];
		$txtSupplierName1 = $rows[43];
		$txtPaymentTerms = $rows[7];
		$chkPurVat = $rows[24];
		$txtSupplierVat = $rows[20];
	}	
	$txtRemark = $rows[8];
	$txtCurr = $rows[4];
	$txtProjectCode = $rows[10];
	$txtCostCentCode = $rows[11];
	
	$txtInvoiceNo = $rows[9];
	$txtPurCategory = $rows[28];
	$txtSrvNo = $rows[29];
	$txtWaybillNo = $rows[30];
	
	$txtPurTaxable = $rows[12];
	$txtPurNoneTaxable = $rows[13];
	$txtPurGrossTotal = $rows[14];
	$txtPurDiscount = $rows[15];
	$txtPurDiscountAmt = $rows[16];
	$txtPurVat = $rows[17];
	$txtPurVatBase1 = $rows[18];
	$txtPurNetTotal = $rows[19];
	$txtPurTotalTaxes  = $rows[25];
	
	
	$txtPurChgAmt   = $rows[21];
	$txtPurChgAmtB1 = $rows[22];
	$txtPurChgAmtB2 = $rows[23];
	$txtPurChgPer   = ($txtPurChgAmt/$txtPurNetTotal)*100;
	
	$txtTotalAmount = $rows[31];
	
	$txtPaymentCondidions  = $rows[32];
		
	$txtNetTotalWithCharges = number_format($txtPurNetTotal + $txtPurChgAmt, $DecimalBase,".","");
	
	$txtJvFolio	    = $rows[26];
	$txtJvRef 	    = $rows[27];
	
	$txtPurchaseType = $rows[33];
	
	if($Module_PurchasesJvWHT == 1){
		$txtWHTChk = $rows[34];
		$chkWHT = $rows[34];
		$txtWHTAcc = $rows[35];
		$txtWHTPer = $rows[36];
		$txtWHTAmt = $rows[37];
	}
	$txtauto_paymentrqst = $rows[38];
	$txtShippedIn = $rows[39];

	$query = " Select Count(*) FROM Temp_PurchasesDt ".
			 " WHERE Purchase_id = ".$txtPurId;
	$result = selectData($connection, $query);
	$txtPurCountDetail = $result[0];
	if($txtPurCountDetail == '') $txtPurCountDetail = 0;
	$txtInvoiceDate = $rows[40];
	$fromGRN = $rows[41];
	
}

if($ShowInvoiceDate == 1){
	$ndate = explode('/',$txtInvoiceDate);
	$txtInvoiceDate1 = $ndate[2]."-".$ndate[1]."-".$ndate[0];
	$query = "select date_format(DATE_ADD(date_format('$txtInvoiceDate1','%Y-%m-%d'),INTERVAL $txtPaymentTerms DAY), '%d/%m/%Y')  ; ";
	$res = mysql_query($query,$connection);
	$row = mysql_fetch_row($res);
	//$txtMaturityDate = $row[0];
	
}
//$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";

echo"<table cellpadding='0' cellspacing='0' border='0'  align='center' class='layout-width'>";
include_once("header.php");
echo" <tr><td  valign='top'>";

include_once("sidemenu.php");
echo"  </td></tr>";


echo" <tr style='height:26px;'>
		<td  valign='top' id='content-top'>
			<table border='0' cellpadding='0' cellspacing='0' style='table-layout:fixed; height:26px;' class='layout-width'>
			<tr style='height:26px;'>
				<td style='width:38px; height:26px;'>&nbsp;</td>
				<td valign='middle' style='width:300px; height:26px;'><span class='title'>PURCHASE</span></td>
				<td class='message' valign='middle' style='height:26px;'>".htmlspecialchars($message, ENT_QUOTES)."</td>
			</tr></table>
		</td>
	  </tr>";

echo"<tr>
		<td  height='34'  valign='top' id='content-top2'>
			<table border='0' cellpadding='0' cellspacing='0' class='layout-width'>
			<tr>
				<td width='30'  height='34'>&nbsp;</td>
				<td valign='middle' height='34' width='800px' align='left'>";

	//if ($FI_PurchasesApp == 1)
	//echo"<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_PurchaseCategory)' $style title='Add Item'>";
	//echo" <button type='button' id='btnAddItem' name='btnAddItem' onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_PurchaseCategory);return false;' title='Add Item'><span><span>Add Item</span></span></button>";
	
if ($txtPurId != '')
	echo" <button type='button' id='btnAddCharges' name='btnAddCharges' onclick='AddCharges();return false;' title='AddCharges'><span><span>Add Charges</span></span></button>";	

echo" <button type='button' id='btnClear' name='btnClear' onclick='ClearPage();return false;' title='Clear Page'><span><span>Clear Page</span></span></button>";	

				
if ($txtPurId != '')
	echo" <button type='button' id='btnCancel' name='btnCancel' onclick='CancelRecord();return false;' title='Cancel Changes'><span><span>Cancel</span></span></button>";	

	
if ($txtPurId != '')
	echo" <button type='button' id='btnPost' name='btnPost' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter);return false;' title='Save Changes'><span><span>Save</span></span></button>";

//if ($txtPurId != ''){
	//if($Module_sizes == 1 && $Module_Color == 1){
//	echo" <button type='button' id='btnPost' name='btnPost' onclick=\"PrintBarcode('$txtPurId', '', '1')\" title='Save Changes'><span><span>Print Barcodes</span></span></button>";
//	//}
//	}
if ($txtPurId == '')
	echo" <button type='button' id='btnSearch' name='btnSearch' onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";	


if ($txtPurId == '')
	echo" <button type='button' id='btnPending' name='btnPending' onclick='SearchForPending();return false;' title='Pending Goods Receive Note'><span><span>Pending</span></span></button>";	


				
if ($Module_Grn == 1 && $FI_PurchasesApp == 1) {
	echo" <button type='button' id='btnLoadGRN' name='btnLoadGRN' onclick='LoadGRN();return false;' title='Load GRN'><span><span>Load GRN</span></span></button>";

}

if (($Module_Grn == 0 && $FI_PurchasesApp == 1) or $Module_DownPayment==1){
	echo" <button type='button' id='btnSearchPorder' name='btnSearchPorder' onclick='SearchConfirmedPorder($FI_PurchaseCategory);return false;' title='Search Confirmed Porder'><span><span>Load Purchase Order</span></span></button>";


}

if ($txtPurId !='')	
	echo"<button type='button' id='btnUpload' name='btnUpload' 
			onclick=\"UploadDocuments('purchase');return false;\" title='Upload Documents'><span><span>Upload Documents</span></span></button>";
if($auto_paymentrqst == 1){
if($txtauto_paymentrqst == '') $txtauto_paymentrqst =0;
echo "<span class='style1'><input type='checkbox' name='chkpaymentrqst' id='chkpaymentrqst' ".($txtauto_paymentrqst == 1?'checked':'').">Auto Payment Request</span>";
}
echo"</td><td align=right>";


if($Module_ImportExcell==1)
echo"<table border=0><tr><td align='center' valign='middle'>
<img src='./img/xls-icon.png' height='20px' width='22px' title='Download Excel Sheet' style='cursor: pointer;' onclick=\"downloadExcel();\">
<button type='button' id='btnImp' name='btnImp' onclick=\"ImportExcell('$txtPurId',$Module_RestrictProjCost,$Module_RestrictCost,$Module_Project,$Module_CostCenter,$FI_PurchaseCategory);return false;\" title='Import From Excel'><span><span>Import from Excell</span></span></button>
<input type='file'  name='image'    id='image' style='width:200px;' accept='file/xls'>
</td>
</tr></table>";

echo"	</td></tr></table>";
echo"</td></tr>";				

		
echo"<tr><td id='content-body'>
<table border='0'  align='center' valign='top' width=100% class='tablecontent'>
   <tr bgcolor='#F7F7F7'><td valign='top' align='left' colspan='10'>";
   
   	
$strt = $_SESSION['StartFinancial_Date'];
$end = $_SESSION['EndFinancial_Date'];
print <<<HERE

		<table border="0" style='table-layout:fixed'>
		  <col width=80>
		  <col width=70>
		  <col width=50>
		  <col width=120>
		  <col width=40>
		  <col width=70>
		  <col width=50>
		  <col width=70>
		  <col width=100>
		  <col width=150>
		  <col width=270>

		<tr bgcolor="#F7F7F7" height='30'>
          <td valign="center" align='left' ><span class="style1">Reference&nbsp;<span class="style16">*</span></span></td>
		  <td><font face='Verdana' size='2'><b>&nbsp;$txtRef</b></font><input type='hidden' name='txtPurCountDetail' value='$txtPurCountDetail' ><input type='hidden' name='txtPurId' value='$txtPurId' size='10'><input type="hidden" name="txtRef" value="$txtRef" size='10' readonly></td>
		  <td align="left"><span class="style1">Date&nbsp;<span class="style16">*</span></span></td>
		  <td><input type='text' name='txtDate' id='txtDate' value='$txtDate'   onBlur=checkDateFormat(this,$strt,$end)    onchange='SetMaturityDate();' maxlength='10' style='width:80px;' >
		        <A HREF="#" onClick="displayCalendar(document.purchase.txtDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A>
			<input type='hidden' name='txtJvFolio' value='$txtJvFolio' >
		    <input type='hidden' name='txtSorderRef' value='$txtSorderRef' >			   
			<input type='hidden' name='txtJvRef' value='$txtJvRef' >			   
		  </td>
HERE;

if ($Module_PostToJournal == 1) {
	echo" <td align='left'><span class='style1'>Folio</span></td>	
		  <td><font face='Verdana' size='2'><b>&nbsp;$txtJvFolio</b></font></td>
		  <td align='left'><span class='style1'>JV Ref.</span></td>	
		  <td><font face='Verdana' size='2'><b>&nbsp;$txtJvRef</b></font></td> ";
} else 	{
	echo" <td align='left' colspan='4'>&nbsp;</td>";
}

print <<<HERE

          <td align='left' ><span class='style1'>Maturity&nbsp;<span class="style16">*</span></span></td>
          <td ><input type='text' name='txtMaturityDate' value='$txtMaturityDate'  onBlur='checkDateFormat(this)'   maxlength='10' style='width:100px;' >
						  <A HREF="#" onClick="displayCalendar(document.purchase.txtMaturityDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A></td>

HERE;

// Check If Vat Applied
$VatApplied = 0;
$txtModeVat = "";

//echo insertDate($txtDate).' > '.$Setup_VatStartDate.' && '.$Setup_VatPercentage.' || '.$Module_AdditionalTaxes;
if ((insertDate($txtDate) > $Setup_VatStartDate && $Setup_VatPercentage != 0) || ($Module_AdditionalTaxes == 1)) {		  
  $txtModeVat = " disabled ";
  $VatApplied = 1;
}



$Parameters = array();
$Parameters['Module_Unit1Method'] = $Module_Unit1Method;
$Parameters['Module_Pack'] = $Module_Pack;
$Parameters['Module_DoubleUnit'] = $Module_DoubleUnit;
$Parameters['Module_Project'] = $Module_Project;
$Parameters['Module_CostCenter'] = $Module_CostCenter;
$Parameters['Module_ProjectDt'] = $Module_ProjectDt;
$Parameters['Module_CostCenterDt'] = $Module_CostCenterDt;
$Parameters['Module_RestrictProjCost'] = $Module_RestrictProjCost;
$Parameters['Module_RestrictCost'] = $Module_RestrictCost;
$Parameters['ShowCostCentLayout'] = $ShowCostCentLayout;
$Parameters['Module_SerialNo'] = $Module_SerialNo;
$Parameters['Module_ExpireDate'] = $Module_ExpireDate;
$Parameters['Module_AdditionalTaxes'] = $Module_AdditionalTaxes;
$Parameters['PurchaseTTC'] = $PurchaseTTC;
$Parameters['ShowItemSellingPrice'] = $ShowItemSellingPrice;
$Parameters['DecimalBase'] = $DecimalBase;
$Parameters['Base1'] = $base1;
$Parameters['Base2'] = $base2;
$Parameters['Setup_VatPercentage'] = $Setup_VatPercentage;
$Parameters['VatApplied'] = $VatApplied;
$Parameters['FI_PurchasesVATMod'] = $FI_PurchasesVATMod;
$Parameters['FI_PurchaseCategory'] = $FI_PurchaseCategory;
$Parameters['FI_PurchasesVAT'] = $FI_PurchasesVAT;
$Parameters['Module_Grn'] = $Module_Grn;


$Parameters['SetupDftWareHouse'] = $SetupDftWareHouse;
$Parameters['defaultwarehouse']  = $defaultwarehouse;

$Parameters['txtDate'] 		   = $txtDate;
$Parameters['txtSupplierCode'] = $txtSupplier;
$Parameters['txtCurrCode']     = $txtCurr;
$Parameters['Module_Heatno'] = $Module_Heatno;
$Parameters['Login_location'] = $Login_location;
$Parameters['module_locationPurchases'] = $module_locationPurchases;
$Parameters['costcent_applyvat'] = $costcent_applyvat;
$Parameters['Module_PurchasesJvWHT'] = $Module_PurchasesJvWHT;
$Parameters['Module_ChargesPurchase'] = $Module_ChargesPurchase; 
$Parameters['purchase_doubleunit'] = $purchase_doubleunit;
$Parameters['showCIF'] = $showCIF;
$_SESSION['gpur_parameters']  = $Parameters;


echo"	  <td rowspan='7' valign='top'>";

echo"	<div id='totals' style='width:270px; margin-top:3px; float:right;'>";
	ShowPurchaseTotals($connection,$txtPurId,$_SESSION['gpur_parameters'],$_SESSION['gpur_arrayaccess']);
echo"	</div>"; 

echo"	  </td>
		</tr>";

/*
print <<<HERE
		  <td rowspan='6' valign='top'><table border='0' style='table-layout:fixed'>
			<col width=100>
			<col width=110>
			
			<tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Taxable</span></td> 
			 <td align='left'><input type='text' name='txtPurTaxable' value='$txtPurTaxable' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>
		  </tr>
		  <tr bgcolor='#D8D8D8' height='25'>
			 <td valign='center' align='right' ><span class='style1'>None Taxable</span></td> 
 			 <td align='left'><input type='text' name='txtPurNoneTaxable' value='$txtPurNoneTaxable' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>

		  </tr>
		  <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Gross Total</span></td> 
			 <td align='left'><input type='text' name='txtPurGrossTotal' value='$txtPurGrossTotal' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>
		  </tr>
		  <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Discount</span></td> 
			 <td align='left'><input type='text' name='txtPurDiscount' value='$txtPurDiscount' maxlength='5'  style='text-align:right; width:40px; height=18px;' onKeyup='CalcPurDiscount(1, $DecimalBase,$VatApplied,$Setup_VatPercentage);' >%
			                  <input type='text' name='txtPurDiscountAmt' value='$txtPurDiscountAmt' maxlength='20' style='text-align:right; width:44px; height=18px;' onKeyup='CalcPurDiscount(2, $DecimalBase,$VatApplied,$Setup_VatPercentage);' ></td>
		  </tr>

HERE;



echo "    <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><input name='chkPurVat' type='checkbox' id='chkPurVat' value='1' onClick='SetPurVat($DecimalBase,$VatApplied,$Setup_VatPercentage,$PurchaseTTC);'   "; 
	          if($chkPurVat==1) echo "checked />"; else echo " />";   
echo "   	 <span class='style1'>VAT $Setup_VatPercentage%</span></td> 
			 <td align='left'>";
				//If User Has Access To Modify Vat Base1
				$VatModiMode = ' readonly ';
				if ($FI_PurchasesVATMod == 1 && $base1 == $txtCurr)
					$VatModiMode = '';
				
				echo "<input type='text' name='txtPurVat' value='$txtPurVat' maxlength='20' style='text-align:right; width:100px; height=18px;' $VatModiMode >";
				
				//If User Has Access To Modify Vat Base1
				if ($FI_PurchasesVATMod == 1){
					echo "<br><input type='text' name='txtPurVatBase1' value='$txtPurVatBase1' size='12' maxlength='20' style='text-align:right; height=18px;' >";
				} else {
					echo "<br><input type='hidden' name='txtPurVatBase1' value='$txtPurVatBase1'  >";
				}
				
echo "		 </td>
		  </tr>";
		  
	if ($Module_AdditionalTaxes == 1) {
		echo"<tr bgcolor='#D8D8D8' height='20'>
			   <td valign='center' align='right' ><span class='style1'>Taxes</span></td> 
			   <td align='left'><input type='text' name='txtPurTotalTaxes' value='$txtPurTotalTaxes' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>
		     </tr>";
	} else {
		echo "<input type='hidden' name='txtPurTotalTaxes' value='$txtPurTotalTaxes'>";
	}

echo"     <tr bgcolor='#D8D8D8' height='25'>
			 <td valign='center' align='right' ><span class='style1'>Net Total</span></td> 
			 <td align='left'><input type='text' name='txtPurNetTotal' value='$txtPurNetTotal' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>
		  </tr>";
		  
echo"     <tr bgcolor='#D8D8D8'>
			 <td valign='center' align='right' ><span class='style1'>NetTotal + Charges</span></td> 
			 <td align='left'>
				<input type='hidden' name='txtPurChgAmt' value='$txtPurChgAmt'>
				<input type='text' name='txtNetTotalWithCharges' value='$txtNetTotalWithCharges' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'>
			</td>
		  </tr>";		  
		  
echo"	  </table></td>				  
		</tr>";
*/


$supplierRead = '';
if ($fromGRN == 1) $supplierRead = 'readonly';

echo"   <tr bgcolor='#F7F7F7'  height='30'>
		  <td align='left' ><span class='style1'>Supplier&nbsp;<span class='style16'>*</span></span></td>";
echo"     <td colspan='7' ><span class='style1'>";
echo"     <label>
           <input type='text' name='txtSupplier' id='txtSupplier' value='$txtSupplier' onBlur='SetMaturityDate();'  style='width:110px;' maxlength='10' $supplierRead onchange=\"CheckLookup('chkcodeexists','suppliers','ledger_number',this.value,'lstSupplierCodeH'); \"  ";

if ($fromGRN != 1)	
	echo "	onkeydown='return kdClient(0,event);' ";
    echo "  /> <input type='text' name='txtSupplierName' id='txtSupplierName' value='$txtSupplierName' style='width:270px;' $supplierRead onchange=\"CheckLookup('chkcodeexists','suppliers','ledger_name',this.value,'lstSupplierNameH');\" /> ";
if ($fromGRN != 1)		   
	echo "	   <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Supplier ' id='lstSupplierCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSupplier(1); ' /> </span></label>
		   <label><img src='img/btnopen.jpg' title='Select Supplier' id='lstSupplierNameH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSupplierName(1);' style='display:none;' /></label>";
		   
echo "   <input type='hidden' name='txtSupplierVat' id='txtSupplierVat' value='$txtSupplierVat' />
          </label>
          </span>
          </td>";

echo"     <td align='left' ><span class='style1'>Payment Terms</span></td>";
echo"     <td ><span class='style1'><input type='text' name='txtPaymentTerms' id='txtPaymentTerms' value='$txtPaymentTerms' style='width:100px;' readonly /></span></td>";
echo"   </tr>";

//MODULE RANDOM SUPPLIER
if($Module_RandomeSupplier == 1){ 
	echo"   <tr bgcolor='#F7F7F7' >
			  <td align='left' ><span class='style1'>Supplier(1)&nbsp;<span class='style16'>*</span></span></td>";
	echo"     <td colspan='6' ><span class='style1'><label>";
	echo"      <input type='text' name='txtSupplier1' id='txtSupplier1' value='$txtSupplier1' onBlur='SetPorVatFlag();'  style='width:110px;' maxlength='10' onchange=\"CheckLookup('chkcodeexists','suppliers','ledger_number',this.value,'lstSupplierCodeH'); \" />
			   <input type='text' name='txtSupplierName1' id='txtSupplierName1' value='$txtSupplierName1' style='width:275px;' onchange=\"CheckLookup('chkcodeexists','suppliers','ledger_name',this.value,'lstSupplierNameH');\" />
			   <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Supplier ' id='lstSupplierCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSupplier(55); ' /> </span></label>
			   <label><img src='img/btnopen.jpg' title='Select Supplier' id='lstSupplierNameH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSupplierName(55);' style='display:none;' /></label>
			   </label></span>
			  </td>";
	
	 
	echo"   </tr>";}else{
		echo "<input type='hidden' name='txtSupplier1' id='txtSupplier1' value='' />";
	}
	
	
	//MODULE RANDOM SUPPLIER

if($txtPurId=='')
	$txtPaymentCondidions = $Porder_TermsConditions;
	
echo"     <tr><td  align='left' ><span class='style1'>Payment Terms & Conditions</span></td>";
echo"     <td colspan=5><textarea name='txtPaymentCondidions' cols=47>$txtPaymentCondidions</textarea></td>";
if($Module_Purchase_Pending && $Login_Purchase_Pending){
echo "<td></td><td></td>";
echo "<td  align='left' ><span class='style1'>Type </span></td><td colspan=1><select name='txtPurchaseType' id='txtPurchaseType' style='width:100px;'>";

echo "<option value='' ";
if($txtPurchaseType != 'PENDING') echo " selected ";
echo " ></option>";
echo "<option value='PENDING' ";
if($txtPurchaseType == 'PENDING') echo " selected ";
echo " >Pending</option>";
echo "</select></td>";
}
echo "</tr>";

echo"   <tr bgcolor='#F7F7F7'  height='30'>
		  <td align='left' ><span class='style1'>Remark</span></td><td colspan='7' > <span class='style1'>
		  <input type='text' name='txtRemark' value='".htmlspecialchars($txtRemark, ENT_QUOTES)."'  style='width:385px;' maxlength='100' ></td>";
		  
echo"     <td align='left' ><span class='style1'>Currency&nbsp;<span class='style16'>*</span></span></td>";
// checking if purchase is currency restricted 
if($ps_restrictCurrency == 1)
{
	$isdisabledCur = 'disabled';
}else{
	$isdisabledCur = '';
}
echo"     <td ><span class='style1'><select name='txtCurr' id='txtCurr' style='width:60px;' onchange='ChangeCurrency();' $isdisabledCur >";
		  echo"<option></option>";
		  while($curf=mysql_fetch_row($resultcurrency)){
		  echo"<option ";
			if ($txtCurr==$curf[0])
				echo " selected ";
		    echo" value='$curf[0]'>$curf[0] </option>";
		  }
		  echo"</select></span></td>";	
echo"   </tr>";		  

echo"   <tr bgcolor='#F7F7F7'  height='30'>
		  <td align='left' ><span class='style1'>Shipped In</span></td><td colspan='7' > <span class='style1'>
		  <input type='text' name='txtShippedIn' id='txtShippedIn' value='".htmlspecialchars($txtShippedIn, ENT_QUOTES)."'  style='width:385px;' maxlength='100' ></td>";
if($ShowInvoiceDate == 1) 		  
echo "<td align='left'><span class='style1'>Invoice Date&nbsp;<span class='style16'></span></span></td>
	 <td><input type='text' name='txtInvoiceDate' id='txtInvoiceDate' value='$txtInvoiceDate'   onBlur=checkDateFormat(this,$strt,$end)    onchange='ChangeMaturityDate();' maxlength='10' style='width:80px;' >
	 <A HREF='#' onClick=\"displayCalendar(document.purchase.txtInvoiceDate,'dd/mm/yyyy',this); return false;\" NAME='anchor1' ID='anchor1'><img src='./img/cal.gif' border=0 align=center></A></td>";
else echo "<td></td><td></td>";	 
echo "  </tr>";		  


echo"   <tr bgcolor='#F7F7F7'>";

if ($Module_Project == 1) {
	echo" <td align='left' ><span class='style1'>Project&nbsp;<span class='style16'>*</span></span></td>
	      <td align='left' colspan='2'> <span class='style1'>
		    <input type='text' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' style='width:90px;' maxlength='20' onchange=\"CheckLookup('chkcodeexists','project','project_code',this.value,'lstProjectCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Project ' id='lstProjectCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
} else {
	echo" <td align='left' colspan='3'><input type='hidden' name='txtProjectCode' id='txtProjectCode' value='' /></td>";

}			

if ($Module_CostCenter == 1 && $ShowCostCentLayout == 1) {		  
	echo" <td align='right' ><span class='style1'>Costcenter&nbsp;<span class='style16'>*</span></span></td>		
		  <td align='left' colspan='4'><span class='style1'>
		    <input type='text' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' style='width:139px;' maxlength='20' onchange=\"CheckLookup('chkcodeexists','costcent','costcent_code',this.value,'lstCostCentCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Costcenter ' id='lstCostCentCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
} else {
	echo" <td align='left' colspan='5'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' /></td>";

}
			

echo"     <td align='left' ><span class='style1'>Invoice No.</span></td>";
echo"     <td ><span class='style1'><input type='text' name='txtInvoiceNo' value='".htmlspecialchars($txtInvoiceNo, ENT_QUOTES)."' style='width:100px;' maxlength='25'  /></span></td>";
echo"   </tr>";
echo"   <tr bgcolor='#F7F7F7' height='25'>";

	if ($FI_PurchaseCategory == 0) {
		echo" <td align='left' ><span class='style1'>Category</span></td>
			  <td align='left' colspan='3'> <span class='style1'>";
		echo" <input type='radio' name='txtPurCategory' id='txtPurCategory' value='0' "; if($txtPurCategory==0 || $txtPurCategory=='') echo "checked />"; else echo " />";  echo " Local";
		echo" <input type='radio' name='txtPurCategory' id='txtPurCategory' value='1' "; if($txtPurCategory==1) echo "checked />"; else echo " />";  echo " Import";
        echo"</span></td>";
	} else {
		echo" <td align='left' colspan='4' >&nbsp;<input type='hidden' name='txtPurCategory' id='txtPurCategory' value='$txtPurCategory' /></td>";
	}	

echo"     <td colspan='2' align='right' ><span class='style1'>Waybill No.</span></td>";
echo"     <td colspan='2'><span class='style1'><input type='text' name='txtWaybillNo' value='".htmlspecialchars($txtWaybillNo, ENT_QUOTES)."' style='width:100px;' maxlength='45'  /></span></td>";
echo"	  <td valign='left' align='right' ><span class='style1'>Charges $base1</span><br><span class='style1'>(".number_format($txtPurChgPer, $DecimalBase)." %)</span></td> ";
echo"  	  <td align='left'><input type='text' name='txtPurChgAmtB1' value='$txtPurChgAmtB1' maxlength='20' readonly style='text-align:right; width:100px;'></td>";
echo"	</tr>";

echo"   <tr bgcolor='#F7F7F7'>
			<td align='left'><span class='style1'>Total Amount</span></td>
			<td align='left' colspan='2'><span class='style1'><input type='text' name='txtTotalAmount' id='txtTotalAmount' value='$txtTotalAmount' style='width:110px;'  /></span></td>
			<td align='center'></td>
			<td colspan='2' align='right' ><span class='style1'>Srv No.</span></td>
			<td colspan='2' ><span class='style1'><input type='text' name='txtSrvNo' value='".htmlspecialchars($txtSrvNo, ENT_QUOTES)."' style='width:100px;' maxlength='45'  /></span></td>
			<td align='right' ><span class='style1'>Charges $base2</span></td>
			<td align='left'><input type='text' name='txtPurChgAmtB2' value='$txtPurChgAmtB2' maxlength='20' readonly style='text-align:right; width:100px;'></td>
		</tr>";

if ($Module_PurchasesJvWHT == 1) {
	echo"<tr bgcolor='#F7F7F7' height='25'>";
	echo"	<td valign='center' align='left' ><span class='style1'>
				<input type='hidden' name='txtWHTChk' id='txtWHTChk' value='$txtWHTChk' size='1'/>
				<input name='chkWHT' type='checkbox' id='chkWHT' value='1' onClick='SetWHT($DecimalBase);'   "; 
				if ($txtWHTChk==1 ) echo " checked ";  echo " />WHT"; 
	echo"	</span></td>";
	echo"   <td colspan='2'><span class='style1'><input type='text' name='txtWHTPer' id='txtWHTPer' value='$txtWHTPer' style='width:90px;' maxlength='5' onkeyup='CalcWHTAmount($DecimalBase);' />(%)</span></td>";
	echo"   <td align='left' ><span class='style1'>WHT Amount</span></td>";
	echo"   <td colspan='2'><span class='style1'><input type='text' name='txtWHTAmt' id='txtWHTAmt' value='$txtWHTAmt' style='width:90px;' maxlength='20'  /></span></td>";
	echo"   <td align='left' colspan='2'><span class='style1'>WHT Account</span></td>";
	echo"   <td colspan='2'><span class='style1'><input type='text' name='txtWHTAcc' id='txtWHTAcc' value='$txtWHTAcc' style='width:90px;' maxlength='10'  /></span>
				<label><span class='style1'><img src='img/btnopen.jpg' title=' Select Account ' width='15' height='17' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistLedgers(9); '  /></span></label></td>";
	//echo"   <td align='left'>&nbsp;</td>";			
	echo"</tr>";
} 		
		

			
$querygrn=" select distinct grnpurchases.purchase_reference ".
		  " from grnpurchases,grnpurchasesdt,temp_purchasesdt where temp_purchasesdt.purchase_id = '".$txtPurId."'
		  and grnpurchases.purchase_id=grnpurchasesdt.purchase_id
		  and grnpurchasesdt.purchasedt_id=temp_purchasesdt.relateddt_id  ";
		  
$resultgrn=mysql_query($querygrn,$connection) or die(mysql_error());
$grnref='';
while($rowsgrn=mysql_fetch_array($resultgrn)){
	if($grnref=='')
		$grnref = $rowsgrn[0];
	else
	$grnref = $grnref.','.$rowsgrn[0];
}
echo "<tr height='10px'><td></td></tr>";
echo "<tr bgcolor='#D8D8D8' height='20px;'>";
if($grnref!=''){
echo" <td align='left' colspan='1'><span class='style1'><b>Grn Ref:</span></td><td>";
	echo $grnref;
	
echo"</td>";
} else {
	echo" <td align='left' colspan='1'></td><td></td>";
}
echo "<td colspan='2'></td>";
echo "<td align='center'><button type='button' id='btnRates' name='btnRates' onclick='ShowRateParity();return false;' title='Rate/Parity'><span><span>Rate/Parity</span></span></button></td>";
echo "<td></td>";
if($txtPurId != '')
echo "<td align='center'><button type='button' id='btnItemPr' name='btnItemPr' onclick='ShowItems();return false;' title='Items/Price'><span><span>Items/Price</span></span></button></td>";
else echo "<td></td>";
echo "<td colspan='3'></td>";
echo "</tr>";

echo "<tr height='10px'><td></td></tr>";

if ($Barcode==1) {		
echo"   <tr bgcolor='#D8D8D8' height='30px;'>
			<td align='left' colspan='10'><span class='style1'>Barcode</span>
				<input type='text' name='txtItemBarcode' value='".htmlspecialchars($txtItemBarcode, ENT_QUOTES)."' style='width:130px;' maxlength='20' onkeydown='return Barcodekd(event);'/>
				<span class='style1'>Qty&nbsp;</span>
				<input type='text' name='txtItemQty' value='$txtItemQty' style='width:70px;' maxlength='10'/>
				<span class='style1'>Warehouse</span>
				<input type='text' name='txtItemWarehouse' id='txtItemWarehouse' value='".htmlspecialchars($txtItemWarehouse, ENT_QUOTES)."' style='width:70px;' maxlength='15'/>
				<label><span><img src='img/openlist.png' title='Select Warehouse' width='20' height='20' border='0' onMouseOver=\"style.cursor='pointer'\" onClick='showlistWarehouse1();' style='vertical-align:bottom;'/></span></label>
				<button type='button' id='btnSubmitBar' name='btnSubmitBar' onclick='SubmitItemBarcode($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_PurchaseCategory);return false;' title='Submit'><span><span>Submit</span></span></button>
			</td>	
		</tr>";
} else {

echo"   <tr bgcolor='#D8D8D8' height='30px;'>
			<td align='left' colspan='10'><span class='style1'></span>
				<input type='hidden' name='txtItemBarcode' value='".htmlspecialchars($txtItemBarcode, ENT_QUOTES)."' style='width:130px;' maxlength='20' onkeydown='return Barcodekd(event);'/>
				<span class='style1'></span>
				<input type='hidden' name='txtItemQty' value='$txtItemQty' style='width:70px;' maxlength='10'/>
				<span class='style1'></span>
				<input type='hidden' name='txtItemWarehouse' id='txtItemWarehouse' value='".htmlspecialchars($txtItemWarehouse, ENT_QUOTES)."' style='width:70px;' maxlength='15'/>
				<label><span><img src='img/openlist.png' hidden='hidden' title='Select Warehouse' width='20' height='20' border='0' onMouseOver=\"style.cursor='pointer'\" onClick='showlistWarehouse1();' style='vertical-align:bottom;'/></span></label>
				<button type='button' id='btnSubmitBar' hidden='hidden' name='btnSubmitBar' onclick='SubmitItemBarcode($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_PurchaseCategory);return false;' title='Submit'><span><span>Submit</span></span></button>
			</td>	
		</tr>";



} 


/*
echo"   <tr><td colspan='11' valign='top'>";
echo"	<div style='overflow:scroll; height:180px; width:990px;' >";
echo"     <table border='0' style='table-layout:fixed'>
          <col width=20>
		  <col width=20>
		  <col width=20>";
		  
if ($Module_DoubleUnit == 1) {		  
	echo" <col width=120>
		  <col width=120>
		  <col width=200>
		  <col width=70>
		  <col width=50>
		  <col width=60>
		  <col width=50>
		  <col width=60>
		  <col width=50>
		  <col width=60>
		  <col width=90>
		  <col width=50>
		  <col width=100>";
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
	if ($Module_ExpireDate == 1) {
		echo"<col width=80>";
		echo"<col width=80>";
	}	  
} else {
	echo" <col width=120>
		  <col width=120>
		  <col width=200>
		  <col width=80>
		  <col width=60>
		  <col width=50>
		  <col width=60>
		  <col width=90>
		  <col width=50>
		  <col width=100>";
		  
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
	if ($Module_ExpireDate == 1) {
		echo"<col width=80>";
		echo"<col width=80>";
	}
}		  
		  
		echo"<tr height='25'>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
        echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item Code Packed</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Description</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>WH</span></td>";
		
		if ($Module_DoubleUnit == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit1</span></td>";
			
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Qty</span></td>";
		
		if ($Module_DoubleUnit == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2 Qty</span></td>";
		}
		
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>SN</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Volume</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>$PriceLabel</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Disc(%)</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Total</span></td>";
		
		if ($Module_ProjectDt == 1)	
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Project</span></td>";
		if ($Module_CostCenterDt == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>CostCenter</span></td>";
		if ($Module_ExpireDate == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Batch No</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Expire Date</span></td>";
		}
	
        echo"</tr>";
		  
		if ($txtPurId != '' ) {
		      
			  
			  //Checking For Difference Btw Qty and Count SerialNo
			  $QtySerNoCheck = 0;
			  echo '<script type="text/javascript" language="javascript">';
			  echo ' x = document.purchase; ';
  			  echo ' x.QtySerNo.value=0; ';
			  echo '</script>';
			  
			  
			$querydt = " Select PurchasesDt.PurchaseDt_ID, PurchasesDt.Item_CodePacked, PurchasesDt.Item_code, Item_Description, PurchasesDt.Warehouse_Code, ".
					   " Purchasedt_Remark, PurchaseDt_Quantity, PurchaseDt_Volume, Round(PurchaseDt_Price, ".$DecimalBase."), PurchaseDt_PriceBase1, PurchaseDt_PriceBase2, ".
					   " Round(PurchaseDt_DiscountPer, ".$DecimalBase."), PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2,  ".
					   " Round(((PurchaseDt_Quantity*PurchaseDt_Price)-((PurchaseDt_Quantity*PurchaseDt_Price*ifNull(PurchaseDt_DiscountPer,0))/100)), ".$DecimalBase.") As Total, ".
					   " Count(SerialNo_Code) As CountSerialNo, ifNull(item_withserialno,0) As ItemWithSerialNo, Round(PurchaseDt_PriceTTC, ".$DecimalBase."), ".
					   " Round(((PurchaseDt_Quantity*PurchaseDt_PriceTTC)-((PurchaseDt_Quantity*PurchaseDt_PriceTTC*ifNull(PurchaseDt_DiscountPer,0))/100)), ".$DecimalBase.") As TotalTTC, ".
					   " ifNull(PorderDt.PorderDt_Quantity,0), PurchasesDt.RelatedDt_Id, PurchasesDt.Item_Unit2Qty, Item_UnitPurchaseDesc, Item_UnitSalesDesc, ".
					   " Date_Format(PurchaseDt_ExpireDate,'%d/%m/%Y') As PurchaseDt_ExpireDate, PurchaseDt_BatchNo, PurchasesDt.Project_code, PurchasesDt.CostCent_Code ".
					   " From Temp_PurchasesDt As PurchasesDt Left Join Items on PurchasesDt.Item_code = Items.Item_code ".
					   " Left Join PorderDt on PorderDt.PorderDt_ID = PurchasesDt.RelatedDt_Id  ".
					   " Left Join Temp_Purchasesserialno on PurchasesDt.PurchaseDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					   //" And Temp_Purchasesserialno.Logged_Code = '".$_SESSION['useraccount']."' ".
					   " And Temp_Purchasesserialno.Journal_Type = 'PI' ".
					   " Where PurchasesDt.Purchase_ID = ".$txtPurId.
					   //" And PurchasesDt.Logged_Code = '".$_SESSION['useraccount']."' ".
					   " Group By  PurchasesDt.PurchaseDt_ID ".
					   " Order By PurchasesDt.PurchaseDt_ID Desc ";
			//echo $querydt;
			$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){
			    
				$ct+=1;

				if($ct%2==0)
					$Color="style='background-color:".$grid_color1."'";
				else			
					$Color="style='background-color:".$grid_color2."'";	
					
					
				$vPorderDtQty  = $rowsdt[21];
				$vPorderDtId   = $rowsdt[22];
				$vPorRemainQty = 9999999;
				
				
				if (!empty($vPorderDtId) && $vPorderDtId != '') {
				
					$sub_query1 = " Select Sum(if(Journal_Type='PI', ifNull(PurchasesDt.PurchaseDt_Quantity,0), ifNull(PurchasesDt.PurchaseDt_Quantity,0)*(-1))) As QuantityPurchased ".
								  " From PurchasesDt ".
								  " Where PurchasesDt.RelatedDt_ID =  '".$vPorderDtId."' ".
								  " And PurchasesDt.Journal_Type In ('PI','PR') ".
								  " And PurchasesDt.PurchaseDt_Id != '".$rowsdt[0]."' ";
					$sub_result1 = selectData($connection, $sub_query1);
					if ($sub_result1[0] == '') $sub_result1[0] = 0;
				
					$sub_query2 = " Select Sum(ifNull(Temp_PurchasesDt.PurchaseDt_Quantity,0)) As QuantityPurchasedTemp ".
								  " From Temp_PurchasesDt ".
								  " Where Temp_PurchasesDt.RelatedDt_ID =  '".$vPorderDtId."' ".
								  " And Temp_PurchasesDt.Journal_Type = 'PI' ".
								  " And Temp_PurchasesDt.PurchaseDt_Id != '".$rowsdt[0]."' ";
					$sub_result2 = selectData($connection, $sub_query2);
					if ($sub_result2[0] == '') $sub_result2[0] = 0;		  
				
				
					//Get The Remaining Qty
					$vPorRemainQty = ($vPorderDtQty - ($sub_result1[0] + $sub_result2[0]));
					
				}		
					
						
				
				echo "<tr ".$Color." >";
				
				// If ItemWithSerialNo True And ModuleSerialNo True	
				if ($rowsdt[18] == 1 && $Module_SerialNo == 1) 
					echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_addserial.png' onMouseOver=\"style.cursor='hand'\" onclick=\"AddSerialNo('".$rowsdt[0]."','".htmlentities($rowsdt[2])."',$rowsdt[6],'".$rowsdt[4]."','".$vPorRemainQty."')\" title='Add Serial Nos'  ></span></td>";
				else
					echo "	<td align='center' valign='center'>&nbsp;</td>";
					
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_edit.png'  onMouseOver=\"style.cursor='hand'\" onclick=UpdatePurDt('".$rowsdt[0]."','".$vPorRemainQty."') title='Edit Record'  ></span></td>";
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/c_delete.png'  onMouseOver=\"style.cursor='hand'\" onclick=\"DeletePurDt('".$rowsdt[0]."','".htmlentities($rowsdt[1])."','".htmlentities($rowsdt[2])."')\" title='Delete Record'  ></span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[1]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[2]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[3]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[4]."</span></td>";
				
				if ($Module_DoubleUnit == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[25]."</span></td>";
				
				// if Total Quantity Differs From Total SerialNos And
				// If ItemWithSerialNo True And ModuleSerialNo True	
				if (($rowsdt[6] != $rowsdt[17] && $rowsdt[18] != 0 && $Module_SerialNo == 1) || ($rowsdt[6] == 0 && $rowsdt[18] != 0 && $Module_SerialNo == 1)) {
				    if ($QtySerNoCheck == 0) {
						$QtySerNoCheck = 1;
						
						echo '<script type="text/javascript" language="javascript">';
						echo ' x = document.purchase; ';
						echo ' x.QtySerNo.value=1; ';
						echo '</script>';
					}					
						
					echo "	<td align='right' style='background-color:#FF0000' ><a href='#' onClick=\"EditPurDtQty('".$rowsdt[0]."','".htmlentities($rowsdt[2])."','".$vPorRemainQty."')\" ><span class='style28' style='text-decoration:underline;'>".$rowsdt[6]."</span></a></td>";
					//echo "	<td align='right' style='background-color:#FF0000'><span class='style28'>".$rowsdt[6]."</span></td>";
				} else	
					echo "	<td align='right'><span class='style15'>".$rowsdt[6]."</span></td>";
					
				if ($Module_DoubleUnit == 1) { 
					echo "	<td align='left'><span class='style15'>".$rowsdt[24]."</span></td>";	
					echo "	<td align='right'><span class='style15'>".$rowsdt[23]."</span></td>";	
				}	
				
				echo "	<td align='right'><span class='style15'>".$rowsdt[17]."</span></td>";
				echo "	<td align='right'><span class='style15'>".$rowsdt[7]."</span></td>";
				
				if ($PurchaseTTC == 1) 
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[19], $DecimalBase)."</span></td>";
				else
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[8], $DecimalBase)."</span></td>";
					
				echo "	<td align='right'><span class='style15'>".$rowsdt[11]."</span></td>";
				
				if ($PurchaseTTC == 1) 
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[20], $DecimalBase)."</span></td>";
				else
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[16], $DecimalBase)."</span></td>";
					
					
				if ($Module_ProjectDt == 1)	
					echo "	<td align='left'><span class='style15'>".$rowsdt[28]."</span></td>";
				if ($Module_CostCenterDt == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[29]."</span></td>";
				if ($Module_ExpireDate == 1) {
					echo "	<td align='left'><span class='style15'>".$rowsdt[27]."</span></td>";
					echo "	<td align='left'><span class='style15'>".$rowsdt[26]."</span></td>";
				}	
					
				echo "</tr>";
						
					
								
			}
			
			
		 }
		
		echo "</table></div>";   

echo"   </td></tr>";
*/
/*
echo"   <tr bgcolor='#D8D8D8' height='30'><td colspan='11' align='center'>";

if ($FI_PurchasesApp == 1)
	echo"<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_PurchaseCategory)' $style title='Add Item'>";
				
echo"       <input type='button' id='btnAddCharges' name='btnAddCharges' value='Add Charges'   onclick='AddCharges();' $style title='AddCharges'>";	
echo"       <input type='button' id='btnClear' name='btnClear' value='Clear Page'   onclick='ClearPage();' $style title='Clear Page'>";
				
if ($txtPurId != '')
	echo"   <input type='button' name='btnCancel' id='btnCancel' value='Cancel' onclick='CancelRecord();' $style title='Cancel Changes'>";
	
if ($txtPurId != '')
	echo"   <input type='button' name='btnPost' id='btnPost' value='Save' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter);' $style	title='Save Changes' />";

if ($txtPurId == '')
	echo"   <input name='btnSearch' type='button' id='btnSearch' value='Search' onclick='SearchForRef();' $style title='Search By Reference' />";

if ($txtPurId == '')
	echo"   <input name='btnPending' type='button' id='btnPending' value='Pending' onclick='SearchForPending();' $style title='Pending Purchases'  />";

				
if ($Module_Grn == 1 && $FI_PurchasesApp == 1) {
	echo"	<input type='button' name='btnLoadGRN' id='btnLoadGRN' value='Load GRN' onclick='LoadGRN();' $style title='Load GRN' /> ";
}
else if ($Module_Grn == 0 && $FI_PurchasesApp == 1) {
	echo"	<input type='button' name='btnSearchPorder' id='btnSearchPorder' value='Load Purchase Order' onclick='SearchConfirmedPorder();' $style title='Search Confirmed Porder' /> ";

}

echo"   </td></tr>";	*/

echo"   <tr bgcolor='#ffffff'><td colspan='11' valign='top'>";
echo"	<div id='datagrid' class='grid' style='width:1090px;' >";

//Show Items Grid
ShowPurchaseDtGrid($connection,'PI',$txtPurId,$_SESSION['gpur_parameters'],$_SESSION['gpur_arrayaccess'],'PurchasesDt.PurchaseDt_ID');

echo"	  </div>"; 
echo"   </td></tr>"; 
echo"   </table></td></tr>"; 
 echo"   </table></td></tr><tr height='30'><td align='center' id='content-bottom' ></td></tr>";  
echo"   </table></td></tr>"; 

echo" </table>  ";//end of last table menu
	
if ($actionmode == "post" && $PrPurId != '') {
	echo '<script type="text/javascript" language="javascript">';
	
	if ($Login_FastPrint == 1) 
		echo ' PrintPurchase(\''.$PrPurId.'\', \''.$PrPurRef.'\'); ';
	//if($Module_sizes == 1 && $Module_Color == 1){
	?>
	
	<?php
	//}
	echo '';
		
	echo ' ClearPage1(); ';
	echo '</script>';

}

print <<<HERE
</form>
</body>

HERE;

?>