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

$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);
}
$fromdate   =$_POST["fromdate"];
$todate     =$_POST["todate"];

$querydate="select search_startingdate from setup";
$resultdate=mysql_query($querydate,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdate)){
	extract($rows);
}	
$MainCompanyName=explode('_',$_SESSION['dbName']); 
$QueryDir = " Select Date_Format(StartFinancialDate,'%d/%m/%Y') 
			From ".$_SESSION['dbLabel'].".Directories ". 	
			" Where  Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			" and Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
//echo $QueryDir;			
$ResultDir=mysql_query($QueryDir,$connection) or die(mysql_error());   
$RowsDir=mysql_fetch_row($ResultDir);
$StartFinancialDate = $RowsDir[0];


if ($fromdate == '') {
if ($search_startingdate == '-1') {
	$fromdate = $StartFinancialDate;
}

else if($search_startingdate == '0') {
	$fromdate = date('01/m/Y');
}

else if($querydate > '0') {
	$added_timestamp = strtotime('-'.$search_startingdate.' month', time());

	$fromdate = date('01/m/Y', $added_timestamp); 
}
}

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

if ($perpage == '' ) $perpage = $config['trowlimit'][0];

$querylog=" select ifNull(FI_ReturnDeliveryDel,0) As FI_ReturnDeliveryDel, ifNull(FI_ReturnDeliveryMod,0) As FI_ReturnDeliveryMod, ".
          " ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ".
		  " ifNull(ShowTransaction,0) As ShowTransaction, ifnull(FI_ReturnDeliveryConfirm,0) as FI_ReturnDeliveryConfirm ".
          " 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_Delivery,0) As Module_Delivery, ifNull(Module_DirectStock,0) As Module_DirectStock, ".
		     " 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, ".
             " ifNull(Module_PrintWaybill,0) As Module_PrintWaybill, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ifnull(Module_ConfirmDR,0) as Module_ConfirmDR ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


//Access Mode On Insert/Edit/Delete
$DelMode  = 1;
$EditMode =1;
$PrevMode = 1;

$PrevHint   = '';
$PrevHint1  = '';
$EditHint   = '';
$DelHint    = '';



$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ifNull(Setup_MultiLangPrint,0) as Setup_MultiLangPrint 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, ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, ".
			  " LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
              " 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];
if (empty($ledgerinclude)) $ledgerinclude = 0;

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

$PProjectCode = "".$PProjectCode;
$PCostCentCode = "".$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;

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">
<title>Search Return Delivery</title>
<script type="text/javascript" language="javascript">

function clearform()
{
  document.search.keyword.value='';
  document.search.PProjectCode.value='';
  document.search.PCostCentCode.value='';
  document.search.fromdate.value = '';
  document.search.todate.value = '';
  document.search.action='Form_ReturnDeliverySearch.php';
  document.search.submit();

}

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

