<?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_PurchaseOrder.php");

$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_PurchaseOrder as loginaccess 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_PurchaseOrderApp,0) As FI_PurchaseOrderApp, ifNull(FI_PorderConfirmed,0) As FI_PorderConfirmed, ".
		  " ifNull(FI_PurchaseCategory,0) As FI_PurchaseCategory, ifNull(Login_FastPrint,0) As Login_FastPrint ".
		  " 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);
}
	
//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_PorderConfirm,0) As Module_PorderConfirm, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_Unit1Method,0) As Module_Unit1Method ".
			 " ,ifNull(Module_Heatno,0) As Module_Heatno,ifNull(Module_ChargesPurchase,0) As Module_ChargesPurchase".
			 ", ifnull(Module_ImportExcell,0) as Module_ImportExcell, ifnull(Module_PurchaseRequest,0) as Module_PurchaseRequest ".
			 " ,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,Porder_TermsConditions, ".
					" ifnull(showCIF,0) as showCIF, ifnull(ps_restrictCurrency,0) as ps_restrictCurrency ".
					" 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);
} //echo $querydflwh;

//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']."' ".
			  " and (loginstk.project_code is not null and loginstk.project_code != '') ".
			  " 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']."' ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') ".
 			   " 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());







$approvedby 	= $_POST["approvedby"]; if ($approvedby == ""){$approvedby = $_GET["approvedby"];} 
$txtPurChgAmt 	= $_POST["txtPurChgAmt"]; if ($txtPurChgAmt == ""){$txtPurChgAmt = $_GET["txtPurChgAmt"];} 
$porder_actualdate 	= $_POST["porder_actualdate"]; if ($porder_actualdate == ""){$porder_actualdate = $_GET["porder_actualdate"];} 
$txtPurNetTotal 	= $_POST["txtPurNetTotal"]; if ($txtPurNetTotal == ""){$txtPurNetTotal = $_GET["txtPurNetTotal"];} 

$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"];}   
$PrPorId 	= $_POST["PrPorId"]; if ($PrPorId == ""){$PrPorId = $_GET["PrPorId"];}

