<?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_DataGrid1.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_PurchaseRequest as loginaccess,language 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_PurchaseRequestApp,0) As FI_PurchaseRequestApp, ifNull(FI_PRequestConfirmed,0) As FI_PRequestConfirmed, ifnull(FI_MaterialRequisition,0) as FI_MaterialRequisition, ".
		  " ifNull(FI_PurchaseCategory,0) As FI_PurchaseCategory, ifNull(Login_FastPrint,0) As Login_FastPrint, ifnull(FI_PurchaseRequestItems,0) as FI_PurchaseRequestItems  ".
		  " 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);
}

$querylog=" select ifnull(fi_pendingpurchaserequest,0) fi_pendingpurchaserequest".
		  " 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 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_PRequestConfirm,0) As Module_PRequestConfirm, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method ".
			 " ,ifnull(Module_PurchaseRequestPrice,0) as Module_PurchaseRequestPrice,ifnull(PrequestReferenceByProject,0) as PrequestReferenceByProject ".
			 " ,ifnull(module_PRWarehouse,0) as module_PRWarehouse, ifnull(Module_Heatno,0) as Module_Heatno ". 
			 " 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 From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}
	
//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);
}

//Read From SalesSetup Table
$querySalesSetup="Select Warehouse As SetupDftWareHouse, ifNull(ShowCostCentLayout,0) As ShowCostCentLayout From PurchaseSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//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);
}

$querydflwh="select warehouse_code as defaultwarehouse from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and ifNull(default_warehouse,0) = 1 ";

$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}

$_SESSION['prqstdefaultcostcent'] = $defaultcostcent;
$_SESSION['prqstdefaultwarehouse'] = $defaultwarehouse;
$_SESSION['prqstdefaultproject'] = $defaultproject;
$_SESSION['prqstsetupdefaultWareHouse'] = $SetupDftWareHouse;

//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());


	$querylang="select language, reference, Find, Cancel, Refresh, Print, Excel, Details, 
	showdetail, Warehouse, Datefr_to, Priority, Project, ItemCode_Desc, Status, Costcenter, Type, 
	Shipping_met, Requestedby, Category, MSR, Refabr, Porder, GRN, Date, Reason, Confirmed, conf_date,
	appr_date, created_by, orderedby, approvedby, new_item, mainwarehouse, qty_exist, orderedqty, transqty, qty, unit
	from ".$_SESSION['dbLabel'].".requested_item where 
			language='$language'";

//echo $querylang;
$resultlang=mysql_query($querylang,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($resultlang)){
		extract($rows);
		
	}







$actionmode = $_POST["actionmode"]; if ($actionmode == ""){$actionmode = $_GET["actionmode"];}   
$mainaction = $_POST["mainaction"]; if ($mainaction == ""){$mainaction = $_GET["mainaction"];}   
$message 	= $_POST["message"]; if ($message == ""){$message = $_GET["message"];}   
$PrPrqstId 	= $_POST["PrPrqstId"]; if ($PrPrqstId == ""){$PrPrqstId = $_GET["PrPrqstId"];}

$txtPorCountDetail 	= $_POST["txtPorCountDetail"]; if ($txtPorCountDetail == ""){$txtPorCountDetail = $_GET["txtPorCountDetail"];} 
$txtPreqId    		= $_POST["txtPreqId"]; if ($txtPreqId == ""){$txtPreqId = $_GET["txtPreqId"];} 
$txtRef 			= $_POST["txtRef"]; if ($txtRef == ""){$txtRef = $_GET["txtRef"];} 
$txtDate 			= $_POST["txtDate"]; if ($txtDate == ""){$txtDate = $_GET["txtDate"];} 
$txtRequestBy 	   	= $_POST["txtRequestBy"]; if ($txtRequestBy == ""){$txtRequestBy = $_GET["txtRequestBy"];} 
$txtPurpose 	   	= $_POST["txtPurpose"]; if ($txtPurpose == ""){$txtPurpose = $_GET["txtPurpose"];} 
$txtLocation 	   	= $_POST["txtLocation"]; if ($txtLocation == ""){$txtLocation = $_GET["txtLocation"];} 
$txtUserName 	   	= $_POST["txtUserName"]; if ($txtUserName == ""){$txtUserName = $_GET["txtUserName"];} 
$txtPriority 	   	= $_POST["txtPriority"]; if ($txtPriority == ""){$txtPriority = $_GET["txtPriority"];} 
$txtCurr   			= $_POST["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_GET["txtCurr"];} 
$txtRemark  		= $_POST["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_GET["txtRemark"];} 
$txtProjectCode 	= $_POST["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_GET["txtProjectCode"];} 
$txtCostCentCode	= $_POST["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_GET["txtCostCentCode"];} 
$txtReqStatus		= $_POST["txtReqStatus"]; if ($txtReqStatus == ""){$txtReqStatus = $_GET["txtReqStatus"];} 
$txtStatusRemark	= $_POST["txtStatusRemark"]; if ($txtStatusRemark == ""){$txtStatusRemark = $_GET["txtStatusRemark"];} 
$txtDeliveryPlace	= $_POST["txtDeliveryPlace"]; if ($txtDeliveryPlace == ""){$txtDeliveryPlace = $_GET["txtDeliveryPlace"];} 
$txtDeliveryContact	= $_POST["txtDeliveryContact"]; if ($txtDeliveryContact == ""){$txtDeliveryContact = $_GET["txtDeliveryContact"];} 



if (empty($mainaction)) $mainaction = 'insert';
	
if($txtRequestBy=='' && $mainaction=='insert')
$txtRequestBy = $_SESSION['username'];
	
$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">

<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'});
		});
		
	if (document.getElementById('itemcode[1]'))
		document.getElementById('itemcode[1]').focus();
		
	
		$(document).on('focusin', '.table-focus-g1', function() {
			AutoSaveRecordGrid(this.id,'SelectedRec','ModRec_G1','imgSubmitPReqstDt');
			selRecordColor(this,'SelectedRec','SelectedRecColor');
		});
		
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
	
	});
	
	
</script>

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


