<?php

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


include("config.inc.php");
include("function.inc.php");
include("Functions_Trans.php");
set_time_limit(0);

$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 ifNull(FI_DeliveryApp,0) As FI_DeliveryApp, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ".
		  " ifNull(FI_sorderconfirmed,0) As FI_SalesOrderConfirm, ifNull(login_disapprovesorder,0) As Login_DisapproveSorder, ifNull(FI_FrmRestrictWarehouse,0) As FI_FrmRestrictWarehouse, ".
		  " 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);
}

$EditHint = '';
$EditMode = '';

$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, 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 PurchaseSetup Table
$queryPurchaseSetup="Select PurchaseTTC, ifNull(ShowCostCentLayout,0) As ShowCostCentLayout From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent, ".
			 " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_TransferSorder,0) As Module_TransferSorder  From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$MainCompanyName=explode('_',$_SESSION['dbName']);

$queryperiod= " Select ifNull(LockViewPeriod,0) As LockViewPeriod, ViewPeriodDate, ifNull(ViewLockDaily,0) As ViewLockDaily, ViewNumberOfDays ".
              " From ".$_SESSION['dbLabel'].".ListUserDir  ".
			  " Where Usercode='".$_SESSION['useraccount']."' ".
			  " And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			  " And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
			  
$resultperiod = mysql_query($queryperiod,$connection) or die(mysql_error());
$rowsperiod   = mysql_num_rows($resultperiod);

while($rows=mysql_fetch_array($resultperiod)){
	extract($rows);
}	
			  