$txtPorCountDetail 	= $_POST["txtPorCountDetail"]; if ($txtPorCountDetail == ""){$txtPorCountDetail = $_GET["txtPorCountDetail"];} 
$txtPorId    		= $_POST["txtPorId"]; if ($txtPorId == ""){$txtPorId = $_GET["txtPorId"];} 
$txtRef 			= $_POST["txtRef"]; if ($txtRef == ""){$txtRef = $_GET["txtRef"];} 
$txtDate 			= $_POST["txtDate"]; if ($txtDate == ""){$txtDate = $_GET["txtDate"];} 
$txtRequestDate 	= $_POST["txtRequestDate"]; if ($txtRequestDate == ""){$txtRequestDate = $_GET["txtRequestDate"];} 
$txtExpiryDate    	= $_POST["txtExpiryDate"]; if ($txtExpiryDate == ""){$txtExpiryDate = $_GET["txtExpiryDate"];} 
$txtSupplier 	   	= $_POST["txtSupplier"]; if ($txtSupplier == ""){$txtSupplier = $_GET["txtSupplier"];} 
$txtSupplier1 	   	= $_POST["txtSupplier1"]; if ($txtSupplier1 == ""){$txtSupplier1 = $_GET["txtSupplier1"];} 
$txtSupplierName 	= $_POST["txtSupplierName"]; if ($txtSupplierName == ""){$txtSupplierName = $_GET["txtSupplierName"];} 
$txtSupplierVat 	= $_POST["txtSupplierVat"]; if ($txtSupplierVat == ""){$txtSupplierVat = $_GET["txtSupplierVat"];} 
$txtPaymentTerms	= $_POST["txtPaymentTerms"]; if ($txtPaymentTerms == ""){$txtPaymentTerms = $_GET["txtPaymentTerms"];} 
$txtPaymentCondidions	= $_POST["txtPaymentCondidions"]; if ($txtPaymentCondidions == ""){$txtPaymentCondidions = $_GET["txtPaymentCondidions"];} 
$porder_downpayment	= $_POST["porder_downpayment"]; if ($porder_downpayment == ""){$porder_downpayment = $_GET["porder_downpayment"];} 
$porder_downperc	= $_POST["porder_downperc"]; if ($porder_downperc == ""){$porder_downperc = $_GET["porder_downperc"];} 
$porder_downamount	= $_POST["porder_downamount"]; if ($porder_downamount == ""){$porder_downamount = $_GET["porder_downamount"];} 
$txtRequestBy 	   	= $_POST["txtRequestBy"]; if ($txtRequestBy == ""){$txtRequestBy = $_GET["txtRequestBy"];} 
$txtCurr   			= $_POST["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_GET["txtCurr"];} 
$txtSupplierContact	= $_POST["txtSupplierContact"]; if ($txtSupplierContact == ""){$txtSupplierContact = $_GET["txtSupplierContact"];} 
$txtPorCategory   	= $_POST["txtPorCategory"]; if ($txtPorCategory == ""){$txtPorCategory = $_GET["txtPorCategory"];} 
$txtRemark  		= $_POST["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_GET["txtRemark"];} 
$txtPrequestReference	= $_POST["txtPrequestReference"]; if ($txtPrequestReference == ""){$txtPrequestReference = $_GET["txtPrequestReference"];} 
$txtProjectCode 	= $_POST["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_GET["txtProjectCode"];} 
$txtCostCentCode	= $_POST["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_GET["txtCostCentCode"];} 
$txtStatusRemark	= $_POST["txtStatusRemark"]; if ($txtStatusRemark == ""){$txtStatusRemark = $_GET["txtStatusRemark"];} 
$txtDeliveryPlace	= $_POST["txtDeliveryPlace"]; if ($txtDeliveryPlace == ""){$txtDeliveryPlace = $_GET["txtDeliveryPlace"];} 
$txtDeliveryContact	= $_POST["txtDeliveryContact"]; if ($txtDeliveryContact == ""){$txtDeliveryContact = $_GET["txtDeliveryContact"];} 
$txtPorDiscountAmt	= $_POST["txtPorDiscountAmt"]; if ($txtPorDiscountAmt == ""){$txtPorDiscountAmt = $_GET["txtPorDiscountAmt"];} 
$txtPorDiscount		= $_POST["txtPorDiscount"]; if ($txtPorDiscount == ""){$txtPorDiscount = $_GET["txtPorDiscount"];} 
 
 


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('por-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('por-nextcell');
		
		
		
	});
	
	function ShowSlidingDiv(PDivID) {
	$(PDivID).slideToggle();
}
</script>


<script type="text/javascript" language="javascript">

function CalcDownDiscount(index,decimal){

	if(document.purchase.porder_downamount.value > 0 )
		var porder_downamount = parseFloat(document.purchase.porder_downamount.value);
	else
		var porder_downamount = 0;
		
	if(document.purchase.txtPorNetTotal.value > 0 )
		var txtPorNetTotal = parseFloat(document.purchase.txtPorNetTotal.value);
	else
		var txtPorNetTotal = 0;
			
	if(document.purchase.porder_downperc.value > 0 )		
		var porder_downperc = parseFloat(document.purchase.porder_downperc.value);
	else
		var porder_downperc = 0;
		
		
	if(index==1  && txtPorNetTotal > 0 && porder_downperc > 0 ){
		document.purchase.porder_downamount.value = roundNumber(txtPorNetTotal * porder_downperc / 100,decimal);	
	}
	else if(index==2   && txtPorNetTotal > 0 && porder_downamount > 0 ){
		document.purchase.porder_downperc.value = roundNumber((porder_downamount / txtPorNetTotal) * 100 ,decimal) ;
	}

}


function setdown(){

if(document.purchase.chk_porder_downpayment.checked)
	document.purchase.porder_downpayment.value=1;
else
document.purchase.porder_downpayment.value=0;

if(document.purchase.chk_porder_downpayment.checked){
document.purchase.porder_downperc.disabled = false;
document.purchase.porder_downamount.disabled = false;

} else {
document.purchase.porder_downperc.disabled = true;
document.purchase.porder_downamount.disabled = true;
document.purchase.porder_downperc.value = '';
document.purchase.porder_downamount.value = '';
}



}

function UploadDocuments(vform){

var txtPorId = document.purchase.txtPorId.value;

win = window.open('UploadDocuments.php?vform='+vform+'&porderid='+txtPorId, '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 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_PurchaseOrder_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] ;
				}
				if(data[2] != ''){
					document.getElementById('item_price['+index+']').value = data[2];
				}
				if(data[3] != ''){
					document.getElementById('item_qtyexist['+index+']').value = data[3];
				}
				data  = '';			
			}
		}
		 
		
		xmlhttp.open("GET","Form_PurchaseOrder_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 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  checkval(){
var vPaymentTerms = document.purchase.txtPaymentTerms.value;

if (vPaymentTerms >= 0){
}
else {
	alert('Invalid Input.');
	document.purchase.txtPaymentTerms.focus();
	}
}

function  changevaluedate(){


var vPaymentTerms = document.purchase.txtPaymentTerms.value;

if (vPaymentTerms >= 0){
var ms = new Date().getTime() + (86400000 * vPaymentTerms);
    var added = new Date(ms);
	
	document.purchase.txtExpiryDate.value = (added.getDate() + "/" + (added.getMonth() + 1) + "/" + added.getFullYear());

}	
}	

function CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost){
  
    x = document.purchase;
	
	var PorDate = x.txtDate.value;
	var PorRequestDate = x.txtRequestDate.value;
	var PorSupplier = x.txtSupplier.value;
	var PorCurr = x.txtCurr.value;
	var PorProject = x.txtProjectCode.value;
	var PorCostCenter = x.txtCostCentCode.value;
	
	var vPorRequestDate = PorRequestDate.split('/');
	vPorRequestDate = vPorRequestDate[2]+vPorRequestDate[1]+vPorRequestDate[0];
	var vPorDate = PorDate.split('/');
	vPorDate = vPorDate[2]+vPorDate[1]+vPorDate[0];
	
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	if (PorDate=='' )
	{
		alert("Date Column is mandatory!");
		x.txtDate.focus();
		return 0;
	}
	else if (vPorRequestDate<vPorDate)
	{
		alert("Delivery Date must be greater than Purchase Order Date");
		x.PorRequestDate.focus();
		return 0;
	}
	else if (PorRequestDate=='')
	{
		alert("Delivery Date Column is mandatory!");
		x.txtRequestDate.focus();
		return 0;
	}
	else if (PorSupplier=='' )
	{
		alert("Supplier Column is mandatory!");
		x.txtSupplier.focus();
		return 0;
	}
	else if (PorCurr=='' )
	{
		alert("Currency Column is mandatory!");
		x.txtCurr.focus();
		return 0;
	}
	else if (PorProject=='' && ModuleRestProj==1 && ModuleProj==1)
	{
		alert("Project is mandatory!");
		x.txtProjectCode.focus();
		return 0;
	}
	else if (PorCostCenter=='' && ModuleRestCost==1 && ModuleCost==1 && document.getElementById('txtCostCentCode').type == 'text')
	{
		alert("CostCenter is mandatory!");
		x.txtCostCentCode.focus();
		return 0;
	}
			
	
	else
	return 1 ;	
}


function CheckFieldsDt(PIndex){
  
    x = document.purchase;
	
	var PorDtItem 	   = document.getElementById('itemcode['+PIndex+']').value;
	var PorDtWarehouse = document.getElementById('warehousecode['+PIndex+']').value;
	var PorDtQty       = document.getElementById('pordtquantity['+PIndex+']').value;
	var PorDtQty2	   = document.getElementById('unit2qty['+PIndex+']').value;
	var PorDtPrice     = document.getElementById('price['+PIndex+']').value;
	var PorDtDisc      = document.getElementById('pordtdiscount['+PIndex+']').value;
	var AvailableQty   = document.getElementById('prequestqty['+PIndex+']').value;
	var PrequestRef    = document.getElementById('prequestref['+PIndex+']').value;
	
	
	
	var vmode = x.actionmode.value;
	
	if (PorDtPrice == '')   PorDtPrice = 0;
	if (PorDtQty2 == '')    PorDtQty2 = 0;
	if (PorDtQty == '')     PorDtQty = 0;
	if (PorDtDisc == '')    PorDtDisc = 0;
	if (AvailableQty == '') AvailableQty = 0;
	
	PorDtQty     = parseFloat(PorDtQty);	
	AvailableQty = parseFloat(AvailableQty);
	
	
	if (PorDtItem=='')
	{
		alert("Item is mandatory!");
		document.getElementById('itemcode['+PIndex+']').focus();
		return 0;
	}	
	else if (PorDtWarehouse=='')
	{
		alert("Warehouse is mandatory!");
		document.getElementById('warehousecode['+PIndex+']').focus();
		return 0;
	}
	else if (PorDtQty*1 != PorDtQty/1 || PorDtQty <= 0  ) {
		alert('Quantity ('+PorDtQty+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('pordtquantity['+PIndex+']').focus();
		return 0;
	}
	else if (PorDtQty > AvailableQty && AvailableQty >= 0 && PrequestRef != "") {
		alert('Quantity entered not allowed. Qty must be <= Remaining Requested Qty ['+AvailableQty+'].');
		document.getElementById('pordtquantity['+PIndex+']').focus();
		return 0;
	}
	else if ((PorDtPrice*1 != PorDtPrice/1 || PorDtPrice < 0) ) {
		alert('Price should be a NUMERIC and POSITIVE value');
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((PorDtDisc != '' && PorDtDisc*1 != PorDtDisc/1) ) {
		alert('Discount should be a NUMERIC value');
		document.getElementById('pordtdiscount['+PIndex+']').focus();
		return 0;
	}
	else if ((PorDtQty2 != '' && PorDtQty2*1 != PorDtQty2/1) ) {
		alert('Item Qty2 should be a NUMERIC value.');
		document.getElementById('unit2qty['+PIndex+']').focus();
		return 0;
	}
	
		
	
	else
	return 1 ;	
}

function AddCharges() {
	x = document.purchase;
	var PurId  = x.txtPorId.value;
	
	if (PurId != '') {
		win = window.open('Form_PurchaseOrderCharges.php?txtChgPurId='+PurId, 'Form_PurchaseOrderCharges', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=780,height=400,top=100');		
		win.creator = self;
		win.focus();		
	} else
	{
		alert('Please enter at least one item first.');
	}
}


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.action='Form_PurchaseOrder.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_PurchaseOrder.php';
	x.submit();
}


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

function PostChanges(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost) {
	x = document.purchase;
	var PorId  = x.txtPorId.value;
	var vMainMode = x.mainaction.value;
	
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	var vPorVatChkbx = 0;
	if (x.ChkPorVat.checked)
		vPorVatChkbx = 1;	
	
	if (x.txtPorCountDetail.value == 0 || x.txtPorCountDetail.value == '') {
		alert('Save not allowed. Please add items.');
	}
	else
	{
		if (result == 1) {
			if (confirm ( "Are you sure you want to Save current Purchase Order?"))
			{
				//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('btnAddItem'))
						x.btnAddItem.disabled = true;
					
					x.actionmode.value='post';
					x.action="Form_PurchaseOrder_Actions.php?mode=post&mainmode="+vMainMode+"&SPorId="+PorId+"&SPorVatChkbx="+vPorVatChkbx;
				//	alert('Form_PurchaseOrder_Actions.php?mode=post&mainmode='+vMainMode+'&SPorId='+PorId+'&SPorVatChkbx='+vPorVatChkbx);
					x.submit();
				}	
			}
		}	
	}
}

function ConfirmOrder(PorId) {
	x = document.purchase;
	var vMainMode = x.mainaction.value;
	
	
	//if (confirm ( "Do you want to Confirm saved purchase order?"))
	{
		x.actionmode.value='confirmorder';
		x.action="Form_PurchaseOrder_Actions.php?mode=confirmorder&mainmode="+vMainMode+"&SPorId="+PorId;
		x.submit();
	} 
	/*else {
		x.actionmode.value='confirmorder';
		x.submit();
	}*/
	

}

	
function DeletePorDt(PorDtId, ItemPackCode, ItemCode) {
	x = document.purchase;
	var PorId  = x.txtPorId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = '';
	
	var vPorVatChkbx = 0;
	if (x.ChkPorVat.checked)
		vPorVatChkbx = 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_PurchaseOrder_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SPorId="+PorId+"&SPorDtId="+PorDtId+"&SPorVatChkbx="+vPorVatChkbx;
		x.submit();
	}

}

function UpdatePorDt(PorDtId) {
    x = document.purchase;
	var vPorId = x.txtPorId.value;
	var vPorDate = x.txtDate.value;
	
	var vPorVatChkbx = 0;
	if (x.ChkPorVat.checked)
		vPorVatChkbx = 1;	
		
	var vMainMode = x.mainaction.value;
	win = window.open('Form_PurchaseOrderDetail.php?mainaction='+vMainMode+'&actionmode=&PPorId='+vPorId+'&PPorDate='+vPorDate+'&PPorDtId='+PorDtId+'&PPorVatChkbx='+vPorVatChkbx, 'Form_PurchaseOrderDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=720,height=320,top=100');		
	win.creator = self;
	win.focus();		

}




//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.purchase;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtPorId.value='';
		x.txtRef.value='';
		x.txtDate.value='';
		x.txtRequestDate.value='';
		x.txtExpiryDate.value='';
		x.txtSupplier.value='';
		x.txtSupplierName.value='';
		x.txtSupplier1.value='';
		x.txtSupplierName1.value='';
		x.txtSupplierVat.value='';
		x.txtPaymentTerms.value='';
		x.txtPaymentCondidions.value='';
		x.txtRequestBy.value='';
		x.txtSupplierContact.value='';
		x.txtRemark.value='';
		x.txtCurr.value='';
		x.txtPorCategory.value='';
		x.txtProjectCode.value='';
		x.txtCostCentCode.value='';
		//x.txtPorStatus.value='';
		x.txtStatusRemark.value='';
		x.txtDeliveryPlace.value='';
		x.txtDeliveryContact.value='';
		x.txtPrequestReference.value='';
		
		x.txtPurChgAmtB1.value='';
		x.txtPurChgAmtB2.value='';
		
		x.txtPorTaxable.value='';
		x.txtPorNoneTaxable.value='';
		x.txtPorGrossTotal.value='';
		x.txtPorDiscount.value='';
		x.txtPorDiscountAmt.value='';
		x.txtPorVat.value='';
		x.txtPorNetTotal.value='';
		x.txtPorTotalTaxes.value='';
		
		//x.txtPorStatus[0].checked = true;
		x.txtPorCategory[0].checked = true;
			
		x.message.value='';
		x.txtPorCountDetail.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 vPorId = x.txtPorId.value;
	var vPorDate = x.txtDate.value;
	var vPorRequestDate = x.txtRequestDate.value;
	var vPorExpiryDate = x.txtExpiryDate.value;
	
	var vPorSupplier = x.txtSupplier.value;
	var vPorRemark = x.txtRemark.value;
	var vPorCurr = x.txtCurr.value;
	var vPorProjectCode = x.txtProjectCode.value;
	var vPorCostCentCode = x.txtCostCentCode.value;
	var vPorDiscount = x.txtPorDiscount.value;
	var vPorDiscountAmt = x.txtPorDiscountAmt.value;
	
	var vPorRequestBy = x.txtRequestBy.value;
	var vPorSupplierContact = x.txtSupplierContact.value;
	var vPorDeliveryPlace = x.txtDeliveryPlace.value;
	var vPorDeliveryContact = x.txtDeliveryContact.value;
	var vPorStatusRemark = x.txtStatusRemark.value;
	
	
	
    /*for (var i=0; i < x.txtPorStatus.length; i++)
	{
		if (x.txtPorStatus[i].checked)
		{
		  var vPorStatus = x.txtPorStatus[i].value;
		}
	}*/
	
	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPorCategory.length; i++)
		{
			if (x.txtPorCategory[i].checked)
			{
			  var vPorCategory = x.txtPorCategory[i].value;
			}
		}
	} else {
		var vPorCategory = x.txtPorCategory.value;
	}	
	
	var vPorVatChkbx = 0;
	if (x.ChkPorVat.checked)
		vPorVatChkbx = 1;	
	
	var vMainMode = x.mainaction.value;
	
	vPorRemark          = vPorRemark.replace('&','%26');
	vPorRequestBy       = vPorRequestBy.replace('&','%26');
	vPorSupplierContact = vPorSupplierContact.replace('&','%26');
	vPorDeliveryPlace   = vPorDeliveryPlace.replace('&','%26');
	vPorDeliveryContact = vPorDeliveryContact.replace('&','%26');
	vPorStatusRemark    = vPorStatusRemark.replace('&','%26');
	
	vPorRemark          = vPorRemark.replace('#','%23');
	vPorRequestBy       = vPorRequestBy.replace('#','%23');
	vPorSupplierContact = vPorSupplierContact.replace('#','%23');
	vPorDeliveryPlace   = vPorDeliveryPlace.replace('#','%23');
	vPorDeliveryContact = vPorDeliveryContact.replace('#','%23');
	vPorStatusRemark    = vPorStatusRemark.replace('#','%23');
	var txtPaymentCondidions = x.txtPaymentCondidions.value;
	var porder_downpayment = x.porder_downpayment.value;
	var porder_downperc = x.porder_downperc.value;
	var porder_downamount = x.porder_downamount.value;
	
	
	if (result == 1) {
		win = window.open('Form_PurchaseOrderDetail.php?mainaction='+vMainMode+'&actionmode=&PPorId='+vPorId+'&PPorDate='+vPorDate+'&PPorRequestDate='+vPorRequestDate+
		                  '&PPorExpiryDate='+vPorExpiryDate+'&PPorSupplier='+vPorSupplier+'&PPorCurr='+vPorCurr+'&PPorProjectCode='+vPorProjectCode+'&PPorCostCentCode='+vPorCostCentCode+
						  '&PPorDiscount='+vPorDiscount+'&PPorDiscountAmt='+vPorDiscountAmt+'&PPorVatChkbx='+vPorVatChkbx+'&PPorCategory='+vPorCategory+
						  '&PPorRemark='+vPorRemark+'&PPorRequestBy='+vPorRequestBy+'&PPorSupplierContact='+vPorSupplierContact+'&PPorDeliveryPlace='+vPorDeliveryPlace+
						  '&PPorDeliveryContact='+vPorDeliveryContact+'&PPorStatusRemark='+vPorStatusRemark+'&txtPaymentCondidions='+txtPaymentCondidions
						  +'&porder_downpayment='+porder_downpayment+'&porder_downperc='+porder_downperc+'&porder_downamount='+porder_downamount
						  , 'Form_PurchaseOrderDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=670,height=320,top=100');		
		win.creator = self;
		win.focus();		
	}	
	
    
}


