<?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_DeliveryDel,0) As FI_DeliveryDel, ifNull(FI_DeliveryMod,0) As FI_DeliveryMod, ".
          " ifNull(FI_DeliveryConfirmed,0) As FI_DeliveryConfirmed, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ".
		  " ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ifNull(ShowTransaction,0) As ShowTransaction, ifNull(FI_ModInvStatusDlv,0) As FI_ModInvStatusDlv ".
          " 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, Module_BatchNo, Module_ExpireDate 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
$SaDelMode  =1;
$SaEditMode =1;
$SaConfMode =1;	
$SaPrevMode = 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,FI_login_ViewDocument as FI_login_ViewDocument ".
              " 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($option)) $option = 1;
if (empty($orderby)) $orderby = 1;
if (empty($searchby)) $searchby = 2;

if ($startrange=='')
	$startrange = 0;
if ($perpage=='')
	$perpage = 20;

if($txtDate == '') $txtDate = date('d/m/Y');
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 Delivery</title>
<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>

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

function SendEmail(PId, PRef){
	

	document.search.action='sendMailAttached.php?vform=Delivery&SId='+PId;
	document.search.submit();

}

function UploadDocuments(vform,txtPorId){



	win = window.open('UploadDocuments.php?vform='+vform+'&prqstid='+txtPorId +'&readonly=readonly', 'Upload', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	  win.creator = self;
	  win.focus();	 
  
  }

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

}

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