//echo $queryperiod;	

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on (($Module_ProjectParent=1 and project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%')) or ($Module_ProjectParent=0 and project.project_code = loginstk.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());
$projectexist  = mysql_num_rows($projectresult);		  

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on (($Module_CostCenterParent=1 and costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%')) or ($Module_CostCenterParent=0 and costcent.costcent_code = 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());
$costcentexist  = mysql_num_rows($costcentresult);	

$querywh=" select distinct warehouse.warehouse_code, warehouse_name ".
         " from warehouse inner join ".$_SESSION['dbLabel'].".loginstk on warehouse.warehouse_code = loginstk.warehouse_code ".
		 " where user_account='".$_SESSION['useraccount']."' ".
		 " and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
		 " order by warehouse.warehouse_code";
//echo $querywh;		 
$whresult = mysql_query($querywh,$connection) or die(mysql_error());
$whexist  = mysql_num_rows($whresult);	  
$defaultwarehouse = mysql_fetch_row($whresult);

$actionmode 	= $_POST["actionmode"]; if ($actionmode == ""){$actionmode = $_GET["actionmode"];}   
$mainmode   	= $_POST["mainmode"]; if ($mainmode == ""){$mainmode = $_GET["mainmode"];}   
$mode   		= $_POST["mode"]; if ($mode == ""){$mode = $_GET["mode"];}   
$PMode   		= $_POST["PMode"]; if ($PMode == ""){$PMode = $_GET["PMode"];}   
$message 		= $_POST["message"]; if ($message == ""){$message = $_GET["message"];}   
$GeneratedId 	= $_POST["GeneratedId"]; if ($GeneratedId == ""){$GeneratedId = $_GET["GeneratedId"];}   
$SelectedRows 	= $_POST["SelectedRows"]; if ($SelectedRows == ""){$SelectedRows = $_GET["SelectedRows"];}   
$txtPorId 		= $_POST["txtPorId"]; if ($txtPorId == ""){$txtPorId = $_GET["txtPorId"];}   
$PorId 			= $_POST["PorId"]; if ($PorId == ""){$PorId = $_GET["PorId"];}   
$suppcode 		= $_POST["suppcode"]; if ($suppcode == ""){$suppcode = $_GET["suppcode"];}   

$keyword    = $_POST['keyword']; if ($keyword == ""){$keyword = $_GET["keyword"];}
$lstItems   = $_POST['lstItems']; if ($lstItems == ""){$lstItems = $_GET["lstItems"];}
$perpage    = $_POST['perpage']; if ($perpage == ""){$perpage = $_GET["perpage"];}
$startrange = $_POST['startrange']; if ($startrange == ""){$startrange = $_GET["startrange"];}


$SPorId    			= $_GET["SPorId"]; if ($SPorId == ""){$SPorId = $_POST["SPorId"];} 
$PPorId    			= $_GET["PPorId"]; if ($PPorId == ""){$PPorId = $_POST["PPorId"];} 
$PPorDate 			= $_GET["PPorDate"]; if ($PPorDate == ""){$PPorDate = $_POST["PPorDate"];} 
$PPorCurr   		= $_GET["PPorCurr"]; if ($PPorCurr == ""){$PPorCurr = $_POST["PPorCurr"];} 
$PPorRequestDate 	= $_GET["PPorRequestDate"]; if ($PPorRequestDate == ""){$PPorRequestDate = $_POST["PPorRequestDate"];} 
$PPorExpiryDate    	= $_GET["PPorExpiryDate"]; if ($PPorExpiryDate == ""){$PPorExpiryDate = $_POST["PPorExpiryDate"];} 
$PPorSupplier 	   	= $_GET["PPorSupplier"]; if ($PPorSupplier == ""){$PPorSupplier = $_POST["PPorSupplier"];} 
$PPorDiscount 		= $_GET["PPorDiscount"]; if ($PPorDiscount == ""){$PPorDiscount = $_POST["PPorDiscount"];} 
$PPorDiscountAmt	= $_GET["PPorDiscountAmt"]; if ($PPorDiscountAmt == ""){$PPorDiscountAmt = $_POST["PPorDiscountAmt"];} 
$PPorVatChkbx 		= $_GET["PPorVatChkbx"]; if ($PPorVatChkbx == ""){$PPorVatChkbx = $_POST["PPorVatChkbx"];} 
$PPorRequestBy 	   	= $_GET["PPorRequestBy"]; if ($PPorRequestBy == ""){$PPorRequestBy = $_POST["PPorRequestBy"];} 
$PPorSupplierContact= $_GET["PPorSupplierContact"]; if ($PPorSupplierContact == ""){$PPorSupplierContact = $_POST["PPorSupplierContact"];} 
$PPorCategory   	= $_GET["PPorCategory"]; if ($PPorCategory == ""){$PPorCategory = $_POST["PPorCategory"];} 
$PPorRemark  		= $_GET["PPorRemark"]; if ($PPorRemark == ""){$PPorRemark = $_POST["PPorRemark"];} 
$txtPrequestReference	= $_GET["txtPrequestReference"]; if ($txtPrequestReference == ""){$txtPrequestReference = $_POST["txtPrequestReference"];} 
$PPorProjectCode 		= $_GET["PPorProjectCode"]; if ($PPorProjectCode == ""){$PPorProjectCode = $_POST["PPorProjectCode"];} 
$PPorCostCentCode		= $_GET["PPorCostCentCode"]; if ($PPorCostCentCode == ""){$PPorCostCentCode = $_POST["PPorCostCentCode"];} 
$PPorStatusRemark		= $_GET["PPorStatusRemark"]; if ($PPorStatusRemark == ""){$PPorStatusRemark = $_POST["PPorStatusRemark"];} 
$PPorDeliveryPlace		= $_GET["PPorDeliveryPlace"]; if ($PPorDeliveryPlace == ""){$PPorDeliveryPlace = $_POST["PPorDeliveryPlace"];} 
$PPorDeliveryContact	= $_GET["PPorDeliveryContact"]; if ($PPorDeliveryContact == ""){$PPorDeliveryContact = $_POST["PPorDeliveryContact"];} 


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" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css">
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>
<title>Search Confirmed Purchase Order</title>
<script type="text/javascript" language="javascript">

function RefreshPage()
{
	document.search.action='Form_PurchaseLoadRequest.php?startrange=0';
   document.search.submit();

}

function clearform()
{
  document.search.keyword.value='';
  document.search.action='Form_PurchaseLoadRequest.php';
  document.search.submit();

}



function PrintPreview(SorId)
{
	var str = '';

	str = 'Form_TransferSalesOrderPreview.php?SorderId='+SorId;
	window.open(str);
	
	self.close();

}

function ShowHideDetails(PorId, Option, startrange) {
	/*if (Option == 'S') {
		document.search.SelectedID.value = PorId;
		document.search.action='Form_PurchaseLoadRequest.php?startrange='+startrange+'&SelectedID='+PorId;
	}
	else if (Option == 'H') {
		document.search.SelectedID.value = '';
		document.search.action='Form_PurchaseLoadRequest.php?startrange='+startrange;
	}	
	
	document.search.submit();*/
	
	vSlideDivId = '#displaydetails'+PorId;
	$(vSlideDivId).slideToggle();
}


function LoadForm() 
{
	x=document.search;
	x.keyword.focus();
	
	ChangeLocation();
}

function SetNextPage(startrange,perpage){ 
	document.search.action='Form_PurchaseLoadRequest.php?keyword=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}

function SetPrvPage(startrange,perpage){
	document.search.action='Form_PurchaseLoadRequest.php?keyword=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}



function SelectRecord(RecordId,suppcode){
		
	document.search.PMode.value=1;	
	document.search.action="Form_PurchaseOrder_Actions.php?mainmode=copyrequest&PurReqId="+RecordId+"&suppcode="+suppcode;
	document.search.submit();


}

function UnConfirmOrder(SorId, SorRef){

	var vMainMode = '';
	var vMsg = '';
	
	vMainMode = 'unconfirmorder';
	vMsg = 'Are you sure you want to Unconfirm order with reference = '+SorRef+' ?';
	
	if (SorId != '') {
		if (confirm (vMsg) )
		{
			document.search.action="Form_Transfer_Actions.php?mainmode="+vMainMode+"&SSaId="+SorId;
			document.search.submit();
		}
	}
	
}

function LoadData(){

x = document.search;

		var vSelectedRows = document.search.SelectedRows.value;	
		var vMode = x.mainaction.value;
		x.mode.value = 'copyrequest';
		var vSaID = document.search.PorId.value;
		var str1 = "Form_PurchaseOrder_Actions.php?mode=copyrequest&PordId="+vSaID+"&SSaDtId="+vSelectedRows;
		
			var  the_data =  str1 + '&SPorId='+x.txtPorId.value+
					'&PPorId='+x.txtPorId.value+
					'&PPorDate='+x.PPorDate.value+
					'&PPorCurr='+x.PPorCurr.value+
					'&PPorRequestDate='+x.PPorRequestDate.value+
					'&PPorSupplier='+x.PPorSupplier.value+
					'&PPorDiscount='+x.PPorDiscount.value+
					'&PPorDiscountAmt='+x.PPorDiscountAmt.value+
					'&PPorVatChkbx='+x.PPorVatChkbx.value+
					'&PPorProjectCode='+x.PPorProjectCode.value+
					'&PPorCostCentCode='+x.PPorCostCentCode.value+
					'&PPorRemark='+encodeURIComponent(x.PPorRemark.value)+
					'&PPorRequestBy='+encodeURIComponent(x.PPorRequestBy.value)+
					'&PPorSupplierContact='+encodeURIComponent(x.PPorSupplierContact.value)+
					'&PPorDeliveryPlace='+encodeURIComponent(x.PPorDeliveryPlace.value)+
					'&PPorDeliveryContact='+encodeURIComponent(x.PPorDeliveryContact.value)+
					'&PPorStatusRemark='+encodeURIComponent(x.PPorStatusRemark.value) + 
					'&txtPrqstid='+encodeURIComponent(x.txtPrqstid.value) 				
					;
					

	
	
	if (vSelectedRows != '') {
		
		document.search.PMode.value=1;	
		document.search.action= the_data;
		document.search.submit();
	} else
		alert ('Please Select an Item.');
	
}


function ChangeLocation()
{
    if (document.search.PMode.value == 1) {
	    var GenId = document.search.GeneratedId.value;
		
		opener.document.purchase.txtPorId.value=GenId;
	    opener.document.purchase.actionmode.value='submitrecord';
		opener.document.purchase.message.value = document.search.message.value;
		opener.document.purchase.action='Form_PurchaseOrder.php';
		opener.document.purchase.submit();
		self.close();
	}	
}

function SelectMaster(obj,vName,PRqst_id,vEmptyItemCode) {

if(vEmptyItemCode==1){
	alert('Cannot Load this Purchase Request Before Filling the Item Code'); 
	obj.checked = false;
	return;
}
   document.getElementById('txtPrqstid').value = PRqst_id;
   
   var MasterCheckName, DetailCheckName, RecName;
   var x, y, z, t;
   
   for (var i=1; i <= document.search.i.value; i++)
  {
    MasterCheckName='M'+i;
	RecName = 'Rec'+MasterCheckName;
	
	x = document.getElementById(MasterCheckName);
	y = document.getElementById(RecName);
	t = document.getElementById(vName);
	
	if (x.checked && x.value == t.value) {
		for (var j=1; j <= y.value; j++)
		{
			DetailCheckName=MasterCheckName+'D'+j;
	
			z = document.getElementById(DetailCheckName);
			z.checked = true;
		}	
	} 
	else if (!(x.checked) &&  x.value == t.value){ 
		for (var j=1; j <= y.value; j++)
		{
			DetailCheckName=MasterCheckName+'D'+j;
	
			z = document.getElementById(DetailCheckName);
			z.checked = false;
		}
	
	}
    
  }
  
  SelectDetail();
  

}

function SelectDetail(obj,vItemCode) {


 if(vItemCode==''){
	alert('Cannot Load this Purchase Request Before Filling the Item Code');
	obj.checked = false;
	return;
}

	var MasterCheckName, DetailCheckName, RecName, vSelectedRows;
	var x, y, z;
	
	vSelectedRows = '';
	for (var i=1; i <= document.search.i.value; i++)
	{
		MasterCheckName='M'+i;
		RecName = 'Rec'+MasterCheckName;
		
		x = document.getElementById(MasterCheckName);
		y = document.getElementById(RecName);
		
		
		for (var j=1; j <= y.value; j++)
		{
			DetailCheckName=MasterCheckName+'D'+j;
		
			z = document.getElementById(DetailCheckName);
			
			if (z.checked)
				vSelectedRows = vSelectedRows + ',' + z.value;
		}	
		
		
	}
	
	vSelectedRows = vSelectedRows.substr(1);
	document.search.SelectedRows.value = vSelectedRows;
}

function SubmitForm()
{	
 
  //document.search.keyword.value='';
  document.search.action='Form_PurchaseLoadRequest.php?startrange=0';
  document.search.submit();

}

</script>

<style type="text/css">

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 2px;
	margin-left: 1px;
}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}

.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}

.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #000000 ;font-size: 10px;}

</style>

					
</head>
<body onLoad='LoadForm();' class='bodybackground'>
<form name='search' method='post' action=''>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='txtPorId' value='$txtPorId'>
<input type='hidden' name='PorId' value='$PorId'>
<input type='hidden' name='GeneratedId' value='$GeneratedId'>
<input type='hidden' name='SelectedRows' value='$SelectedRows'>
<input type='hidden' name='mode' value='$mode'>
<input type='hidden' name='mainmode' value='$mainmode'>
<input type='hidden' name='PPorDate' value='$PPorDate'>
<input type='hidden' name='PPorRequestDate' value='$PPorRequestDate'>
<input type='hidden' name='PPorSupplier' value='$PPorSupplier'>
<input type='hidden' name='PPorDiscount' value='$txtPorDiscount'>
<input type='hidden' name='PPorDiscountAmt' value='$PPorDiscountAmt'>
<input type='hidden' name='PPorVatChkbx' value='$PPorVatChkbx'>
<input type='hidden' name='PPorProjectCode' value='$PPorProjectCode'>
<input type='hidden' name='PPorRemark' value='$PPorRemark'>
<input type='hidden' name='PPorCostCentCode' value='$PPorCostCentCode'>
<input type='hidden' name='PPorRequestBy' value='$PPorRequestBy'>
<input type='hidden' name='PPorSupplierContact' value='$PPorSupplierContact'>
<input type='hidden' name='PPorDeliveryPlace' value='$PPorDeliveryPlace'>
<input type='hidden' name='PPorDeliveryContact' value='$PPorDeliveryContact'>
<input type='hidden' name='PPorStatusRemark' value='$PPorStatusRemark'>
<input type='hidden' name='PPorCurr' value='$PPorCurr'>
<input type='hidden' name='txtPrqstid' id='txtPrqstid' value='$txtPrqstid'>


					
HERE;

echo "<input type='hidden' name='message' value='".htmlspecialchars($message, ENT_QUOTES)."'>";
echo "<input type='hidden' name='PSaRemark' value='".htmlspecialchars($PSaRemark, ENT_QUOTES)."' > 
	  <input type='hidden' name='PSaDriverName' value='".htmlspecialchars($PSaDriverName, ENT_QUOTES)."' >
	  <input type='hidden' name='PSaVehicleNumber' value='".htmlspecialchars($PSaVehicleNumber, ENT_QUOTES)."' >
	  <input type='hidden' name='PSaDAddress' value='".htmlspecialchars($PSaDAddress, ENT_QUOTES)."' > 
	  <input type='hidden' name='PSaIAddress' value='".htmlspecialchars($PSaIAddress, ENT_QUOTES)."'> ";


	  
$PRef = GetSQLValueString($keyword, 'text');


if (empty($ViewPeriodDate))
   $ViewPeriodDate = 'Null';
if (empty($ViewNumberOfDays))   
   $ViewNumberOfDays = 1;
   
   
   
/*  $querysearch=" Select Distinct prequest.PRqst_id as PRqst_id, prequest.PRqst_reference
			, Date_Format(prequest.PRqst_date,'%d-%m-%Y') As PRqst_date, prequest.PRqst_remark,".
			 " Project.Project_Name As ProjectName ".
			 " ,prequest.Project_Code as Project_Code".
			 " ,prequest.Costcenter_code as Costcent_code".
			 " ,prequest.User_Name as User_Name".
			 " ,ifNull(Temp_prequest.PRqst_id, -1) As TemppurchaserequestId from prequest".
			 " Left Join Project on prequest.Project_Code = Project.Project_Code ".
			 " Left Join Temp_prequest on Temp_prequest.PRqst_id = prequest.PRqst_id ".
			 " Inner Join ( Select PRqst_id, porderdt.RelatedDt_ID, ".
			 "              Sum(ifNull(porderdt.porderdt_quantity,0)) As QuantityUsed, Sum(ifNull(temp_porderdt.porderdt_quantity,0)) As QuantityUsedTemp, ".
			 "              ifNull(prequestdt.prqstdt_quantity,0) As QuantityRequested ".
			 "              From prequestdt ".
			 "              Left Join porderdt on (porderdt.RelatedDt_ID = prequestdt.PRqstDt_id And porderdt.porder_Id != '".$PorId."') ".
			 "		    	Left Join temp_porderdt on temp_porderdt.RelatedDt_ID = prequestdt.PRqstDt_id ".
			 "  			Group by PRqst_id, porderdt.RelatedDt_ID, temp_porderdt.RelatedDt_ID ".
			 "				Having (QuantityRequested - QuantityUsed) > 0   ".
			 "			) As Q on Q.PRqst_id = prequest.PRqst_id "; 
 */
$querysearch=" Select Distinct prequest.PRqst_id as PRqst_id, prequest.PRqst_reference
			, Date_Format(prequest.PRqst_date,'%d-%m-%Y') As PRqst_date, prequest.PRqst_remark,".
			 " Project.Project_Name As ProjectName ".
			 " ,prequest.Project_Code as Project_Code".
			 " ,prequest.Costcenter_code as Costcent_code".
			 " ,prequest.User_Name as User_Name".
			 " ,ifNull(Temp_prequest.PRqst_id, -1) As TemppurchaserequestId, sum(ifNull(prequestdt.prqstdt_quantity,0) - ifNull(porderdt.porderdt_quantity,0)) as totsum from prequest".
			 " Left Join Project on prequest.Project_Code = Project.Project_Code ".
			 " Left Join Temp_prequest on Temp_prequest.PRqst_id = prequest.PRqst_id ".
			 " left join prequestdt on prequestdt.PRqst_id = prequest.PRqst_id
				Left Join porderdt on (porderdt.RelatedDt_ID = prequestdt.PRqstDt_id And porderdt.porder_Id != '".$PorId."' )
				Left Join temp_porderdt on temp_porderdt.RelatedDt_ID = prequestdt.PRqstDt_id ";	 		 
if ($projectexist >	0)
  $querysearch= $querysearch." left join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
							 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
							 "             and (project_code is not null and project_code != '') ".
							 "			 ) Q1 on prequest.Project_Code like concat(Q1.project_code,'%') ";
							 
if ($costcentexist > 0)
  $querysearch= $querysearch." left join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
							 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
							 "             and (costcent_code is not null and costcent_code != '') ".
							 "			 ) Q2 on prequest.CostCenter_code like concat(Q2.costcent_code,'%') ";							 

				 
$querysearch= $querysearch.											 
			 " Where prequest.PRqst_reference = ifNull($PRef, prequest.PRqst_reference) ".
			 " And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(prequest.PRqst_date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',prequest.PRqst_date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
             "                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(prequest.PRqst_date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ";
if($FI_PurchaseRequestItems == 1)			 
	$querysearch= $querysearch." And  exists ( select 1 from prequestdt where prequestdt.PRqst_id = prequest.PRqst_id and PRqstDt_approvedlevel = 1 and ifnull(PRqstDt_status,'r') = 'u' 
							and if($whexist > 0,upper(prequestdt.warehouse_code)=upper('$defaultwarehouse[0]'),1=1 )	limit 1) ";
else if($FI_PurchaseRequestItems == 0)	
	$querysearch= $querysearch." and ifnull(prequest.Prqst_Confirmed,0) = 1 ";	
$querysearch= $querysearch." And ifNull(prequest.PRqst_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
$querysearch= $querysearch." group by prequest.PRqst_id, prequestdt.PRqst_id, porderdt.RelatedDt_ID  having totsum > 0 ";
			 
$querysearch= $querysearch." Order By prequest.PRqst_reference Desc ";
			 
//echo $querysearch; 
if ($PMode != '1') {
$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());
$totalrows = mysql_num_rows($resultsearch);
	
if ($startrange=='' || $PRef != 'Null')
	$startrange = 0;
if ($perpage=='')
	$perpage = 20;
		
$querysearch = $querysearch." limit ".$startrange.",".$perpage;

$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());	

}		  