function DeleteRecordGrid(filepath,formname,transid,PorDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	x = document.purchase;
	var vPorId    = x.txtPorId.value;
	var vPorCurr  = x.txtCurr.value;
	var vPorDate  = x.txtDate.value;
	var vPorDiscount = x.txtPorDiscount.value;
	var vMainMode = x.mainaction.value;
	var vVatChkbx = x.txtPorVatChk.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,'PO-TOT','TOTALS','totals',transid,-1);
				}
			}
		}

		xmlhttp.open("GET","Form_PurchaseOrder_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SPorId="+vPorId+"&SPorDtId="+PorDtId+"&SPorVatChkbx="+vVatChkbx+"&txtCurr="+vPorCurr+"&txtDate="+vPorDate+"&txtPorDiscount="+vPorDiscount);
		xmlhttp.send();
	}	

}


function SubmitRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction,ModuleRestProj,ModuleRestCost,ModuleProj,ModuleCost,FIPurchaseCategory) {
	
	x = document.purchase;
	document.getElementById('imgSubmit['+PIndex+']').disabled = true;
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	if (result == 1) {
		result = CheckFieldsDt(PIndex);
	}

	var PorDtId   = document.getElementById('pordtid['+PIndex+']').value; 
	if (PorDtId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPorCategory.length; i++)
		{
			if (x.txtPorCategory[i].checked)
			{
			  var vPorCategory = x.txtPorCategory[i].value;
			}
		}
	} else {
		var vPorCategory = x.txtPorCategory.value;
	}
	
	/*for (var i=0; i < x.txtPorStatus.length; i++)
	{
		if (x.txtPorStatus[i].checked)
		{
		  var vPorStatus = x.txtPorStatus[i].value;
		}
	}*/	

	var txtPaymentCondidions = x.txtPaymentCondidions.value;
	var porder_downpayment = x.porder_downpayment.value;
	var porder_downperc = x.porder_downperc.value;
	var porder_downamount = x.porder_downamount.value;
	
	if(document.getElementById("txtPurCost["+PIndex+"]"))
		var porcost = document.getElementById("txtPurCost["+PIndex+"]").value;
	else var porcost = 0;
	if( porcost == '') porcost = 0;
	
	if(document.getElementById("txtPurFreight["+PIndex+"]"))
		var porfreight = document.getElementById("txtPurFreight["+PIndex+"]").value;
	else var porfreight = 0;
	if( porfreight == '') porfreight = 0;
	
	var vShippingmethod = document.getElementById("shippingmethod").value;
	
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SPorId='+x.txtPorId.value+
					'&PPorId='+x.txtPorId.value+
					'&PPorDate='+x.txtDate.value+
					'&PPorCurr='+x.txtCurr.value+
					'&txtPaymentCondidions='+encodeURIComponent(txtPaymentCondidions)+
					'&porder_downpayment='+porder_downpayment+
					'&porder_downperc='+porder_downperc+
					'&porder_downamount='+porder_downamount+
					'&PPorRequestDate='+x.txtRequestDate.value+
					'&PPorExpiryDate='+x.txtExpiryDate.value+
					'&PPorSupplier='+x.txtSupplier.value+
					'&PPorSupplier1='+x.txtSupplier1.value+
					'&PPorDiscount='+x.txtPorDiscount.value+
					'&PPorDiscountAmt='+x.txtPorDiscountAmt.value+
					'&PPorVatChkbx='+x.txtPorVatChk.value+
					'&PPorProjectCode='+x.txtProjectCode.value+
					'&PPorCostCentCode='+x.txtCostCentCode.value+
					'&PPorCategory='+vPorCategory+
					'&PPorRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PPorRequestBy='+encodeURIComponent(x.txtRequestBy.value)+
					'&PPorSupplierContact='+encodeURIComponent(x.txtSupplierContact.value)+
					'&PPorDeliveryPlace='+encodeURIComponent(x.txtDeliveryPlace.value)+
					'&PPorDeliveryContact='+encodeURIComponent(x.txtDeliveryContact.value)+
					'&PPorStatusRemark='+encodeURIComponent(x.txtStatusRemark.value)+
					'&SPorDtId='+document.getElementById('pordtid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecode['+PIndex+']').value+
					'&porderdt_heatno='+document.getElementById('porderdt_heatno['+PIndex+']').value+
					'&txtItemCode='+encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value)+
					'&txtPorDtRemark='+document.getElementById('remarkdt['+PIndex+']').value+
					'&txtPorDtQty='+document.getElementById('pordtquantity['+PIndex+']').value+
					'&txtPorDtQty2='+document.getElementById('unit2qty['+PIndex+']').value+
					'&txtPorDtPrice='+document.getElementById('price['+PIndex+']').value+
					'&txtPorDtDiscount='+document.getElementById('pordtdiscount['+PIndex+']').value+
					'&txtProjectCodeDt='+document.getElementById('projectcodedt['+PIndex+']').value+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value+
					'&txtporcost='+porcost+'&txtporfreight='+porfreight+'&txtShippingmethod='+vShippingmethod;
		
	
	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_PurchaseOrder_Actions.php", true);
		
			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");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){ 
							transid = data[0].transid;
							
							x.txtPorId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'itemcode['+index+']';
						
						createCookie('por-nextcell',nextcell);
						
						ReloadGrid(filepath,formname,transid,'datagrid',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
							ReloadGridDt(filepath,'PO-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_PurchaseOrder_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}
}


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

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



function SetMaturityDate() {
	x = document.purchase;
	var vmode = x.mainaction.value;
	
	if(x.txtSupplierVat.value == 1)
	    x.ChkPorVat.checked = true;
    
	//if (vmode == 'insert' || vmode == 'edit') {
	    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()); 
		
	//}  
	
	    
		
}

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];
   	
	//fdate = dt_array[2] + "-" + dt_array[1] + "-" + dt_array[0];
	// "mm/dd/yyyy"
	fdate = dt_array[1] + "/" + dt_array[0] + "/" + dt_array[2];
	
	return fdate;
}