function Request_Items(){

win = window.open('Form_PurchaseRequestItems.php?transtype=p', 'Request', '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 LoadMaterialReq(){
	win = window.open('Form_PRequest_LoadMaterialReq.php', 'LoadMaterialReq', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	win.creator = self;
	win.focus();
}
function UploadDocuments(vform){

var prqstid = document.purchasereq.txtPreqId.value;

win = window.open('UploadDocuments.php?vform='+vform+'&prqstid='+prqstid, '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 FillDetail(prjct,cst){

var x =  document.purchasereq;

if (document.getElementById(prjct))
if (document.getElementById(prjct).value == '')
	document.getElementById(prjct).value =  x.txtProjectCode.value;
	
	
if (document.getElementById(cst))
if (document.getElementById(cst).value == '')	
	document.getElementById(cst).value = x.txtCostCentCode.value;

}

function onloadfunc(){

if (document.getElementById('itemocde[1]'))
	document.getElementById('itemocde[1]').focus();

}

function dokeypurchaserequest(e,obj,rowindx,columnslist,vbutname){

	//if (e.ctrlKey == false)
	//return;
	var vindx = rowindx;
	if (!e) { var e = window.Events;}
    var intKey = (window.Events) ? e.which : e.keyCode;


	var columnsarray=new Array();
	columnsarray = columnslist.split(",");
	var firstcell = columnsarray[0];
	var lastcell  = columnsarray[columnsarray.length-1];
	var arrayname = obj.id.split("[");

	if (( ((intKey == 37) || (intKey == 39)) && e.ctrlKey )  ||  (intKey == 13))
	{
		var cindx = columnsarray.indexOf(arrayname[0]);
		
		if (intKey == 37) { //left key
			var nextindx = Number(cindx) - 1;
		}
		if (intKey == 13 || intKey == 39) { //right key
			var nextindx = Number(cindx) + 1;
		}


		var nextitem = columnsarray[nextindx] + '[' + rowindx + ']' ;

		
		if (document.getElementById(nextitem)) {
			var nextobj = document.getElementById(nextitem);
			nextobj.focus();
			if(nextobj.type!='select-one')
			nextobj.select();
		}
		else { 
			var nextrow  = rowindx + 1;
			var nextcell = firstcell + '[' +  nextrow + ']';
				
			var imgname = 'imgSubmit' + vbutname + '[' +  rowindx + ']';
			
			document.getElementById(imgname).click();
			
			if (document.getElementById(nextcell) ) {
				document.getElementById(nextcell).focus();
				if(document.getElementById(nextcell).type!='select-one')
				document.getElementById(nextcell).select();
			}	
					
		}	
	}
	else if ( ((intKey == 38) || (intKey == 40)) && e.ctrlKey) {
		
		if (intKey == 38) 
			rowindx = rowindx - 1;
		if (intKey == 40) 
			rowindx = rowindx + 1;
			
		var nextitem =  arrayname[0] + '[' + rowindx + ']';
		if (document.getElementById(nextitem)) {
			var nextobj = document.getElementById(nextitem);
			nextobj.focus();
			if(nextobj.type!='select-one')
			nextobj.select();
		}	
	}

}


function returncolor(vobj,vtextname,vcolorname,vassetsdtid){

if (document.getElementById(vtextname).value=='')
	{
		document.getElementById(vtextname).value = vobj.id;
		document.getElementById(vcolorname).value = vobj.style.backgroundColor;
	}	
else {
var prevobj = document.getElementById(vtextname).value;
document.getElementById(prevobj).style.backgroundColor = document.getElementById(vcolorname).value;

		document.getElementById(vtextname).value = vobj.id;
		document.getElementById(vcolorname).value = vobj.style.backgroundColor;
}	
//vobj.style.backgroundColor='#D7DADD';
}

function CheckFields(ModuleRestProj, ModuleRestCost){
  
    x = document.purchasereq;
	Module_PurchaseRequestPrice = x.Module_PurchaseRequestPrice.value;
	
	var PreqDate = x.txtDate.value;
	var PreqCurr = x.txtCurr.value;
	var PreqProject = x.txtProjectCode.value;
	var PreqCostCenter = x.txtCostCentCode.value;
	var PreqDelivery = x.txtDeliveryDate.value;
	
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	if (PreqDate=='' )
	{
		alert("Date Column is mandatory!");
		x.txtDate.focus();
		return 0;
	}
	else if (PreqDelivery<PreqDate)
	{
		alert("Delivery Date must be greater than Request Date");
		x.txtDeliveryDate.focus();
		return 0;
	}
	
	else if (PreqCurr=='' && Module_PurchaseRequestPrice==1)
	{
		alert("Currency Column is mandatory!");
		x.txtCurr.focus();
		return 0;
	}
	else if (PreqProject=='' && ModuleRestProj==1)
	{
		alert("Project is mandatory!");
		x.txtProjectCode.focus();
		return 0;
	}
	else if (PreqCostCenter=='' && ModuleRestCost==1 && document.getElementById('txtCostCentCode').type == 'text')
	{
		alert("CostCenter is mandatory!");
		x.txtCostCentCode.focus();
		return 0;
	}
			
	
	else
	return 1 ;	
}




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

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

function CancelRecord(){
	x = document.purchasereq;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	//var PorDtId = x.txtPorDtId.value;
	var PorId = x.txtPreqId.value;
	
	if (confirm ( "Are you sure you want to Delete current pending purchase request permenantly?"))
	{
		ClearForm('All');
		x.txtPreqId.value = PorId;
		x.mainaction.value='insert';
		x.actionmode.value='cancel';
		x.action='Form_PurchaseRequest.php';
		x.submit();
	}
    
}

function PostChanges(ModuleRestProj, ModuleRestCost) {
	var x = document.purchasereq;
	var PreqId  = x.txtPreqId.value;
	var vMainMode = x.mainaction.value;
	
	var vPorVatChkbx = 0;
	if (x.ChkReqVat.checked)
		vPorVatChkbx = 1;	
	
	vitem = 'itemcode[0]';
	prqstdtitemdescription = 'prqstdtitemdescription[0]';
	
	var result = CheckFields(ModuleRestProj, ModuleRestCost);
	
	if (document.getElementById(vitem).value == 0 && document.getElementById(prqstdtitemdescription).value=='') {
		alert('Save not allowed. Please add items.');
	}
	else
	{
		if (result == 1) {
			if (confirm ( "Are you sure you want to Save current Purchase Request?"))
			{
				//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 {
					
							x.btnPost.disabled = true;
							x.btnCancel.disabled = true;
							x.btnClear.disabled = true;
							
							if (document.getElementById('btnAddItem'))
								x.btnAddItem.disabled = true;
							
							x.actionmode.value='post'; 
							x.action="Form_PurchaseRequest_Actions.php?mode=post&mainmode="+vMainMode+"&SPreqId="+PreqId+"&SPorVatChkbx="+vPorVatChkbx;
							x.submit();
							
							}
			}
		}	
	}
}

function ConfirmRequest(PreqId) {
	x = document.purchasereq;
	var vMainMode = x.mainaction.value;
	
	
	if (confirm ( "Do you want to Confirm saved purchase request?"))
	{
		x.actionmode.value='confirmrequest';
		x.action="Form_PurchaseRequest_Actions.php?mode=confirmrequest&mainmode="+vMainMode+"&SPreqId="+PreqId;
		x.submit();
	} else {
		x.actionmode.value='confirmrequest';
		x.submit();
	}
	

}


function deleteprequestsdt(prqstid,prqstdtid, ItemPackCode, ItemCode,filepath){

if (ItemPackCode != '')
	   vDelMsg = "Are you sure you want to Delete Pack Item "+ItemPackCode+" ?";
	else  
	   vDelMsg = "Are you sure you want to Delete Item "+ItemCode+" ?";
	   
	   
var x =  document.purchasereq;
txtDate =  x.txtDate.value;

var SPorVatChkbx = 0;
	if (x.ChkReqVat.checked)
		SPorVatChkbx = 1;	
 
txtReqDiscount = x.txtReqDiscount.value;

	   
if (confirm ( vDelMsg ))
	{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
				{ 
							//document.getElementById('testdatagrid').innerHTML = xmlhttp.responseText;
							var data = xmlhttp.responseText.split('[BRK]');
							if (data[1] !='')
								alert(data[1]);
							ReloadGrid(filepath,'PReq',prqstid,'datagrid','','','ADD','','','','',0,'',function() {
								document.getElementById('SelectedRec').value='';		});
							ReloadGridDt(filepath,'PReq-totals','totalsdatagrid','totalsdatagrid',prqstid,-1);
														
				}
		}
  }

xmlhttp.open("GET","Form_PurchaseRequest_Actions.php?prqstid="+prqstid+"&actionmode=deletedt&prqstdtid="+prqstdtid+"&txtDate="+txtDate+"&SPorVatChkbx="+SPorVatChkbx+"&txtReqDiscount="+txtReqDiscount,true);
xmlhttp.send();

}
}
	

function clearprequestdt(vrec,VPurchaseTTC,FIPurchaseCategory){

var itemcodepacked = 'itemcodepacked['+vrec+']';
var itemcode = 'itemcode['+vrec+']';
var itemdescription = 'itemdescription['+vrec+']';
var prqstdtitemdescription = 'prqstdtitemdescription['+vrec+']';
var warehousecode = 'warehousecode['+vrec+']';
var itemunitsalesdesc = 'itemunitsalesdesc['+vrec+']';
var itemunitpurchasedesc = 'itemunitpurchasedesc['+vrec+']';
var itemunit2qty = 'itemunit2qty['+vrec+']';
var prqstdtquantity = 'prqstdtquantity['+vrec+']';
var prqstdtOquantity = 'prqstdtOquantity['+vrec+']';
var prqstdtCquantity = 'prqstdtCquantity['+vrec+']';

if (VPurchaseTTC==1)
	var prqstdtpricettc = 'prqstdtpricettc['+vrec+']';
else	
var prqstdtprice = 'prqstdtprice['+vrec+']';

var prqstdtdiscount = 'prqstdtdiscount['+vrec+']';

if (VPurchaseTTC==1)
	var prqstdttotalttc = 'prqstdttotalttc['+vrec+']';
else
	var prqstdttotal = 'prqstdttotal['+vrec+']';

var item_vat = 'item_vat['+vrec+']';
var i_unitcoef = 'i_unitcoef['+vrec+']';
var prqstdtprojectcode = 'prqstdtprojectcode['+vrec+']';
var prqstdtcostcentercode = 'prqstdtcostcentercode['+vrec+']';
var prqstdt_Remark = 'prqstdt_Remark['+vrec+']';


document.getElementById(itemcodepacked).value='';
document.getElementById(itemcode).value='';
document.getElementById(prqstdtitemdescription).value='';
document.getElementById(itemdescription).value='';
document.getElementById(warehousecode).value='';
document.getElementById(itemunitsalesdesc).value='';
document.getElementById(itemunitpurchasedesc).value='';
document.getElementById(itemunit2qty).value='';
document.getElementById(prqstdtquantity).value='';
document.getElementById(prqstdtOquantity).value='';
document.getElementById(prqstdtCquantity).value='';

if (VPurchaseTTC==1)
	document.getElementById(prqstdtpricettc).value='';
else	
	document.getElementById(prqstdtprice).value='';
	
document.getElementById(prqstdtdiscount).value='';

if (VPurchaseTTC==1)
	document.getElementById(prqstdttotalttc).value='';
else	
	document.getElementById(prqstdttotal).value='';
	
document.getElementById(item_vat).value='';
document.getElementById(i_unitcoef).value='';
document.getElementById(prqstdtprojectcode).value='';
document.getElementById(prqstdtcostcentercode).value='';
document.getElementById(prqstdt_Remark).value='';

}

