<?php

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


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

$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(FI_FrmRestrictWarehouse,0) As FI_FrmRestrictWarehouse ".
          " 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 from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
extract($rowsetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_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);
}


//Read From Module Table
$querymodule="Select ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ifNull(Module_Delivery,0) As Module_Delivery  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";
$whresult = mysql_query($querywh,$connection) or die(mysql_error());
$whexist  = mysql_num_rows($whresult);	  

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


//Get Default Project
$querydflproject="select project_code as defaultproject from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_project=1 ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}
	
//Get Default Coscenter
$querydflcostcent="select costcent_code as defaultcostcent from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_costcenter=1 ";
$resultdflcostcent=mysql_query($querydflcostcent,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflcostcent)){
	extract($rows);
}

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

if (empty($searchby)) $searchby = 2;	
					   
if ($PSaClientCode != '' && $PSaId != '') {

	$queryitems = " Select Items.Item_Code, Items.Item_description,  ".
	              " ifNull(DeliveryDt.DeliveryDt_Quantity,0) - (Sum(ifNull(SalesDt.SaleDt_Quantity,0)) + Sum(ifNull(Temp_SalesDt.SaleDt_Quantity,0))) As QuantityRemaining ".
				  " From DeliveryDt ".
				  " Left Join Items on DeliveryDt.Item_code = Items.Item_code ".
				  " Left Join SalesDt on (SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_id And SalesDt.Journal_Type = 'SI' And SalesDt.Sale_Id != '".$PSaId."') ".
				  " Left Join Temp_SalesDt on (Temp_SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_id And Temp_SalesDt.Journal_Type = 'SI') ".
				  " Left Outer Join DeliveryDt DR on DeliveryDt.DeliveryDt_ID = DR.RelatedDt_ID  and  DR.Journal_Type = 'DR' ";
				  
	if ($whexist > 0 && $FI_FrmRestrictWarehouse == 1)
		$queryitems = $queryitems.  " Inner join ( select distinct loginstk.warehouse_code from ".$_SESSION['dbLabel'].".loginstk ".
									" 				where loginstk.user_account='".$_SESSION['useraccount']."' ".
									" 				and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
									"			 ) Q1 on DeliveryDt.warehouse_code = Q1.warehouse_code ";

	$queryitems = $queryitems.
				  " Where ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0  ".
				  " And (('".$PSaClientCode."' != '' and DeliveryDt.Client_Code = '".$PSaClientCode."') or ('".$PSaClientCode."' = '' and 1 = 1)) ".
				  " And ifNull(Item_Pack,0) = 0 ".
				  " Group By DeliveryDt.Item_code ".
				  " Having QuantityRemaining > 0 ".
				  " Order By Items.Item_Code  ";

} else
{
	$queryitems = " Select Item_Code, Item_description From Items Where ifNull(Item_Pack,0) = 0 Order By Item_Code ";
}
	
$resultitems= mysql_query($queryitems,$connection) or die(mysql_error());

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 Deliveries</title>
<script type="text/javascript" language="javascript">
HERE;

if ($config['SalesLoadRefresh'] != '')
	echo"setInterval(function(){window.location.reload(true)},".$config['SalesLoadRefresh'].");";

print <<<HERE
function RefreshPage()
{
  document.search.submit();

}

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

}

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

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

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



function SelectRecord(RecordId){
	var vSaID = document.search.PSaId.value;
	
	document.search.PMode.value=1;	
	document.search.action="Form_Sales_Actions.php?mainmode=loaddelivery&SSaId="+vSaID+"&SelectedRec="+RecordId;
	document.search.submit();
	
	
	
	/*opener.document.sales.txtSaId.value=RecordId;
	opener.document.sales.mainaction.value='insert';
	opener.document.sales.actionmode.value='';
	
	
	
	self.close();*/
	

}

function LoadData(){
	var vSelectedRows = document.search.SelectedRows.value;
	
	if (vSelectedRows != '') {
		var vSaID = document.search.PSaId.value;
		document.search.PMode.value=1;	
		document.search.action="Form_Sales_Actions.php?mainmode=loaddelivery&SSaId="+vSaID+"&SSaDtId="+vSelectedRows;
		document.search.submit();
	} else
		alert ('Please Select an Item.');
	
}

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