function CalcPorDiscount(option, dec, vatapplied, vatperc) {
	x = document.purchase;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var TaxAmt = x.txtPorTaxable.value;
	var GrossTotal = x.txtPorGrossTotal.value;
	var DisPer = x.txtPorDiscount.value;
	var DisAmt = x.txtPorDiscountAmt.value;
	var VatAmt = x.txtPorVat.value;
	var TaxesAmt = x.txtPorTotalTaxes.value;
	var Othercharges = x.txtPorder_Othercharges.value;
	
	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
		alert('Discount Amount should be a NUMERIC value');
		x.txtPorDiscountAmt.focus();
		return 0;
	}
	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
		alert('Discount Percentage should be a NUMERIC value');
		x.txtPorDiscount.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 && (DisPer > 0 || DisAmt > 0)) 
	{
		if (option == 1 )  //Option by Percentage Get The Amount
			x.txtPorDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
		else if (option == 2 ){  //Option by Amount Get The Per
		    x.txtPorDiscount.value = roundNumber(((DisAmt/GrossTotal)*100),dec);
				
			if (DisAmt > 0) x.txtPorDiscount.readOnly = true; 
			else x.txtPorDiscount.readOnly = false;
					
		}

		// Calculation of Vat Amount and Net Total
		DisAmt = x.txtPorDiscountAmt.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.txtPorVat.value      = formatNumber(VatAmt,dec);
		x.txtPorNetTotal.value = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);
		
	}   
update_netcharges();	
	
}


function update_netcharges(){
x = document.purchase;

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

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

x.txtPorder_NetTotalCharges.value = vCharges+vnet;
}

function CalcNetTotal(option, dec, vatapplied, vatperc) {
	x = document.purchase;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var TaxAmt = x.txtPorTaxable.value;
	var GrossTotal = x.txtPorGrossTotal.value;
	var DisPer = x.txtPorDiscount.value;
	var DisAmt = x.txtPorDiscountAmt.value;
	var VatAmt = x.txtPorVat.value;
	var TaxesAmt = x.txtPorTotalTaxes.value;
	var Othercharges = x.txtPorder_Othercharges.value;
	
	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
		alert('Discount Amount should be a NUMERIC value');
		x.txtPorDiscountAmt.focus();
		return 0;
	}
	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
		alert('Discount Percentage should be a NUMERIC value');
		x.txtPorDiscount.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.txtPorDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
		else if (option == 2 ){  //Option by Amount Get The Per
		    x.txtPorDiscount.value = roundNumber(((DisAmt/GrossTotal)*100),dec);
				
			if (DisAmt > 0) x.txtPorDiscount.readOnly = true; 
			else x.txtPorDiscount.readOnly = false;
					
		}

		// Calculation of Vat Amount and Net Total
		DisAmt = x.txtPorDiscountAmt.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.txtPorVat.value      = formatNumber(VatAmt,dec);
		x.txtPorNetTotal.value = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);
		
	}   
	
	update_netcharges();	
}

function SetPorVat(dec, vatapplied, vatperc, PurchaseTTC) {
	x = document.purchase;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var vAmount = 0;
	
	var TaxAmt = x.txtPorTaxable.value;
	var GrossTotal = x.txtPorGrossTotal.value;
	var VatAmt = x.txtPorVat.value;
	var DisAmt = x.txtPorDiscountAmt.value;
	var NetTotal = x.txtPorNetTotal.value;
	var TaxesAmt = x.txtPorTotalTaxes.value;
	var Othercharges = x.txtPorder_Othercharges.value;
	
	if (TaxAmt == '') TaxAmt = 0;
	if (GrossTotal == '') GrossTotal = 0;
	if (Othercharges == '') Othercharges = 0;
	if (VatAmt == '') VatAmt = 0;
	if (DisAmt == '') DisAmt = 0;
	if (NetTotal == '') NetTotal = 0;
	if (TaxesAmt == '') TaxesAmt = 0;
	
	VatAmt = parseFloat(VatAmt);
	NetTotal = parseFloat(NetTotal);
	DisAmt = parseFloat(DisAmt);
	TaxAmt = parseFloat(TaxAmt);
	GrossTotal = parseFloat(GrossTotal) ;
	Othercharges = parseFloat(Othercharges);
	TaxesAmt = parseFloat(TaxesAmt);
	
	if (x.ChkPorVat.checked) {
		
		// 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.txtPorVatChk.value			 = 1;
		x.txtPorTaxable.value    = formatNumber(TaxAmt,dec);
		x.txtPorGrossTotal.value = formatNumber(GrossTotal,dec);
		x.txtPorVat.value        = formatNumber(VatAmt,dec);
		GrossTotal = GrossTotal + Othercharges;
		x.txtPorNetTotal.value   = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);
	}
	else
	{	x.txtPorVatChk.value			 = 0;
		GrossTotal = GrossTotal + Othercharges;
		if (PurchaseTTC == 1) {
			x.txtPorVat.value        = formatNumber(0,dec);
			x.txtPorTaxable.value    = formatNumber(TaxAmt + VatAmt,dec);
			x.txtPorGrossTotal.value = formatNumber(GrossTotal + VatAmt,dec);
		}
		else {
			x.txtPorVat.value      = formatNumber(0,dec);
			x.txtPorNetTotal.value = formatNumber(roundNumber((NetTotal - VatAmt),dec),dec);
		}	
	}  
	

}

function SetPorVatFlag() {
	x = document.purchase;
	var vmode = x.mainaction.value;
	
	if(x.txtSupplierVat.value == 1)
	    x.ChkPorVat.checked = true;
}		