function submitPReqstDt(PrqstDtId,PreqId,vrec,vmode,VPurchaseTTC,FIPurchaseCategory,filepath){

 x = document.purchasereq;
	Module_PurchaseRequestPrice = x.Module_PurchaseRequestPrice.value;
var SPrqstDtId = PrqstDtId;

	if (vmode=='i')
		 var vactionmode = 'submitprqstdt';
	else
		var vactionmode = 'editdt';	
						
var itemcodepacked = 'itemcodepacked['+vrec+']';
var itemcode = 'itemcode['+vrec+']';
var prqstdtitemdescription = 'prqstdtitemdescription['+vrec+']';
var itemdescription = 'itemdescription['+vrec+']';
var warehousecode = 'warehousecode['+vrec+']';
var prqstdtquantity = 'prqstdtquantity['+vrec+']';
var prqstdtOquantity = 'prqstdtOquantity['+vrec+']';
var prqstdtCquantity = 'prqstdtCquantity['+vrec+']';
var itemunitpurchasedesc = 'itemunitpurchasedesc['+vrec+']';
var itemunit2qty = 'itemunit2qty['+vrec+']';
var prqstdtpricettc = 'prqstdtpricettc['+vrec+']';
var prqstdtprice = 'prqstdtprice['+vrec+']';
var prqstdttotalttc = 'prqstdttotalttc['+vrec+']';
var prqstdttotal = 'prqstdttotal['+vrec+']';
var prqstdtdiscount = 'prqstdtdiscount['+vrec+']';
var prqstdtprojectcode = 'prqstdtprojectcode['+vrec+']';
var prqstdtcostcentercode = 'prqstdtcostcentercode['+vrec+']';
var prqstdt_Remark = 'prqstdt_Remark['+vrec+']';
var prqstdtheatno = 'prqstdtheatno['+vrec+']';
var prqstdt_RequiredDate = 'prqstdt_RequiredDate['+vrec+']';
var prequestdt_unitsalesdesc = 'itemunitsalesdesc['+vrec+']';


var value1 = document.getElementById(itemcodepacked).value;
var value2 = encodeURIComponent(document.getElementById(itemcode).value);
var value3 = document.getElementById(itemdescription).value;
var value4 = document.getElementById(warehousecode).value;

var value5 = document.getElementById(prqstdtquantity).value; 
var value6 = document.getElementById(itemunitpurchasedesc).value;
var value7 = document.getElementById(itemunit2qty).value;



	var vPorVatChkbx = 0;
	if (document.purchasereq.ChkReqVat.checked)
		vPorVatChkbx = 1;	
		
		
if (VPurchaseTTC==1)
	{
		var value8 = document.getElementById(prqstdtpricettc).value;
		var value9 = 0;
	}	
else
	{
			var value8 = 0;
			var value9 = document.getElementById(prqstdtprice).value;
	}

if (VPurchaseTTC==1)
	{
	var value10 = document.getElementById(prqstdttotalttc).value;
	var value11 = 0;
	}
else {
	var value10 = 0;
	var value11 = document.getElementById(prqstdttotal).value;
	}

	
var value12 = document.getElementById(prqstdtdiscount).value;

if (document.getElementById(prqstdtprojectcode))
	var value13 = document.getElementById(prqstdtprojectcode).value;
	else 
	var value13 ='';
		
if (document.getElementById(prqstdtcostcentercode))	
	var value14 = document.getElementById(prqstdtcostcentercode).value;
	else 
	var value14 ='';
	
var value29 = document.getElementById(prqstdt_Remark).value;

var value30 = document.getElementById(prqstdtitemdescription).value;
var value31 = document.getElementById(prqstdtOquantity).value;
var value32 = document.getElementById(prqstdtCquantity).value;
var value36 = document.getElementById(prequestdt_unitsalesdesc).value;

var value37 = document.getElementById(prqstdtheatno).value;
var value38 = document.getElementById(prqstdt_RequiredDate).value;

//if (PreqId=='')
	{	var x =  document.purchasereq;
		var value15 = x.txtDate.value;
		var value17 = x.txtCurr.value;
		var value18 = x.txtProjectCode.value;
		var value19 = x.txtCostCentCode.value;
		var value20 = x.txtRequestBy.value;
		var value39 = x.txtDeliveryDate.value;
		var value33 = x.txtPurpose.value;
		var value34 = x.txtLocation.value;
		
		var value35 = x.txtPriority.value;
		
		var value21 = x.txtRemark.value;
		
		/*if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtReqCategory.length; i++)
		{
			if (x.txtReqCategory[i].checked)
			{
			  var value22 = x.txtReqCategory[i].value;
			}
		}
	} else {
		var value22 = x.txtReqCategory.value;
	}	
	*/
				
		/*for (var i=0; i < x.txtReqStatus.length; i++)
	{
		if (x.txtReqStatus[i].checked)
		{
		  var value23 = x.txtReqStatus[i].value;
		}
	}*/
		var value23 = x.txtReqStatus.value;
		var value24 = x.txtStatusRemark.value;
		var value25 = x.txtDeliveryPlace.value;
		var value26 = x.txtDeliveryContact.value;
		var value27 = '';
		var value28 = x.txtReqDiscount.value;

		
		if (value15=='')
{
			alert("Date is mandatory!");
			x.txtDate.focus();
			return 0;
} else 		if (value15>value38)
{
			alert("Required Date Should be Greater than Requisition Date!");
			x.txtDate.focus();
			return 0;
}

else 		if (value17==''  && Module_PurchaseRequestPrice==1)
{
			alert("Currency is mandatory!");
			x.txtCurr.focus();
			return 0;
} else
		if (value18=='' && document.getElementById('txtProjectCode').type == 'text')
{
			alert("Project is mandatory!");
			x.txtProjectCode.focus();
			return 0;
} else
		if (value19=='' && document.getElementById('txtCostCentCode').type == 'text')
{
			alert("Costcenter is mandatory!");
			x.txtCostCentCode.focus();
			return 0;
}
			
	
	}
	
if (document.getElementById(itemcode).value=='' && document.getElementById(prqstdtitemdescription).value=='')
{
			alert("Item is mandatory!");
			document.getElementById(itemcode).focus();
return 0;
}

if (document.getElementById(warehousecode).value=='')
{
			alert("Warehouse is mandatory!");
			document.getElementById(warehousecode).focus();
return 0;
}

if (document.getElementById(prqstdtOquantity).value=='')
{
			alert("Quantity is mandatory!");
			document.getElementById(prqstdtOquantity).focus();
return 0;
}

if (Module_PurchaseRequestPrice==1) {
	if (VPurchaseTTC==1)
		{
			if (document.getElementById(prqstdtpricettc).value=='')
			{
						alert("Price is mandatory!");
						document.getElementById(prqstdtpricettc).focus();
			return 0;
			}
	}
	else {
			if (document.getElementById(prqstdtprice).value=='')
			{
						alert("Price is mandatory!");
						document.getElementById(prqstdtprice).focus();
			return 0;
			}

	}
}

var prqstsid = document.getElementById('txtPreqId').value;
$("#Loader").addClass("ajaxsaving");

	var SubBtnID = 'imgSubmitPReqstDt['+vrec+']';
	var SubBtnObj = document.getElementById(SubBtnID);
	$(SubBtnObj).unbind('click');
	$(SubBtnObj).removeAttr("onclick");	

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)
    {
		{ 		  
			if (vmode=='i')
				{  
					
					
					
					var data = xmlhttp.responseText.split("[BRK]");
					document.getElementById('txtPreqId').value = data[1];
					//document.getElementById('testdatagrid').innerHTML = data[0];
					
				
			
				document.purchasereq.mainaction.value='edit';
				document.purchasereq.actionmode.value='edit';
			
				if (prqstsid==''){				
						document.purchasereq.action='Form_PurchaseRequest.php';				
						document.purchasereq.submit();
						
					}
					else {

					ReloadGrid(filepath,'PReq',prqstsid,'datagrid','','','ADD','','','','',0,'',function() {
						var focusedvrec = parseInt(vrec) + 1;
						var focused = 'itemcode['+focusedvrec+']';
						document.getElementById(focused).focus();
					});
					ReloadGridDt(filepath,'PReq-totals','totalsdatagrid','totalsdatagrid',prqstsid,-1);
					$("#Loader").removeClass("ajaxsaving");
					}
			
				}	
			else {
			
					
				
					//document.getElementById('testdatagrid').innerHTML =  xmlhttp.responseText;
					// xmlhttp.responseText;
				
					 ReloadGrid(filepath,'PReq',prqstsid,'datagrid','','','ADD','','','','',0,'',function() {
									var focusedvrec = parseInt(vrec) + 1;
									var focused = 'itemcode['+focusedvrec+']';
									document.getElementById(focused).focus();
								});
					ReloadGridDt(filepath,'PReq-totals','totalsdatagrid','totalsdatagrid',prqstsid,-1);
								$("#Loader").removeClass("ajaxsaving");
				
				}						
			
			
				//document.getElementById('qwqw').innerHTML = this.responseText;			
			
	}
		}
  }
