<?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_salesorderdel,0) As FI_SalesOrderDel, ifNull(Fi_salesordermod,0) As FI_SalesOrderMod, ".
          " ifNull(FI_sorderconfirmed,0) As FI_SalesOrderConfirm, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ".
		  " ifNull(login_disapprovesorder,0) As Login_DisapproveSorder, ifNull(Login_CancelSorder,0) As Login_CancelSorder, ".
		  " ifNull(ShowTransaction,0) As ShowTransaction, ifnull(RA_StatementofAccount,0) as RA_StatementofAccount, ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice ".
          " 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());
//ECHO  $querylog;
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

$querySalesSetup="Select ifnull(SubItem_Production,0) as SubItem_Production, ifnull(sorderproduction,0) as sorderproduction From SorderSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//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, ".
			 " ifNull(Module_TransferSorder,0) As Module_TransferSorder, ifNull(Module_AutoTransSorder,0) As Module_AutoTransSorder, ".
			 " ifnull(Module_ReferenceByProject,0) as Module_ReferenceByProject, ifNull(Module_GenerateSorderJV,0) As Module_GenerateSorderJV 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
$SorDelMode =1;
$SorEditMode =1;
$SorPrevMode =1;
$SorConfMode =1;	
$SorDispMode =1;	

$PrevHint   = '';
$EditHint   = '';
$DelHint    = '';
$ConfHint   = '';
$UnconfHint = '';
$CancelHint = '';


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

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

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

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

if (empty($option))   $option = 1;
if (empty($option1))  $option1 = 1;
if (empty($orderby))  $orderby = 1;
if (empty($searchby)) $searchby = 2;

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

 
	
print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css">
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>
<title>Search Preparation Order</title>
<script type="text/javascript" language="javascript">


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.option1.value='';
  document.search.PProjectCode.value='';
  document.search.PCostCentCode.value='';
  document.search.fromdate.value = '';
  document.search.todate.value = '';
 
  document.search.action='Form_SalesOrderSearch.php';
  document.search.submit();

}

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

