<?php

session_start();
if($_SESSION['dbName']==""){
header("location:../index.php");
}


include("config.inc.php");
include("function.inc.php");
include("Functions_Trans.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");

$fromdate   =$_POST["fromdate"];
$todate     =$_POST["todate"];

if ($fromdate == '')
	$fromdate = date('01/m/Y');

if ($todate == '')
	$todate =  date('d/m/Y');


$querylog=" select ifNull(FI_ReturnGrnDel,0) As FI_ReturnGrnDel, ifNull(FI_ReturnGrnMod,0) As FI_ReturnGrnMod, ifNull(FI_ReturnGrnApp,0) As FI_ReturnGrnApp, ".
          " ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(ShowTransaction,0) As ShowTransaction ".
		  " 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_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}




$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2 from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
extract($rowsetup);
}

$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);		  

$queryledger= " select distinct ledger_number, ledger_include ".
              " from ".$_SESSION['dbLabel'].".ledgerstk  ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " and (ledger_number is not null and ledger_number != '') ".
			  " order by ledger_number";
$ledgerresult = mysql_query($queryledger,$connection) or die(mysql_error());
$ledgerexist  = mysql_num_rows($ledgerresult);	
$rows=mysql_fetch_array($ledgerresult) ;
$ledgerinclude = $rows[1];

$querylog="select ifNull(FI_PurchaseCategory,0) As FI_PurchaseCategory 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);
}

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


$PurType 	= $_POST['PurType']; if ($PurType == ""){$PurType = $_GET["PurType"];}
$PMode    	= $_POST['PMode']; if ($PMode == ""){$PMode = $_GET["PMode"];}
$message    = $_POST['message']; if ($message == ""){$message = $_GET["message"];}
$keyword    = $_POST['keyword']; if ($keyword == ""){$keyword = $_GET["keyword"];}
$searchby   = $_POST['searchby']; if ($searchby == ""){$searchby = $_GET["searchby"];}
$orderby    = $_POST['orderby']; if ($orderby == ""){$orderby = $_GET["orderby"];}
$perpage    = $_POST['perpage']; if ($perpage == ""){$perpage = $_GET["perpage"];}
$startrange = $_POST['startrange']; if ($startrange == ""){$startrange = $_GET["startrange"];}
$category   = $_POST['category']; if ($category == ""){$category = $_GET["category"];}
$PProjectCode 	= $_POST['PProjectCode']; if ($PProjectCode == ""){$PProjectCode = $_GET["PProjectCode"];}
$PCostCentCode	= $_POST['PCostCentCode']; if ($PCostCentCode == ""){$PCostCentCode = $_GET["PCostCentCode"];}



if ((!isset($PProjectCode)) && $Module_Project == 1)
	$PProjectCode = $defaultproject;
if ((!isset($PCostCentCode)) && $Module_CostCenter == 1)	
	$PCostCentCode = $defaultcostcent;	

if (empty($orderby))  $orderby = 1;
if (empty($searchby)) $searchby = 2;
if ($startrange=='')  $startrange = 0;
if ($perpage=='')	  $perpage = 20;

if (empty($category)) $category = $FI_PurchaseCategory;
if (empty($category)) $category = 0;

$CategoryMode = '';
if ($FI_PurchaseCategory != 0) $CategoryMode = ' disabled ';

$Title = '';
$Title = 'List of Return Goods Receive Note';


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 Goods Receive Note</title>
<script type="text/javascript" language="javascript">

function clearform()
{
  document.search.keyword.value='';
  document.search.category.value='';
  document.search.PProjectCode.value='';
  document.search.PCostCentCode.value='';
  document.search.fromdate.value = '';
  document.search.todate.value = '';

  document.search.action='Form_RetGoodRecNoteSearch.php';
  document.search.submit();

}

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

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

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



function DeleteRecord(PurId, PurRef){
	
	if (PurId != '') {
		if (confirm ( "Are you sure you want to Delete this record with reference = "+PurRef+" ?") )
		{
			document.search.action="Form_RetGoodRecNote_Actions.php?mainmode=delete&SPurId="+PurId;
			document.search.submit();
		}
	}
	
}

function UpdateRecord(PurId){
	
	document.search.action="Form_RetGoodRecNote_Actions.php?mainmode=search&SPurId="+PurId;
	document.search.submit();
	
	document.search.PMode.value=1;
	
	opener.document.purchase.txtPurId.value=PurId;
	opener.document.purchase.mainaction.value='edit';
	opener.document.purchase.actionmode.value='';
	
	//opener.document.purchase.action='Form_RetGoodRecNote.php';
	//opener.document.purchase.submit();
	
	
	//self.close();
	

}