xmlhttp.open("GET","Form_PurchaseRequest_Actions.php?vmode="+vmode+"&value1="+value1+"&value2="+value2+"&value3="+value3
											+"&value4="+value4+"&value5="+value5+"&value6="+value6+"&value7="+value7+"&value8="+value8+"&value9="+value9
											+"&value10="+value10+"&value11="+value11+"&value12="+value12+"&value13="+value13+"&value14="+value14+"&value15="+value15
											+"&value17="+value17+"&value18="+value18+"&value19="+value19+"&value20="+value20+"&value21="+value21
											+"&value23="+value23+"&value24="+value24+"&value25="+value25+"&value26="+value26+"&value27="+value27+"&value28="+value28
											+"&value29="+value29+"&value30="+value30+"&value31="+value31+"&value32="+value32+"&value33="+value33+"&value34="+value34
											+"&value35="+value35+"&value36="+value36+"&prqstdtheatno="+value37+"&PreqId="+PreqId+"&SPrqstDtId="+SPrqstDtId
											+"&PPorVatChkbx="+vPorVatChkbx+"&prqstdt_RequiredDate="+value38+"&txtDeliveryDate="+value39
											+"&txtPreqId="+PreqId+"&actionmode="+vactionmode,true);

xmlhttp.send();

    
}


function checkstatus(vrec){

var itemunitsalesdesc = 'itemunitsalesdesc['+vrec+']';	
var itemcode = 'itemcode['+vrec+']';

if(document.getElementById(itemcode).value != '')
	document.getElementById(itemunitsalesdesc).readOnly = true;
	else
	document.getElementById(itemunitsalesdesc).readOnly = false;

}

function CheckItemCode(obj,vrec){

var itemunitsalesdesc = 'itemunitsalesdesc['+vrec+']';	
var itemcode = 'itemcode['+vrec+']';	

if(obj.value=='' && document.getElementById(itemcode).value != '')
	document.getElementById(itemunitsalesdesc).readOnly = true;
	else
	document.getElementById(itemunitsalesdesc).readOnly = false;

}


function setitemcode(val,vfield1,vfield2,vfield3,vfield4,vfield5,vfield6,vgridname,btnname,btnname1,codedesc,item){

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]");
					var resp = data[1];
					
					if (resp==0)
						{
							if (codedesc==1)
								document.getElementById(btnname).click();
							else	
								document.getElementById(btnname1).click();
						}
						else
							{	
								if (codedesc==1)
									document.getElementById(vfield2).value = resp;
								else	
									document.getElementById(vfield1).value = resp;
							}	
						//showsearchpage('itemcode',vfield1,vfield2,vfield3,vfield4,vfield5,vfield6,800,500);

				}
		}
  }

  if (codedesc==1)
	xmlhttp.open("GET","Form_PurchaseRequest_Actions.php?vitemcode="+val+"&codedesc="+codedesc+"&actionmode=checkitemcode&item="+item,true);
else	
  if (codedesc==2)
	xmlhttp.open("GET","Form_PurchaseRequest_Actions.php?vitemdesc="+val+"&codedesc="+codedesc+"&actionmode=checkitemcode&item="+item,true);  
  
  
xmlhttp.send();

}

function setwarehousecode(val,vfield1,btnname){

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]");
					var resp = data[1];
					
					if (resp==0)
						{
							document.getElementById(btnname).click();
						}
						
						//showsearchpage('itemcode',vfield1,vfield2,vfield3,vfield4,vfield5,vfield6,800,500);

				}
		}
  }

xmlhttp.open("GET","Form_PurchaseRequest_Actions.php?vwarehousecode="+val+"&actionmode=checkwarehousecode",true);
xmlhttp.send();

}

function setprojectcode(val,vfield1,btnname){

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]");
					var resp = data[1];
					
					if (resp==0)
						{
							document.getElementById(btnname).click();
						}
						
						//showsearchpage('itemcode',vfield1,vfield2,vfield3,vfield4,vfield5,vfield6,800,500);

				}
		}
  }

xmlhttp.open("GET","Form_PurchaseRequest_Actions.php?vprojectcode="+val+"&actionmode=checkprojectcode",true);
xmlhttp.send();

}


function setcostcentercode(val,vfield1,btnname){

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]");
					var resp = data[1];
					
					if (resp==0)
						{
							document.getElementById(btnname).click();
						}
						
						//showsearchpage('itemcode',vfield1,vfield2,vfield3,vfield4,vfield5,vfield6,800,500);

				}
		}
  }

xmlhttp.open("GET","Form_PurchaseRequest_Actions.php?vcostcentercode="+val+"&actionmode=checkcostcentercode",true);
xmlhttp.send();

}
function CalcPorDtTotal(vrec,dec,VPurchaseTTC) {
	
	x = document.purchasereq;
	var prqstdtquantity = 'prqstdtquantity['+vrec+']';
	
	if (VPurchaseTTC==1)
	var prqstdttotal = 'prqstdttotalttc['+vrec+']';
	else
	var prqstdttotal = 'prqstdttotal['+vrec+']';
	
	
	if (VPurchaseTTC==1)
	var prqstdtprice = 'prqstdtpricettc['+vrec+']';
	else
	var prqstdtprice = 'prqstdtprice['+vrec+']';
	
	var prqstdtdiscount = 'prqstdtdiscount['+vrec+']';
	
	
	var Qty = document.getElementById(prqstdtquantity).value;
	
	var txtPorDtTotal = document.getElementById(prqstdttotal).value;
	
	
	
	var Price = document.getElementById(prqstdtprice).value;
	
	var Discount = document.getElementById(prqstdtdiscount).value;
	
	
	
	if (Qty == '') Qty = 0;
	if (Price == '') Price = 0;
	if (Discount == '') Discount = 0;
	
	Qty = parseInt(Qty);
	Price = parseFloat(Price);
	Discount = parseFloat(Discount);
	
	if (Qty > 0 && Price >= 0)
	   document.getElementById(prqstdttotal).value = Math.round(((Qty*Price) - (Qty*Price*Discount/100))*Math.pow(10,dec))/Math.pow(10,dec);

}

function CalcQty2(vrec,ModuleUnit1Method,Option) {
	
	x = document.purchasereq;
	var prqstdtquantity = 'prqstdtquantity['+vrec+']';
	var prqstdtOquantity = 'prqstdtOquantity['+vrec+']';
	var prqstdtCquantity = 'prqstdtCquantity['+vrec+']';
	
	var itemunit2qty = 'itemunit2qty['+vrec+']';
	var i_unitcoef = 'i_unitcoef['+vrec+']';
	
	var QtyO = document.getElementById(prqstdtOquantity).value;
	var QtyC = document.getElementById(prqstdtCquantity).value;
	
	if (QtyC=='')	QtyC = 0;
	if (QtyO=='')	QtyO = 0;
		
	document.getElementById(prqstdtquantity).value = QtyO -  QtyC;
	var Qty = document.getElementById(prqstdtquantity).value;
	
	var Qty2 = document.getElementById(itemunit2qty).value;
	var type2 = document.getElementById(itemunit2qty).type;
	var i_unitcoef = document.getElementById(i_unitcoef).value;
	UnitCoef = i_unitcoef;
	
	
	if (Qty == '')  Qty = 0;
	if (Qty2 == '') Qty2 = 0;
	
	if(ModuleUnit1Method == 1) {
		if (Qty > 0 && Option == 1 && type2 == 'text') {
			document.getElementById(itemunit2qty).value = Qty*UnitCoef;
		}	
		else if (Qty == 0 && Option == 1 && type2 == 'text') {
			document.getElementById(itemunit2qty).value = '';
		}
	}
	//Case Modify Qty and Qty2 Should Be Empty
	else if(ModuleUnit1Method == 0 && Option == 1 && Qty2 == 0) {
		if (Qty > 0 && UnitCoef != 0 && type2 == 'text') {
			document.getElementById(itemunit2qty).value = Qty/UnitCoef;
		}	
		else if (Qty == 0 && type2 == 'text') {
			document.getElementById(itemunit2qty).value = '';
		}
	}
	//Case Modify Qty2 Get Qty
	else if(ModuleUnit1Method == 0 && Option == 2) {
		if (Qty2 > 0 && type2 == 'text') {
			document.getElementById(prqstdtquantity).value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && type2 == 'text') {
			document.getElementById(prqstdtquantity).value = '';
		}
	}
}