function SetNextPage(startrange,perpage,option){ 

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

function SetPrvPage(startrange,perpage,option){

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


function DeleteRecord(SorId, SorRef, option){

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

function UpdateRecord(SorId){
		
	document.search.action="Form_SalesOrder_Actions.php?mainmode=search&SSorId="+SorId;
	document.search.submit();
	
	document.search.PMode.value=1;
	
	opener.document.salesorder.txtSorId.value=SorId;
	opener.document.salesorder.mainaction.value='edit';
	opener.document.salesorder.actionmode.value='';
	
	//opener.document.salesorder.action='Form_SalesOrder.php';
	//opener.document.salesorder.submit();
	
	
	//self.close();
	

}


function duplicateSorder(SorId, SorRef){
	var vMainMode = 'duplicateSorder';
	var vMsg = 'Are you sure you want to Duplicate Sales order with reference = '+SorRef+' ?';
	if (SorId != '') {
		if (confirm (vMsg) )
		{
			document.search.action="Form_SalesOrder_Actions.php?mode=&mainmode="+vMainMode+"&SSorId="+SorId;
			document.search.submit();
		}
	}
}

function cancelPreProduction(SorId, SorRef){
	var vMainMode = 'cancelFromPreproduction';
	var vMsg = 'Are you sure you want to Cancel Sales order with reference = '+SorRef+' from Preproduction ?';
	if (SorId != '') {
		if (confirm (vMsg) )
		{
			document.search.action="Form_SalesOrder_Actions.php?mode=&mainmode="+vMainMode+"&SSorId="+SorId;
			document.search.submit();
		}
	}
}

function ConfirmOrder(SorId, SorRef, option, Mode){

	var vMainMode = '';
	var vMsg = '';
	
	if (Mode == 1) {
		vMainMode = 'confirmorder'; 
		vMsg = 'Are you sure you want to Confirm order with reference = '+SorRef+' ?';
	}
	else {
		vMainMode = 'unconfirmorder';
		vMsg = 'Are you sure you want to Unconfirm order with reference = '+SorRef+' ?';
	}
	
	if (SorId != '') {
		if (confirm (vMsg) )
		{
			document.search.action="Form_SalesOrder_Actions.php?mainmode="+vMainMode+"&SSorId="+SorId+"&SOption="+option;
			document.search.submit();
		}
	}
	
}


function CancelOrder(SorId, SorRef, option){

	if (SorId != '') {
		if (confirm ( "Are you sure you want to Cancel order with reference = "+SorRef+" ?") )
		{
			document.search.action="Form_SalesOrder_Actions.php?mainmode=cancelorder&SSorId="+SorId+"&SOption="+option;
			document.search.submit();
		}
	}
	
}


function RetrieveOrder(SorId, SorRef, option){

	if (SorId != '') {
		if (confirm ( "Are you sure you want to Retrieve Canceled Order with reference = "+SorRef+" ?") )
		{
			document.search.action="Form_SalesOrder_Actions.php?mainmode=retrieveorder&SSorId="+SorId+"&SOption="+option;
			document.search.submit();
		}
	}
	
}

function DisapproveOrder(SorId, SorRef, option){

	if (SorId != '') {
		if (confirm ( "Are you sure you want to Disapprove order with reference = "+SorRef+" ?") )
		{
			document.search.action="Form_SalesOrder_Actions.php?mainmode=disapproveorder&SSorId="+SorId+"&SOption="+option;
			document.search.submit();
		}
	}
	
}

function ApproveOrder(SorId, SorRef, option){

	if (SorId != '') {
		if (confirm ( "Are you sure you want to Approve order with reference = "+SorRef+" ?") )
		{
			document.search.action="Form_SalesOrder_Actions.php?mainmode=approveorder&SSorId="+SorId+"&SOption="+option;
			document.search.submit();
		}
	}
	
}

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


function PrintPreview(SorId, SorType,exports)
{
	var str = '';
	var vShowDetail = 1;
	
	if (SorType == 'QO') {
		vShowDetail = 0;
		if (confirm ( "Do you want to Print with Detail ?","Yes","No") )
		{
			vShowDetail = 1;
		}
	}
	if(document.search.chkhs.checked)
		var chkhs = 1;
		else
		var chkhs = 0;
	var plang = document.search.lang.value;
	
	if(document.search.export.checked)
		var exp = 1;
		else
		var exp = 0;
		
	if(document.search.exportexcell.checked)
		var vexportexcell = 1;
		else
		var vexportexcell = 0;
		
	if(exp==1)
		str = 'Form_SorderExportPreview.php?SorderId='+SorId+'&ShowDetail='+vShowDetail+'&exportexcell='+vexportexcell+'&chkhs='+chkhs+'&plang='+plang+'&exp='+ exports;
	else	
		str = 'Form_SalesOrderPreview.php?SorderId='+SorId+'&ShowDetail='+vShowDetail+'&export='+exp+'&sorder='+SorType+'&exp='+ exports;
	window.open(str);
	
	//self.close();

}

function PrintPreviewNoPrice(SorId, SorType)
{
	var str = '';
	var vShowDetail = 1;
	
	if (SorType == 'QO') {
		vShowDetail = 0;
		if (confirm ( "Do you want to Print with Detail ?","Yes","No") )
		{
			vShowDetail = 1;
		}
	}
	if(document.search.export.checked)
		var exp = 1;
		else
		var exp = 0;
	if(document.search.exportexcell.checked)
		var vexportexcell = 1;
		else
		var vexportexcell = 0;
		
	if(document.search.chkhs.checked)
		var chkhs = 1;
		else
		var chkhs = 0;
	var plang = document.search.lang.value;
		
    if(exp==1)
		str = 'Form_SorderExportPreviewNoPrice.php?SorderId='+SorId+'&ShowDetail='+vShowDetail+'&exportexcell='+vexportexcell+'&chkhs='+chkhs+'&PLang=EN';
	else
	str = 'Form_SalesOrderPreviewNoPrice.php?SorderId='+SorId+'&ShowDetail='+vShowDetail+'&PLang=EN&sorder='+SorType;
	window.open(str);
	
	//self.close();

}

function ChangeLocation()
{
    if (document.search.PMode.value == 1) {
		opener.document.salesorder.action='Form_SalesOrder.php';
		opener.document.salesorder.submit();
		self.close();
	} else {
		opener.document.salesorder.txtSorId.value='';
		opener.document.salesorder.mainaction.value='';
		opener.document.salesorder.actionmode.value='';
	}
}

function SelectStatus()
{
  document.search.keyword.value='';

  document.search.action='Form_SalesOrderSearch.php?startrange=0';
  document.search.submit();

}

function SelectSearchBy()
{	

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

}

function SubmitForm()
{	

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

}

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



function OpenAutoTransfer(SorId,SorRef,startrange,perpage,option){

if (confirm ( "Are you sure you want to Auto Transfer order with reference = "+SorRef+" ?") ) {
/*
win = window.open('Form_SalesOrderAutoTransfer.php?SorId='+SorId+'&SorRef='+SorRef, 'Form_SalesOrderDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=250,height=250,top=100,left=450');		
	win.creator = self;
	win.focus();		
*/
	document.search.action='Form_SalesOrder_Actions.php?startrange='+startrange+'&perpage='+perpage+'&SorId='+SorId+'&mode=transfer'+'&SorRef='+SorRef;
	document.search.submit();
	
}	



}

function PrintStatement(Base1Curr,ModuleReferenceByProject,txtClientCode,txtProjectCode,txtCostCentCode) {
	var vCurrDate = new Date();
	var m = vCurrDate.getMonth()+1;
	var d = vCurrDate.getDate();
	var vMonth = (m < 10) ? '0' + m : m;
	var vDays  = (d < 10) ? '0' + d : d; 
	var vYear  = vCurrDate.getYear();
	
	
	varfromledger  = txtClientCode;
	vartoledger    = txtClientCode;
	varfromproject = txtProjectCode;
	vartoproject   = txtProjectCode;
	varfromcst     = txtCostCentCode;
	vartocostcent  = txtCostCentCode;
	varfromdate    = "01/01/" + vYear;
	vartodate 	   = vDays + "/" + vMonth + "/" + vYear;
	
	if (ModuleReferenceByProject == 1) {
		str =   'Rep_StatementProjCost.php?option=1&fromdate='+varfromdate+'&todate='+vartodate+'&fromledger='+varfromledger+'&toledger='+vartoledger
			   +'&fromproject='+varfromproject+'&toproject='+vartoproject+'&fromcst='+varfromcst+'&tocostcent='+vartocostcent
			   +'&currency='+Base1Curr+'&groupby=1&balance=1&prtvaluedate=1&prtjvtype=1&prtprevbal=1&showdetail=1&alltypes=1'
			   +'&exclude=0&jvtype=&parentprjcost=0';
	} else {
		str =   'rep_statementofaccount.php?fromdate=&todate=&fromledger='+varfromledger+'&toledger='+vartoledger
			   +'&dateoption=1&transaction=3&ledgeroption=1&curr=1&currbase1=0&currbase2=0&cum=0'
			   +'&alltypes=1&exclude=0&jvtype=&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=1'
			   +'&prtjvtype=0&prtcostcent=0&prtproject=0&prevbal=1&dtjv=0&dtdate=1&checks=1';
	}
   
   
	window.open(str);
}

function SelectRecord(Obj, SelectedRec, SelectedRecColor, sorder_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('sorderid').value = sorder_id;
	document.getElementById(Obj.id).style.backgroundColor ='#B8EDFF';

}

function generateBarcode2(){
	var SoId = document.getElementById('sorderid').value;
	if(SoId == ''){
		alert("Please Select a Sale Order!");
		return 0;
	} else {
		var str = "Rep_AllItemBarcode.php?transid="+SoId+"&trans_type=SO";
		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 SoId = document.getElementById('sorderid').value;
	if(SoId == ''){
		alert("Please Select a Sale Order!");
		return 0;
	} else {
		var str = "Rep_AllItemBarcode3.php?transid="+SoId+"&trans_type=SO";
		window.open(str, 'itembarcode','width=260,height=500,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
	}
}
</script>

<style type="text/css">

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 0px;
	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;
}
.style15 {color: #5151FF; }
.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #000000 ;font-size: 10px;}

</style>

<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>

</head>
<body onLoad='LoadForm();' class='bodybackground'>
<form name='search' method='post' action="">
<input type='hidden' name='sorderid' id='sorderid' 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;
			
$querysearch=" Select Distinct Sorder.Sorder_ID, Sorder.Sorder_Reference, Date_Format(Sorder.Sorder_Date,'%d-%m-%Y') As Sorder_Date, ".
             " Sorder.Client_Code As ClientCode, Clients.Ledger_name As ClientName, Sorder.Currency_code, ".
			 " Project.Project_Name As ProjectName, Costcent.Costcent_name As CostcentName, Salesmen.Ledger_Name As SalesmanName, ".
			 " Round((if($SalesTTC=1,ifNull(Sorder.Sorder_Taxable,0)*(1+$Setup_VatPercentage/100),ifNull(Sorder.Sorder_Taxable,0)) + ifNull(Sorder.Sorder_NoneTaxable,0) + if($SalesTTC=1,0,IfNull(Sorder.Sorder_VAT,0)) - ifNull(Sorder.Sorder_DiscountAmount,0) + ".
			 " ifNull(Sorder.Sorder_TransportAmount,0) + (ifNull(Sorder.Sorder_Tax1,0) + ifNull(Sorder.Sorder_Tax2,0) + ifNull(Sorder.Sorder_Tax3,0) + ifNull(Sorder.Sorder_Tax4,0) + ifNull(Sorder.Sorder_Tax5,0))), ".$DecimalBase.") As NetTotal,  ".
			 " if(ifNull(Sorder.Sorder_disapproved,0)=1, 'Disapproved', if(Sorder.Sorder_Type='CA', 'Canceled', if(ifNull(Sorder.Sorder_confirmed,0)=1, 'Confirmed', 'Unconfirmed'))) As Sorder_Status, ".
			 " ifNull(Temp_Sorder.Sorder_Id, -1) As TempSorderId, Sorder.Sorder_Type, ".
			 " if(ifNull(Sorder.Sorder_Status,0)=0, 'Pending', if(ifNull(Sorder.Sorder_Status,0)=1, 'Delivered', 'Transferred')) As Sorder_Progress, ".
			 " Sorder.User_Account As UserAccount, Sorder.Sorder_ConfirmUser As SorderConfirmUser ,Sorder.Transfer_id as Transfer_id
			   ,Transfer.Transfer_Reference as Transfer_Reference, Sorder.Project_Code as Project_Code,Sorder.Costcent_code as Costcent_code, journal_folio, journal_refgovernment ".
			 " From Sorder Left Join Clients on Sorder.Client_Code = Clients.Ledger_Number ".
			 " Left Join Project on Sorder.Project_Code = Project.Project_Code ".
			 " Left Join Costcent on Sorder.Costcent_code = Costcent.Costcent_code ".
			 " Left Join Salesmen on Sorder.Salesman_Code = Salesmen.Ledger_Number ".
			 " Left Join Temp_Sorder on Temp_Sorder.Sorder_Id = Sorder.Sorder_Id ".
			 " Left Join Transfer on Sorder.Transfer_id = Transfer.Transfer_id ".
			 " Left Join journal on journal.journal_id = sorder.journal_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 Sorder.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Sorder.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 Sorder.costcent_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Sorder.costcent_code = Q2.costcent_code )) ";							 



if($ledgerinclude== 1 && $ledgerexist > 0) {
	$querysearch = $querysearch." And Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								"              where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								"              and (ledger_number is not null and ledger_number != '') ".
								"              and Sorder.Client_Code like concat(ledgerstk.ledger_number,'%') ".
								"            ) ";
}
if($ledgerinclude== 0 && $ledgerexist > 0){
	$querysearch = $querysearch." And Not Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								"                  where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								"          	       and (ledger_number is not null and ledger_number != '') ".
								"                  and Sorder.Client_Code like concat(ledgerstk.ledger_number,'%') ".
								"                ) ";	
}
							 
$querysearch= $querysearch.											 
			 " Where (($searchby = 2 and Sorder.Sorder_Reference Like Concat(ifNull($PRef, Sorder.Sorder_Reference),'%')) Or ".
			 "        ($searchby = 1 and Date_Format(Sorder.Sorder_Date,'%Y-%m-%d') = ifNull(Date_Format($PRef,'%Y-%m-%d'), Date_Format(Sorder.Sorder_Date,'%Y-%m-%d'))) Or  ".
			 "        ($searchby = 3 and (Sorder.Client_Code Like Concat(ifNull($PRef, Sorder.Client_Code),'%') or Clients.Ledger_name Like Concat('%', ifNull($PRef, Clients.Ledger_name),'%')) ) Or  ".
			 "        ($searchby = 4 and (Sorder.Salesman_Code Like Concat(ifNull($PRef, Sorder.Salesman_Code),'%') or Salesmen.Ledger_Name Like Concat('%', ifNull($PRef, Salesmen.Ledger_Name),'%') )) Or  ".
			 "        ($searchby = 5 and Upper(Sorder.User_Account) Like Concat(ifNull(Upper($PRef), Upper(Sorder.User_Account)),'%')) Or  ".
			 "        ($searchby = 6 and Upper(ifNull(Sorder.Sorder_ConfirmUser,-1)) Like Concat(ifNull(Upper($PRef), Upper(ifNull(Sorder.Sorder_ConfirmUser,-1))),'%')) )  ".
			 //" And Sorder.Journal_Type = 'SO' ".
			 " And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Sorder.Sorder_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Sorder.Sorder_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
             "                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Sorder.Sorder_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ".
             " And (($option = 2 and ifNull(Sorder.Sorder_confirmed,0)=1 and ifNull(Sorder.Sorder_disapproved,0)=0) or ($option = 3 and ifNull(Sorder.Sorder_confirmed,0)=0 and ifNull(Sorder.Sorder_disapproved,0)=0) or ".
	  		 "      ($option = 4 and ifNull(Sorder.Sorder_disapproved,0)=1) or ($option = 5 and Sorder.Sorder_Type='CA') or ($option = 1 and 1=1) ) ".
			 " And (($option1 = 2 and ifNull(Sorder.Sorder_Status,0) = 0) or ($option1 = 3 and ifNull(Sorder.Sorder_Status,0) = 1) or ".
			 "      ($option1 = 4 and ifNull(Sorder.Sorder_Status,0) = 2) or ($option1 = 1 and 1 = 1)) ".
			 " And ifNull(Sorder.Sorder_BelongsToGrp,0) >= ifNull($FI_BelongsToGrp,0) ";
			 
if ($ShowTransaction != 1)
	$querysearch= $querysearch." And ( Upper(Sorder.User_Account) = Upper('".$_SESSION['useraccount']."') || Upper(Sorder.assignto_user) = Upper('".$_SESSION['useraccount']."'))";
			 
if ($PProjectCode != '')
	$querysearch= $querysearch." And Sorder.project_code like concat('".$PProjectCode."','%') ";
if ($PCostCentCode != '')
	$querysearch= $querysearch." And Sorder.costcent_code like concat('".$PCostCentCode."','%') ";	
			 
if ($fromdate != '' && $todate !='' )
	$querysearch = $querysearch." And Date_Format(Sorder.Sorder_Date,'%Y-%m-%d') between '".explodeword($fromdate)."' and '".explodeword($todate)."' ";
if ($orderby == 1)
	$querysearch= $querysearch." Order By Sorder.Sorder_Date Desc, Sorder.Sorder_Reference Desc ";
else if ($orderby == 2)
	$querysearch= $querysearch." Order By Sorder.Sorder_Reference Desc ";	
	
			 
//echo $querysearch;			 

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

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


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:1200px' align='center' valign='middle'>
			<table border='0'>
			<tr><td><span class='style3'>List of Preparation Order
			</span></td></tr>
			</table>
		</td>
		<td id='search-top3' style='height:34px; width:31px;'>&nbsp;</td>
	</tr>";

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



echo"<table border='0' cellspacing='1' style='table-layout:fixed'>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>";
if($SubItem_Production == 1) echo "<col width=20>";
echo "<col width=20>
	  <col width=20>
	  <col width=20>
	 
	  <col width=65>
	  <col width=70>
	  <col width=80>
	  <col width=135>
	  <col width=70>
	  <col width=80>
	  <col width=80>
	  <col width=55>
	  <col width=90>
	  <col width=75>
	  <col width=75>
	  <col width=80>
	  <col width=80>
	  <col width=20>
	  		     

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

}			

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

}	  

echo" <td align='right' ><span class='style4'>Order By</span></td>		
		  <td align='left' colspan='2' ><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></td>";
echo"  <td align='right' valign='center' colspan='2'><span class='style4'>Process Status&nbsp;</span></td>";			 
echo"  <td align='left' valign='center' colspan='4'><span class='style4'><select name='option1' id='option1' value='$option1' onchange='SelectStatus();'>";
		
		if ($option1==1)
			$s31 = 'selected';
		else if ($option1==2)
			$s32 = 'selected';
		else if ($option1==3)
			$s33 = 'selected';
		else if ($option1==4)
			$s34 = 'selected';	
			
		echo"<option ".$s31." value='1'>All</option>
			 <option ".$s32." value='2'>Pending</option>
			 <option ".$s33." value='3'>Delivered</option>
			 <option ".$s34." value='4'>Transferred</option>
			 </select></span></td>";		  
		echo" </tr>";
		echo" <tr class='Search-header-bg'>";	  
		echo"   <td align='left' colspan='5'><span class='style4'>Search By</span></td>
		<td align='left' colspan='7'><span class='style4'><input type='text' name='keyword' id='keyword' value='$keyword' size='15' maxlength='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();' style='width:110px;'>";
		
			if ($searchby==1)		$s21 = 'selected';
			else if ($searchby==2)	$s22 = 'selected';
			else if ($searchby==3)	$s23 = 'selected';
			else if ($searchby==4)	$s24 = 'selected';		
			else if ($searchby==5)	$s25 = 'selected';			
			else if ($searchby==6)	$s26 = 'selected';	
			else if ($searchby==7)	$s27 = 'selected';	
				
			echo"<option ".$s21." value='1'>Date (yyyy-mm-dd)</option>
				 <option ".$s22." value='2'>Reference</option>
				 <option ".$s23." value='3'>Client</option>
				 <option ".$s24." value='4'>Salesman</option>
				 <option ".$s25." value='5'>Create User</option>
				 <option ".$s26." value='6'>Confirm User</option>";
				 
			if($FI_DeliverySalesPrice==1)
				echo "<option ".$s27." value='7'>Amount</option>";
			
			echo "</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 align='right' valign='center' ><span class='style4'>Status&nbsp;</span></td>
		<td align='left' valign='center' colspan='2'><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';
		else if ($option==4)
			$s4 = 'selected';
		else if ($option==5)
			$s5 = 'selected';
			
		echo"<option ".$s1." value='1'>All</option>
			 <option ".$s2." value='2'>Confirmed</option>
			 <option ".$s3." value='3'>Unconfirmed</option>
			 <option ".$s4." value='4'>Disapproved</option>
			 <option ".$s5." value='5'>Canceled</option>
			 </select></span></td><td colspan='7'>&nbsp;&nbsp;&nbsp;<span class='style4'>Export</span>&nbsp;
			 <input type='checkbox' name='export' id='export' value=1>&nbsp;
			 &nbsp;&nbsp;&nbsp;&nbsp;<span class='style4'>Excell</span>&nbsp;<input type='checkbox' name='exportexcell' id='exportexcell' value=1>&nbsp;
			 
			| <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	
			<input type='checkbox' name='chkhs' id='chkhs' >HS Code	
			
		</span>
		
			 
			 </td>";
		
		
echo" </tr>";
echo" <tr class='Search-header-bg'>
<td colspan = '11' height = '30px'><span class='style4'>&nbsp;From</span><input type='text' name='fromdate' id='fromdate' value='$fromdate' maxlength='10' size='8'>
			 <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;<span class='style4'>To</span><input type='text' name='todate' id='todate' value='$todate' maxlength='10' size='8'>
			 <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>
			 <td><button type='button' id='btnBar2' name='btnBar2'  onclick=\"generateBarcode2();\" title='Print Barcode 2'><span><span>Barcode 2</span></span></button></td>
			<td colspan = '10'><button type='button' id='btnBar3' name='btnBar3'  onclick=\"generateBarcode3();\" title='Print Barcode 3'><span><span>Barcode 3</span></span></button></td>";
echo" </tr>";
echo "</table>
		</td>
		<td id='search-content3' style='width:31px;'>&nbsp;</td>"; 
echo" </tr>";

	  echo"<tr>
		<td  id='search-content1' style='height:34px;width:31px;'>&nbsp;</td>
		<td  id='search-content2' style='height:34px;width:1025px;'>
		<table width='100%' border=0>
		<tr>
			<td align='right' style='width:380px;'><span class='style4'>Per Page </span><span class='style4'><select name='perpage' id='perpage' value='$perpage' onchange=\"RefreshPage();\">";
              
            $perpages = $config['trowlimit'];
			foreach ($perpages as $val){
			echo" <option value = '$val' "; if ($perpage ==$val) echo "selected"; 
			echo" >$val</option> ";
			}
	echo'	
				 </select></span></td>
			<td  style="width:74px;border-right:1px solid #000000;text-align:right;">';
			
			if($startrange > 0)
				echo"<img src='img/firstpage.png' title='First Page' onMouseOver=\"style.cursor='hand'\" onclick=SetFirstPage('".$startrange."','".$perpage."')>";

			$diff= $startrange - $perpage;
				
			if (($diff) >= 0 ){
				$prvstartrange = $startrange - $perpage;
				echo"&nbsp;&nbsp;<img src='img/arrowleft.png' title='Previous' onMouseOver=\"style.cursor='hand'\"  onclick=SetPrvPage('".$prvstartrange."','".$perpage."')>";
			}
			else
				echo "&nbsp;";
		
echo"		</td><td  align='left' style='width:74px;'>";
		
		
			if ($startrange <= $totalrows){
				$startrange1 = $startrange + $perpage;
				if  ($startrange1 < $totalrows){
					echo"<img src='img/arrowright.png' title='Next' onMouseOver=\"style.cursor='hand'\" onclick=SetNextPage('".$startrange1."','".$perpage."')>";
					echo"&nbsp;&nbsp;<img src='img/lastpage.png' title='Last Page' onMouseOver=\"style.cursor='hand'\" onclick=SetLastPage('".$perpage."','".$totalrows."')>";	
				}
			} else
				echo "&nbsp;";
				
			
echo"		</td><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:1200px;'>
			<table border='0'  cellpadding='0' cellspacing='1' style='width:1345px;'>
	  
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>";
if($SubItem_Production == 1) echo "<col width=20>";  
if($sorderproduction == 1) echo "<col width=20>";  
echo"<col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=20>
	  <col width=65>";
if($Module_GenerateSorderJV == 1 || $Module_GenerateSorderJV == 2)
	echo "<col width=65><col width=65>";
echo "<col width=120>
	  <col width=80>
	  <col width=135>
	  <col width=70>
	  <col width=80>
	  <col width=80>
	  <col width=55>
	  <col width=90>
	  <col width=75>
	  <col width=75>
	  <col width=80>
	  <col width=80>
	  <col width=20>";	
	  
	if($message!=''){
		echo"<tr class='Search-header-bg'>
				<td height='15' align='center' colspan='24' 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='center'><span class='style4'>&nbsp;</span></td>
		<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>";
	if($SubItem_Production == 1)	
		echo"<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>";
	if($sorderproduction == 1)	
		echo"<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>";
	
	
	echo"<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
		<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
		<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
		<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
		<td  height='25' align='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>";
		
 echo "	<td  height='25' align='left'><span class='style4'>Documents </span></td>";///////////////////////////
		
		
echo  "	<td  height='25' align='left'><span class='style4'>Reference </span></td>";
		
	if($Module_GenerateSorderJV == 1 || $Module_GenerateSorderJV == 2)
	echo "<td  height='25' align='left'><span class='style4'>Folio </span></td>
		<td  height='25' align='left'><span class='style4'>JV Ref. </span></td>";
		
	echo "<td  height='25' align='center'><span class='style4'>Date </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'>CostCenter</span></td>
		<td  height='25' align='center'><span class='style4'>Salesman</span></td>";
	if($FI_DeliverySalesPrice==1)
	echo "		
		<td  height='25' align='center'><span class='style4'>Currency</span></td>
		<td  height='25' align='center'><span class='style4'>Total</span></td>";
	echo "
		<td  height='25' align='center'><span class='style4'>Status</span></td>
		<td  height='25' align='center'><span class='style4'>Progress</span></td>
		<td  height='25' align='center'><span class='style4'>Create User</span></td>
		<td  height='25' align='center'><span class='style4'>Confirm User</span></td>
		<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
	  </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."'";	
	
	if ($Sorder_Status == 'Unconfirmed')
		$Color="style='background-color:#D7F754'";	
	else if ($Sorder_Status == 'Disapproved')
		$Color="style='background-color:#FF0000;'";	
	
	$PrevHint     = 'Preview (with price)';
	$PrevHint1    = 'Preview (without price)';
	$EditHint     = 'Edit Record';
	$DelHint      = 'Delete Record';
	$ConfHint     = 'Confirm Order';
	$UnconfHint   = 'Unconfirm Order';
	$CancelHint   = 'Cancel Order';
	$RetrieveHint = 'Retrieve Order';
	$DisappHint   = 'Disapprove Order';
	$AppHint   = 'Approve Order';
	$TransferHint   = 'Auto Transfer';
	
	if ($TempSorderId != -1) {$PrevHint=$PrevHint1=$EditHint=$DelHint=$ConfHint=$UnconfHint=$CancelHint=$RetrieveHint=$DisappHint=$AppHint=$TransferHint = 'Exists in Pending';}
	
    if ($FI_SalesOrderMod == 0)	$SorEditMode =0; 
	else if ($FI_SalesOrderMod == 1 && $TempSorderId != -1) $SorEditMode =0;
	else if ($FI_SalesOrderMod == 1 && $TempSorderId == -1) $SorEditMode =1;
	
	if ($FI_SalesOrderDel == 0)	$SorDelMode =0; 
	else if ($FI_SalesOrderDel == 1 && $TempSorderId != -1) $SorDelMode =0;
	else if ($FI_SalesOrderDel == 1 && $TempSorderId == -1) $SorDelMode =1;
	
	if ($FI_SalesOrderConfirm == 0)	$SorConfMode =0; 
	else if ($FI_SalesOrderConfirm == 1 && $TempSorderId != -1) $SorConfMode = 0;
	else if ($FI_SalesOrderConfirm == 1 && $TempSorderId == -1) $SorConfMode = 1;
	
	
	if ($Login_DisapproveSorder == 0)	$SorDisappMode =0; 
	else if ($Login_DisapproveSorder == 1 && $TempSorderId != -1) $SorDisappMode =0;
	else if ($Login_DisapproveSorder == 1 && $TempSorderId == -1) $SorDisappMode =1;
	
	if ($Login_CancelSorder == 0)	$SorCancelMode = 0; 
	else if ($Login_CancelSorder == 1 && $TempSorderId != -1) $SorCancelMode =0;
	else if ($Login_CancelSorder == 1 && $TempSorderId == -1) $SorCancelMode =1;
	
	
	if ($TempSorderId != -1) $SorPrevMode =0; else $SorPrevMode =1;
	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($Sorder_Date))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($Sorder_Date)) >= $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	
	if ($ExceedLockPeriod == 1){
		$SorEditMode = 0;
		$SorDelMode = 0;
	}
	
	
	echo'<tr '.$Color.' ';
	echo "onMouseOver=\"style.cursor='pointer'\"  id='row$ct' onclick=\"SelectRecord(this,'SelectedRec','SelectedRecColor','".$Sorder_ID."');\" ";
	echo ">";
	if($SorPrevMode==1){
		if($FI_DeliverySalesPrice==1)
	   echo'<td align="center"><span class="style5"><img src="img/mag.jpg" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreview('.$Sorder_ID.', \''.$Sorder_Type.'\',0);"  title="'.$PrevHint.'"  style="width: 15px; height: 15px; " ></span></td>';
   
   
		echo'<td align="center"><span class="style5"><img src="img/print.png" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreviewNoPrice('.$Sorder_ID.', \''.$Sorder_Type.'\');"  title="'.$PrevHint1.'" style="width: 15px; height: 15px; " ></span></td>';
		echo'<td align="center"><span class="style5"><img src="img/excelbtn.png" onMouseOver="style.cursor=\'hand\'"  onclick="PrintPreview('.$Sorder_ID.', \''.$Sorder_Type.'\',1);"  title="Exp Excel" style="width: 15px; height: 15px; " ></span></td>';
	} else 
		echo"<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>";		
			
			
	if ($FI_SalesOrderMod == 1 && $SorEditMode==1)		
		echo'<td align="center"><span class="style5"><img src="img/edit.png" onMouseOver="style.cursor=\'hand\'" onclick="UpdateRecord('.$Sorder_ID.');" title="'.$EditHint.'" style="width: 20px; height: 20px; "></span></td>';
	else 	
		echo'<td align="center"><span class="style5">&nbsp;</span></td>';	
			
			
	if ($FI_SalesOrderConfirm == 1 && $SorConfMode==1) {
	
		echo'<td align="center"><span class="style5"><img src="img/confirmorder.png" onMouseOver="style.cursor=\'hand\'" onclick="ConfirmOrder('.$Sorder_ID.', \''.$Sorder_Reference.'\','.$option.', 1);" title="'.$ConfHint.'" style="width: 15px; height: 15px; "  ></span></td>
			 <td align="center"><span class="style5"><img src="img/unconfirmorder.png" onMouseOver="style.cursor=\'hand\'" onclick="ConfirmOrder('.$Sorder_ID.', \''.$Sorder_Reference.'\','.$option.', 2);" title="'.$UnconfHint.'" style="width: 15px; height: 15px; "  ></span></td>';
	} else {
		echo'<td align="center" colspan="2"><span class="style5"></span></td>';
	}
	
	
if($SubItem_Production == 1){
	if ($FI_SalesOrderMod == 1 && $SorEditMode==1)		
	echo'<td align="center"><span class="style5"><img src="img/duplicate-icon.png" onMouseOver="style.cursor=\'hand\'" onclick="duplicateSorder('.$Sorder_ID.', \''.$Sorder_Reference.'\')"; title="Duplicate Sales Order" style="width: 15px; height: 15px; "  ></span></td>';
	else 	
	echo'<td align="center"><span class="style5">&nbsp;</span></td>';
}
	// Cancel Preproduction
	if($sorderproduction == 1){
		if ($FI_SalesOrderMod == 1 && $SorEditMode==1)		
		echo'<td align="center"><span class="style5"><img src="img/cancelorder.png" onMouseOver="style.cursor=\'hand\'" onclick="cancelPreProduction('.$Sorder_ID.', \''.$Sorder_Reference.'\')"; title="Cancel From Preproduction" style="width: 15px; height: 15px; "  ></span></td>';
		else 	
		echo'<td align="center"><span class="style5">&nbsp;</span></td>';
	}	
	if($RA_StatementofAccount ==1)
		echo'<td align="center"><span class="style5"><img src="img/print.png" onMouseOver="style.cursor=\'hand\'" onclick="PrintStatement(\''.$base1.'\',\''.$Module_ReferenceByProject.'\',\''.$ClientCode.'\',\''.$Project_Code.'\',\''.$Costcent_code.'\')"; title="Print Client Statement" style="width: 15px; height: 15px; "  ></span></td>';
	else echo'<td align="center"><span class="style5"></span></td>';
	
	if ($Login_CancelSorder == 1 && $SorCancelMode==1) {		
		echo'<td align="center"><span class="style5"><img src="img/cancelorder.png" onMouseOver="style.cursor=\'hand\'" onclick="CancelOrder('.$Sorder_ID.', \''.$Sorder_Reference.'\','.$option.');" title="'.$CancelHint.'" style="width: 15px; height: 15px; "  ></span></td>';
	} else {
		echo'<td align="center"><span class="style5"></span></td>';
	}
	
	if (($Login_CancelSorder == 1 || $Login_DisapproveSorder == 1) && $SorCancelMode==1) {	
		echo'<td align="center"><span class="style5"><img src="img/retrieveorder.png" onMouseOver="style.cursor=\'hand\'" onclick="RetrieveOrder('.$Sorder_ID.', \''.$Sorder_Reference.'\','.$option.');" title="'.$RetrieveHint.'" style="width: 15px; height: 15px; "  ></span></td>';
	} else {
		echo'<td align="center"><span class="style5"></span></td>';
	}
	
	if ($Login_DisapproveSorder == 1 && $SorDisappMode==1) {		
		echo'<td align="center"><span class="style5"><img src="img/disapprove.png" onMouseOver="style.cursor=\'hand\'" onclick="DisapproveOrder('.$Sorder_ID.', \''.$Sorder_Reference.'\','.$option.');" title="'.$DisappHint.'" style="width: 15px; height: 15px; "  ></span></td>';
	} else {
		echo'<td align="center"><span class="style5"></span></td>';
	}
	if ($Login_DisapproveSorder == 1 && $SorDisappMode==1) {		
		echo'<td align="center"><span class="style5"><img src="img/approve.jpg" onMouseOver="style.cursor=\'hand\'" onclick="ApproveOrder('.$Sorder_ID.', \''.$Sorder_Reference.'\','.$option.');" title="'.$AppHint.'" style="width: 15px; height: 15px; "  ></span></td>';
	} else {
		echo'<td align="center"><span class="style5"></span></td>';
	}
	
	if ($Module_AutoTransSorder == 1 && $SorPrevMode==1 && $Transfer_id=='' && $SorEditMode==1  && $Sorder_Type == 'SO'){
		echo'<td align="center"><span class="style5"><img src="img/tr.gif" onMouseOver="style.cursor=\'hand\'" onclick="OpenAutoTransfer('.$Sorder_ID.', \''.$Sorder_Reference.'\',\''.$startrange.'\',\''.$perpage.'\','.$option.');" title="'.$TransferHint.'" style="width: 15px; height: 15px; "  ></span></td>';
	} else {
		echo'<td align="center"><span class="style5">'.$Transfer_Reference.'</span></td>';
	}
	
	echo'<td align="center"><span class="style5"><img src="img/details.gif" onMouseOver="style.cursor=\'hand\'"  onclick="ShowHideDetails('.$Sorder_ID.', \''.'S'.'\','.$startrange.');" title="Show Details" style="width:15px; height:15px; "></span></td>';	
	// echo " <td align = \"center\" <span class = \"style5\"> <a onclick=\"UploadDocuments('salesorder','$Sorder_ID');\" >View </a> </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(\''.'salesorder'.'\','.$Sorder_ID.');"  title="Show Document" style="width: 18px; height: 15px; " ></span></td>';	
	}else{
		echo'<td align="center"><span class="style5">&nbsp;</span></td>';
	}
	echo'	<td align="left"><span class="style5">'.$Sorder_Reference.'</span></td> ';
	if($Module_GenerateSorderJV == 1 || $Module_GenerateSorderJV == 2)
	echo '	<td align="left"><span class="style5">'.$journal_folio.'</span></td>
			<td align="left"><span class="style5">'.$journal_refgovernment.'</span></td> ';
			
	echo '	<td align="center"><span class="style5">'.$Sorder_Date.'</span></td>
			<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>
			<td align="left"><span class="style5">'.$SalesmanName.'</span></td> ';
	if($FI_DeliverySalesPrice==1)		
	echo '	<td align="center"><span class="style5">'.$Currency_code.'</span></td>
			<td align="right"><span class="style5">'.number_format($NetTotal, $DecimalBase).'</span></td> ';
			
	echo '  <td align="left"><span class="style5">'.$Sorder_Status.'</span></td>
			<td align="left"><span class="style5">'.$Sorder_Progress.'</span></td>
			<td align="left"><span class="style5">'.$UserAccount.'</span></td>
			<td align="left"><span class="style5">'.$SorderConfirmUser.'</span></td>';
			
	if ($FI_SalesOrderDel == 1 && $SorDelMode == 1)		
		echo'<td align="center"><span class="style5"><img src="img/delete.png" onMouseOver="style.cursor=\'hand\'" onclick="DeleteRecord('.$Sorder_ID.', \''.$Sorder_Reference.'\','.$option.');" title="'.$DelHint.'" '.$SorDelMode.' ></span></td>';
	else 	
		echo'<td align="center"><span class="style5">&nbsp;</span></td>';
			
	echo'</tr>';
	
	$sub_query = " Select SorderDt.SorderDt_id, SorderDt.Item_CodePacked, SorderDt.Item_code, Item_Description, SorderDt.Warehouse_Code, ".
				 " Item_UnitSalesDesc, SorderDt_Quantity, Round(SorderDt_Price, ".$DecimalBase."), Round(SorderDt_Discount, ".$DecimalBase."),  ".
				 " Round(((SorderDt_Quantity*SorderDt_Price)-((SorderDt_Quantity*SorderDt_Price*ifNull(SorderDt_Discount,0))/100)), ".$DecimalBase.") As Total, ".
				 " Round(SorderDt_PriceTTC, ".$DecimalBase."), ".
				 " Round(((SorderDt_Quantity*SorderDt_PriceTTC)-((SorderDt_Quantity*SorderDt_PriceTTC*ifNull(SorderDt_Discount,0))/100)), ".$DecimalBase.") As TotalTTC ".
				 " From SorderDt Left Join Items on SorderDt.Item_code = Items.Item_code ".
				 " Where SorderDt.Sorder_ID = ".$Sorder_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'.$Sorder_ID;
			
		echo "<tr ".$Color.">";
		echo "<td colspan='24' valign='top' align='left'><div id='$SlideDivId' class='div-search-details' style='display:none; margin-left:180px;'>";
		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($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($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:1025px;' valign='top'><table width='100%' border=0 height=28px>
		<tr><td style='width:280px;'>&nbsp;</td><td   style='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 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='380px'>&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;
}
?>