function ChangeLocation()
{
    if (document.search.PMode.value == 1) {
	    var vSaId = document.search.PSaId.value;
		
		opener.document.sales.txtSaId.value=vSaId;
	    opener.document.sales.mainaction.value='';
		opener.document.sales.actionmode.value='submitrecord';
		opener.document.sales.message.value = document.search.message.value;
		opener.document.sales.action='Form_Sales.php';
		opener.document.sales.submit();
		self.close();
	}	
}

function SelectMaster(vName) {

   
   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() {
	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 SelectSearchBy()
{	
  //document.search.keyword.value='';
  document.search.action='Form_Sales_LoadDelivery.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 SetFirstPage(startrange,perpage){
	document.search.action='Form_Sales_LoadDelivery.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_Sales_LoadDelivery.php?startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}

function SubmitForm()
{	

  //document.search.keyword.value='';
  document.search.action='Form_Sales_LoadDelivery.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}

.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='GeneratedId' value='$GeneratedId'>
<input type='hidden' name='SelectedRows' value='$SelectedRows'>

<input type='hidden' name='PSaDate' value='$PSaDate'>
<input type='hidden' name='PSaId' value='$PSaId'>
<input type='hidden' name='PSaMaturityDate' value='$PSaMaturityDate'>
<input type='hidden' name='PSaClientCode' value='$PSaClientCode'>
<input type='hidden' name='PSaSalesmanCode' value='$PSaSalesmanCode'>
<input type='hidden' name='PSaCurr' value='$PSaCurr'>
<input type='hidden' name='PSaProjectCode' value='$PSaProjectCode'>
<input type='hidden' name='PSaCostCentCode' value='$PSaCostCentCode'>
<input type='hidden' name='PSaDiscount' value='$PSaDiscount'>
<input type='hidden' name='PSaDiscountAmt' value='$PSaDiscountAmt'>
<input type='hidden' name='PSaVatChkbx' value='$PSaVatChkbx'>
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='PSaIAddress' value='".htmlspecialchars($PSaIAddress, ENT_QUOTES)."' > ";

$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, Salesmen.Ledger_Name As SalesmanName, ".
			 " Round((ifNull(Deliveries.Delivery_Taxable,0) + ifNull(Deliveries.Delivery_NoneTaxable,0) + ifNull(Deliveries.Delivery_VAT,0) - ifNull(Deliveries.Delivery_TransportAmount,0) - ".
			 " ifNull(Deliveries.Delivery_DiscountAmount,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,  ".
			 " ifNull(Temp_Deliveries.Delivery_Id, -1) As TempDeliveryId, Deliveries.Sorder_Reference As Sorder_Reference, Q.QuantitySoldTemp ".
			 " From Deliveries Left Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
			 " Left Join Project on Deliveries.Project_Code = Project.Project_Code ".
			 " Left Join Salesmen on Deliveries.Salesman_Code = Salesmen.Ledger_Number ".
			 " Left Join Temp_Deliveries on Temp_Deliveries.Delivery_Id = Deliveries.Delivery_Id ".
			 " Inner Join ( Select Delivery_ID, Sum(QuantityDelivered - QuantitySold) as QuantityAvail, Sum(QuantitySoldTemp) as QuantitySoldTemp ".
			 "			    From (           ".
			 "                     Select DeliveryDt.Delivery_ID, DeliveryDt.Item_Code, ".
			 "                     Sum(ifNull(SalesDt.SaleDt_Quantity,0) + ifNull(DR.DeliveryDt_Quantity,0)) As QuantitySold, ".
			 "					   Sum(ifNull(Temp_SalesDt.SaleDt_Quantity,0)) As QuantitySoldTemp,  ".
			 "                     ifNull(DeliveryDt.DeliveryDt_Quantity,0) As QuantityDelivered ".
			 "             		   From DeliveryDt ".
			 "         		       Left Join SalesDt on (SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_id And SalesDt.Journal_Type = 'SI' And SalesDt.Sale_Id != '".$PSaId."') ".
			 "		    		   Left Join Temp_SalesDt on (Temp_SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_id And Temp_SalesDt.Journal_Type = 'SI') ".
			 "       		       Left Outer Join DeliveryDt DR on DeliveryDt.DeliveryDt_ID = DR.RelatedDt_ID  and  DR.Journal_Type = 'DR' ".
			 "	            	   Where ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0  ".
			 "             		   And (('".$PSaClientCode."' != '' and DeliveryDt.Client_Code = '".$PSaClientCode."') or ('".$PSaClientCode."' = '' and 1 = 1)) ".
			 "             		   And (('".$lstItems."' != '' and DeliveryDt.Item_Code = '".$lstItems."') or ('".$lstItems."' = '' and 1 = 1)) ".
			 "              	   Group by item_code,DeliveryDt.Delivery_ID, SalesDt.RelatedDt_ID, Temp_SalesDt.RelatedDt_ID ".
			 "              	) as A Group By Delivery_ID ".
			 "	                  Having QuantityAvail > 0 ".
			 "	          ) As Q on Q.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 ($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 Deliveries.Client_Code like concat(Q3.ledger_number,'%') ) or ($ledgerinclude = 0 and Deliveries.Client_Code Not like concat(Q3.ledger_number,'%') ) or Deliveries.Client_Code is null) ";							 	
							 
if ($whexist > 0 && $FI_FrmRestrictWarehouse == 1)
  $querysearch= $querysearch." Inner join ( select distinct deliverydt.Delivery_Id ".
							 " 				from deliverydt inner join ".$_SESSION['dbLabel'].".loginstk on deliverydt.warehouse_code = loginstk.warehouse_code ".
							 " 				where loginstk.user_account='".$_SESSION['useraccount']."' ".
							 " 				and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
							 "			 ) Q4 on Deliveries.Delivery_Id = Q4.Delivery_Id ";							 
							 
$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.Sorder_Reference Like Concat( ifNull($PRef, Deliveries.Sorder_Reference),'%')) )  ".
			 " And Deliveries.Journal_Type = 'DI' ".
			 " 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 (!empty($PSaClientCode))			 
	$querysearch= $querysearch." And Deliveries.Client_Code = ifNull('".$PSaClientCode."', Deliveries.Client_Code) ";

if ($PProjectCode != '')
	$querysearch= $querysearch." And Deliveries.project_code like concat('".$PProjectCode."','%') ";
if ($PCostCentCode != '')
	$querysearch= $querysearch." And Deliveries.Costcent_code like concat('".$PCostCentCode."','%') ";			 
	
	
/*if ($ledgerexist > 0)
  $querysearch= $querysearch." And (($ledgerinclude = 1 and Deliveries.Client_Code In (select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk where user_account='".$_SESSION['useraccount']."') ) Or ".
                             "      ($ledgerinclude = 0 and Deliveries.Client_Code Not In (select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk where user_account='".$_SESSION['useraccount']."') ) ) ";      
*/			 
$querysearch= $querysearch." Order By Deliveries.Delivery_Reference Desc ";
			 
//echo $querysearch; exit;
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='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'>List of Deliveries
			</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=65>
	  <col width=80>
	  <col width=70>
	  <col width=80>
	  <col width=210>
	  <col width=80>
	  <col width=100>
	  <col width=55>
	  <col width=110>

	  <tr class='Search-header-bg'>";
	  
if ($Module_Project == 1) {
	echo" <td align='left' colspan='2'><span class='style4'>Project</span></td>
	      <td align='left' colspan='2'><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='4'><input type='hidden' name='PProjectCode' id='PProjectCode' value='$PProjectCode' /></td>";

}			

if ($Module_CostCenter == 1) {		  
	echo" <td align='left' ><span class='style4'>&nbsp;Costcenter</span></td>
		  <td align='left' ><span class='style4'>
		    <input type='text' name='PCostCentCode' id='PCostCentCode' value='$PCostCentCode' size='15' 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='left' colspan='4'>&nbsp;</td>";

echo" </tr>
      <tr class='Search-header-bg'>
	    <td align='left' colspan='2'><span class='style4'>Item</span></td>
		<td align='left' colspan='8'>";
    echo"<select name='lstItems' id='lstItems' style='font-size:11px; width:375px; 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>	
      <tr class='Search-header-bg'>
	    <td align='left' colspan='2'><span class='style4'>Search by</span></td>
		<td align='left' colspan='4'><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>
		<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'>Client</option>
				 <option ".$s24." value='4'>Sorder 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><td colspan='5'>&nbsp;</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='left' style='width:180px;'>* Exists in Pending Sales</td>
			<td align='right' style='width:200px;'><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>";	
 
if($message!=''){
		echo"	  <tr class='Search-header-bg'>
		<td height='15' align='center' colspan='8' class='searchmessage'>".$message."</td>
		</tr>";
	}
	  
 echo"<tr><td id='search-content1' style='width:31px;'>&nbsp;</td>
		<td id='search-content2'>
			<div style='overflow:scroll;height:400px;width:880px;'>
			<table border='0'  cellpadding='0' cellspacing='1' style='width:920px;' >
	  <col width=20>
	  <col width=20>
	  <col width=80>
	  <col width=80>
	  <col width=75>
	  <col width=80>
	  <col width=210>
	  <col width=100>
	  <col width=100>
	  <col width=55>
	  <col width=100>
	
	  <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'>Sorder Ref </span></td>
		<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>
		<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>
	  </tr>";
		

if ($PMode != '1') {	

$i = 0;

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

	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
	
	
	if ($TempDeliveryId != -1) { $EditHint = 'Exists in Pending'; $EditMode = 0; }
	else { $EditHint = 'Select Record'; $EditMode = 1; }
	
	echo'<tr '.$Color.'>';
			
		if (!empty($PSaId)) {
				
		    $SelMaster  = 'M'.$i;
			$$SelMaster = $Delivery_ID;
			   
			echo"<td align='center'><span class='style5'><input type='checkbox' name='$SelMaster' id='$SelMaster' value='".$$SelMaster."' onclick='SelectMaster(this.name);' /></span></td>";
			
			
		} else {
			if ($QuantitySoldTemp > 0)
				echo'<td align="center">*</td>';
			else if ($EditMode == 1)
				echo'<td align="center"><span class="style5"><img src="img/edit.png" onMouseOver="style.cursor=\'hand\'" onclick="SelectRecord('.$Delivery_ID.');" title="'.$EditHint.'" ></span></td>';	
			else
				echo'<td align="center">&nbsp;</td>';	
		}
		
		if (empty($PSaId)) {
			echo'<td align="center"><span class="style5"><img src="img/details.gif" onMouseOver="style.cursor=\'hand\'"  onclick="ShowHideDetails('.$Delivery_ID.', \''.'S'.'\','.$startrange.');" title="Show Details" style="width:15px; height:15px; "></span></td>';
		} else {
			echo'<td align="center"><span class="style5">&nbsp;</span></td>';
		}
		
		echo'<td align="left"><span class="style5">'.$Delivery_Reference.'</span></td>
			 <td align="center"><span class="style5">'.$Delivery_Date.'</span></td>
			 <td align="left"><span class="style5">'.$Sorder_Reference.'</span></td>
			 <td align="left"><span class="style5">'.$ClientCode.'</span></td>
			 <td align="left"><span class="style5">'.$ClientName.'</span></td>
			 <td align="left"><span class="style5">'.$ProjectName.'</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>
		
		</tr>';
		
		if (!empty($PSaId)) {
		
			echo" <tr><td colspan='11'><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 DeliveryDt.DeliveryDt_id, DeliveryDt.Item_CodePacked, DeliveryDt.Item_code, Item_Description, DeliveryDt.Warehouse_Code, ".
					   " (ifNull(DeliveryDt.DeliveryDt_Quantity,0) - Sum(ifNull(SalesDt.SaleDt_Quantity,0) + ifNull(Temp_SalesDt.SaleDt_Quantity,0) + ifNull(DR.DeliveryDt_Quantity,0))) As QuantityRemaining  ".
					   " From DeliveryDt ".
					   " Left Join Items on DeliveryDt.Item_code = Items.Item_code ".
					   " Left Join SalesDt on (SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_id And SalesDt.Journal_Type = 'SI' And SalesDt.Sale_Id != '".$PSaId."') ".
					   " Left Join Temp_SalesDt on (Temp_SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_id And Temp_SalesDt.Journal_Type = 'SI') ".
					   " Left Outer Join DeliveryDt DR on DeliveryDt.DeliveryDt_ID = DR.RelatedDt_ID  and  DR.Journal_Type = 'DR' ";
					   
					   /*" Left Join ( Select SalesDt.RelatedDt_ID, SalesDt.Item_code, SalesDt.Item_CodePacked, Sum(ifNull(SalesDt.SaleDt_Quantity,0)) As QuantitySold ".
					   "             From SalesDt ".
					   "             Where (SalesDt.RelatedDt_ID != '' or SalesDt.RelatedDt_ID Is Not Null)  ".
					   "             And SalesDt.Sale_Id != '".$PSaId."' ".
					   "             Group By SalesDt.RelatedDt_ID, SalesDt.Item_code, SalesDt.Item_CodePacked  ".
					   "            ) Q1 on Q1.Item_code = DeliveryDt.Item_code  and Q1.RelatedDt_ID = DeliveryDt.DeliveryDt_id ".
					   " Left Join ( Select Temp_SalesDt.RelatedDt_ID, Temp_SalesDt.Item_code, Temp_SalesDt.Item_CodePacked, Sum(ifNull(Temp_SalesDt.SaleDt_Quantity,0)) As QuantitySoldTemp ".
					   "             From Temp_SalesDt ".
					   "             Where (Temp_SalesDt.RelatedDt_ID != '' or Temp_SalesDt.RelatedDt_ID Is Not Null) ".
					   "             Group By Temp_SalesDt.RelatedDt_ID, Temp_SalesDt.Item_code, Temp_SalesDt.Item_CodePacked ".
					   "            ) Q2 on Q2.Item_code = DeliveryDt.Item_code  and Q2.RelatedDt_ID = DeliveryDt.DeliveryDt_id ".
					  */
				
			if ($whexist > 0 && $FI_FrmRestrictWarehouse == 1)
				$querydt = $querydt." Inner join ( select distinct loginstk.warehouse_code from ".$_SESSION['dbLabel'].".loginstk ".
									" 				where loginstk.user_account='".$_SESSION['useraccount']."' ".
									" 				and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
									"			 ) Q4 on DeliveryDt.warehouse_code = Q4.warehouse_code ";

			$querydt = $querydt.
					   " Where DeliveryDt.Delivery_ID = ".$Delivery_ID.
					   " And ifNull(DeliveryDt.DeliveryDt_OldData,0) = 0  ".
					   " And (('".$lstItems."' != '' and DeliveryDt.Item_Code = '".$lstItems."') or ('".$lstItems."' = '' and 1 = 1)) ".
					   " Group By DeliveryDt.DeliveryDt_id, DeliveryDt.Item_code ".
					   " Having QuantityRemaining > 0 ".
					   " Order By DeliveryDt.DeliveryDt_id, DeliveryDt.Item_CodePacked, DeliveryDt.Item_code ";
			
			//echo "<br>".$querydt;
			
			$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();' /></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[5]."</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 DeliveryDt.DeliveryDt_ID, DeliveryDt.Item_CodePacked, DeliveryDt.Item_code, Item_Description, DeliveryDt.Warehouse_Code, ".
						 " Item_UnitSalesDesc, DeliveryDt_Quantity, Round(DeliveryDt_Price, ".$DecimalBase."), Round(DeliveryDt_DiscountPer, ".$DecimalBase."),  ".
						 " Round(((DeliveryDt_Quantity*DeliveryDt_Price)-((DeliveryDt_Quantity*DeliveryDt_Price*ifNull(DeliveryDt_DiscountPer,0))/100)), ".$DecimalBase.") As Total, ".
						 " Round(DeliveryDt_PriceTTC, ".$DecimalBase."), ".
						 " Round(((DeliveryDt_Quantity*DeliveryDt_PriceTTC)-((DeliveryDt_Quantity*DeliveryDt_PriceTTC*ifNull(DeliveryDt_DiscountPer,0))/100)), ".$DecimalBase.") As TotalTTC ".
						 " From DeliveryDt Left Join Items on DeliveryDt.Item_code = Items.Item_code ".
						 " Where DeliveryDt.Delivery_ID = ".$Delivery_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'.$Delivery_ID;
					
				echo "<tr ".$Color.">";
				echo "<td colspan='11' 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:920px;' 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>
						  <td width='100px' align='center'><span class='style4'>Price</span></td>
						  <td width='80px' align='center'><span class='style4'>Disc(%)</span></td>
						  <td width='120px' align='center'><span class='style4'>Total</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>";
					
					if ($SalesTTC == 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 "<input type='hidden' name='i' value='$i'>";
echo"</table></div></td><td id='search-content3' style='width:31px;'>&nbsp;</td></tr>";		

if (!empty($PSaId)) {
	echo"   <tr bgcolor='#DDDDDD'><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: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;

?>