echo"<table cellpadding='0' cellspacing='0' border='0'  align='left' style='table-layout:fixed'  width='790px'>";
echo"<tr>
		<td id='search-top1' style='height:34px; width:31px;'>&nbsp;</td>
	  	<td id='search-top2' style='height:34px;' align='center' valign='middle'>
			<table border='0'>
			<tr><td><span class='style3'>List of Confirmed Purchase Request
			</span></td></tr>
			</table>
		</td>
		<td id='search-top3' style='height:34px; width:31px;'>&nbsp;</td>
	</tr>";

echo"<tr><td id='search-content1' style='width:31px;'>&nbsp;</td>
		 <td id='search-content2' >";


echo"<table border='0' cellspacing='1' style='table-layout:fixed'>
	  
	  <col width=20>
	  <col width=20>
	  <col width=65>
	  <col width=70>
	  <col width=80>
	  <col width=220>
	  <col width=80>
	  <col width=100>
		     
	
	  <tr class='Search-header-bg'>
	    <td align='left' colspan='4'><span class='style4'>Search by Reference</span></td>
		<td align='left' colspan='6'><span class='style4'><input type='text' name='keyword' id='keyword' value='$keyword' size='15' maxlength='30'/><input type='hidden' name='PMode' id='PMode' value='$PMode' size='15' maxlength='30'/></span>
		   <button type='button' id='btnSubmit' name='btnSubmit' onclick='SubmitForm(); return false;' title='Find'><span><span>Find</span></span></button>
			<button type='button' id='btnCancel' name='btnCancel' onclick='clearform();return false;' title='Cancel'><span><span>Cancel</span></span></button></td>";
		