function PrintPurchaseOrder(PorId, PorRef) {
	var str = '';
	//var PorId = document.purchase.txtPorId.value;
	if (confirm ( "Do you want to Print current Purchase Order with reference "+PorRef+" ?"))
	{
		str = 'Form_PurchaseOrderPreview.php?PorderId='+PorId;
		window.open(str);
	}	
}


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=4&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)
		vname=encodeURIComponent(document.purchase.txtSupplierName.value);
	else if(str == 55)
		vname=encodeURIComponent(document.purchase.txtSupplierName1.value);
  
	window.open('List_Supplier.php?frm=4&item='+str+'&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){
	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,'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 showlistHeatNo(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vHeatNoCode = encodeURIComponent(document.getElementById('porderdt_heatno['+PIndex+']').value);
	
	window.open('List_HeatNo.php?frm=1&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 CalcPorDtTotal(option,dec,PIndex) {
	x = document.purchase;
	var vmode = x.actionmode.value;
	var Qty      = document.getElementById('pordtquantity['+PIndex+']').value;
	var Price    = document.getElementById('price['+PIndex+']').value;
	var Discount = document.getElementById('pordtdiscount['+PIndex+']').value;
	var Total    = document.getElementById('pordttotal['+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('pordttotal['+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 CalcPorDtPrice(option,dec,PIndex){ 
	
	var purcost = document.getElementById("txtPurCost["+PIndex+"]").value;
	var purfreight = document.getElementById("txtPurFreight["+PIndex+"]").value;
	var qty = document.getElementById("pordtquantity["+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("pordttotal["+PIndex+"]").value = qty*roundNumber(purprice,dec);
}

function CalcQty2(ModuleUnit1Method,Option,PIndex) { 
	x = document.purchase;
	var Qty  = document.getElementById('pordtquantity['+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('pordtquantity['+PIndex+']').value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('pordtquantity['+PIndex+']').value = '';
		}
	}
}

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


function LoadConfirmedTrRequest(Module_RestrictProjCost,Module_RestrictCost,ModuleProject, ModuleCostCenter){
	var	txtPorId = document.purchase.txtPorId.value;
	
	var suppcode  = document.purchase.txtSupplier.value;
	var PorId  = document.purchase.txtPorId.value;
	
	var str1 = 'Form_PurchaseLoadRequest.php?suppcode='+suppcode+'&PorId='+PorId;

		
		
	/*if (document.purchase.txtSupplier.value=='')
	{
		alert("Supplier Column is mandatory!");
		document.purchase.txtSupplier.focus();
		return 0;
	}	*/	
		//var result = CheckFields(ModuleProject, ModuleCostCenter,Module_RestrictProjCost,Module_RestrictCost);
	
		result  =1;
		x = document.purchase;
		var vMode = x.mainaction.value;
			var  the_data =  str1 + '&mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SPorId='+x.txtPorId.value+
					'&PPorId='+x.txtPorId.value+
					'&PPorDate='+x.txtDate.value+
					'&PPorCurr='+x.txtCurr.value+
					'&PPorRequestDate='+x.txtRequestDate.value+
					'&PPorExpiryDate='+x.txtExpiryDate.value+
					'&PPorSupplier='+x.txtSupplier.value+
					'&PPorDiscount='+x.txtPorDiscount.value+
					'&PPorDiscountAmt='+x.txtPorDiscountAmt.value+
					'&PPorVatChkbx='+x.txtPorVatChk.value+
					'&PPorProjectCode='+x.txtProjectCode.value+
					'&PPorCostCentCode='+x.txtCostCentCode.value+
					'&PPorRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PPorRequestBy='+encodeURIComponent(x.txtRequestBy.value)+
					'&PPorSupplierContact='+encodeURIComponent(x.txtSupplierContact.value)+
					'&PPorDeliveryPlace='+encodeURIComponent(x.txtDeliveryPlace.value)+
					'&PPorDeliveryContact='+encodeURIComponent(x.txtDeliveryContact.value)+
					'&PPorStatusRemark='+encodeURIComponent(x.txtStatusRemark.value);
		
		if (result == 1) {
			win = window.open(the_data,'List of Confirmed Purchase Request', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=820,height=600,top=100,left=20');		
			win.creator = self;
			win.focus();		
		}
	
}
function showText(){
	var vPorId = document.purchase.txtPorId.value;
	var vPaymentTerms = encodeURIComponent(document.getElementById("txtPaymentCondidions").value);
	
	window.open('form_termsText.php?frm=1&txtPorId='+vPorId+'&vPaymentTerms='+vPaymentTerms,'mywindow','width=865,height=680,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function getItemInfo(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('warehousecode['+index+']').value = data[1];
				}					
			}
		}
		
		
		xmlhttp.open("GET","Form_PurchaseOrder_Actions.php?actionmode=getItemInfo&item_code="+item_code,true);
		xmlhttp.send();
	}
}


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.txtPorCategory.length; i++)
		{
			if (x.txtPorCategory[i].checked)
			{
			  var vPorCategory = x.txtPorCategory[i].value;
			}
		}
	} else {
		var vPorCategory = x.txtPorCategory.value;
	}
	
	var txtPaymentCondidions = x.txtPaymentCondidions.value;
	var porder_downpayment = x.porder_downpayment.value;
	var porder_downperc = x.porder_downperc.value;
	var porder_downamount = x.porder_downamount.value;
	
	var vShippingmethod = document.getElementById("shippingmethod").value;
	
	var vMode = 'import';
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SPorId='+x.txtPorId.value+
					'&PPorDate='+x.txtDate.value+
					'&PPorCurr='+x.txtCurr.value+
					'&porder_downpayment='+porder_downpayment+
					'&porder_downperc='+porder_downperc+
					'&porder_downamount='+porder_downamount+
					'&PPorRequestDate='+x.txtRequestDate.value+
					'&PPorExpiryDate='+x.txtExpiryDate.value+
					'&PPorSupplier='+x.txtSupplier.value+
					'&PPorDiscount='+x.txtPorDiscount.value+
					'&PPorDiscountAmt='+x.txtPorDiscountAmt.value+
					'&PPorVatChkbx='+x.txtPorVatChk.value+
					'&PPorProjectCode='+x.txtProjectCode.value+
					'&PPorCostCentCode='+x.txtCostCentCode.value+
					'&PPorCategory='+vPorCategory+
					'&PPorRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PPorRequestBy='+encodeURIComponent(x.txtRequestBy.value)+
					'&PPorSupplierContact='+encodeURIComponent(x.txtSupplierContact.value)+
					'&PPorDeliveryPlace='+encodeURIComponent(x.txtDeliveryPlace.value)+
					'&PPorDeliveryContact='+encodeURIComponent(x.txtDeliveryContact.value)+
					'&PPorStatusRemark='+encodeURIComponent(x.txtStatusRemark.value)+'&txtShippingmethod='+vShippingmethod;	
	
	if (result == 1) {
			
		
		x.action="Form_PurchaseOrder_Actions.php?"+the_data;
		x.submit();	
		
	}
}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Purchase Order</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='message' value='$message' size='200'>
HERE;

//$message='';

	
//Initializations

$PriceLabel = 'Price';	
if ($PurchaseTTC == 1) 	
	$PriceLabel = 'Price TTC';	
	
	
//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);
}
	
//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($txtRequestDate))	
	$txtRequestDate = displayToday();	
	*/
/*
if (empty($txtExpiryDate))	
	$txtExpiryDate = displayToday();		
	*/
	
if ($FI_PurchaseCategory == 0 || $FI_PurchaseCategory == 1) $txtPorCategory = 0;
else if ($FI_PurchaseCategory == 2) $txtPorCategory = 1;	