function SetNextPage(startrange,perpage){ 

	document.search.action='Form_ReturnDeliverySearch.php?keyword=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}

function SetPrvPage(startrange,perpage){

	document.search.action='Form_ReturnDeliverySearch.php?keyword=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}


function DeleteRecord(RSaId, RSaRef){

	if (RSaId != '') {
		if (confirm ( "Are you sure you want to Delete this record with reference = "+RSaRef+" ?") )
		{
			document.search.action="Form_ReturnDelivery_Actions.php?mainmode=delete&SRSaId="+RSaId;
			document.search.submit();
		}
	}
	
}

function UpdateRecord(RSaId){
		
	document.search.action="Form_ReturnDelivery_Actions.php?mainmode=search&SRSaId="+RSaId;
	document.search.submit();
	
	document.search.PMode.value=1;
	
	
	
	//opener.document.returnsales.action='Form_ReturnDelivery.php';
	//opener.document.returnsales.submit();
	
	
	//self.close();
	

}
function PreviewReport(POption) {
	var str = '';
	var SaId = document.getElementById('SalesId').value;
	var JvId = document.getElementById('JournalId').value;
	
	var vLang = 'EN';
	var vReport = 1;

	if(document.search.chk.checked)
		var printlogo=1;
	else
		var printlogo=0;
	
	if (document.getElementsByName('lang')) {
		for (var i=0; i < document.search.lang.length; i++)
		{
			if (document.search.lang[i].checked)
			{
				vLang = document.search.lang[i].value;
			}
		}
	}

	if (document.getElementsByName('report')) {
		for (var i=0; i < document.search.report.length; i++)
		{
			if (document.search.report[i].checked)
			{
				vReport = document.search.report[i].value;
			}
		}
	}	
	 
	 
 
	if (SaId != '') {
		if (POption == 'PRV') {
			if (vReport == 1)
				str = 'Form_ReturnDeliveryPreview.php?ReturnSalesId='+SaId+'&PLang='+vLang+'&printlogo='+printlogo;
			else if (vReport == 2)
				str = 'Form_ReturnDeliveryWaybillPreview.php?ReturnSalesId='+SaId+'&PLang='+vLang+'&printlogo='+printlogo;
			else if (vReport == 3)
				str = 'Form_JournalPreview.php?journal_id='+JvId;
		}
		else if (POption == 'EXL') {
			if (vReport == 1)
				str = 'Form_ReturnDeliveryPreview.php?ReturnSalesId='+SaId+'&PLang='+vLang+'&PExportExcel=1';
		}
		
		window.open(str);
	} else {
		alert('Please click on an Return invoice.');
	}
	
}


function PrintPreview(RSaId)
{
	var str = '';
	if(document.search.chk.checked)
		var printlogo=1;
	else
		var printlogo=0;
	str = 'Form_ReturnDeliveryPreview.php?ReturnSalesId='+RSaId+'&printlogo='+printlogo;
	window.open(str);
	
	//self.close();

}

function PrintPreviewWaybill(RSaId)
{
	var str = '';
	
	str = 'Form_ReturnDeliveryWaybillPreview.php?ReturnSalesId='+RSaId;
	window.open(str);
	
	//self.close();

}

function PrintPreviewJournal(JvId)
{
	var str = '';
	
	str = 'Form_JournalPreview.php?journal_id='+JvId;
	window.open(str);
	
	//self.close();

}

function ChangeLocation()
{
	var x = document.search;
	var vRSaId = x.SelectedID.value;
	
    if (x.PMode.value == 1 && x.message.value == '') {
		opener.document.returnsales.txtRSaId.value=vRSaId;
		opener.document.returnsales.mainaction.value='edit';
		opener.document.returnsales.actionmode.value='';
	
		opener.document.returnsales.action='Form_ReturnDelivery.php';
		opener.document.returnsales.submit();
		self.close();
	} 
	
}


function SelectSearchBy()
{	

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

}

function SubmitForm()
{	

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

}

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 SelectRecord(Obj, SelectedRec, SelectedRecColor, Delivery_ID, Journal_ID){

	if (document.getElementById(SelectedRec).value=='')
	{
		document.getElementById(SelectedRec).value = Obj.id;
		document.getElementById(SelectedRecColor).value = Obj.style.backgroundColor;
	}	
	else {

		var prevobj = document.getElementById(SelectedRec).value;
		document.getElementById(prevobj).style.backgroundColor = document.getElementById(SelectedRecColor).value;

		document.getElementById(SelectedRec).value = Obj.id;
		document.getElementById(SelectedRecColor).value = Obj.style.backgroundColor;
	}	

	document.getElementById('SalesId').value = Delivery_ID;
	document.getElementById('JournalId').value = Journal_ID;
	document.getElementById(Obj.id).style.backgroundColor ='#B8EDFF';

}

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 RefreshPage()
{
   document.search.action='Form_ReturnDeliverySearch.php?startrange=0';
  document.search.submit();

}

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

function SetLastPage(perpage,totalrows){
	var result=totalrows % perpage;
	if (result == 0) result = perpage;
	startrange=totalrows-result;
	document.search.action='Form_ReturnDeliverySearch.php?startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}

function ConfirmDelivery(SRSaId, SrSaRef){

	var vMainMode = '';
	var vMsg = '';
	
	vMainMode = 'confirmreturndelivery'; 
	vMsg = 'Are you sure you want to Confirm Delivery with reference = '+SrSaRef+' ?';
	
	if (SRSaId != '') {
		if (confirm (vMsg) )
		{
			document.search.action="Form_ReturnDelivery_Actions.php?mainmode="+vMainMode+"&SRSaId="+SRSaId;
			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>
<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 onLoad='LoadForm();' class='bodybackground'>
<form name='search' method='post' action="">
<input type='hidden' name='SalesId' id='SalesId' value=''>
<input type='hidden' name='JournalId' id='JournalId' value=''>
<input type='hidden' name='message' value='$message' size='200'>
<input type='hidden' name='SelectedID' value='$SelectedID' size='200'>
<input type='hidden' name='SelectedRec' id='SelectedRec' value=''>
<input type='hidden' name='SelectedRecColor' id='SelectedRecColor' value=''>
HERE;


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

if (empty($ViewPeriodDate))
   $ViewPeriodDate = 'Null';
if (empty($ViewNumberOfDays))   
   $ViewNumberOfDays = 1;
			
$querysearch=" Select Distinct Deliveries.Delivery_ID, Deliveries.Delivery_Reference, Date_Format(Deliveries.Delivery_Date,'%d-%m-%Y') As Delivery_Date, ".
             " Deliveries.Client_Code As ClientCode, Clients.Ledger_name As ClientName, Deliveries.Currency_code, ".
			 " Project.Project_Name As ProjectName, Costcent.Costcent_name As CostcentName, Salesmen.Ledger_Name As SalesmanName, ".
			 " Round((ifNull(Deliveries.Delivery_Total,0) + ifNull(Deliveries.Delivery_VAT,0) - ifNull(Deliveries.Delivery_DiscountAmount,0) + ifNull(Deliveries.Delivery_TransportAmount,0) + ".
			 " (ifNull(Deliveries.Delivery_Tax1,0) + ifNull(Deliveries.Delivery_Tax2,0) + ifNull(Deliveries.Delivery_Tax3,0) + ifNull(Deliveries.Delivery_Tax4,0) + ifNull(Deliveries.Delivery_Tax5,0))), ".$DecimalBase.") As NetTotal,  ".
			 " if(ifNull(Deliveries.Delivery_Confirmed,0)=1, 'Confirmed', 'Unconfirmed') As Delivery_Status, ".
			 " ifNull(Temp_Deliveries.Delivery_Id, -1) As TempSalesId, Journal.Journal_ID, Journal.Journal_folio, Journal.Journal_refgovernment, Deliveries.Delivery_ReturnRef, ifNull(Deliveries.Delivery_Confirmed,0) as  Delivery_Confirmed, Deliveries.User_Account as USER_Account ".
			 " From Deliveries Left Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
			 " Left Join Project on Deliveries.Project_Code = Project.Project_Code ".
			 " Left Join Costcent on Deliveries.Costcent_code = Costcent.Costcent_code ".
			 " Left Join Salesmen on Deliveries.Salesman_Code = Salesmen.Ledger_Number ".
			 " Left Join Journal on Deliveries.Journal_ID = Journal.Journal_ID ".
			 " Left Join Temp_Deliveries on Temp_Deliveries.Delivery_ID = Deliveries.Delivery_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 Deliveries.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Deliveries.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 Deliveries.costcent_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Deliveries.costcent_code = Q2.costcent_code )) ";

if($ledgerinclude== 1 && $ledgerexist > 0) {
	$querysearch = $querysearch." And Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								"              where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								"              and (ledger_number is not null and ledger_number != '') ".
								"              and Deliveries.Client_Code like concat(ledgerstk.ledger_number,'%') ".
								"            ) ";
}
if($ledgerinclude== 0 && $ledgerexist > 0){
	$querysearch = $querysearch." And Not Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								"                  where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								"          	       and (ledger_number is not null and ledger_number != '') ".
								"                  and Deliveries.Client_Code like concat(ledgerstk.ledger_number,'%') ".
								"                ) ";	
}
							 
$querysearch= $querysearch.											 
			 " Where (($searchby = 2 and Deliveries.Delivery_Reference Like Concat(ifNull($PRef, Deliveries.Delivery_Reference),'%')) Or ".
			 "        ($searchby = 1 and Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d') = ifNull(Date_Format($PRef,'%Y-%m-%d'), Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d'))) Or  ".
			 "        ($searchby = 3 and (Deliveries.Client_Code Like Concat(ifNull($PRef, Deliveries.Client_Code),'%') or Clients.Ledger_name Like Concat('%', ifNull($PRef, Clients.Ledger_name),'%')) ) Or  ".
			 "        ($searchby = 4 and (Deliveries.Salesman_Code Like Concat(ifNull($PRef, Deliveries.Salesman_Code),'%') or Salesmen.Ledger_Name Like Concat('%', ifNull($PRef, Salesmen.Ledger_Name),'%')) ) Or  ".
			 "        ($searchby = 5 and Journal.Journal_folio Like Concat( ifNull($PRef, Journal.Journal_folio),'%')) Or ".
			 "        ($searchby = 6 and Journal.Journal_refgovernment Like Concat( ifNull($PRef, Journal.Journal_refgovernment),'%')) Or  ".
			 "        ($searchby = 7 and Deliveries.Delivery_ReturnRef Like Concat( ifNull($PRef, Deliveries.Delivery_ReturnRef),'%') ) ) ".
			 " And Deliveries.Journal_Type = 'DR' ".
			 " And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Deliveries.Delivery_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
             "                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ".
			 " And ifNull(Deliveries.Delivery_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
			 
if ($ShowTransaction != 1)
	$querysearch= $querysearch." And Upper(Deliveries.User_Account) = Upper('".$_SESSION['useraccount']."') ";
			 
if ($PProjectCode != '')
	$querysearch= $querysearch." And Deliveries.project_code like concat('".$PProjectCode."','%') ";
if ($PCostCentCode != '')
	$querysearch= $querysearch." And Deliveries.costcent_code like concat('".$PCostCentCode."','%') ";

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

if ($orderby == 1)
	$querysearch= $querysearch." Order By Deliveries.Delivery_Date Desc, Deliveries.Delivery_Reference Desc ";
else if ($orderby == 2)
	$querysearch= $querysearch." Order By Deliveries.Delivery_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());		


$FormTitle = 'List of Return Delivery';
if ($Module_Delivery == 0) $FormTitle = 'List of Return Sales';

echo"<table cellpadding='0' cellspacing='0' border='0'  align='left' style='table-layout:fixed' width='1060px'>";
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'>$FormTitle
			</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=20>
	  <col width=20>
	  <col width=65>
	  <col width=70>
	  <col width=65>
	  <col width=40>
	  <col width=40>
	  <col width=75>
	  <col width=125>
	  <col width=80>
	  <col width=80>
	  <col width=90>
	  <col width=55>
	  <col width=130>
	 
	  <tr class='Search-header-bg'>";
	  
if ($Module_Project == 1) {
	echo" <td align='left' colspan='4'><span class='style4'>Project</span></td>
	      <td align='left' colspan='4'><span class='style4'>
		    <input type='text' name='PProjectCode' id='PProjectCode' value='$PProjectCode' size='15' maxlength='20' onkeydown=\"return kd(event)\" /></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='8'><input type='hidden' name='PProjectCode' id='PProjectCode' value='$PProjectCode' /></td>";

}			

if ($Module_CostCenter == 1) {		  
	echo" <td align='left' colspan='2'><span class='style4'>Costcenter</span></td>		
		  <td align='left' colspan='2'><span class='style4'>
		    <input type='text' name='PCostCentCode' id='PCostCentCode' value='$PCostCentCode' size='15' maxlength='20' onkeydown=\"return kd(event)\" /></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='4'><input type='hidden' name='PCostCentCode' id='PCostCentCode' value='$PCostCentCode' /></td>";

}	  

echo"<td align='right' ><span class='style4'>Order By</span></td>		
		<td align='left' colspan='7' ><span class='style4'><select name='orderby' id='orderby' value='$orderby' onchange='RefreshPage();'>";
		
		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> &nbsp;&nbsp;&nbsp;<b>Print Logo</b><input type='checkbox' name='chk' id='chk' ></td>";

		 
		  
echo" </tr>";
echo" <tr class='Search-header-bg'>	  	  
	    <td align='left' colspan='4'><span class='style4'>Search By</span></td>
		<td align='left' colspan='7'><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';		
			else if ($searchby==5)
				$s25 = 'selected';
			else if ($searchby==6)
				$s26 = 'selected';	
			else if ($searchby==7)
				$s27 = 'selected';	
				
			echo"<option ".$s21." value='1'>Date (yyyy-mm-dd)</option>
				 <option ".$s22." value='2'>Reference</option>
				 <option ".$s23." value='3'>Client</option>
				 <option ".$s24." value='4'>Salesman</option>";
				 
				if ($Module_PostToJournal == 1) { 
					echo" <option ".$s25." value='5'>Folio</option>
						  <option ".$s26." value='6'>Jv Ref.</option>";
				} 
			
			echo" <option ".$s27." value='7'>Ret. Invoice 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>";
			
			
if ($Setup_MultiLangPrint == 1) {		
	echo"<td colspan='4'><span class='style4'>
			<input type='radio' name='lang' value='EN' checked>English
			<input type='radio' name='lang' value='FR'>French
			<input type='radio' name='lang' value='AR'>Arabic	
		</span>";
} else {
	echo"<td colspan='9'>&nbsp;";
}



		
echo" </tr>";
echo" <tr height = '23px' class='Search-header-bg'><td colspan = '9'><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>";
echo"<td colspan = '9'>
			<span class='style4'>
				<input type='radio' name='report' value='1' checked>Ret.Invoice
				<input type='radio' name='report' value='2'>Waybill
				<input type='radio' name='report' value='3'>Journal
			</span>
			<button type='button' id='btnPreview' name='btnPreview'  onclick=\"PreviewReport('PRV');\"  title='Preview Report'><span><span>Preview</span></span></button>
			<button type='button' id='btnPrint' name='btnPrint'  onclick=\"PreviewReport('PRT');\" title='Print Report'><span><span>Print</span></span></button>
			<button type='button' id='btnExcel' name='btnExcel'  onclick=\"PreviewReport('EXL');\" title='Generate Excel'><span><span>Excel</span></span></button>";
		echo" </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='70%' border=0>
		<tr>
		
			
		</td>
		
			<td align='right' style='width:120px;'><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."')>";

			$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>
		</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:1000px;'>
			<table border='0'  cellpadding='0' cellspacing='1' style='width:1215px;' >
		  <col width=20><col width=20>";
	if($FI_ReturnDeliveryConfirm == 1 && $Module_ConfirmDR == 1) 	  
		echo "<col width=20>";
	echo "<col width=20><col width=20><col width=20><col width=65>
		  <col width=90><col width=65>
		  <col width=70><col width=70>
		  <col width=100><col width=250>
		  <col width=80><col width=80>
		  <col width=90><col width=55><col width=100>";
	
		  
	if($message!=''){
		echo" <tr class='Search-header-bg'>
				<td height='15' align='center' colspan='17' 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> ";
	
	if($FI_ReturnDeliveryConfirm == 1 && $Module_ConfirmDR == 1) 	
		echo "<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>";
	echo "<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='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'>Ret.Invoice Ref. </span></td>";

	if ($Module_PostToJournal == 1) {	
		echo" <td  height='25' align='center'><span class='style4'>Folio </span></td>
			  <td  height='25' align='center'><span class='style4'>JV Ref. </span></td>";
	} else {
		echo" <td  height='25' align='center' colspan='2'>&nbsp;</td>";
	}

echo"		
		<td  height='25' align='center'><span class='style4'>Client</span></td>
		<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
		<td  height='25' align='center'><span class='style4'>Project</span></td>";
		
		if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
			echo"<td  height='25' align='center'><span class='style4'>CostCenter</span></td>
			     <td  height='25' align='center'><span class='style4'>Salesman</span></td>
				 <td  height='25' align='center'><span class='style4'>Currency</span></td>
				 <td  height='25' align='center'><span class='style4'>Total</span></td>";
		} else {
			echo"<td  height='25' align='center' colspan='2'><span class='style4'>CostCenter</span></td>
				 <td  height='25' align='center' colspan='2'><span class='style4'>Salesman</span></td>";
		}	
		echo "<td  height='25' align='center'><span class='style4'>User Account</span></td>";
	  echo"</tr>";
		

	

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

	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
		
		

	$PrevHint   = 'Preview Ret.Invoice';
	$PrevHint1  = 'Preview Waybill';
	$EditHint   = 'Edit Record';
	$DelHint    = 'Delete Record';
	$ConfHint   = 'Confirm Return Delivery';
	if ($TempSalesId != -1) {$PrevHint=$PrevHint1=$EditHint=$DelHint =$ConfHint = 'Exists in Pending';}
	
    if ($FI_ReturnDeliveryMod == 0)	$EditMode = 0; 
	else if ($FI_ReturnDeliveryMod == 1 && $TempSalesId != -1) $EditMode = 0;
	else if ($FI_ReturnDeliveryMod == 1 && $TempSalesId == -1) $EditMode =1;
	
	if ($FI_ReturnDeliveryDel == 0)	$DelMode =0; 
	else if ($FI_ReturnDeliveryDel == 1 && $TempSalesId != -1) $DelMode =0;
	else if ($FI_ReturnDeliveryDel == 1 && $TempSalesId == -1) $DelMode =1;
	
	
	
	if ($TempSalesId != -1) $PrevMode = 0; else $PrevMode =1;		
	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($Delivery_Date))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($Delivery_Date)) >= $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	
	if ($ExceedLockPeriod == 1){
		$EditMode = 0;
		$DelMode = 0;
	}
	
		   
	echo"<tr  onMouseOver=\"style.cursor='pointer'\"  id='row$ct' onclick=\"SelectRecord(this,'SelectedRec','SelectedRecColor','".$Delivery_ID."','".$Journal_ID."')\"  ".$Color.">";
	
		if($EditMode==1)	
			echo'<td align="center"><span class="style5"><img src="img/edit.png" onMouseOver="style.cursor=\'hand\'" onclick="UpdateRecord('.$Delivery_ID.');" title="'.$EditHint.'" style="width: 20px; height: 20px; "></span></td>';
		else echo'<td align="center">&nbsp;</td>';	
			
		if($DelMode==1)	
			echo'<td align="center"><span class="style5"><img src="img/delete.png" onMouseOver="style.cursor=\'hand\'" onclick="DeleteRecord('.$Delivery_ID.', \''.$Delivery_Reference.'\');" title="'.$DelHint.'" style="width: 20px; height: 20px; "></span></td>';
		else echo'<td align="center">&nbsp;</td>';		
	
	if($FI_ReturnDeliveryConfirm == 1 && $Module_ConfirmDR == 1 && $Delivery_Confirmed == 0 &&  $TempSalesId == -1) 	
		echo'<td align="center"><span class="style5"><img src="img/confirmorder.png" onMouseOver="style.cursor=\'hand\'" onclick="ConfirmDelivery('.$Delivery_ID.', \''.$Delivery_Reference.'\');" title="'.$ConfHint.'"  style="width: 18px; height: 18px; "  ></span></td>';
	else echo'<td align="center">&nbsp;</td>';	
	
	if ((($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) || $Module_Delivery == 1) && $PrevMode==1)
		echo'<td align="center"><span class="style5"><img src="img/print.png" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreview('.$Delivery_ID.');"  title="'.$PrevHint.'" style="width: 15px; height: 15px; "></span></td>';
	else
		echo'<td align="center">&nbsp;</td>';	
			
	if ($Module_Delivery == 0 && $Module_PrintWaybill == 1 && $PrevMode==1)		
		echo'<td align="center"><span class="style5"><img src="img/mag.jpg" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreviewWaybill('.$Delivery_ID.');"  title="'.$PrevHint1.'" style="width: 15px; height: 15px; " ></span></td>';
	else
		echo'<td align="center">&nbsp;</td>';
	
	if ($PrevMode==1)
		echo'<td align="center"><span class="style5"><img src="img/print-green-icon.png" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreviewJournal('.$Journal_ID.');"  title="Print Journal" style="width:18px; height:18px;" ></span></td>';
	else
		echo'<td align="center">&nbsp;</td>';	
			
	echo'		
			<td align="left"><span class="style5">'.$Delivery_Reference.'</span></td>
			<td align="center"><span class="style5">'.$Delivery_Date.'</span></td>
			<td align="center"><span class="style5">'.$Delivery_ReturnRef.'</span></td>';
			
		if ($Module_PostToJournal == 1) {		
			echo' <td align="center"><span class="style5">'.$Journal_folio.'</span></td>
			      <td align="center"><span class="style5">'.$Journal_refgovernment.'</span></td>';
		} else {
			echo" <td align='center' colspan='2'>&nbsp;</td>";
		}
		
	echo'	<td align="center"><span class="style5">'.$ClientCode.'</span></td>
			<td align="left"><span class="style5">'.$ClientName.'</span></td>
			<td align="left"><span class="style5">'.$ProjectName.'</span></td>';
			
			if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
				echo'<td align="left"><span class="style5">'.$CostcentName.'</span></td>
				     <td align="left"><span class="style5">'.$SalesmanName.'</span></td>
					 <td align="center"><span class="style5">'.$Currency_code.'</span></td>
					 <td align="right"><span class="style5">'.number_format($NetTotal, $DecimalBase).'</span></td>';
			} else {
				echo'<td align="left" colspan="2"><span class="style5">'.$CostcentName.'</span></td>
				     <td align="left" colspan="2"><span class="style5">'.$SalesmanName.'</span></td>';
			}	
		echo '<td align="left"><span class="style5">'.$USER_Account.'</span></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:920px;' 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."')>";
				
		//$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."')>";
		}
		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."')>";
				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 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;
}
?>