echo" </tr>
      <tr class='Search-header-bg'>
	    <td align='left' colspan='4'><span class='style4'>Search by Item</span></td>
		<td align='left' colspan='6'>";
    echo"<select name='lstItems' id='lstItems' style='font-size:11px; width:350px; height:18px;' onchange='RefreshPage();' >";
			echo"<option></option>";
			while($itemf=mysql_fetch_row($resultitems)){
				echo"<option ";
				if ($lstItems==$itemf[0])
					echo " selected ";
				echo" value='$itemf[0]'>$itemf[0] - $itemf[1]</option>";
			}
			
			
	echo"</select></td>";
echo" </tr>	";
	echo"
</table>
		</td>
		<td id='search-content3' style='width:31px;'>&nbsp;</td>"; 
echo" </tr>"; 

echo"<tr>
		<td  id='search-content1' style='height:34px;width:31px;'>&nbsp;</td>
		<td  id='search-content2' style='height:34px;width:1025px;'>
		<table width='100%' border=0>
		<tr>
			<td align='right' style='width:380px;'><span class='style4'>Per Page </span><span class='style4'><select name='perpage' id='perpage' value='$perpage' onchange=\"RefreshPage();\">";
              
			if ($perpage==20)
				$s20 = 'selected';
			else if ($perpage==30)
				$s30 = 'selected';
			else if ($perpage==40)
				$s40 = 'selected';
			else if ($perpage==50)
				$s50 = 'selected';

						
							
			echo'<option '.$s20.' value="20">20</option>
				 <option '.$s30.' value="30">30</option>
				 <option '.$s40.' value="40">40</option>
				 <option '.$s50.' value="50">50</option>
				 </select></span></td>
			<td  style="width:74px;border-right:1px solid #000000;text-align:right;">';
			
			if($startrange > 0)
				echo"<img src='img/firstpage.png' title='First Page' onMouseOver=\"style.cursor='hand'\" onclick=SetFirstPage('".$startrange."','".$perpage."')>";

			$diff= $startrange - $perpage;
				
			if (($diff) >= 0 ){
				$prvstartrange = $startrange - $perpage;
				echo"&nbsp;&nbsp;<img src='img/arrowleft.png' title='Previous' onMouseOver=\"style.cursor='hand'\"  onclick=SetPrvPage('".$prvstartrange."','".$perpage."')>";
			}
			else
				echo "&nbsp;";
		