function SetNextPage(startrange,perpage,option){ 

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

function SetPrvPage(startrange,perpage,option){

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


function DeleteRecord(SaId, SaRef, option){

	if (SaId != '') {
		if (confirm ( "Are you sure you want to Delete this record with reference = "+SaRef+" ?") )
		{
			document.search.action="Form_Delivery_Actions.php?mainmode=delete&SSaId="+SaId+"&SOption="+option;
			document.search.submit();
		}
	}
	
}

function UpdateRecord(SaId){
		
	document.search.action="Form_Delivery_Actions.php?mainmode=search&SSaId="+SaId;
	document.search.submit();
	
	document.search.PMode.value=1;
	
	opener.document.sales.txtSaId.value=SaId;
	opener.document.sales.mainaction.value='edit';
	opener.document.sales.actionmode.value='';
	
	//opener.document.sales.action='Form_Delivery.php';
	//opener.document.sales.submit();
	
	
	//self.close();
	

}

function ConfirmRecord(SaId, SaRef, option, Mode){
	var vMainMode = '';
	var vMsg = '';
	
	if (Mode == 1) {
		vMainMode = 'confirmsales'; 
		vMsg = 'Are you sure you want to Confirm delivery with reference = '+SaRef+' ?';
	}
	else {
		vMainMode = 'unconfirmsales';
		vMsg = 'Are you sure you want to Unconfirm delivery with reference = '+SaRef+' ?';
	}
	
	if (SaId != '') {
		if (confirm ( vMsg) )
		{
			document.search.action="Form_Delivery_Actions.php?mainmode="+vMainMode+"&SSaId="+SaId+"&SOption="+option;
			document.search.submit();
		}
	}
	
}

function ShowHideDetails(SaId) {
	vSlideDivId = '#displaydetails'+SaId;
	$(vSlideDivId).slideToggle();
}


function generateBarcode2(){
	var SaId = document.getElementById('SalesId').value;
	if(SaId == ''){
		alert("Please Select an Invoice!");
		return 0;
	} else {
		var str = "Rep_AllItemBarcode.php?transid="+SaId+"&trans_type=DI";
		window.open(str, 'itembarcode','width=260,height=500,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
	}
}

function generateBarcode3(){
	var SaId = document.getElementById('SalesId').value;
	if(SaId == ''){
		alert("Please Select an Invoice!");
		return 0;
	} else {
		var str = "Rep_AllItemBarcode3.php?transid="+SaId+"&trans_type=DI";
		window.open(str, 'itembarcode','width=260,height=500,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
	}
}
function PreviewReport(POption) {
	var str = '';
	var SaId = document.getElementById('SalesId').value;
	var JvId = document.getElementById('JournalId').value;
	var option_to_print = document.search.option_to_print.value;
	var option_to_print2 = document.search.option_to_print2.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(document.search.chkhs.checked)
		var chkhs = 1;
		else
		var chkhs = 0;
	var xplang = document.search.xlang.value;
	
	if(document.getElementById('chktip').checked)
	 var chktip = 1;
	else var chktip = 0;
	if (SaId != '') {
		if (POption == 'PRV') {
			if (vReport == 1)
				str = 'Form_DeliveryPreview.php?SalesId='+SaId+'&PLang='+vLang+'&chktip='+chktip+'&printlogo='+printlogo+'&option_to_print='+option_to_print+'&option_to_print2='+option_to_print2;
			else if (vReport == 2)
				str = 'Form_DeliveryWaybillPreview.php?SalesId='+SaId+'&PLang='+vLang+'&printlogo='+printlogo;
			else if (vReport == 3)
				str = 'Form_DeliveryExportPreview.php?SalesId='+SaId+'&PLang='+vLang+'&chkhs='+chkhs+'&xplang='+xplang;
			else if (vReport == 4)
				str = 'Form_JournalPreview.php?journal_id='+JvId;
		}
		else if (POption == 'EXL') {
			if (vReport == 1)
				str = 'Form_DeliveryPreview.php?SalesId='+SaId+'&PLang='+vLang+'&exp=1';
			else if (vReport == 3)
				str = 'Form_DeliveryExportPreview.php?SalesId='+SaId+'&PLang='+vLang+'&chkhs='+chkhs+'&xplang='+xplang+'&exp=1';
		}
		
		window.open(str);
	} else {
		alert('Please click on an invoice.');
	}
	
}

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 ChangeLocation()
{
    if (document.search.PMode.value == 1) {
		opener.document.sales.action='Form_Delivery.php';
		opener.document.sales.submit();
		self.close();
	} else {
		opener.document.sales.txtSaId.value='';
		opener.document.sales.mainaction.value='';
		opener.document.sales.actionmode.value='';
	}
}

function SelectStatus()
{
  document.search.keyword.value='';
 
  document.search.action='Form_DeliverySearch.php?startrange=0';
  document.search.submit();

}

function SelectSearchBy()
{	

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

}

function SubmitForm()
{	

  //document.search.keyword.value='';
  document.search.action='Form_DeliverySearch.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 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_DeliverySearch.php?startrange=0';
  document.search.submit();

}

function SetFirstPage(startrange,perpage){
	document.search.action='Form_DeliverySearch.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_DeliverySearch.php?startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}

function showlistitem(str){
	var x = document.search;
		
	window.open('select_item.php?item='+str,'mywindow','width=900,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistBatchNo(str) {
	x = document.search;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 580) / 2;
	
	vItemCode = encodeURIComponent(document.getElementById('itemcode').value);
	if(vItemCode == '')
	{ 
		alert('Please select an Item!');
		return 0;
	} else	
	window.open('List_BatchNo.php?frm=13&PItem_Code='+vItemCode,'List_BatchNo','width=580,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistWarehouse() {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('PWarehouseCode').value);
	window.open('List_SorWarehouse.php?frm=10&item=1&PWarehouse_Code='+vWarehouseCode,'List_SorWarehouse','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function refreshSearch(){
	document.search.action = "Form_DeliverySearch.php";
	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>
<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='ReportSelected' id='ReportSelected' value=''>
<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;

$ndate = explode('/', $txtDate);
$txtDate1 = $ndate[2]."-".$ndate[1]."-".$ndate[0];
$companynames = explode('_',$_SESSION['dbName']);
$companyname = $companynames[0];
$dir = $companynames[1];

$querySchema = "select concat(CompanyName,'_',Diryear)
				from ".$_SESSION['dbLabel'].".directories
				where upper(CompanyName) = upper('$companyname') and Diryear = '$dir';";	
	//'$txtDate1' between date_format(StartReportDate,'%Y-%m-%d') and date_format(EndReportDate,'%Y-%m-%d')				and 
//echo $querySchema;exit;
$querysearch = "select Delivery_ID, Delivery_Reference, Delivery_Date, ClientCode, ClientName, Currency_code,   ".
				" ProjectName, CostcentName, SalesmanName, NetTotal, Delivery_Status, Delivery_Remark, Delivery_ManualNo, ".
				" TempSalesId, Journal_ID, Journal_folio, Journal_refgovernment, Sorder_Reference, Delivery_Printed, USER_Account "; 
if($FI_ModInvStatusDlv == 0) $querysearch=$querysearch.", status_id ";	
$querysearch=$querysearch." from ( ";	

$resScehma = mysql_query($querySchema,$connection);
$j = 0;
$querysearch1 = "";
while( $rowSchema = mysql_fetch_row($resScehma)){

$schemaname = $rowSchema[0];

if($j != 0) $querysearch1 = $querysearch1." Union ";

$querysearch1 = $querysearch1." Select distinct Deliveries.Delivery_ID as Delivery_ID, Deliveries.Delivery_Reference as 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 as 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_BonusAmount,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, Deliveries.Delivery_Remark as Delivery_Remark, Deliveries.Delivery_ManualNo as Delivery_ManualNo, deliveries.USER_Account as USER_Account, ".
			 " ifNull(Temp_Deliveries.Delivery_Id, -1) As TempSalesId, Journal.Journal_ID as Journal_ID, Journal.Journal_folio as Journal_folio, Journal.Journal_refgovernment as Journal_refgovernment, ".
			 " Deliveries.Sorder_Reference as Sorder_Reference, Deliveries.Delivery_Printed as Delivery_Printed ";
			 
if($FI_ModInvStatusDlv == 0) $querysearch1=$querysearch1.", status_id ";
			 
$querysearch1=$querysearch1." From $schemaname.Deliveries as Deliveries ".
			 " Left Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
			 " inner Join deliverydt on deliverydt.delivery_id = Deliveries.delivery_id ".
			 " 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 $schemaname.Temp_Deliveries as Temp_Deliveries on Temp_Deliveries.Delivery_ID = Deliveries.Delivery_ID "; 

if($FI_ModInvStatusDlv == 0) 
	$querysearch1=$querysearch1." left join $schemaname.delivery_deliverystatus as delivery_deliverystatus on delivery_deliverystatus.delivery_id = deliveries.delivery_id
							left join deliverystatus_setup on deliverystatus_setup.id = status_id ";
			 
if ($projectexist >	0)
  $querysearch1= $querysearch1." 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)
  $querysearch1= $querysearch1." 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) {
	$querysearch1 = $querysearch1." 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){
	$querysearch1 = $querysearch1." 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,'%') ".
								"                ) ";	
								
}

/*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']."') ) ) ";      
*/
							 
$querysearch1= $querysearch1." Where 1=1 ";
//nabil 2017-07-07 if($FI_ModInvStatusDlv == 0) $querysearch1=$querysearch1." and deliverystatus_last=1 ";

 $querysearch1=$querysearch1." and (($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.Sorder_Reference Like Concat( ifNull($PRef, Deliveries.Sorder_Reference),'%') Or Deliveries.Delivery_SorderReferences Like Concat( '%', ifNull($PRef, Deliveries.Delivery_SorderReferences),'%')) Or ".
			 "        ($searchby = 8 and Deliveries.Delivery_ManualNo Like Concat('%', ifNull($PRef, Deliveries.Delivery_ManualNo),'%')) Or  ".
			 "        ($searchby = 9 and Deliveries.Delivery_Remark Like Concat('%', ifNull($PRef, Deliveries.Delivery_Remark),'%')) Or  ".
			 "        ($searchby = 10 and Round((ifNull(Deliveries.Delivery_Total,0) + ifNull(Deliveries.Delivery_VAT,0) - ifNull(Deliveries.Delivery_DiscountAmount,0) + ifNull(Deliveries.Delivery_TransportAmount,0) + ifNull(Deliveries.Delivery_BonusAmount,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))), 2) ".
			 " 				Like Concat('%', ifNull($PRef, Round((ifNull(Deliveries.Delivery_Total,0) + ifNull(Deliveries.Delivery_VAT,0) - ifNull(Deliveries.Delivery_DiscountAmount,0) + ifNull(Deliveries.Delivery_TransportAmount,0) + ifNull(Deliveries.Delivery_BonusAmount,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))), 2)),'%')) )".
			 " 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 (($option = 2 and ifNull(Deliveries.Delivery_Confirmed,0)=1 ) or ($option = 3 and ifNull(Deliveries.Delivery_Confirmed,0)=0 ) or ($option = 1 and 1=1) ) ".
			 " And ifNull(Deliveries.Delivery_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
if($itemcode != '')			 
	$querysearch1= $querysearch1." And deliverydt.item_code like  concat('".$itemcode."','%')  ";
if($batchnumber != '')			 
	$querysearch1= $querysearch1." And deliverydt.DeliveryDt_BatchNo like  concat('".$batchnumber."','%')  ";
if($PWarehouseCode != '')			 
	$querysearch1= $querysearch1." And deliverydt.Warehouse_Code like concat('".$PWarehouseCode."','%')  ";
if ($ShowTransaction != 1)
	$querysearch1= $querysearch1." And Upper(Deliveries.User_Account) = Upper('".$_SESSION['useraccount']."') ";
			 
if ($PProjectCode != '')
	$querysearch1= $querysearch1." And Deliveries.project_code like concat('".$PProjectCode."','%') ";
if ($PCostCentCode != '')
	$querysearch1= $querysearch1." And Deliveries.costcent_code like concat('".$PCostCentCode."','%') ";
if ($fromdate != '' && $todate !='' )
	$querysearch1 = $querysearch1." And Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d') between '".explodeword($fromdate)."' and '".explodeword($todate)."' ";
			 
$j++;
}

$querysearch = $querysearch.$querysearch1;
if ($orderby == 1)
	$querysearch= $querysearch." ) as Qsearch Order By Delivery_Date Desc, Delivery_Reference Desc ";
else if ($orderby == 2)
	$querysearch= $querysearch." ) as Qsearch Order By Delivery_Reference Desc,  Delivery_Date Desc ";	
//echo $querysearch;	//exit;	
$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());
$totalrows = mysql_num_rows($resultsearch);
	
$querysearch = $querysearch." limit ".$startrange.",".$perpage;
	 


//$row = mysql_fetch_row(mysql_query("SELECT FOUND_ROWS()"));
//$totalrows = $row[0];
	
		
//$querysearch = $querysearch." limit ".$startrange.",".$perpage;

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

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

echo"<table cellpadding='0' cellspacing='0' border='0'  align='left' style='table-layout:fixed' >";
echo"<tr>
		<td id='search-top1' style='height:34px; width:31px;'>&nbsp;</td>
	  	<td id='search-top2' style='height:34px; width:1210px' 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=80>
	  <col width=170>
	  <col width=100>
	  <col width=170>
	  <col width=80>
	  <col width=100>
	  <col width=90>
	  <col width=350>
	  <col width=80>
	
	  <tr class='Search-header-bg'>";
	  
if ($Module_Project == 1) {
	echo" <td align='left'><span class='style4'>Project</span></td>
	      <td align='left'><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='2'><input type='hidden' name='PProjectCode' id='PProjectCode' value='$PProjectCode' /></td>";

}			

if ($Module_CostCenter == 1) {		  
	echo" <td align='left'><span class='style4'>Costcenter</span></td>		
		  <td align='left'><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='2'><input type='hidden' name='PCostCentCode' id='PCostCentCode' value='$PCostCentCode' /></td>";

}	  
echo "<td align='left' colspan='2'>
		<span class='style4'>Date </span> &nbsp;
		<input type='text' name='txtDate' id='txtDate' value='$txtDate'  maxlength='10'  style='width:80px;' onchange=\"refreshSearch();\">
		<A HREF='#' onClick=\"displayCalendar(document.search.txtDate,'dd/mm/yyyy',this);  return false;\" NAME='anchor1' ID='anchor1'><img src='./img/cal.gif' border=0 align=center></A></td>";
echo" 	<td align='left' colspan='2'><span class='style4'>Order By</span>	&nbsp;
		<span class='style4'><select name='orderby' id='orderby' value='$orderby' onchange='SelectStatus();'>";
		
		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;";

echo"	<span class='style4'>Status&nbsp;</span>
		<span class='style4'><select name='option' id='option' value='$option' onchange='SelectStatus();'>";
		
		if ($option==1)
			$s1 = 'selected';
		else if ($option==2)
			$s2 = 'selected';
		else if ($option==3)
			$s3 = 'selected';
			
		echo"<option ".$s1." value='1'>All</option>
			 <option ".$s2." value='2'>Confirmed</option>
			 <option ".$s3." value='3'>Unconfirmed</option>
			 </select></span></td>";
		  
echo" </tr>";

echo" <tr height='30px' bgcolor='#DDDDDD'>	  	  
	    <td align='left'><span class='style4'>Item Code</span></td>";
echo"  <td align='left' ><span class='style4'>
		    <input type='text' name='itemcode' id='itemcode' style='width:138px;' value='$itemcode' onkeydown=\"return kd(event)\" /></span>
		    <label><span class='style4'><img src='img/btnopen.jpg' title=' Select Item ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistitem(9); '  /></span></label></td>";		
echo"  <td align='left'><span class='style4'>Batch No</span></td>";
echo"  <td align='left' ><span class='style4'>
		    <input type='text' name='batchnumber' id='batchnumber' style='width:138px;' value='$batchnumber'  onkeydown=\"return kd(event)\" /></span>
		    <label><span class='style4'><img src='img/btnopen.jpg' title=' Select Batch No ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistBatchNo(9); '  /></span></label></td>";		
echo "<td colspan='2'><span class='style4'>Warehouse</span></td><td colspan='2'><span class='style4'>
		    <input type='text' name='PWarehouseCode' id='PWarehouseCode' style='width:138px;' value='$PWarehouseCode' onkeydown=\"return kd(event)\" /></span>
		    <label><span class='style4'><img src='img/btnopen.jpg' title=' Select Batch No ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistWarehouse(); '  /></span></label>
			</td>";		
echo"</tr>";		
echo" <tr  height='30px' bgcolor='#DDDDDD'>	  	  
	    <td align='left'><span class='style4'>Search By</span></td>
		<td align='left' colspan='3'><span class='style4'><input type='text' name='keyword' id='keyword' value='$keyword' size='15' maxlength='100' 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';	
			else if ($searchby==8)	$s28 = 'selected';	
			else if ($searchby==9)	$s29 = 'selected';	
			else if ($searchby==10)	$s31 = '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'>Sorder Ref.</option>
				  <option ".$s28." value='8'>Manual No</option>
				  <option ".$s29." value='9'>Remark</option>
				  <option ".$s31." value='10'>Amount</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='4'>&nbsp;";
}
		echo"| Export<span class='style4'>
			<input type='radio' name='xlang' value='EN' checked>English
			<input type='radio' name='xlang' value='FR'>French
			<input type='radio' name='xlang' value='AR'>Arabic	
			<input type='checkbox' name='chkhs' id='chkhs' >HS Code	
			";
echo" </tr>";
echo" <tr bgcolor='#DDDDDD' height='30px;'>
		<td colspan='8'>
			<span class='style4'>
				<input type='radio' name='report' value='1' checked>Invoice
				<input type='radio' name='report' value='2'>Waybill
				<input type='radio' name='report' value='3'>Export
				<input type='radio' name='report' value='4'>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>
			<button type='button' id='btnBar2' name='btnBar2'  onclick=\"generateBarcode2();\" title='Print Barcode 2'><span><span>Barcode 2</span></span></button>
			<button type='button' id='btnBar3' name='btnBar3'  onclick=\"generateBarcode3();\" title='Print Barcode 3'><span><span>Barcode 3</span></span></button>
			&nbsp;&nbsp;&nbsp;<b>Print Logo</b><input type='checkbox' name='chk' id='chk' > 
			&nbsp;&nbsp;&nbsp;<b>Print Tips</b><input type='checkbox' name='chktip' id='chktip' >&nbsp;&nbsp;&nbsp;";
			if($Module_BatchNo == 1)
			{
				echo "<input type='checkbox' name='option_to_print' onclick=\"if(document.search.option_to_print.checked) { document.search.option_to_print.value='batch' } else { document.search.option_to_print.value='' }\" value=''> <b>Print Batch No.</b>";
			}
			else
			{
				echo "<input type='hidden' name='option_to_print' value=''>";
			}
			if($Module_ExpireDate == 1)
			{
				echo "<input type='checkbox' name='option_to_print2' onclick=\"if(document.search.option_to_print2.checked) { document.search.option_to_print2.value='expirydate' } else { document.search.option_to_print2.value='' }\" value=''> <b>Print Expiry Date</b>";
			}
			else
			{
				echo "<input type='hidden' name='option_to_print2' value=''>";
			}
		echo"</td>
	  </tr>
	  
<tr class='Search-header-bg'>
<td colspan = '8' height = '30px'><span class='style4'>From&nbsp;</span><input type='text' name='fromdate' id='fromdate' value='$fromdate' maxlength='10' size='9' onkeydown=\"return kd(event);\">
		<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' onkeydown=\"return kd(event);\">
		<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:300px;'><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."','".$option."')>";

			$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."','".$option."')>";
			}
			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."','".$option."')>";
					echo"&nbsp;&nbsp;<img src='img/lastpage.png' title='Last Page' onMouseOver=\"style.cursor='hand'\" onclick=SetLastPage('".$perpage."','".$totalrows."','".$option."')>";	
				}
			} 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:1150px;'>
			<table border='0'  cellpadding='0' cellspacing='1' style='width:1520px;' >
			  <col width=20>
			  <col width=20>
			  <col width=20>
			  <col width=20>
			  <col width=20>
			  <col width=65>
			  <col width=90>
			  <col width=65>
			  <col width=60>
			  <col width=60>
			  <col width=75>
			  <col width=200>
			  <col width=70>
			  <col width=80>
			  <col width=100>
			  <col width=55>
			  <col width=90>
			  <col width=75>
			  <col width=100>
			  <col width=150>
			  <col width=250>";
	  

	  
	if($message!=''){
		echo"<tr class='Search-header-bg'>
				<td height='15' align='center' colspan='18' 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'>&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>";

	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>
			<td  height='25' align='center'><span class='style4'>CostCenter</span></td>";
		
		if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
			echo"<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>
				 <td  height='25' align='center'><span class='style4'>Status</span></td>";
		} else {
			echo"<td  height='25' align='center' colspan='2'><span class='style4'>Salesman</span></td>
				 <td  height='25' align='center' colspan='2'><span class='style4'>Status</span></td>";
		}	
		
	echo"	<td  height='25' align='center'><span class='style4'>Manual No</span></td>
			<td  height='25' align='center'><span class='style4'>User Account</span></td>
			<td  height='25' align='center'><span class='style4'>Remark</span></td>
			<td  height='25' align='center'><span class='style4'>Print #</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 Invoice';
	$PrevHint1  = 'Preview Waybill';
	$EditHint   = 'Edit Record';
	$DelHint    = 'Delete Record';
	
	if ($TempSalesId != -1) {$PrevHint=$PrevHint1=$EditHint=$DelHint = 'Exists in Pending';}
	
    if ($FI_DeliveryMod == 0)	$SaEditMode =0; 
	else if ($FI_DeliveryMod == 1 && $TempSalesId != -1) $SaEditMode =0;
	else if ($FI_DeliveryMod == 1 && $TempSalesId == -1) $SaEditMode =1;
	
	if ($FI_DeliveryDel == 0)	$SaDelMode =0; 
	else if ($FI_DeliveryDel == 1 && $TempSalesId != -1) $SaDelMode =0;
	else if ($FI_DeliveryDel == 1 && $TempSalesId == -1) $SaDelMode =1;
	
	
	if ($TempSalesId != -1) $SaPrevMode =0; else $SaPrevMode =1;		
		
	echo"<tr onMouseOver=\"style.cursor='pointer'\"  id='row$ct' onclick=\"SelectRecord(this,'SelectedRec','SelectedRecColor','".$Delivery_ID."','".$Journal_ID."')\" ".$Color.">";
	//echo $FI_ModInvStatusDlv;

	echo' <td align="center"><span class="style5"><img src="img/email.png" onMouseOver="style.cursor=\'hand\'" onclick="SendEmail('.$Delivery_ID.', \''.$Delivery_Reference.'\');" title="Send email" style="width:17px; height:15px; "></span></td>';



	if($FI_ModInvStatusDlv == 0) $checkStatus = $status_id < 3;
	else if($FI_ModInvStatusDlv == 1) $checkStatus = 1==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){
		$SaEditMode = 0;
		$SaDelMode = 0;
	}
	
	if($SaEditMode==1 && $checkStatus)
		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($SaDelMode==1 && $checkStatus)
		echo'<td align="center"><span class="style5"><img src="img/delete.png" onMouseOver="style.cursor=\'hand\'" onclick="DeleteRecord('.$Delivery_ID.', \''.$Delivery_Reference.'\','.$option.');" title="'.$DelHint.'" style="width: 20px; height: 20px; "></span></td>';
	else 
		echo'<td align="center">&nbsp;</td>';	
		
	/*if ($FI_DeliverySalesPrice == 1 && $SaPrevMode==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 && $SaPrevMode==1)
		echo'<td align="center"><span class="style5"><img src="img/print-green-icon.png" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreviewExport('.$Delivery_ID.');"  title="'.$PrevHint.'" style="width: 18px; height: 18px; " ></span></td>';
	else
		echo'<td align="center">&nbsp;</td>';
			
	if ($Module_Delivery == 0 && $Module_PrintWaybill == 1 && $SaPrevMode==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>';*/
	
	echo'<td align="center"><span class="style5"><img src="img/details.gif" onMouseOver="style.cursor=\'hand\'"  onclick="ShowHideDetails('.$Delivery_ID.');" title="Show Details" style="width:15px; height:15px; "></span></td>';
	if($FI_login_ViewDocument==1){
		echo'   <td align="center"><span class="style5"><img src="img/viewdoc.png" onMouseOver="style.cursor=\'hand\'"  onclick="UploadDocuments(\''.'Delivery'.'\','.$Delivery_ID.');"  title="Show Document" style="width: 18px; height: 15px; " ></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">'.$Sorder_Reference.'</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>
			<td align="left"><span class="style5">'.$CostcentName.'</span></td>';
			
	if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
		echo'<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>
			 <td align="left"><span class="style5">'.$Delivery_Status.'</span></td>';
	} else {
		echo'<td align="left" colspan="2"><span class="style5">'.$SalesmanName.'</span></td>
			 <td align="left" colspan="2"><span class="style5">'.$Delivery_Status.'</span></td>';
	}	
			
	echo'	<td align="left"><span class="style5">'.$Delivery_ManualNo.'</span></td>
			<td align="left"><span class="style5">'.$USER_Account.'</span></td>
			<td align="left"><span class="style5">'.$Delivery_Remark.'</span></td>
			<td align="left"><span class="style5">'.$Delivery_Printed.'</span></td>';
					 
	echo'</tr>';
	
	
	$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_itemdiscount, ".$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='18' valign='top' align='left'><div id='$SlideDivId' class='div-search-details' style='display:none; margin-left:100px;'>";
		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>";
		if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {		  
			echo" <td width='100px' align='center'><span class='style4'>Price</span></td>
				  <td width='80px' align='center'><span class='style4'>Disc(%)</span></td>
				  <td width='120px' align='center'><span class='style4'>Total</span></td>";
		}		  
		echo" </tr>";
		while($sub_rows=mysql_fetch_array($sub_result)){
			echo "<tr><td align='left' valign='top' class='style9'>".$sub_rows[2]."</td>
					  <td align='left' valign='top' class='style9'>".$sub_rows[3]."</td>
					  <td align='left' valign='top' class='style9'>".$sub_rows[4]."</td>
					  <td align='center' valign='top' class='style9'>".$sub_rows[5]."</td>
					  <td align='right' valign='top' class='style9'>".$sub_rows[6]."</td>";
			
			if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
				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"</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."','".$option."')>";
				
		//$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."','".$option."')>";
		}
		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."','".$option."')>";
				echo"&nbsp;&nbsp;<img src='img/lastpage.png' title='Last Page' onMouseOver=\"style.cursor='hand'\" onclick=SetLastPage('".$perpage."','".$totalrows."','".$option."')>";	
			}	
		} 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;
}
?>