function showsearchpage(PIndex){
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vItemCode  = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
	var vDate  = document.purchasereq.txtDate.value;		
	
	window.open('List_SorItems.php?frm=19&index='+PIndex+'&PItem_Code='+vItemCode+'&ItemType=All&TransDate='+vDate+'&vcurr=','List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);		
	win.creator = self;
	win.focus();	
	}
	
function showsearchpage1(vtype,vtext1,vtext2,vtext3,vtext4,vtext5,vtext6,vwidth,vheight){
	var text2value = document.getElementById(vtext2).value;
		
	win = window.open('List_PurItems.php?PItem_Code=&PItem_Description='+text2value+'&item=4&vtype='+vtype+'&vtext1='+vtext1+'&vtext2='+vtext2+'&vtext3='+vtext3
						+'&vtext4='+vtext4+'&vtext5='+vtext5+'&vtext6='+vtext6
						+'&text1value=', 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
	win.creator = self;
	win.focus();	
	}
	
	
function showlistItems(str){
 var vdate, vid;
  x = document.purchasereq;
  
 
  
  vItemGroup = vItemGroup.replace('&','%26');
  
  window.open('List_PurItems.php?item=3','mywindow','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
 
 }
 
function UpdatePorDt(PorDtId) {
    x = document.purchasereq;
	var vPorId = x.txtPreqId.value;
	var vPreqDate = x.txtDate.value;
	var vPorVatChkbx = 0;
	if (x.ChkReqVat.checked)
		vPorVatChkbx = 1;	
		
	var vMainMode = x.mainaction.value;
	
	win = window.open('Form_PurchaseRequestDetail.php?mainaction='+vMainMode+'&actionmode=&PPorId='+vPorId+'&PPreqDate='+vPreqDate+'&PPorDtId='+PorDtId+'&PPorVatChkbx='+vPorVatChkbx, 'Form_PurchaseRequestDetail', '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.purchasereq;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtPreqId.value='';
		x.txtRef.value='';
		x.txtDate.value='';
		x.txtDeliveryDate.value='';
		x.txtRequestBy.value='';
		x.txtPurpose.value='';
		x.txtLocation.value='';
		x.txtPriority.value='';
		x.txtRemark.value='';
		x.txtCurr.value='';
		//x.txtReqCategory.value='';
		x.txtProjectCode.value='';
		x.txtCostCentCode.value='';
		x.txtReqStatus.value='';
		x.txtStatusRemark.value='';
		x.txtDeliveryPlace.value='';
		x.txtDeliveryContact.value='';
		x.txtUserName.value='';
		
		x.txtReqTaxable.value='';
		x.txtReqNoneTaxable.value='';
		x.txtReqGrossTotal.value='';
		x.txtReqDiscount.value='';
		x.txtReqDiscountAmt.value='';
		x.txtReqVat.value='';
		x.txtReqNetTotal.value='';
		x.txtReqTotalTaxes.value='';
		
		x.txtReqStatus.value = '';
		//x.txtReqCategory[0].checked = true;
			
		x.message.value='';
		x.txtPorCountDetail.value='';
		
		x.actionmode.value = '';
		x.mainaction.value = '';
	} 
}

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

	var vPorId = x.txtPreqId.value;
	var vPreqDate = x.txtDate.value;
	var vPreqRequestDate = x.txtDate.value;
	
	
	
	var vPorRemark = x.txtRemark.value;
	var vPreqCurr = x.txtCurr.value;
	var vPreqProjectCode = x.txtProjectCode.value;
	var vPorCostCentCode = x.txtCostCentCode.value;
	var vPorDiscount = x.txtReqDiscount.value;
	var vPorDiscountAmt = x.txtReqDiscountAmt.value;
	
	var vPorRequestBy = x.txtRequestBy.value;
	
	var vtxtPurpose = x.txtPurpose.value;
	var vtxtLocation = x.txtLocation.value;
	var vtxtPriority = x.txtPriority.value;
	
	var vPorDeliveryPlace = x.txtDeliveryPlace.value;
	var vPorDeliveryContact = x.txtDeliveryContact.value;
	var vPorStatusRemark = x.txtStatusRemark.value;
	
	
	
   /* for (var i=0; i < x.txtReqStatus.length; i++)
	{
		if (x.txtReqStatus[i].checked)
		{
		  var vPorStatus = x.txtReqStatus[i].value;
		}
	}*/
	
	  var vPorStatus = x.txtReqStatus.value;
	  
	/*if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtReqCategory.length; i++)
		{
			if (x.txtReqCategory[i].checked)
			{
			  var vPorCategory = x.txtReqCategory[i].value;
			}
		}
	} else {
		var vPorCategory = x.txtReqCategory.value;
	}*/
	
	var vPorVatChkbx = 0;
	if (x.ChkReqVat.checked)
		vPorVatChkbx = 1;	
	
	var vMainMode = x.mainaction.value;
	
	vPorRemark          = vPorRemark.replace('&','%26');
	vPorRequestBy       = vPorRequestBy.replace('&','%26');
	
	vtxtPurpose       = vtxtPurpose.replace('&','%26');
	vtxtLocation       = vtxtLocation.replace('&','%26');
	vtxtPriority       = vtxtPriority.replace('&','%26');
	
	vPorDeliveryPlace   = vPorDeliveryPlace.replace('&','%26');
	vPorDeliveryContact = vPorDeliveryContact.replace('&','%26');
	vPorStatusRemark    = vPorStatusRemark.replace('&','%26');
	
	vPorRemark          = vPorRemark.replace('#','%23');
	vPorRequestBy       = vPorRequestBy.replace('#','%23');
	
	vPorDeliveryPlace   = vPorDeliveryPlace.replace('#','%23');
	vPorDeliveryContact = vPorDeliveryContact.replace('#','%23');
	vPorStatusRemark    = vPorStatusRemark.replace('#','%23');
	
	
	
	if (result == 1) {
		win = window.open('Form_PurchaseRequestDetail.php?mainaction='+vMainMode+'&actionmode=&PPorId='+vPorId+'&PPreqDate='+vPreqDate+'&PPreqRequestDate='+vPreqRequestDate+
		                  +'&PPreqCurr='+vPreqCurr+'&PPreqProjectCode='+vPreqProjectCode+'&PPorCostCentCode='+vPorCostCentCode+
						  '&PPorStatus='+vPorStatus+'&PPorDiscount='+vPorDiscount+'&PPorDiscountAmt='+vPorDiscountAmt+'&PPorVatChkbx='+vPorVatChkbx+
						  '&PPorRemark='+vPorRemark+'&PPorRequestBy='+vPorRequestBy+'&PPorDeliveryPlace='+vPorDeliveryPlace+
						  '&vtxtPurpose='+vtxtPurpose+'&vtxtLocation='+vtxtLocation+'&vtxtPriority='+vtxtPriority+
						  
						  '&PPorDeliveryContact='+vPorDeliveryContact+'&PPorStatusRemark='+vPorStatusRemark, 'Form_PurchaseRequestDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=670,height=320,top=100');		
		win.creator = self;
		win.focus();		
	}	
	
    
}


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

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



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



function CalcPorDiscount(option, dec, vatapplied, vatperc) {
	x = document.purchasereq;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var TaxAmt = x.txtReqTaxable.value;
	var GrossTotal = x.txtReqGrossTotal.value;
	var DisPer = x.txtReqDiscount.value;
	var DisAmt = x.txtReqDiscountAmt.value;
	var VatAmt = x.txtReqVat.value;
	var TaxesAmt = x.txtReqTotalTaxes.value;
	
	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
		alert('Discount Amount should be a NUMERIC value');
		x.txtReqDiscountAmt.focus();
		return 0;
	}
	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
		alert('Discount Percentage should be a NUMERIC value');
		x.txtReqDiscount.focus();
		return 0;
	}
	
	
	if (TaxAmt == '') TaxAmt = 0;
	if (GrossTotal == '') GrossTotal = 0;
	if (DisPer == '') DisPer = 0;
	if (DisAmt == '') DisAmt = 0;
	if (TaxesAmt == '') TaxesAmt = 0;
	
	TaxAmt = parseFloat(TaxAmt);
	GrossTotal = parseFloat(GrossTotal);
	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.txtReqDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
		else if (option == 2 ){  //Option by Amount Get The Per
		    x.txtReqDiscount.value = roundNumber(((DisAmt/GrossTotal)*100),dec);
				
			if (DisAmt > 0) x.txtReqDiscount.readOnly = true; 
			else x.txtReqDiscount.readOnly = false;
					
		}

		// Calculation of Vat Amount and Net Total
		DisAmt = x.txtReqDiscountAmt.value;
		if (DisAmt == '') DisAmt = 0;
		DisAmt = parseFloat(DisAmt);
		
		VatAmt = 0;
		
		if (vatapplied == 1 && x.ChkReqVat.checked) {
			if (TaxAmt > 0)
				VatAmt = roundNumber(((TaxAmt - (DisAmt*TaxAmt/GrossTotal))*vatperc/100),dec);
		} 
		
		VatAmt = parseFloat(VatAmt);		
		x.txtReqVat.value      = formatNumber(VatAmt,dec);
		x.txtReqNetTotal.value = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);
		
	}   
	
	
}