echo"		</td><td  align='left' style='width:74px;'>";
		
		
			if ($startrange <= $totalrows){
				$startrange1 = $startrange + $perpage;
				if  ($startrange1 < $totalrows){
					echo"<img src='img/arrowright.png' title='Next' onMouseOver=\"style.cursor='hand'\" onclick=SetNextPage('".$startrange1."','".$perpage."')>";
					echo"&nbsp;&nbsp;<img src='img/lastpage.png' title='Last Page' onMouseOver=\"style.cursor='hand'\" onclick=SetLastPage('".$perpage."','".$totalrows."')>";	
				}
			} else
				echo "&nbsp;";
				
			
echo"		</td><td style='width:380px;'>&nbsp;</td>
		</tr>";
echo"	</table></td>
		<td id='search-content3' style='width:31px;'>&nbsp;</td>";
echo"</tr>";			

echo"<tr><td id='search-content1' style='width:31px;'>&nbsp;</td>
		<td id='search-content2'>
			<div style='overflow:scroll;height:400px;width:725px;'>
			<table border='0'  cellpadding='0' cellspacing='1'  style='width:940px;'>	
		      <col width=20>
			  <col width=20>
			  <col width=70>
			  <col width=80>
			  <col width=150>
			  <col width=150>
			  <col width=150>
			  <col width=300>";
		
	if($message!=''){
		echo"<tr class='Search-header-bg'>
				<td height='15' align='center' colspan='8' class='searchmessage'>".$message."</td>
			</tr>";
	}
	
	echo"<tr class='Search-Label-bg'>
			<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
			<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
			<td  height='25' align='left'><span class='style4'>Reference </span></td>
			<td  height='25' align='center'><span class='style4'>Date </span></td>
			<td  height='25' align='center'><span class='style4'>Project</span></td>
			<td  height='25' align='center'><span class='style4'>Costcenter</span></td>
			<td  height='25' align='center'><span class='style4'>User</span></td>
			<td  height='25' align='center'><span class='style4'>Remark</span></td>";
	echo" </tr>";
		