if ($txtPorId != '') {
	// Read From Temp Tables For Selected Record				 
	$query = " Select Porder_ID, Porder_Reference, Date_Format(Porder_Date,'%d/%m/%Y') As PorderDate, ".
	         " Date_Format(Porder_RequestDate,'%d/%m/%Y') As RequestDate, Porder_RequestBy, Porder.Currency_code, ".
			 " Porder.Supplier_Code As SupplierCode, Suppliers.Ledger_name As SupplierName, suppliers.Supplier_PaymentTerms, ".
			 " suppliers.Supplier_VAT, Porder_SupplierContact, Porder_Remark, Porder.Project_Code, Porder.Costcent_code,  ".
			 " Date_Format(Expiry_date,'%d/%m/%Y') As ExpiryDate, ifNull(Porder_Import,0), ifNull(Porder_Status,'A'), ".
			 " Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
			 " Round(Porder_Taxable, ".$DecimalBase."), Round(Porder_NoneTaxable, ".$DecimalBase."), ".
			 " Round(Porder_Total, ".$DecimalBase.") As GrossTotal, ".
			 " Round(Porder_DiscountPer, ".$DecimalBase."), Round(Porder_DiscountAmount, ".$DecimalBase."),  ".
			 " ifNull(Porder_VATChckbx,0) As Porder_VatChkbx, Round(Porder_Vat, ".$DecimalBase.") As Porder_Vat, ".
			 " Round((IfNull(Porder_Total,0) + IfNull(Porder_Vat,0) - IfNull(Porder_DiscountAmount,0) + (ifNull(Porder_Tax1,0) + ifNull(Porder_Tax2,0) + ifNull(Porder_Tax3,0) + ifNull(Porder_Tax4,0) + ifNull(Porder_Tax5,0))), ".$DecimalBase.") As Porder_NetTotal,  ".
			 " Round((ifNull(Porder_Tax1,0) + ifNull(Porder_Tax2,0) + ifNull(Porder_Tax3,0) + ifNull(Porder_Tax4,0) + ifNull(Porder_Tax5,0)), ".$DecimalBase.") As TotalTaxes,  ".
			 " Prequest_Ref,porder_paymentcondition,porder_downpayment,porder_downperc,porder_downamount, ".
			 " Round(ifNull(Porder_Charges,0), ".$DecimalBase."), Round(ifNull(Porder_ChargesBase1,0), ".$DecimalBase."), Round(ifNull(Porder_ChargesBase2,0), ".$DecimalBase."), shippingmethod_id, date_format(porder_actualdate, '%d/%m/%Y') as porder_actualdate, approvedby, ".
			 " Porder.Supplier_Code1 As SupplierCode1, s2.Ledger_name As SupplierName1".
			 " From Temp_Porder As Porder ".
			 " Left Join Suppliers on Porder.Supplier_code = Suppliers.Ledger_Number ".
			 " Left Join Suppliers s2 on Porder.Supplier_code1 = s2.Ledger_Number ".
	         " Where Porder_ID = ".$txtPorId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
			 
	//  echo $query."<BR>";
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	extract($rows);
	$txtPorId       = $rows[0];
	$txtRef         = $rows[1];
	$txtDate        = $rows[2];
	$txtRequestDate = $rows[3];
	$txtRequestBy   = $rows[4];
	$txtCurr        = $rows[5];
	
	if (!empty($rows[6])) {
		$txtSupplier        = $rows[6];
		$txtSupplierName    = $rows[7];
		$txtSupplier1        = $rows[40];
		$txtSupplierName1    = $rows[41];
		$txtPaymentTerms    = $rows[8];
		$txtSupplierVat     = $rows[9];
		$txtSupplierContact = $rows[10];
	}
	
	$txtRemark          = $rows[11];
	$txtProjectCode     = $rows[12];
	$txtCostCentCode    = $rows[13];
	$txtExpiryDate      = $rows[14];
	$txtPorCategory     = $rows[15];
	//$txtPorStatus       = $rows[16];
	$txtStatusRemark    = $rows[17];
	$txtDeliveryPlace   = $rows[18];
	$txtDeliveryContact = $rows[19];
	
	$txtPorTaxable     = $rows[20];
	$txtPorNoneTaxable = $rows[21];
	$txtPorGrossTotal  = $rows[22];
	$txtPorDiscount    = $rows[23];
	$txtPorDiscountAmt = $rows[24];
	$ChkPorVat         = $rows[25];
	$txtPorVat         = $rows[26];
	$txtPorNetTotal    = $rows[27];
	$txtPorTotalTaxes  = $rows[28];
	$txtPrequestReference  = $rows[29];
	$txtPaymentCondidions  = $rows[30];
	$porder_downpayment    = $rows[31];
	$porder_downperc    = $rows[32];
	$porder_downamount    = $rows[33];
	
	$txtPurChgAmt   = $rows[34];
	$txtPurChgAmtB1 = $rows[35];
	$txtPurChgAmtB2 = $rows[36];
	$txtPurChgPer   = ($txtPurChgAmt/$txtPurNetTotal)*100;
	
	$shippingmethod = $rows[37];
	
	$txtNetTotalWithCharges = number_format($txtPurNetTotal + $txtPurChgAmt, $DecimalBase,".","");
	
	
	$query = " Select Count(*) FROM Temp_PorderDt ".
			 " WHERE Porder_ID = ".$txtPorId;
	$result = selectData($connection, $query);
	$txtPorCountDetail = $result[0];
	if($txtPorCountDetail == '') $txtPorCountDetail = 0;
	
}


$data = insertDate($txtDate);
$datevalue =  substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2); 
if($txtRequestDate == '' ) $txtRequestDate = $txtDate;

if($txtPaymentTerms=='')
	$txtPaymentTerms=0;
$txtExpiryDate = date('d/m/Y', strtotime($datevalue. ' + '.$txtPaymentTerms.' days'));



//$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 ORDER</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='720px' align='left'>";

//if ($FI_PurchaseOrderApp == 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='btnClear' name='btnClear' onclick='ClearPage();return false;' title='Clear Page'><span><span>Clear Page</span></span></button>";		


if ($txtPorId != '')
	echo" <button type='button' id='btnCancel' name='btnCancel' onclick='CancelRecord();return false;' title='Cancel Changes'><span><span>Cancel</span></span></button>";	
	
if ($txtPorId != '')
	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 ($txtPorId == '')
	echo" <button type='button' id='btnSearch' name='btnSearch' onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";	



if ($txtPorId == '')
	echo" <button type='button' id='btnPending' name='btnPending' onclick='SearchForPending();return false;' title='Pending Purchase Orders'><span><span>Pending</span></span></button>";	

	
if ($txtPorId == '' && $Module_PurchaseRequest == 1)
	echo" <button type='button' id='btnLoadRqst' name='btnLoadRqst' onclick='LoadConfirmedTrRequest($Module_RestrictProjCost,$Module_RestrictCost, $Module_Project,$Module_CostCenter);return false;' title='Load Purchase Request'><span><span>Load Purchase Request</span></span></button>";

	
if ($txtPorId != '')		
		echo" <button type='button' id='btnAddCharges' name='btnAddCharges' onclick='AddCharges();return false;' title='AddCharges'><span><span>Add Charges</span></span></button>";	
	
	
if ($txtPorId !='')	
	echo"<button type='button' id='btnUpload' name='btnUpload' 
			onclick=\"UploadDocuments('purchaseorder');return false;\" title='Upload Documents'><span><span>Upload Documents</span></span></button>";

echo "</td><td align='right'>";			
if($Module_ImportExcell==1)
echo"<table border=0><tr><td>
<button type='button' id='btnImp' name='btnImp' onclick=\"ImportExcell('$txtPorId',$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=80>
		  <col width=50>
		  <col width=110>
		  <col width=80>
		  <col width=140>
		  <col width=110>
		  <col width=160>
		  <col width=270>

		<tr bgcolor="#F7F7F7">
          <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='txtPorCountDetail' value='$txtPorCountDetail' >
			  <input type='hidden' name='txtPorId' value='$txtPorId' size='10'>
			  <input type="hidden" name="txtRef" value="$txtRef" size='10' >
		  </td>
		  <td align="left"><span class="style1">Date&nbsp;<span class="style16">*</span></span></td>
		  <td><input type='text' name='txtDate' value='$txtDate'   onBlur=checkDateFormat(this,$strt,$end)  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></td>
		  <td align='left' ><span class='style1'>Delivery Date&nbsp;<span class="style16">*</span></span></td>
          <td ><input type='text' name='txtRequestDate' value='$txtRequestDate'     maxlength='10' style='width:80px;' readonly>
						  <A HREF="#" onClick="displayCalendar(document.purchase.txtRequestDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A></td>				  
		  <td align='left' ><span class='style1'>Value Date</span></td>
          <td ><input type='text' name='txtExpiryDate' value='$txtExpiryDate'  onBlur='checkDateFormat(this)'  maxlength='10' style='width:80px;' >
						  <A HREF="#" onClick="displayCalendar(document.purchase.txtExpiryDate,'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;