function SetPorVat(dec, vatapplied, vatperc, PurchaseTTC) {
	x = document.purchasereq;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var vAmount = 0;
	
	var TaxAmt = x.txtReqTaxable.value;
	var GrossTotal = x.txtReqGrossTotal.value;
	var VatAmt = x.txtReqVat.value;
	var DisAmt = x.txtReqDiscountAmt.value;
	var NetTotal = x.txtReqNetTotal.value;
	var TaxesAmt = x.txtReqTotalTaxes.value;
	
	if (TaxAmt == '') TaxAmt = 0;
	if (GrossTotal == '') GrossTotal = 0;
	if (VatAmt == '') VatAmt = 0;
	if (DisAmt == '') DisAmt = 0;
	if (NetTotal == '') NetTotal = 0;
	if (TaxesAmt == '') TaxesAmt = 0;
	
	VatAmt = parseFloat(VatAmt);
	NetTotal = parseFloat(NetTotal);
	DisAmt = parseFloat(DisAmt);
	TaxAmt = parseFloat(TaxAmt);
	GrossTotal = parseFloat(GrossTotal);
	TaxesAmt = parseFloat(TaxesAmt);
	
	if (x.ChkReqVat.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.txtReqTaxable.value    = formatNumber(TaxAmt,dec);
		x.txtReqGrossTotal.value = formatNumber(GrossTotal,dec);
		x.txtReqVat.value        = formatNumber(VatAmt,dec);
		x.txtReqNetTotal.value   = formatNumber(roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt),dec),dec);
	}
	else
	{
		if (PurchaseTTC == 1) {
			x.txtReqVat.value        = formatNumber(0,dec);
			x.txtReqTaxable.value    = formatNumber(TaxAmt + VatAmt,dec);
			x.txtReqGrossTotal.value = formatNumber(GrossTotal + VatAmt,dec);
		}
		else {
			x.txtReqVat.value      = formatNumber(0,dec);
			x.txtReqNetTotal.value = formatNumber(roundNumber((NetTotal - VatAmt),dec),dec);
		}	
	}  
	

}

function SetPorVatFlag() {
	x = document.purchasereq;
	var vmode = x.mainaction.value;
	
	
}		

function PrintPurchaseRequest(PreqId, PorRef) {
	var str = '';
	//var PreqId = document.purchasereq.txtPreqId.value;
	if (confirm ( "Do you want to Print current Purchase Request with reference "+PorRef+" ?"))
	{
		str = 'Form_PurchaseRequestPreview.php?PrequestId='+PreqId;
		window.open(str);
	}	
}


function showlistProject(vtype,vtext1,vwidth,vheight,item){
  	var text1value = document.getElementById(vtext1).value;
	if (item=='')
		item = 2;
	win = window.open('List_Project.php?PProject_Code='+text1value+'&item='+item+'&vtype='+vtype+'&vtext1='+vtext1
						+'&text1value='+text1value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
	win.creator = self;
	win.focus();	

	
}
function showlistCostcenter(vtype,vtext1,vwidth,vheight,item){
  	var text1value = document.getElementById(vtext1).value;
	
	if (item=='')
		item = 2;
	win = window.open('List_Costcenter.php?PCostcent_Code='+text1value+'&item='+item+'&vtype='+vtype+'&vtext1='+vtext1
						+'&text1value='+text1value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
	win.creator = self;
	win.focus();	

	
}

function showlistWarehouse(vtype,vtext1,vwidth,vheight){
	var text1value = document.getElementById(vtext1).value;

	win = window.open('List_Warehouses.php?PRef='+text1value+'&str=5&vtype='+vtype+'&vtext1='+vtext1
						+'&text1value='+text1value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
	win.creator = self;
	win.focus();	

	
}


function roundNumber(num, dec) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  newnumber = parseFloat(newnumber); 
  
  return newnumber;
}

function formatNumber(num, dec) { // Arguments: number to format, number of decimal places
	return num.toFixed(dec);
}


function showlistHeatNo(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vHeatNoCode = encodeURIComponent(document.getElementById('prqstdtheatno['+PIndex+']').value);
	
	window.open('List_HeatNo.php?frm=14&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);
}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Purchase Request</title>

<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">

<style>



#table1:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	cursor:pointer;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;

}
#table2:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}
#table3:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}
#tabledt1:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}
#tabledt2:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;

}

#tabledt3:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}
#table5:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}
#table6:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}
#table7:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}
#table8:hover {
	background-color:#f2f2f2;
	border:1px solid #E2E2E2;
	-o-transition:.9s;
  -ms-transition:.9s;
  -moz-transition:.9s;
  -webkit-transition:.9s;
  /* ...and now for the proper property */
  transition:.9s;
cursor:pointer;
}

table.sample {
	border-width: 0px;
	border-spacing: 3px;
	border-style: double;
	border-color: gray;
	border-collapse: collapse;
	background-color: white;
}
table.sample th {
	border-width: 1px;
	padding: 0px;
	border-style: solid;
	border-color: #DCDCDC;
	-moz-border-radius: ;
}
table.sample td {
	border-width: 1px;
	padding: 0px;
	border-style: solid;
	border-color: #E5E5E5;
	-moz-border-radius: ;
}


tablesalary.sample {
	border-width: 0px;
	border-spacing: 3px;
	border-style: double;
	border-color: gray;
	border-collapse: collapse;
	background-color: white;
}
tablesalary.sample th {
	border-width: 1px;
	padding: 0px;
	border-style: solid;
	border-color: #DCDCDC;
	-moz-border-radius: ;
}
tablesalary.sample td {
	border-width: 1px;
	padding: 0px;
	border-style: solid;
	border-color: #E5E5E5;
	-moz-border-radius: ;
}


</style>
<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='purchasereq' method='post'>
<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='';

	echo "<div id='qwqw'></div>";
//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))
	$txtCurr = $base1;
if (empty($txtDate))	
	$txtDate = displayToday();
if (empty($txtDeliveryDate))	
	$txtDeliveryDate = displayToday();	
	
	
if ($FI_PurchaseCategory == 0 || $FI_PurchaseCategory == 1) $txtReqCategory = 0;
else if ($FI_PurchaseCategory == 2) $txtReqCategory = 1;	