if ($PMode != '1') {
$i = 0;

while($rows=mysql_fetch_array($resultsearch)){
		
	extract($rows);
	$ct+=1;
	$i = $i + 1;

	
	
	$querydetailed = " select 1 from prequestdt 
							where prequestdt.PRqst_id = $PRqst_id
							and PRqstDt_approvedlevel = 1 
							and ifnull(PRqstDt_status,'r') = 'u' 
							and (Item_code is null or Item_code = '')	";
	$resultdetailed=mysql_query($querydetailed,$connection) or die(mysql_error());	
	$rowsdetailed=mysql_fetch_array($resultdetailed);
	
	
	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
	
	
	if ($TemppurchaserequestId != -1) { $EditHint = 'Exists in Pending'; $EditMode = ' disabled '; }
	else { $EditHint = 'Select Record'; $EditMode = ''; }
	

	
	echo'<tr '.$Color.'>';
			
	//if (!empty($suppcode)) {
				
	    $SelMaster  = 'M'.$i;
		$$SelMaster = $PRqst_id;
			   
		echo"<td align='center'><span class='style5'><input type='checkbox' name='$SelMaster' id='$SelMaster' value='".$$SelMaster."' onclick=\"SelectMaster(this,this.name,$PRqst_id,'$rowsdetailed[0]');\" /></span></td>";
			
			
	/*} else
	{
		
		//echo'<td align="center"><span class="style5"><img src="img/mag.jpg" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreview('.$PRqst_id.');"  title="'.$PrevHint.'"  style="width: 15px; height: 15px; " '.$SorPrevMode.'></span></td>';
		
		if ($TemppurchaserequestId != -1) 
			echo'<tD>&nbsp;</tD>';
		else
			echo'<td align="center"><span class="style5">
			<img src="img/edit.png" onMouseOver="style.cursor=\'hand\'" onclick=\'SelectRecord('.$PRqst_id.',"'.$suppcode.'");\' title="'.$EditHint.'" '.$EditMode.' style="width: 20px; height: 20px; "></span></td>';	
	}*/

	//if (empty($suppcode)) {
		//echo'	<td align="center"><span class="style5"><img src="img/details.gif" onMouseOver="style.cursor=\'hand\'"  onclick="ShowHideDetails('.$PRqst_id.', \''.'S'.'\','.$startrange.');" title="Show Details" style="width:15px; height:15px; "></span></td>';
	//} else {
		echo'<td align="center">&nbsp;</td>';
	//}
	
	echo'	<td align="left"><span class="style5">'.$PRqst_reference.'</span></td>
			<td align="center"><span class="style5">'.$PRqst_date.'</span></td>
			<td align="center"><span class="style5">'.$Project_Code.'</span></td>
			<td align="left"><span class="style5">'.$Costcent_code.'</span></td>
			<td align="left"><span class="style5">'.$User_Name.'</span></td>
			<td colspan=2 align="left"><span class="style5">'.$PRqst_remark.'</span></td>';
	echo'</tr>';
		
		//if (!empty($suppcode)) {
		
			echo" <tr><td colspan='8'><table border='0' style='table-layout:fixed'>
				   <col width=50>
				   <col width=123>
				   <col width=110>
				   <col width=347>
				   <col width=90>
				   <col width=50>
				   ";
				   
			$querydt = " Select prequestdt.PRqstDt_id, prequestdt.Item_CodePacked, prequestdt.Item_code, Items.Item_Description, prequestdt.Warehouse_Code, ".
					   " prequestdt.PRqstDt_Remark, (ifNull(prequestdt.PRqstDt_Quantity,0) - (ifNull(Q1.QuantityDelivered,0) + ifNull(Q2.QuantityDeliveredTemp,0))) As QuantityRemaining,  ".
					   " Round(prequestdt.PRqstDt_Price, ".$DecimalBase."), prequestdt.PRqstDt_PriceBase1, prequestdt.PRqstDt_PriceBase2, ".
					   " Round(prequestdt.PRqstDt_Discount, ".$DecimalBase."),  ".
					   " Round(((prequestdt.PRqstDt_Quantity*prequestdt.PRqstDt_Price)-((prequestdt.PRqstDt_Quantity*prequestdt.PRqstDt_Price*ifNull(prequestdt.PRqstDt_Discount,0))/100)), ".$DecimalBase.") As Total, ".
					   " Round(prequestdt.PRqstDt_PriceTTC, ".$DecimalBase."), ".
					   " Round(((prequestdt.PRqstDt_Quantity*prequestdt.PRqstDt_PriceTTC)-((prequestdt.PRqstDt_Quantity*prequestdt.PRqstDt_PriceTTC*ifNull(prequestdt.PRqstDt_Discount,0))/100)), ".$DecimalBase.") As TotalTTC ".
					   " From prequestdt Left Join Items on prequestdt.Item_code = Items.Item_code ".
					   " Left Join ( Select porderdt.RelatedDt_ID, porderdt.Item_code, porderdt.Item_CodePacked, Sum(ifNull(porderdt.PorderDt_Quantity,0)) As QuantityDelivered ".
					   "             From porderdt ".
					   "             Where (porderdt.RelatedDt_ID != '' or porderdt.RelatedDt_ID Is Not Null)  ".
					   "             And porderdt.porder_Id != '".$PorId."' ".
					   "             Group By porderdt.RelatedDt_ID, porderdt.Item_code, porderdt.Item_CodePacked  ".
					   "            ) Q1 on Q1.Item_code = prequestdt.Item_code  and Q1.RelatedDt_ID = prequestdt.PRqstDt_id ".
					   " Left Join ( Select temp_porderdt.RelatedDt_ID, temp_porderdt.Item_code, temp_porderdt.Item_CodePacked, Sum(ifNull(temp_porderdt.PorderDt_Quantity,0)) As QuantityDeliveredTemp ".
					   "             From temp_porderdt ".
					   "             Where (temp_porderdt.RelatedDt_ID != '' or temp_porderdt.RelatedDt_ID Is Not Null) ".
					   "             Group By temp_porderdt.RelatedDt_ID, temp_porderdt.Item_code, temp_porderdt.Item_CodePacked ".
					   "            ) Q2 on Q2.Item_code = prequestdt.Item_code  and Q2.RelatedDt_ID = prequestdt.PRqstDt_id ".
					   " Where prequestdt.PRqst_id = ".$PRqst_id.
					   " And (('".$lstItems."' != '' and prequestdt.Item_Code = '".$lstItems."') or ('".$lstItems."' = '' and 1 = 1)) ";
	if($FI_PurchaseRequestItems == 1)
			$querydt = $querydt." and PRqstDt_approvedlevel = 1 and ifnull(PRqstDt_status,'r') = 'u' ";
	$querydt = $querydt." And (ifNull(prequestdt.PRqstDt_Quantity,0) - (ifNull(Q1.QuantityDelivered,0) + ifNull(Q2.QuantityDeliveredTemp,0))) > 0 ".
					   " Order By prequestdt.PRqstDt_id Desc ";
			
			//echo "<br>".$querydt;
			//exit;
			
			$j = 0;
			$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){
			    
				$ct+=1;
				$j = $j + 1;
				
				if($ct%2==0)
					$Color="style='background-color:".$grid_color1."'";
				else			
					$Color="style='background-color:".$grid_color2."'";	
						
				$SelDetail  = $SelMaster.'D'.$j;
				$$SelDetail = $rowsdt[0];
			   
				
				echo "<tr ".$Color." >";
				echo"   <td align='center'><span class='style5'><input type='checkbox' name='$SelDetail' id='$SelDetail' value='".$$SelDetail."' onclick=\"SelectDetail(this,'$rowsdt[2]');\" /></span></td>";
				echo "	<td align='left'><span class='style5'>".$rowsdt[1]."</span></td>";
				echo "	<td align='left'><span class='style5'>".$rowsdt[2]."</span></td>";
				echo "	<td align='left'><span class='style5'>".$rowsdt[3]."</span></td>";
				echo "	<td align='left'><span class='style5'>".$rowsdt[4]."</span></td>";
				echo "	<td align='right'><span class='style5'>".$rowsdt[6]."</span></td>";
				echo "</tr>";
								
			} 		

			$RecName  = 'Rec'.$SelMaster;
			
			echo "<input type='hidden' name='$RecName' id='$RecName' value='$j'>";	  
			echo "</table></td></tr>";
		/*} else {
			$sub_query = " Select PRequestDt.PRqstDt_ID, PRequestDt.Item_CodePacked, PRequestDt.Item_code, if (PRequestDt.Item_code != '', Items.Item_Description, PRequestDt.Item_Description) As Item_Description, ".
						 " PRequestDt.Warehouse_Code, Item_UnitPurchaseDesc, PRqstDt_Quantity, Round(PRqstDt_Price, ".$DecimalBase."), Round(PRqstDt_Discount, ".$DecimalBase."),  ".
						 " Round(((PRqstDt_Quantity*PRqstDt_Price)-((PRqstDt_Quantity*PRqstDt_Price*ifNull(PRqstDt_Discount,0))/100)), ".$DecimalBase.") As Total, ".
						 " Round(PRqstDt_PriceTTC, ".$DecimalBase."), ".
						 " Round(((PRqstDt_Quantity*PRqstDt_PriceTTC)-((PRqstDt_Quantity*PRqstDt_PriceTTC*ifNull(PRqstDt_Discount,0))/100)), ".$DecimalBase.") As TotalTTC ".
						 " From PRequestDt Left Join Items on PRequestDt.Item_code = Items.Item_code ".
						 " Where PRequestDt.PRqst_ID = ".$PRqst_id;

			$sub_result=mysql_query($sub_query,$connection) or die(mysql_error($connection));	
			$sub_totalrows = mysql_num_rows($sub_result);
				
			if ($sub_totalrows > 0) {
				$SlideDivId = 'displaydetails'.$PRqst_id;
					
				echo "<tr ".$Color.">";
				echo "<td colspan='8' valign='top' align='left'><div id='$SlideDivId' class='div-search-details' style='display:none; margin-left:40px;'>";
				echo "<table border='0' style='table-layout:fixed; width:880px;' cellpadding='0' cellspacing='1'>";
				echo "<tr><td width='140px'><span class='style4'>Item Code</span></td>
						  <td width='220px'><span class='style4'>Description</span></td> 
						  <td width='100px'><span class='style4'>Warehouse</span></td> 
						  <td width='60px' align='center'><span class='style4'>Unit1</span></td>
						  <td width='80px' align='center'><span class='style4'>Qty</span></td>";
						  
				if ($Module_PurchaseRequestPrice==1) {		  
					echo" <td width='100px' align='center'><span class='style4'>Price</span></td>
						  <td width='80px' align='center'><span class='style4'>Disc(%)</span></td>
						  <td width='100px' align='center'><span class='style4'>Total</span></td>";
				}		  
				echo" </tr>";
				
				while($sub_rows=mysql_fetch_array($sub_result)){
					echo "<tr><td align='left' valign='top' class='style9'>".$sub_rows[2]."</td>
							  <td align='left' valign='top' class='style9'>".$sub_rows[3]."</td>
							  <td align='left' valign='top' class='style9'>".$sub_rows[4]."</td>
							  <td align='center' valign='top' class='style9'>".$sub_rows[5]."</td>
							  <td align='right' valign='top' class='style9'>".$sub_rows[6]."</td>";
					
					if ($Module_PurchaseRequestPrice==1) {
						if ($PurchaseTTC == 1) {
							echo" <td align='right' valign='top' class='style9'>".number_format($sub_rows[10],$DecimalBase)."</td>
								  <td align='right' valign='top' class='style9'>".number_format($sub_rows[8],$DecimalBase1)."</td>
								  <td align='right' valign='top' class='style9'>".number_format($sub_rows[11],$DecimalBase2)."</td>";
						} else {
							echo" <td align='right' valign='top' class='style9'>".number_format($sub_rows[7],$DecimalBase)."</td>
								  <td align='right' valign='top' class='style9'>".number_format($sub_rows[8],$DecimalBase1)."</td>
								  <td align='right' valign='top' class='style9'>".number_format($sub_rows[9],$DecimalBase2)."</td>";
						}
					}
					echo "</tr>";
						
				}
					
				echo "</table></div></td>";
				echo "</tr>";
			}
		
		}*/
}
	
	echo"</table></div></td><td id='search-content3' style='width:31px;'>&nbsp;</td></tr>";		
	
	