//echo insertDate($txtDate).' > '.$Setup_VatStartDate.' && '.$Setup_VatPercentage.' || '.$Module_AdditionalTaxes;
if ((insertDate($txtDate) > $Setup_VatStartDate && $Setup_VatPercentage != 0) || ($Module_AdditionalTaxes == 1)) {		  
  $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['DecimalBase'] = $DecimalBase;
$Parameters['Base1'] = $base1;
$Parameters['Base2'] = $base2;
$Parameters['Setup_VatPercentage'] = $Setup_VatPercentage;
$Parameters['VatApplied'] = $VatApplied;
$Parameters['FI_PurchaseCategory'] = $FI_PurchaseCategory;
$Parameters['Module_Heatno'] = $Module_Heatno;
$Parameters['Module_ChargesPurchase'] = $Module_ChargesPurchase;


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

$Parameters['txtDate'] 		   = $txtDate;
$Parameters['txtSupplierCode'] = $txtSupplier;
$Parameters['txtCurrCode']     = $txtCurr;

$Parameters['showCIF']     = $showCIF;
$Parameters['Module_PurchaseRequest']     = $Module_PurchaseRequest;

$_SESSION['gpor_parameters']  = $Parameters;


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

echo"	<div id='totals' style='width:270px; margin-top:3px; float:right;'>";
	ShowPurchaseOrderTotals($connection,$txtPorId,$_SESSION['gpor_parameters'],$_SESSION['gpor_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=140>
			
			<tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Taxable</span></td> 
			 <td align='left'><input type='text' name='txtPorTaxable' value='$txtPorTaxable' maxlength='20' readonly style='text-align:right; width:120px; 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='txtPorNoneTaxable' value='$txtPorNoneTaxable' maxlength='20' readonly style='text-align:right; width:120px; 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='txtPorGrossTotal' value='$txtPorGrossTotal' maxlength='20' readonly style='text-align:right; width:120px; 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='txtPorDiscount' value='$txtPorDiscount' maxlength='5'  style='text-align:right; width:40px; height=18px;' onKeyup='CalcPorDiscount(1, $DecimalBase,$VatApplied,$Setup_VatPercentage);' >%
			                  <input type='text' name='txtPorDiscountAmt' value='$txtPorDiscountAmt' maxlength='20' style='text-align:right; width:64px; height=18px;' onKeyup='CalcPorDiscount(2, $DecimalBase,$VatApplied,$Setup_VatPercentage);' ></td>
		  </tr>

HERE;

echo "    <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><input type='checkbox' name='ChkPorVat' id='ChkPorVat' value='1' onClick='SetPorVat($DecimalBase,$VatApplied,$Setup_VatPercentage,$PurchaseTTC);'   "; 
	          if($ChkPorVat==1) echo "checked />"; else echo " />";   
echo "   	 <span class='style1'>VAT $Setup_VatPercentage%</span></td> 
			 <td align='left'>
			   <input type='text' name='txtPorVat' value='$txtPorVat' maxlength='20' style='text-align:right; width:120px; height=18px;'  >
			 </td>";
echo "  </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='txtPorTotalTaxes' value='$txtPorTotalTaxes' maxlength='20' readonly style='text-align:right; width:120px; height=18px;'></td>
		     </tr>";
	} else {
		echo "<input type='hidden' name='txtPorTotalTaxes' value='$txtPorTotalTaxes'>";
	}

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='txtPorNetTotal' value='$txtPorNetTotal' maxlength='20' readonly style='text-align:right; width:120px; height=18px;'></td>
		  </tr>
		  
		  </table></td>				  
		</tr>";

*/



echo"   <tr bgcolor='#F7F7F7' >
		  <td align='left' ><span class='style1'>Supplier&nbsp;<span class='style16'>*</span></span></td>";
echo"     <td colspan='5' ><span class='style1'><label>";
echo"      <input type='text' name='txtSupplier' id='txtSupplier' value='$txtSupplier' onBlur='SetPorVatFlag();'  style='width:110px;' maxlength='10' onchange=\"CheckLookup('chkcodeexists','suppliers','ledger_number',this.value,'lstSupplierCodeH'); \" />
           <input type='text' name='txtSupplierName' id='txtSupplierName' value='$txtSupplierName' style='width:285px;' 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(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>
		   <input type='hidden' name='txtSupplierVat' id='txtSupplierVat' value='$txtSupplierVat' />
          </label></span>
          </td>";

echo"     <td align='left' ><span class='style1'>Payment Due Date</span></td>";
//echo"     <td ><font face='Verdana' size='2'><b>&nbsp;$txtPaymentTerms</b></font><span class='style1'><input type='hidden' name='txtPaymentTerms' value='$txtPaymentTerms' style='width:100px;' /></span></td>";
echo"     <td ><input type='text' name='txtPaymentTerms' value='$txtPaymentTerms' onchange='changevaluedate()' onblur='checkval()' style='width:100px;' /></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='5' ><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:285px;' 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
/*
echo"   <tr bgcolor='#F7F7F7' >";

echo"     <td  align='left' ><span class='style1'>Payment Condition</span></td>";
//echo"     <td ><font face='Verdana' size='2'><b>&nbsp;$txtPaymentTerms</b></font><span class='style1'><input type='hidden' name='txtPaymentTerms' value='$txtPaymentTerms' style='width:100px;' /></span></td>";
echo"     <td colspan=1><input type='text' name='txtPaymentCondidions' value='$txtPaymentCondidions' style='width:400px;' /></td>";
echo"     <td><span class='style1'>Down Payment</span></td>
		  <td><input type='checkbox' name='porder_downpayment' id='porder_downpayment'></td>";
echo"   </tr>";
*/

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

if($txtPaymentCondidions=='')
	$txtPaymentCondidions = $Porder_TermsConditions;

echo"     <td  align='left' ><span class='style1'>Payment Terms</span></td>";
echo"     <td colspan=5>";
echo "<textarea name='txtPaymentCondidions' cols=54  style='width:400px;'id='txtPaymentCondidions'>$txtPaymentCondidions</textarea>";
echo "<label><span class='style1'><img src='img/btnopen.jpg' title='Show Full Text ' id='lstProjectCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showText(); '  /></span></label></td>";

if($porder_downpayment==''){
	$porder_downpayment = 0;
	
	}
	


echo"     <td><span class='style1'>Down Payment</span></td>
		  <td>";
		   if($porder_downpayment==0)
			$stat = ' readonly ';
			else
			$stat = '';
			
		  if($porder_downpayment==0)
			echo"<input type='checkbox' name='chk_porder_downpayment' id='chk_porder_downpayment' onclick='setdown()'>";
		else
			echo"<input type='checkbox' name='chk_porder_downpayment' id='chk_porder_downpayment' checked onclick='setdown()'>";
			
		  echo"<input type='hidden' name='porder_downpayment' id='porder_downpayment' value='$porder_downpayment'>
		  
		  <input type='text' name='porder_downperc' id='porder_downperc'   onchange='CalcDownDiscount(1,$DecimalBase)'	value='$porder_downperc' style='width:30px'>%
		  <input type='text' name='porder_downamount' id='porder_downamount'  value='$porder_downamount'     onchange='CalcDownDiscount(2,$DecimalBase)'	 style='width:70px'>
		  
		  </td>";
echo"</tr>";

echo"   <tr bgcolor='#F7F7F7'>
		  <td align='left' ><span class='style1'>Request By</span></td>
		  <td colspan='5' ><span class='style1'>
			<input type='text' name='txtRequestBy' value='".htmlspecialchars($txtRequestBy, ENT_QUOTES)."'  style='width:400px;' maxlength='50' >
		  </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;' $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'>		
		  <td align='left' ><span class='style1'>Contact</span></td>
		  <td colspan='5' ><span class='style1'>
			<input type='text' name='txtSupplierContact' value='".htmlspecialchars($txtSupplierContact, ENT_QUOTES)."'  style='width:400px;' maxlength='50' >
		  </td>";

		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='txtPorCategory' id='txtPorCategory0' value='0' "; if($txtPorCategory==0 || $txtPorCategory=='') echo "checked />"; else echo " />";  echo " Local";
		echo" <input type='radio' name='txtPorCategory' id='txtPorCategory1' value='1' "; if($txtPorCategory==1) echo "checked />"; else echo " />";  echo " Import";
        echo"</span></td>";
	} else {
		echo" <td align='left' colspan='4' >&nbsp;<input type='hidden' name='txtPorCategory' id='txtPorCategory' value='$txtPorCategory' /></td>";
	}	

	
echo"	</tr>";

echo"   <tr bgcolor='#F7F7F7'>
		  <td align='left' ><span class='style1'>Remark</span></td>
		  <td colspan='5' ><span class='style1'>
			<input type='text' name='txtRemark' value='".htmlspecialchars($txtRemark, ENT_QUOTES)."'  style='width:400px;' maxlength='100' >
		  </td>";

 
	echo" <td align='left' colspan='1' ><span class='style1'>Prequest Ref.</span></td>";
	echo" <td align='left' colspan='1' ><span class='style1'>
			<input type='text' name='txtPrequestReference' value='$txtPrequestReference'  readonly style='width:100px;' maxlength='100' ></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:100px;' 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='left' ><span class='style1'>Costcenter&nbsp;<span class='style16'>*</span></span></td>		
		  <td align='left' colspan='2'><span class='style1'>
		    <input type='text' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' style='width:164px;' 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='3'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='' /></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' height='30px'>";
/*
echo"<td align='left' ><span class='style1'>Status</span></td>
		  <td colspan='5' ><span class='style1'>";
echo"		<input type='radio' name='txtPorStatus' id='txtPorStatus' value='A' "; if($txtPorStatus=='A' || $txtPorStatus=='') echo "checked />"; else echo " />";  echo " Approved";
echo"		<input type='radio' name='txtPorStatus' id='txtPorStatus' value='P' "; if($txtPorStatus=='P') echo "checked />"; else echo " />";  echo " Pending";
echo"		<input type='radio' name='txtPorStatus' id='txtPorStatus' value='R' "; if($txtPorStatus=='R') echo "checked />"; else echo " />";  echo " Rejected";
echo"		<input type='radio' name='txtPorStatus' id='txtPorStatus' value='C' "; if($txtPorStatus=='C') echo "checked />"; else echo " />";  echo " Canceled";
echo"	  </td>";
*/

		  echo"<td align='left' ><span class='style1'>Status Remark</span></td>
		  <td colspan='5' ><span class='style1'>
			<input type='text' name='txtStatusRemark' value='".htmlspecialchars($txtStatusRemark, ENT_QUOTES)."'  style='width:400px;' maxlength='100' >
		  </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> ";		
		
		
echo"   <tr bgcolor='#F7F7F7'>
		  <td align='left' ><span class='style1'>Delivery Address</span></td>
		  <td colspan='5' ><span class='style1'>
			<input type='text' name='txtDeliveryPlace' value='".htmlspecialchars($txtDeliveryPlace, ENT_QUOTES)."'  style='width:400px;' maxlength='50' >
		  </td>
		  <td align='left' ><span class='style1'>Delivery Contact</span></td>
		  <td colspan='2' ><span class='style1'>
			<input type='text' name='txtDeliveryContact' value='".htmlspecialchars($txtDeliveryContact, ENT_QUOTES)."'  style='width:350px;' maxlength='50' >
		  </td>
		</tr> ";	
		
echo"   <tr bgcolor='#F7F7F7'>
		  <td align='left' ><span class='style1'>Shipping Method</span></td>
		  <td colspan='5' ><span class='style1'><select name='shippingmethod'  id='shippingmethod' style='width:100px;'><option value=''></option>";
$queryshipping = "select shippingmethod_id, shippingmethod_description from shipping_methods";
$resshipping = mysql_query($queryshipping,$connection);
while($rwshipping = mysql_fetch_row($resshipping)){
	echo "<option value='$rwshipping[0]' ".($shippingmethod == $rwshipping[0]?'selected':'').">$rwshipping[1]</option>";
}	
echo" 	</select>	  	
		  </td>
		  <td align='left' ><span class='style1'>Approved By</span></td>
		  <td colspan='2' ><span class='style1'><input type='text' name='approvedby' value='$approvedby' style='width: 120px'> Date <input type='text' name='porder_actualdate' value='$porder_actualdate'     maxlength='10' style='width:80px;' readonly>
						  <A HREF=\"#\" onClick=\"displayCalendar(document.purchase.porder_actualdate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><img src='./img/cal.gif' border=0 align=center></A></td>
		</tr> ";	
		
			

echo"   <tr bgcolor='#F7F7F7' height='20'><td colspan='9' align='center'>&nbsp;</td></tr>";

		  
		  
/*
echo"   <tr><td colspan='9' valign='top'>";
echo"	<div style='overflow:scroll; height:180px; width:985px;' >";
echo"     <table border='0' style='table-layout:fixed'>
		  <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=40>
		  <col width=70>
		  <col width=40>
		  <col width=70>
		  <col width=90>
		  <col width=50>
		  <col width=110>";
		  
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
	
} else {
	echo" <col width=120>
		  <col width=120>
		  <col width=200>
		  <col width=80>
		  <col width=70>
		  <col width=100>
		  <col width=50>
		  <col width=120>";
		  
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
}		  
		  
		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'>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'>$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>";
			
        echo"</tr>";
		  
		if ($txtPorId != '' ) {
			  
			  
			$querydt = " Select PorderDt.PorderDt_ID, PorderDt.Item_CodePacked, PorderDt.Item_code, Item_Description, PorderDt.Warehouse_Code, ".
					   " PorderDt_Remark, PorderDt_Quantity, Round(PorderDt_Price, ".$DecimalBase."), Round(PorderDt_PriceTTC, ".$DecimalBase."), ".
					   " Round(PorderDt_Discount, ".$DecimalBase."), ".
					   " Round(((PorderDt_Quantity*PorderDt_Price)-((PorderDt_Quantity*PorderDt_Price*ifNull(PorderDt_Discount,0))/100)), ".$DecimalBase.") As Total, ".
					   " Round(((PorderDt_Quantity*PorderDt_PriceTTC)-((PorderDt_Quantity*PorderDt_PriceTTC*ifNull(PorderDt_Discount,0))/100)), ".$DecimalBase.") As TotalTTC, ".
					   " PorderDt.Item_Unit2Qty, Item_UnitPurchaseDesc, Item_UnitSalesDesc, PorderDt.Project_code, PorderDt.CostCent_Code ".
					   " From Temp_PorderDt As PorderDt Left Join Items on PorderDt.Item_code = Items.Item_code ".
					   " Where PorderDt.Porder_ID = ".$txtPorId.
					   " Order By PorderDt.PorderDt_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."'";	
						
				echo "<tr ".$Color." >";
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_edit.png'  onMouseOver=\"style.cursor='hand'\" onclick=UpdatePorDt('".$rowsdt[0]."') 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=\"DeletePorDt('".$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[14]."</span></td>";
					
				echo "	<td align='right'><span class='style15'>".$rowsdt[6]."</span></td>";
				
				if ($Module_DoubleUnit == 1) { 
					echo "	<td align='left'><span class='style15'>".$rowsdt[13]."</span></td>";	
					echo "	<td align='right'><span class='style15'>".$rowsdt[12]."</span></td>";	
				}
				
				if ($PurchaseTTC == 1) 
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[8], $DecimalBase)."</span></td>";
				else
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[7], $DecimalBase)."</span></td>";
					
				echo "	<td align='right'><span class='style15'>".$rowsdt[9]."</span></td>";
				
				if ($PurchaseTTC == 1) 
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[11], $DecimalBase)."</span></td>";
				else
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[10], $DecimalBase)."</span></td>";
					
				if ($Module_ProjectDt == 1)	
					echo "	<td align='left'><span class='style15'>".$rowsdt[15]."</span></td>";
				if ($Module_CostCenterDt == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[16]."</span></td>";
					
				echo "</tr>";
						
					
								
			}
			
			
		 }
		
		echo "</table></div>";   

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

if ($FI_PurchaseOrderApp == 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='btnClear' name='btnClear' value='Clear Page'   onclick='ClearPage();' $style title='Clear Page'>";

if ($txtPorId != '')
	echo"   <input type='button' name='btnCancel' id='btnCancel' value='Cancel' onclick='CancelRecord();' $style title='Cancel Changes'>";
	
if ($txtPorId != '')
	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 ($txtPorId == '')
	echo"   <input name='btnSearch' type='button' id='btnSearch' value='Search' onclick='SearchForRef();' $style title='Search By Reference' />";

if ($txtPorId == '')
	echo"   <input name='btnPending' type='button' id='btnPending' value='Pending' onclick='SearchForPending();' $style title='Pending Purchase Orders'  />";
	
if ($txtPorId == '')
	echo"   <input name='btnLoadRqst' type='button' id='btnLoadRqst' value='Load Purchase Request' onclick='LoadConfirmedTrRequest($Module_RestrictProjCost,$Module_RestrictCost, $Module_Project,$Module_CostCenter);' $style title='Load Purchase Request'  />";
	
echo"   </td></tr>";*/	


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

//Show Items Grid
ShowPurchaseOrderDtGrid($connection,'PO',$txtPorId,$_SESSION['gpor_parameters'],$_SESSION['gpor_arrayaccess'],'PorderDt.PorderDt_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>  ";//end of last table menu

if (($actionmode == "post" || $actionmode == "confirmorder") && $PrPorId != '') {

	$query    = " SELECT Porder_Reference, ifNull(Porder_Confirmed,0) ".
			    " FROM Porder".
                " WHERE Porder_id = $PrPorId ";
	$result   = selectData($connection, $query);
	$PrPorRef = $result[0];
	$PorConfirmed = $result[1];
		
	$AskComfirm = 0;
	
	echo '<script type="text/javascript" language="javascript">';
	/*
	if (($mainaction == "insert" || ($mainaction == "edit" && $PorConfirmed == 0)) && $actionmode == "post" && $Module_PorderConfirm == 1 && $FI_PorderConfirmed == 1) {
		echo ' ConfirmOrder(\''.$PrPorId.'\'); ';
		
		$AskComfirm = 1;
	*/	
	
	if	 (($AskComfirm == 1 && $actionmode == "confirmorder") || $AskComfirm == 0) {
		if ($Login_FastPrint == 1) 
			echo ' PrintPurchaseOrder(\''.$PrPorId.'\', \''.$PrPorRef.'\'); ';
			
		echo ' ClearPage1(); ';
	}
	
	echo '</script>';

}



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

HERE;

?>