if (($actionmode == "submitrecord" || $mainaction == "edit" || $actionmode == "editdt" || $actionmode == "deletedt" || $actionmode == "post") && $txtPreqId != '') {
	// Read From Temp Tables For Selected Record				 
	$query = " Select PRqst_id, PRqst_reference, Date_Format(PRqst_date,'%d/%m/%Y') As PrequestDate, ".
	         " Date_Format(PRqst_DeliveryDate,'%d/%m/%Y') As DeliveryDate, PRqst_RequestBy, Prequest.Currency_code, ".
			 " Null, Null, Null, ".
			 " Null, Null, PRqst_remark, Prequest.Project_Code, Prequest.Costcent_code,  ".
			 " null , ifNull(Prqst_Import,0), ifNull(PRqst_Status,'A'), ".
			 " Status_Remark, PRqst_DeliveryPlace, PRqst_DeliveryContact,  ".
			 " Round(PRqst_Taxable, ".$DecimalBase."), Round(PRqst_NoneTaxable, ".$DecimalBase."), ".
			 " Round(PRqst_Total, ".$DecimalBase.") As GrossTotal, ".
			 " Round(PRqst_DiscountPer, ".$DecimalBase."), Round(PRqst_DiscountAmount, ".$DecimalBase."),  ".
			 " ifNull(PRqst_VATChckbx,0) As PRqst_VATChckbx, Round(PRqst_Vat, ".$DecimalBase.") As PRqst_Vat, ".
			 " Round((IfNull(PRqst_Total,0) + IfNull(PRqst_Vat,0) - IfNull(PRqst_DiscountAmount,0) + (ifNull(Prqst_Tax1,0) + ifNull(Prqst_Tax2,0) + ifNull(Prqst_Tax3,0) + ifNull(Prqst_Tax4,0) + ifNull(Prqst_Tax5,0))), ".$DecimalBase.") As Prequest_NetTotal,  ".
			 " Round((ifNull(Prqst_Tax1,0) + ifNull(Prqst_Tax2,0) + ifNull(Prqst_Tax3,0) + ifNull(Prqst_Tax4,0) + ifNull(Prqst_Tax5,0)), ".$DecimalBase.") As TotalTaxes  ".
			 " ,Prequest.username as username,PRqst_Purpose,PRqst_Location,PRqst_Priority".
			 " From Temp_PRequest As Prequest ".
	         " Where PRqst_id = '".$txtPreqId."'";
			 
			 
			 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	
	$txtPreqId       	= $rows[0];
	$txtRef         	= $rows[1];
	$txtDate        	= $rows[2];
	$txtDeliveryDate 	= $rows[3];
	$txtRequestBy  		= $rows[4];
	$txtCurr        	= $rows[5];
	
	
	$txtRemark          = $rows[11];
	$txtProjectCode     = $rows[12];
	$txtCostCentCode    = $rows[13];
	
	$txtReqCategory     = $rows[15];
	$txtReqStatus       = $rows[16];
	$txtStatusRemark    = $rows[17];
	$txtDeliveryPlace   = $rows[18];
	$txtDeliveryContact = $rows[19];
	
	$txtReqTaxable     = $rows[20];
	$txtReqNoneTaxable = $rows[21];
	$txtReqGrossTotal  = $rows[22];
	$txtReqDiscount    = $rows[23];
	$txtReqDiscountAmt = $rows[24];
	$ChkReqVat         = $rows[25];
	$txtReqVat         = $rows[26];
	$txtReqNetTotal    = $rows[27];
	$txtReqTotalTaxes  = $rows[28];
	$txtUserName  = $rows[29];
	
	$txtPurpose  = $rows[30];
	$txtLocation  = $rows[31];
	$txtPriority  = $rows[32];
	
	


	
	
	$query = " Select Count(*) FROM Temp_PRequest ".
			 " WHERE PRqst_id = ".$txtPreqId;
	$result = selectData($connection, $query);
	$txtPorCountDetail = $result[0];
	if($txtPorCountDetail == '') $txtPorCountDetail = 0;
	
}



//Search/Cancel Mode	
if ($actionmode == "cancel" && $txtPreqId != '') {
	
		
	// Delete From Temp Tables Already Filled By Search
	$query = " DELETE FROM Temp_PRequestDt ".
			 " WHERE PRqst_id = ".$txtPreqId;
			 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 
	  
	
	  
	$query = " DELETE FROM Temp_PRequest ".
			 " WHERE PRqst_id = ".$txtPreqId;
			 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
	if (!updateData($connection, $query, true))
      $message  = mysql_error();   

	$txtPreqId = '';
}






//$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 REQUEST</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_PurchaseRequestApp == 1)
//	echo"	<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $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>";	

	echo"<button type='button' id='btnCancel' name='btnCancel' ";
if ($actionmode=='cancel' || ($actionmode=='' && $mainaction!='edit'))
					echo " disabled ";
			
echo" onclick='CancelRecord();return false;' title='Cancel Changes'><span><span>$Cancel</span></span></button>";	


	echo"<button type='button' id='btnPost' name='btnPost' ";
		if (($actionmode=='' || $actionmode=='cancel') && $mainaction!='edit')
					echo " disabled ";
	echo" onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost);return false;' title='Save Changes'><span><span>Save Changes</span></span></button>";	
	
	echo"<button type='button' id='btnSearch' name='btnSearch' ";
	if (($actionmode!='' && $actionmode!='cancel') || $mainaction=='edit') 
		    echo " disabled ";
	echo" onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";


	echo"<button type='button' id='btnPending' name='btnPending' ";
	if (($actionmode!='' && $actionmode!='cancel') || $mainaction=='edit') 
		    echo " disabled ";
	echo" onclick='SearchForPending();return false;' title='Pending Purchase Requests'><span><span>Pending</span></span></button>";
		
	if ($txtPreqId !='')	
	echo"<button type='button' id='btnUpload' name='btnUpload' 
			onclick=\"UploadDocuments('prequest');return false;\" title='Upload Documents'><span><span>Upload Documents</span></span></button>";
	

	if($fi_pendingpurchaserequest ==1 && $FI_PurchaseRequestItems == 1)
	echo"<button type='button' id='btnRequest' name='btnRequest' 
			onclick=\"Request_Items();return false;\" title='Request Items'><span><span>Request Items</span></span></button>";
	
	if($FI_MaterialRequisition == 1){
		echo"<button type='button' id='btnLoad' name='btnLoad' 
			onclick=\"LoadMaterialReq();return false;\" title='Load Material Requisition'><span><span>Load Material Requisition</span></span></button>";
	}	
		
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"  cellpadding='0' style='table-layout:fixed;width:1055px'>
		  <col width=90>
		  <col width=90>
		  <col width=50>
		  <col width=120>
		  <col width=80>
		  <col width=120>
		  <col width=90>
		  <col width=85>
		  <col width=250>

		<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='txtPreqId' id='txtPreqId' value='$txtPreqId' size='10'>
			  <input type="hidden" name="txtRef" id='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.purchasereq.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</span></td>
          <td ><input type='text' name='txtDeliveryDate' value='$txtDeliveryDate' readonly maxlength='10' style='width:80px;' >
			  <A HREF="#" onClick="displayCalendar(document.purchasereq.txtDeliveryDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A>
		  </td>
		 				  

HERE;

/*<input type='text' name='txtRequestDate' value='$txtRequestDate' maxlength='10' style='width:80px;' >
						  <A HREF="#" onClick="displayCalendar(document.purchasereq.txtRequestDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A>*/
						  
if ($Module_PurchaseRequestPrice==1) {
	$cu = "<span class='style1'>Currency&nbsp;<span class='style16'>*</span>";
	$hid = ' ';
}
else {
	$hid = ' hidden ';
	$cu = "";
}
echo"     <td align='left' >$cu</td>";
echo"     <td ><span class='style1'><select name='txtCurr' id='txtCurr' $hid style='width:60px;'>";
		  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>";	

// 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;
  
}
$_SESSION["VatApplied"] = $VatApplied;

$_SESSION["PurchaseTTC"]= $PurchaseTTC;
$_SESSION["Setup_VatPercentage"] = $Setup_VatPercentage;
$_SESSION["DecimalBase"] = $DecimalBase;

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

echo"	<div id='totalsdatagrid' ";
	if ($Module_PurchaseRequestPrice==0)
		echo " style='visibility:hidden;' ";
	echo " > ";
ShowPRequestDtTotalsGrid($connection,'PQ',$txtPreqId,$PurchaseTTC,$VatApplied,$Setup_VatPercentage,$DecimalBase);
echo"	  </div>"; 		  
		  
echo"</td></tr>";


if($txtUserName=='')	$txtUserName=$_SESSION['username'];



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' id='txtRequestBy' value='".htmlspecialchars($txtRequestBy, ENT_QUOTES)."'  style='width:400px;' maxlength='50' readonly>
		  <td align='left' colspan=3><span class='style1'>User Name </span>&nbsp;&nbsp;&nbsp;&nbsp;
		  <input type='text' name='txtUserName' id='txtUserName' value='".$txtUserName."'  style='width:120px;' maxlength='50' readonly>
		  </td>";
echo"	</tr>";

echo"   <tr bgcolor='#F7F7F7' >
		  <td align='left' ><span class='style1'>Purpose</span></td>
		  <td colspan='5' ><span class='style1'>
			<input type='text' name='txtPurpose' id='txtPurpose' value='".htmlspecialchars($txtPurpose, ENT_QUOTES)."'  style='width:400px;' maxlength='50' >
		  <td align='left' colspan=3><span class='style1'>Location of Use&nbsp;</span><input type='text' name='txtLocation' id='txtLocation' value='".htmlspecialchars($txtLocation, ENT_QUOTES)."'  style='width:200px;' maxlength='50' ></span></td>";