echo "<input type='hidden' name='i' value='$i'>";

//if (!empty($suppcode)) {
	echo"   <tr ><td id='search-content1' style='height:34px; width:31px;'>&nbsp;</td><td id='search-content2' style='height:34px; width:850px;' valign='top' align='center'>
	<button type='button' id='btnLoad' name='btnLoad' onclick='LoadData();return false;' title='Load'><span><span>Load</span></span></button>
	</td><td id='search-content3' style='height:34px; width:31px;'>&nbsp;</td>
	
	</tr>";
//}		
		

		
}	
	
echo"	<tr >
		<td id='search-bottom1' style='height:34px; width:31px;'>&nbsp;</td>
		<td id='search-bottom2' style='height:34px; width:908px;' valign='top'><table width='100%' border=0 height=28px>
		<tr><td style='width:380px;'>&nbsp;</td><td align='right' style='width:74px;border-right:1px solid #000000;'>";
		
			if($startrange > 0)
				echo"<img src='img/firstpage.png' title='First Page' onMouseOver=\"style.cursor='hand'\" onclick=SetFirstPage('".$startrange."','".$perpage."','".$category."')>";
				
		//$diff= $startrange - $perpage;
		
		if (($diff) >= 0 ){
			//$prvstartrange = $startrange - $perpage;
			echo"<img src='img/arrowleft.png' title='Previous' onMouseOver=\"style.cursor='hand'\"  onclick=SetPrvPage('".$prvstartrange."','".$perpage."','".$category."')>";
		}
		else
			echo "&nbsp;";
		
		echo"</td><td width='150' align='center'>";
		
		
		if ($startrange <= $totalrows){
			//$startrange = $startrange + $perpage;
			if  ($startrange1 < $totalrows){
				echo"<img src='img/arrowright.png' title='Next' onMouseOver=\"style.cursor='hand'\" onclick=SetNextPage('".$startrange1."','".$perpage."','".$category."')>";
				echo"&nbsp;&nbsp;<img src='img/lastpage.png' title='Last Page' onMouseOver=\"style.cursor='hand'\" onclick=SetLastPage('".$perpage."','".$totalrows."','".$category."')>";	
			}	
		} else
			echo "&nbsp;";
			
		echo"</td><td width='380'>&nbsp;</td></tr>";
		echo"</table></td><td id='search-bottom3' style='height:34px; width:31px;'>&nbsp;</td>";

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

	


          

		  

print <<<HERE

</form>
</body>

HERE;

?>