function PrintPreview(PurId)
{
	var str = '';
	var vPrtSer     = 0;
	
	
	if (confirm ( "Do you want to Print this Return GRN with Serial No ?","Yes","No") )
	{
		vPrtSer = 1;
	}
	
	str = 'Form_RetGoodRecNotePreview.php?PurchaseId='+PurId+'&PrtSer='+vPrtSer;
	window.open(str);

}

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

function ChangeLocation()
{
	
    if (document.search.PMode.value == 1) {
		opener.document.purchase.action='Form_RetGoodRecNote.php';
		opener.document.purchase.submit();
		self.close();
	}	
}

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

}

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

}

function SelectSearchBy()
{	

  //document.search.keyword.value='';
  //document.search.action='Form_RetGoodRecNoteSearch.php?startrange=0';
  document.search.submit();

}

function SubmitForm()
{	

  //document.search.keyword.value='';
  document.search.action='Form_RetGoodRecNoteSearch.php?startrange=0';
  document.search.submit();

}

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

}

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

function showlistProject(str){

  window.open('List_SorProject.php?frm=6&item='+str,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(str){

  window.open('List_SorCostcenter.php?frm=6&item='+str,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function SetFirstPage(startrange,perpage,category){
	document.search.action='Form_RetGoodRecNoteSearch.php?startrange=0&perpage='+perpage+'&category='+category;
	document.search.submit();
}

function SetLastPage(perpage,totalrows,category){
	var result=totalrows % perpage;
	if (result == 0) result = perpage;
	startrange=totalrows-result;
	document.search.action='Form_RetGoodRecNoteSearch.php?startrange='+startrange+'&perpage='+perpage+'&category='+category;
	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='PurType' value='$PurType'>
HERE;

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

if (empty($ViewPeriodDate))
   $ViewPeriodDate = 'Null';
if (empty($ViewNumberOfDays))   
   $ViewNumberOfDays = 1;
			
$querysearch=" Select Distinct GrnPurchases.Purchase_ID, GrnPurchases.Purchase_Reference, Date_Format(GrnPurchases.Purchase_Date,'%d-%m-%Y') As Purchase_Date, ".
             " GrnPurchases.Supplier_code As SupplierCode,	Suppliers.Ledger_name As SupplierName, GrnPurchases.Currency_code, ".
			 " Project.Project_Name As ProjectName, Costcent.Costcent_name As CostcentName, ".
			 " ifNull(Temp_GrnPurchases.Purchase_ID, -1) As TempPurchaseId, ifNull(GrnPurchases.Purchase_Type,'PI') As PurchaseType, ".
			 " GrnPurchases.Purchase_ReturnRef ".
			 " From GrnPurchases Left Join Suppliers on GrnPurchases.Supplier_code = Suppliers.Ledger_Number ".
			 " Left Join Project on GrnPurchases.Project_Code = Project.Project_Code ".
			 " Left Join Costcent on GrnPurchases.Costcent_code = Costcent.Costcent_code ".
			 " Left Join Temp_GrnPurchases on Temp_GrnPurchases.Purchase_ID = GrnPurchases.Purchase_ID ";
			 
if ($projectexist >	0)
  $querysearch= $querysearch." Inner 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 (($Module_ProjectParent=1 and GrnPurchases.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and GrnPurchases.project_code = Q1.project_code )) ";
							 
if ($costcentexist > 0)
  $querysearch= $querysearch." Inner 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 (($Module_CostCenterParent=1 and GrnPurchases.costcent_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and GrnPurchases.costcent_code = Q2.costcent_code )) ";

if ($ledgerexist > 0)
  $querysearch= $querysearch." Inner join ( select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk ".
							 "			    where user_account='".$_SESSION['useraccount']."' ".
							 "              and (ledger_number is not null and ledger_number != '') ".
							 "			 )  Q3 on (($ledgerinclude = 1 and GrnPurchases.Supplier_code like concat(Q3.ledger_number,'%') ) or ($ledgerinclude = 0 and GrnPurchases.Supplier_code Not like concat(Q3.ledger_number,'%') ) or GrnPurchases.Supplier_code is null) ";							 

							 
/*if ($ledgerexist > 0)
  $querysearch= $querysearch." And (($ledgerinclude = 1 and GrnPurchases.Supplier_code In (select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk where user_account='".$_SESSION['useraccount']."') ) Or ".
                             "      ($ledgerinclude = 0 and GrnPurchases.Supplier_code Not In (select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk where user_account='".$_SESSION['useraccount']."') ) ) ";      
*/
							 
$querysearch= $querysearch.											 
			 " Where (($searchby = 2 and GrnPurchases.Purchase_Reference Like Concat(ifNull($PRef, GrnPurchases.Purchase_Reference),'%')) Or ".
			 "        ($searchby = 1 and Date_Format(GrnPurchases.Purchase_Date,'%Y-%m-%d') = ifNull(Date_Format($PRef,'%Y-%m-%d'), Date_Format(GrnPurchases.Purchase_Date,'%Y-%m-%d'))) Or  ".
			 "        ($searchby = 3 and (GrnPurchases.Supplier_code Like Concat(ifNull($PRef, GrnPurchases.Supplier_code),'%') or Suppliers.Ledger_name Like Concat('%', ifNull($PRef, Suppliers.Ledger_name),'%')) ) Or  ".
			 "        ($searchby = 4 and GrnPurchases.Purchase_ReturnRef Like Concat( ifNull($PRef, GrnPurchases.Purchase_ReturnRef),'%') ) ) ".
			 " And GrnPurchases.Journal_Type = 'PR' ".
			 //" And ifNull(GrnPurchases.Purchase_Grn,0) = 1 ".
			 " And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(GrnPurchases.Purchase_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',GrnPurchases.Purchase_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
             "                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(GrnPurchases.Purchase_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ".
			 " And (($category = 1 and ifNull(GrnPurchases.Purchase_Import,0)=0 ) or ($category = 2 and ifNull(GrnPurchases.Purchase_Import,0)=1 ) or ($category = 0 and 1=1) ) ".
			 " And ifNull(GrnPurchases.Purchase_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
			 
if ($ShowTransaction != 1)
	$querysearch= $querysearch." And Upper(GrnPurchases.User_Account) = Upper('".$_SESSION['useraccount']."') ";
			 
if ($PProjectCode != '')
	$querysearch= $querysearch." And GrnPurchases.project_code like concat('".$PProjectCode."','%') ";
if ($PCostCentCode != '')
	$querysearch= $querysearch." And GrnPurchases.costcent_code like concat('".$PCostCentCode."','%') ";	

if ($fromdate != '' && $todate !='' )
	$querysearch = $querysearch." And Date_Format(GrnPurchases.Purchase_Date,'%Y-%m-%d') between '".explodeword($fromdate)."' and '".explodeword($todate)."' ";
			 

if ($orderby == 1)
	$querysearch= $querysearch." Order By GrnPurchases.Purchase_Date Desc, GrnPurchases.Purchase_Reference Desc ";
else if ($orderby == 2)
	$querysearch= $querysearch." Order By GrnPurchases.Purchase_Reference Desc ";	
	
			 
//echo $querysearch;			 

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

		
$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='950px'>";
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'>$Title
			</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=25>
	  <col width=20>
	  <col width=20>
	  <col width=80>
	  <col width=90>
	  <col width=80>
	  <col width=95>
	  <col width=160>
	  <col width=140>
	  <col width=165>

	  <tr class='Search-header-bg'>";
	  
if ($Module_Project == 1) {
	echo" <td align='left' colspan='3'><span class='style4'>Project</span></td>
	      <td align='left' colspan='3'><span class='style4'>
		    <input type='text' name='PProjectCode' id='PProjectCode' value='$PProjectCode' size='15' maxlength='15' /></span>
		    <label><span class='style4'><img src='img/btnopen.jpg' title=' Select Project ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
} else {
	echo" <td align='left' colspan='6'><input type='hidden' name='PProjectCode' id='PProjectCode' value='$PProjectCode' /></td>";

}			

if ($Module_CostCenter == 1) {		  
	echo" <td align='right'><span class='style4'>Costcenter</span></td>		
		  <td align='left'><span class='style4'>
		    <input type='text' name='PCostCentCode' id='PCostCentCode' value='$PCostCentCode' size='17' maxlength='15' /></span>
		    <label><span class='style4'><img src='img/btnopen.jpg' title=' Select Costcenter ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
			
} else {
	echo" <td align='left' colspan='2'><input type='hidden' name='PCostCentCode' id='PCostCentCode' value='$PCostCentCode' /></td>";

}	  
echo" <td align='right' valign='center' ><span class='style4'>Category</span>
		<span class='style4'><select name='category' id='category' value='$category' onchange='SelectCategory();' $CategoryMode>";
		
		if ($category==0 || $category=='')
			$s1 = 'selected';
		else if ($category==1)
			$s2 = 'selected';
		else if ($category==2)
			$s3 = 'selected';
			
		echo"<option ".$s1." value='0'>All</option>
			 <option ".$s2." value='1'>Local</option>
			 <option ".$s3." value='2'>Export</option>
			 </select></span></td>";

echo" <td align='right' colspan='2'><span class='style4'>Order By</span>		
		<span class='style4'><select name='orderby' id='orderby' value='$orderby' onchange='SelectOrderBy();'>";
		
		if ($orderby==1)
			$s11 = 'selected';
		else if ($orderby==2)
			$s12 = 'selected';
			
		echo"<option ".$s11." value='1'>Date</option>
			 <option ".$s12." value='2'>Reference</option>
			 </select></span></td>";
  
echo" </tr>
	  <tr class='Search-header-bg'>	  
	    <td align='left' colspan='3'><span class='style4'>Search By</span></td>
		<td align='left' colspan='8'><span class='style4'><input type='text' name='keyword' id='keyword' value='$keyword' size='15' maxlength='30' onkeydown='return kd(event)'/><input type='hidden' name='PMode' id='PMode' value='$PMode' size='15' maxlength='30'/></span>
			
			<select name='searchby' id='searchby' value='$searchby' onchange='SelectSearchBy();'>";
		
			if ($searchby==1)
				$s21 = 'selected';
			else if ($searchby==2)
				$s22 = 'selected';
			else if ($searchby==3)
				$s23 = 'selected';
			else if ($searchby==4)
				$s24 = 'selected';
				
			echo"<option ".$s21." value='1'>Date (yyyy-mm-dd)</option>
				 <option ".$s22." value='2'>Reference</option>
				 <option ".$s23." value='3'>Supplier</option>
				 <option ".$s24." value='4'>Grn Ref.</option>
				 </select>";	
				 
echo"	     <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' height='23px'>
<td colspan='11'><span class='style4'>From&nbsp;</span><input type='text' name='fromdate' id='fromdate' value='$fromdate' maxlength='10' size='9'>
		<A HREF=\"#\" onClick=\"displayCalendar(document.search.fromdate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span>
&nbsp; &nbsp;<span class='style4'>To&nbsp;</span><input type='text' name='todate' id='todate' value='$todate' maxlength='10' size='9'>
		<A HREF=\"#\" onClick=\"displayCalendar(document.search.todate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span></td>
</tr>
</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();\">";
              
            $perpages = $config['trowlimit'];
			foreach ($perpages as $val){
			echo" <option value = '$val' "; if ($perpage ==$val) echo "selected"; 
			echo" >$val</option> ";
			}
	echo'	
				 </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."','".$category."')>";

			$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."','".$category."')>";
			}
			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."','".$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 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:870px;'>
			<table border='0'  cellpadding='0' cellspacing='1' style='width:930px;'>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=80>
	  <col width=90>
	  <col width=80>
	  <col width=100>
	  <col width=200>
	  <col width=150>
	  <col width=150>";
	  
	if($message!=''){
		echo"<tr class='Search-header-bg'>
				<td height='15' align='center' colspan='11' 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='center'><span class='style4'>&nbsp;</span></td>
			<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
			<td  height='25' align='center'><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'>Grn Ref. </span></td>
			<td  height='25' align='center'><span class='style4'>Supplier</span></td>
			<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
			<td  height='25' align='center'><span class='style4'>Project</span></td>
			<td  height='25' align='center'><span class='style4'>CostCenter</span></td>
		</tr>";
		


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

	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
			
	
	//Access Mode On Insert/Edit/Delete
	$PurDelMode =1;
	$PurEditMode =1;
	$PurPrevMode =1;

	$PrevHint = 'Preview';
	$EditHint = 'Edit Record';
	$DelHint  = 'Delete Record';
	
	if ($TempPurchaseId != -1) {$PrevHint=$EditHint=$DelHint = 'Exists in Pending';}

	if ($FI_ReturnGrnMod == 0)	$PurEditMode =0; 
	else if ($FI_ReturnGrnMod == 1 && $TempPurchaseId != -1)   $PurEditMode =0; 
	else if ($FI_ReturnGrnMod == 1 && $TempPurchaseId == -1)   $PurEditMode =1;
		
	if ($FI_ReturnGrnDel == 0)	$PurDelMode =0; 
	else if ($FI_ReturnGrnDel == 1 && $TempPurchaseId != -1)  $PurDelMode =0;
	else if ($FI_ReturnGrnDel == 1 && $TempPurchaseId == -1)  $PurDelMode =1;
	
	if ($TempPurchaseId != -1) $PurPrevMode = 0; else $PurPrevMode =1;
	
	echo'<tr '.$Color.'>';
	
	if($PurPrevMode==1)
	    echo'<td align="center"><span class="style5"><img src="img/mag.jpg" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreview('.$Purchase_ID.');"  title="'.$PrevHint.'"  style="width: 15px; height: 15px; "></span></td>';
	else 
		echo'<td align="center">&nbsp;</td>';	
			
	if($PurEditMode==1)	
		echo'<td align="center"><span class="style5"><img src="img/edit.png" onMouseOver="style.cursor=\'hand\'" onclick="UpdateRecord('.$Purchase_ID.');" title="'.$EditHint.'"  style="width: 20px; height: 20px; "></span></td>';
	else 
		echo'<td align="center">&nbsp;</td>';		
		
	if($PurDelMode==1)	
		echo'<td align="center"><span class="style5"><img src="img/delete.png" onMouseOver="style.cursor=\'hand\'" onclick="DeleteRecord('.$Purchase_ID.', \''.$Purchase_Reference.'\');" title="'.$DelHint.'" style="width: 20px; height: 20px; "></span></td>';
	else 
		echo'<td align="center">&nbsp;</td>';	

	echo'	<td align="center"><span class="style5"><img src="img/details.gif" onMouseOver="style.cursor=\'hand\'"  onclick="ShowHideDetails('.$Purchase_ID.', \''.'S'.'\','.$startrange.');" title="Show Details" style="width:15px; height:15px; "></span></td>';
			
	echo'	<td align="left"><span class="style5">'.$Purchase_Reference.'</span></td>
			<td align="center"><span class="style5">'.$Purchase_Date.'</span></td>
			<td align="center"><span class="style5">'.$Purchase_ReturnRef.'</span></td>
			<td align="center"><span class="style5">'.$SupplierCode.'</span></td>
			<td align="left"><span class="style5">'.$SupplierName.'</span></td>
			<td align="left"><span class="style5">'.$ProjectName.'</span></td>
			<td align="left"><span class="style5">'.$CostcentName.'</span></td>
		</tr>';
		
		
	$sub_query = " Select GrnPurchasesDt.PurchaseDt_ID, GrnPurchasesDt.Item_CodePacked, GrnPurchasesDt.Item_code, Item_Description, GrnPurchasesDt.Warehouse_Code, ".
				 " Item_UnitPurchaseDesc, PurchaseDt_Quantity, Round(PurchaseDt_Price, ".$DecimalBase."), Round(PurchaseDt_DiscountPer, ".$DecimalBase."),  ".
				 " Round(((PurchaseDt_Quantity*PurchaseDt_Price)-((PurchaseDt_Quantity*PurchaseDt_Price*ifNull(PurchaseDt_DiscountPer,0))/100)), ".$DecimalBase.") As Total, ".
				 " Round(PurchaseDt_PriceTTC, ".$DecimalBase."), ".
				 " Round(((PurchaseDt_Quantity*PurchaseDt_PriceTTC)-((PurchaseDt_Quantity*PurchaseDt_PriceTTC*ifNull(PurchaseDt_DiscountPer,0))/100)), ".$DecimalBase.") As TotalTTC ".
				 " From GrnPurchasesDt Left Join Items on GrnPurchasesDt.Item_code = Items.Item_code ".
				 " Where GrnPurchasesDt.Purchase_ID = ".$Purchase_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'.$Purchase_ID;
			
		echo "<tr ".$Color.">";
		echo "<td colspan='11' valign='top' align='left'><div id='$SlideDivId' class='div-search-details' style='display:none; margin-left:85px;'>";
		echo "<table border='0' style='table-layout:fixed; width:620px;' cellpadding='0' cellspacing='1'>";
		echo "<tr><td width='140px'><span class='style4'>Item Code</span></td>
				  <td width='240px'><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>
			 </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>";
  			echo "</tr>";
				
		}
			
		echo "</table></div></td>";
		echo "</tr>";
	}	
}
							
			
		
echo"</table></div></td><td id='search-content3' style='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:850px;' valign='top'><table width='100%' border=0 height=28px>
		<tr><td style='width:280px;'>&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='left'>";
		
		
		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='170'>&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;

function explodeword($date)
{

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}

?>