echo"	</tr>";
  
  $sel1 = '';
  $sel2 = '';
  $sel3 = '';
  
	if ($txtPriority=='low')
		$sel1 = ' selected ';
		else	
	if ($txtPriority=='medium')
		$sel2 = ' selected ';
		else
	if ($txtPriority=='high')
		$sel3 = ' selected ';		
		else
		$sel2 = ' selected ';
		
echo"   <tr bgcolor='#F7F7F7' >
		  <td align='left' ><span class='style1'>Priority</span></td>
		  <td colspan='5' ><span class='style1'>
			<select name='txtPriority' id='txtPriority' >
			<option $sel1 value='low'>Low</option>
			<option $sel2 value='medium'>Medium</option>
			<option $sel3 value='high'>High</option>
		  <td align='left' colspan=3><span class='style1'></span></span></td>";
echo"	</tr>";

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

/*if ($FI_PurchaseCategory == 0) 
	echo" <td align='left' colspan='2'  bgcolor='#D8D8D8'><span class='style1'>Category</span></td>";		  
else 
	echo" <td align='left' colspan='2'>&nbsp;</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=setprojectcode(this.value,'txtProjectCode','imgprojectbtnheader')  /></span>
		    <label><span class='style1'><img src='img/scroll-down-1.png' title=' Select Project ' id='imgprojectbtnheader' width='20' height='20' border='0' onMouseOver=\"style.cursor='pointer'\"  onclick=\"showlistProject('project','txtProjectCode','800','500',2)\"  /></span></label></td>";
} else {
	echo" <td align='left' colspan='3'><input type='hidden' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' /></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=setcostcentercode(this.value,'txtCostCentCode','imgcostcenterbtnheader')  /></span>
		    <label><span class='style1'><img src='img/scroll-down-1.png' id='imgcostcenterbtnheader' title=' Select Costcenter ' width='20' height='20' border='0' onMouseOver=\"style.cursor='pointer'\"  onclick=\"showlistCostcenter('costcenter','txtCostCentCode','800','500',2) \" /></span></label></td>";
} else {
	echo" <td align='left' colspan='3'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode'   /></td>";

}
			
/*if ($FI_PurchaseCategory == 0) {
	echo" <td align='left' colspan='2'   bgcolor='#D8D8D8'><span class='style1'>&nbsp;&nbsp;";
	echo" <input type='radio' name='txtReqCategory' id='txtReqCategory' value='0' "; if($txtReqCategory==0 || $txtReqCategory=='') echo "checked />"; else echo " />";  echo " Local";
	echo" <input type='radio' name='txtReqCategory' id='txtReqCategory' value='1' "; if($txtReqCategory==1) echo "checked />"; else echo " />";  echo " Export";
    echo"</span></td>";
} else {
	echo" <td align='left' colspan='2' >&nbsp;<input type='hidden' name='txtReqCategory' id='txtReqCategory' value='$txtReqCategory' /></td>";
}
*/	
echo"   </tr>";

echo"   <tr bgcolor='#F7F7F7' >
		  <td align='left' ><span class='style1'></span></td>
		  <td colspan='7' ><span class='style1'>";
/* echo"		<input type='radio' name='txtReqStatus' readonly id='txtReqStatus' value='A' "; if($txtReqStatus=='A' || $txtReqStatus=='') echo "checked />"; else echo " />";  echo " Approved";
echo"		<input type='radio' name='txtReqStatus' id='txtReqStatus' value='P' "; if($txtReqStatus=='P') echo "checked />"; else echo " />";  echo " Pending";
echo"		<input type='radio' name='txtReqStatus' id='txtReqStatus' value='R' "; if($txtReqStatus=='R') echo "checked />"; else echo " />";  echo " Rejected";
echo"		<input type='radio' name='txtReqStatus' id='txtReqStatus' value='C' "; if($txtReqStatus=='C') echo "checked />"; else echo " />";  echo " Canceled"; */

echo"<input type='hidden' name='txtReqStatus' value='$txtReqStatus' id='txtReqStatus'>";
if($txtReqStatus=='A')
	echo "";
else	
if($txtReqStatus=='P')
	echo "";
else	
if($txtReqStatus=='R')
	echo "";
else	
if($txtReqStatus=='C')
	echo "";

echo"<input type='hidden' name='txtStatusRemark' id='txtStatusRemark'>";
echo "</tR>";
/*echo"	<tr bgcolor='#F7F7F7' ></td>
		  <td align='left' ><span class='style1'>Status Remark</span></td>
		  <td colspan='7' ><span class='style1'>
			<input type='text' name='txtStatusRemark' value='".htmlspecialchars($txtStatusRemark, ENT_QUOTES)."'  style='width:400px;' maxlength='100' >
		  </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"   </table></td></tr>";		

		
			

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

/*	   

echo"   <tr  bgcolor='#D8D8D8'><td colspan='9' align=center valign='top'>";
echo"     <table border='0' style='table-layout:fixed'>
		  
		  ";
		  
		  
		
		

	  
			

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

//if ($FI_PurchaseRequestApp == 1)
//	echo"	<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $FI_PurchaseCategory)' $style title='Add Item'>";
	
echo"   <input type='button' id='btnClear' name='btnClear' value='Clear Page'   onclick='ClearPage();' $style title='Clear Page'>";
echo"   <input type='button' name='btnCancel' id='btnCancel' value='Cancel' ";//cancel
		if ($actionmode=='cancel' || ($actionmode=='' && $mainaction!='edit'))
			echo " disabled ";
		echo" onclick='CancelRecord();' $style title='Cancel Changes'>";
				
echo"   <input name='btnPost' type='button' id='btnPost' value='Save' ";//post
		if (($actionmode=='' || $actionmode=='cancel') && $mainaction!='edit')
			echo " disabled ";
		echo" onclick='PostChanges();' $style	title='Save Changes' />";

echo"   <input type='button' name='btnSearch' id='btnSearch' value='Search' onclick='SearchForRef();' $style title='Search By Reference' ";
        if (($actionmode!='' && $actionmode!='cancel') || $mainaction=='edit') 
		    echo " disabled ";
		echo " />";
				
echo"   <input type='button' name='btnPending' id='btnPending' value='Pending' onclick='SearchForPending();' $style title='Pending Purchase Requests' ";
        if (($actionmode!='' && $actionmode!='cancel') || $mainaction=='edit')
		    echo " disabled ";
		echo " />";				

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



echo"   </table></td></tr>"; */
		
echo"   <tr bgcolor='#ffffff'><td colspan='10' valign='top'>";
echo"	<div id='main' >";
echo"	<div id='Loader' class=''><div></div></div>";
echo"	<div id='datagrid' class='' style='width:990px;' >";

//Show Items Grid



ShowPRequestDtGrid($connection,'PQ',$txtPreqId,$orderby,$startrange,$perpage,$option,$direction,$base1,$base2,$DecimalBase,$Module_DoubleUnit,$Module_ProjectDt,$Module_CostCenterDt,$PriceLabel,$Module_Unit1Method,$PurchaseTTC,$FIPurchaseCategory,$Module_PurchaseRequestPrice,$Module_Pack, $Module_Heatno);

echo"	  </div>"; 
echo"   </td></tr>"; 
		
	echo"   <tr><td colspan='9' valign='top'>";

echo"	<div id='testdatagrid' class='' style='width:1090px;' >";


echo"	  </div>"; 
echo"	  </div>"; 
echo"   </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 == "confirmrequest") && $PrPrqstId != '') {

	$query    = " SELECT PRqst_reference, ifNull(Prqst_Confirmed,0) ".
			    " FROM Prequest".
                " WHERE Prqst_id = $PrPrqstId ";
	$result   = selectData($connection, $query);
	$PrPreqstRef = $result[0];
	$PorConfirmed = $result[1];
		
	$AskComfirm = 0;
	
	echo '<script type="text/javascript" language="javascript">';
	
	if (($mainaction == "insert" || ($mainaction == "edit" && $PorConfirmed == 0)) && $actionmode == "post" && $Module_PRequestConfirm == 1 && $FI_PRequestConfirmed == 1) {
		echo ' ConfirmRequest(\''.$PrPrqstId.'\'); ';
		
		$AskComfirm = 1;
	}	
	
	if	 (($AskComfirm == 1 && $actionmode == "confirmrequest") || $AskComfirm == 0) {
		if ($Login_FastPrint == 1) 
			echo ' PrintPurchaseRequest(\''.$PrPrqstId.'\', \''.$PrPreqstRef.'\'); ';
			
		echo ' ClearPage1(); ';
	}
	
	echo '</script>';

}



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

HERE;

?>