<?php

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

include("function.inc.php");
include("config.inc.php");
set_time_limit(0);

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

$querylog=" select ifNull(FI_DeliveryApp,0) As FI_DeliveryApp, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ".
		  " ifNull(FI_sorderconfirmed,0) As FI_SalesOrderConfirm, ifNull(login_disapprovesorder,0) As Login_DisapproveSorder, ifNull(FI_FrmRestrictWarehouse,0) As FI_FrmRestrictWarehouse ".
          " ,PrequestApproved_Level As PrequestApproved_Level  ".
		  " ,ifnull(fi_pendingpurchaserequest,0) fi_pendingpurchaserequest".
		  " ,ifnull(fi_pendingtransferrequest,0) fi_pendingtransferrequest".
		  " ,ifnull(fi_pendingadjustmentrequest,0) fi_pendingadjustmentrequest".
		  " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

$EditHint = '';
$EditMode = '';

$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, 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 Module Table
$querymodule=" Select ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
			 " ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_PRequestConfirm,0) As Module_PRequestConfirm, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method ".
			 " ,ifnull(Module_PurchaseRequestPrice,0) as Module_PurchaseRequestPrice ".
			 " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$querydflwh="select warehouse_code as defaultwarehouse from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and ifNull(default_warehouse,0) = 1 ";

$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC, ifNull(Sale_MinPendingQty,0) As Sale_MinPendingQty, ifNull(Sale_MaxExceedQty,0) As Sale_MaxExceedQty From SalesSetup";
$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_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent, ".
			 " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_TransferSorder,0) As Module_TransferSorder  From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$MainCompanyName=explode('_',$_SESSION['dbName']);

$queryperiod= " Select ifNull(LockViewPeriod,0) As LockViewPeriod, ViewPeriodDate, ifNull(ViewLockDaily,0) As ViewLockDaily, ViewNumberOfDays ".
              " From ".$_SESSION['dbLabel'].".ListUserDir  ".
			  " Where Usercode='".$_SESSION['useraccount']."' ".
			  " And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			  " And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
			  
$resultperiod = mysql_query($queryperiod,$connection) or die(mysql_error());
$rowsperiod   = mysql_num_rows($resultperiod);

while($rows=mysql_fetch_array($resultperiod)){
	extract($rows);
}	
			  
//echo $queryperiod;	

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on (($Module_ProjectParent=1 and project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%')) or ($Module_ProjectParent=0 and project.project_code = loginstk.project_code )) ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " and (loginstk.project_code is not null and loginstk.project_code != '') ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist  = mysql_num_rows($projectresult);		  

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on (($Module_CostCenterParent=1 and costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%')) or ($Module_CostCenterParent=0 and costcent.costcent_code = loginstk.costcent_code )) ".
			   " where user_account='".$_SESSION['useraccount']."' ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') ".
			   " order by costcent.costcent_code";
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentexist  = mysql_num_rows($costcentresult);	

$querywh=" select distinct warehouse.warehouse_code, warehouse_name ".
         " from warehouse inner join ".$_SESSION['dbLabel'].".loginstk on warehouse.warehouse_code = loginstk.warehouse_code ".
		 " where user_account='".$_SESSION['useraccount']."' ".
		 " and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
		 " order by warehouse.warehouse_code";
$whresult = mysql_query($querywh,$connection) or die(mysql_error());
$whexist  = mysql_num_rows($whresult);	  

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

$prqstid 	= $_POST["prqstid"]; if ($prqstid == ""){$prqstid = $_GET["prqstid"];}
$reqType 	= $_POST["reqType"]; if ($reqType == ""){$reqType = $_GET["reqType"];}
$actionmode	= $_POST["actionmode"]; if ($actionmode == ""){$actionmode = $_GET["actionmode"];}


if ($actionmode=='insert') {
		if($reqType == 'p')	
			$query = "select PRqst_remark,Project_Code,Costcent_code,currency_code from prequest where prqst_id = $prqstid";
		else if($reqType == 'mr')	
			$query = "select MReq_remark as PRqst_remark,Project_Code,Costcent_code,currency_code from materialreq where MReq_id = $prqstid";
			$result=mysql_query($query,$connection) or die(mysql_error());
			while($rows=mysql_fetch_array($result)){
				extract($rows);
				}

				fbegin();
				$adjustmentrequest_id = get_nextsequence('Adjustment_id','',$connection);	
				fcommit();

				fbegin();
				$adjustmentrequest_reference = get_nextsequence('OUT_Reference','',$connection);	
				fcommit();
				
				fbegin();
				
				
				$query = "insert into adjustment(adjustment_id,adjustment_reference,Adjustment_Date,Adjustment_Remak
						,Project_code,Costcent_Code,Adjustment_EntryType	,User_account, ";
			if($reqType == 'p')				
				$query .= " prqst_id ";
			else if($reqType == 'mr')	
				$query .= " MReq_id ";
				$query .=" )
						 values
							(".$adjustmentrequest_id."
							,".$adjustmentrequest_reference."
							,now()
							,'".ereg_replace("'","\'",$PRqst_remark)."'
							,".GetSQLValueString($Project_Code,'text')."
							,".GetSQLValueString($Costcent_code,'text')."
							,'O' 
							,'".$_SESSION['useraccount']."'
							,$prqstid
							)";
			//echo $query."<br>";
			//exit;
			$resultheader=mysql_query($query,$connection) or die(mysql_error());
			if($reqType == 'p')	
				$query= " select Item_code,warehouse_code,PRqstDt_Remark,PRqstDt_Price,PRqstDt_PriceBase1,PRqstDt_PriceBase2 
							,CostCent_code,Project_code,Item_UnitCoef,Item_Unit2Qty,PRqstDt_id
							from prequestdt where prqst_id = $prqstid";
			else if($reqType == 'mr')	
				$query= " select Item_code,warehouse_code,MReqDt_Remark as PRqstDt_Remark,MReqDt_Price as PRqstDt_Price,MReqDt_PriceBase1 as PRqstDt_PriceBase1,MReqDt_PriceBase2  as PRqstDt_PriceBase2
							,CostCent_code,Project_code,Item_UnitCoef,Item_Unit2Qty,MReqDt_id as PRqstDt_id
							from materialreqdt where MReq_id = $prqstid";	
				$result5=mysql_query($query,$connection) or die(mysql_error());
				$result5s=mysql_query($query,$connection) or die(mysql_error());
				$i=0;
				
				
				while($rowdts=mysql_fetch_array($result5s)){
						$yy = 'transferwarehousecode'.$i;					
						$towarehouse = $$yy;
						if ($towarehouse=='')
							{
							  $warehousemsg = "<font color=red>Warehouse can not be empty.</font>";
							  echo $warehousemsg;
							}
				$i+=1;			
				}
				$i=0;
				
				//echo $warehousemsg;
				
				if ($warehousemsg =='')
				while($rowdt=mysql_fetch_array($result5)){
							extract($rowdt);
							
							$PAdjustmentrequestdt_id = get_nextsequence('AdjustmentDt_id','',$connection);	
							
									$query = "select BASE1 from setup limit 1";
									$result1=mysql_query($query,$connection)	or die( mysql_error());
										while($row=mysql_fetch_array($result1)){
										extract($row);
										}
										
								$query="select curdt_parity from curdt where currency_code='".$BASE1."'  order by curdt_date desc";
								//echo $query;
								$result1=mysql_query($query,$connection)	or die( mysql_error());
								
								while($row=mysql_fetch_array($result1)){
								extract($row);
								}
								$item_sellingprice2=$p_item_sellingprice1/$curdt_parity;
						
						
						if ($Item_Unit=='')
							$Item_Unit = 1;
							
						if ($Item_Unit2Qty=='')
							$Item_Unit = 0;
							
						$xx = 'transferqty'.$i;					
						$p_item_quantity = $$xx;
						//echo $p_item_quantity;
						
						if ($p_item_quantity=='')
							$p_item_quantity = 0;
						
						$yy = 'transferwarehousecode'.$i;					
						$towarehouse = $$yy;
						//echo $towarehouse;
						
						if ($Item_code=='') {
						$zz = 'item_code'.$i;
						$Item_code = $$zz;
						}
						
						if ($p_item_quantity != 0) {
						
						/*$query11 = "update prequestdt set PRqstDt_status = 'c',PRqstDt_approvedlevel='$PrequestApproved_Level' where PRqstDt_id = $PRqstDt_id";
						//echo $query11;
						//exit;
						$resultdt11=mysql_query($query11,$connection)	or die( mysql_error());
						*/
						if($reqType == 'p')
							$query12 = "update prequestdt set PRqstDt_CQuantity = '$p_item_quantity'
										where PRqstDt_id = $PRqstDt_id";
						else if($reqType == 'mr')	
							$query12 = "update materialreqdt set MReqDt_CQuantity = '$p_item_quantity'
										where MReqDt_id = $PRqstDt_id";							
						$resultdt12=mysql_query($query12,$connection)	or die( mysql_error());
						
						if($reqType == 'p')
							$query12 = "update prequestdt set PRqstDt_Quantity = ifnull(PRqstDt_Quantity,0) - ifnull(PRqstDt_CQuantity,0) where PRqstDt_id = $PRqstDt_id";
						else if($reqType == 'mr')
							$query12 = "update materialreqdt set MReqDt_Quantity = ifnull(MReqDt_Quantity,0) - ifnull(MReqDt_CQuantity,0) where MReqDt_id = $PRqstDt_id";
						$resultdt12=mysql_query($query12,$connection)	or die( mysql_error());
						
						
						$query = "insert into adjustmentdt
								(adjustmentdt_id,adjustment_id,Adjustment_Date,item_code,AdjustmentDt_Quantity
								,AdjustmentDt_Price,AdjustmentDt_PriceBase1,AdjustmentDt_PriceBase2
								,Warehouse_Code,costcent_code
								,project_code,currency_code";
								
								if ($Module_DoubleUnit==1)
								$query = $query."
								,Item_UnitCoef
								,Item_Unit2Qty ";
								
								
								$query = $query.") values(
							  '".$PAdjustmentrequestdt_id."'
							  ,'".$adjustmentrequest_id."'
							  ,NOW()
							  ,'".$Item_code."'						  
							  ,'".-1*$p_item_quantity."'
							  ,".$PRqstDt_Price."
							  ,".$PRqstDt_PriceBase1."
							  ,".$PRqstDt_PriceBase2."
							   ,".GetSQLValueString($towarehouse,'text')."
							  ,".GetSQLValueString($CostCent_code,'text')."
							 ,".GetSQLValueString($Project_code,'text')."
							 ,".GetSQLValueString($currency_code,'text')."";
							
							if ($Module_DoubleUnit==1)
								$query = $query.",'".$Item_UnitCoef."' ,".$Item_Unit2Qty." ";
							   
					   
								$query = $query.")";
				//echo $query."<br>";
				//exit;
				$resultdt=mysql_query($query,$connection)	or die( mysql_error());
				}
				$i+=1;
				}
				
				if ($resultheader and $resultdt)
					{
					fcommit();
					}
				else
					frollback();

if ($warehousemsg=='')
print <<<HERE
<script type="text/javascript" language="javascript">
opener.document.search.submit();
self.close();
</script>
HERE;

}



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" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">
<title>Pending Request Items</title>
<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;
}
.style15 {color: #5151FF; font-size: 10px;}
.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: #FFFFFF ;font-size: 10px;}

</style>

<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">
<script type="text/javascript" src="js/grid/UI_DataGrid.js"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>


<link type="text/css" href="js/calendar/jquery.datepick.css" rel="stylesheet">
<script type="text/javascript" src="js/calendar/jquery.datepick.js"></script>

<link type="text/css" href="js/grid/scripts/jquery-ui.css" rel="stylesheet">
<script type="text/javascript" src="js/grid/scripts/jquery-ui.min.js"></script>

<script type="text/javascript" language="javascript">
	$(document).ready(function() { 
		
		$(document).on('focus', '.date', function() {
			$('.date').datepick({showTrigger: '#calImg'});
		});
		
		$(document).on('focusin', '.table-focus-g1', function() {
			AutoSaveRecordGrid(this.id);
		});
		
		
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
		//Set Cursor Position After Page Reload
		var NextElement = readCookie('so-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('so-nextcell');
		
	
	});
	
	
</script>

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

function checkqty(indx,qty){
 
 trqty = 'transferqty' + indx;
 trqty = document.getElementById(trqty).value;
 
 if (trqty>qty) {
	alert('Qty can exceed '+qty);
	document.getElementById('transferqty' + indx).value = qty;
	document.getElementById('transferqty' + indx).focus();
	}
}

function showsearchpage(vtype,vtext1,vtext2,vtext3,vtext4,vtext5,vtext6,vwidth,vheight){

	var text1value = document.getElementById(vtext1).value;
	
	if (document.getElementById(vtext2))
		var text2value = document.getElementById(vtext2).value;
else
		var text2value = '';
		
		
	win = window.open('List_PurItems.php?PItem_Code='+text1value+'&PItem_Description=&item=4&vtype='+vtype+'&vtext1='+vtext1+'&vtext2='+vtext2+'&vtext3='+vtext3
						+'&vtext4='+vtext4+'&vtext5='+vtext5+'&vtext6='+vtext6
						+'&text1value='+text1value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
	win.creator = self;
	win.focus();	
	}

	
function setitemcode(val,vfield1,vfield2,vfield3,vfield4,vfield5,vfield6,vgridname,btnname,btnname1,codedesc, reqType){

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
				{ 	var data = xmlhttp.responseText.split("[BRK]");
					var resp = data[1];
					
					if (resp==0)
						{
							if (codedesc==1)
								document.getElementById(btnname).click();
							else	
								document.getElementById(btnname1).click();
						}
						else
							{	
								if (codedesc==1)
									document.getElementById(vfield2).value = resp;
								else	
									document.getElementById(vfield1).value = resp;
							}	
						//showsearchpage('itemcode',vfield1,vfield2,vfield3,vfield4,vfield5,vfield6,800,500);

				}
		}
  }
if(reqType == 'p') var str = "Form_PurchaseRequest_Actions.php";
else  if(reqType == 'mr') var str = "Form_MaterialRequisition_Actions.php";
 
  if (codedesc==1)
	xmlhttp.open("GET",str+"?vitemcode="+val+"&codedesc="+codedesc+"&actionmode=checkitemcode",true);
else	
  if (codedesc==2)
	xmlhttp.open("GET",str+"?vitemdesc="+val+"&codedesc="+codedesc+"&actionmode=checkitemcode",true);  
  
  
xmlhttp.send();

}



function showlistWarehouseqtyexists(vtype,vtext1,vtext2,vwidth,vheight,vitem,vdate){
	
	var text1value = document.getElementById(vtext1).value;

	win = window.open('List_WarehousesQtyExists.php?PRef='+text1value+'&str=10&vtype='+vtype+'&vtext1='+vtext1+'&vtext2='+vtext2+'&vitem='+vitem+'&vdate='+vdate
						+'&text1value='+text1value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
	win.creator = self;
	win.focus();	

	
}


function showlistWarehouse(vtype,vtext1,vwidth,vheight){
	var text1value = document.getElementById(vtext1).value;

	win = window.open('List_Warehouses.php?PRef='+text1value+'&str=5&vtype='+vtype+'&vtext1='+vtext1
						+'&text1value='+text1value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
	win.creator = self;
	win.focus();	

	
}


function savedata(){
/*
if (document.create.towarehouse.value=='') {
alert('Please fill to warehouse.');
document.create.towarehouse.focus();
return;
}*/
document.create.actionmode.value='insert';
document.create.submit();

}


</script>


</head>
<body>
<form name='create' method='post' action=''>
<input type='hidden' name='actionmode' value='$actionmode' >
<input type='hidden' name='PRqstDt_approvedlevel' value='$PRqstDt_approvedlevel' >
HERE;


echo"<table cellpadding='0' cellspacing='0' border='1'  align='center' class='grid_data' width=430px>
<col width=170>
<col width=220>
<col width=150>
<col width=120>
<col width=95>";


if ($_GET["prqstid"]=='')
	$prqstid = $_POST["prqstid"];
	
	echo " <tr><th>Item Code</th><th>Description</th><th colspan=1>Warehouse</th>";
	//<th colspan=1>To Warehouse</th>
	echo " <th colspan=1>Qty</th><th colspan=1>Qty Exists</th>";


	
// purchase request part	

if($reqType == 'p')	
	$query=" select prequest.prqst_reference as prqst_reference,date_format(prequest.prqst_date,'%d/%m/%Y') as prqst_date,prequest.currency_code as currency_code
				,prequest.prqst_total as prqst_total,prequestdt.item_code as item_code,items.item_description as item_description,prequestdt.item_description as item_description1 
				,PRqstDt_OQuantity,PRqstDt_CQuantity,PRqstDt_Quantity,PRqstDt_id,PRqstDt_status,prequest.PRqst_id as PRqst_id,ifnull(PRqstDt_approvedlevel,5000) as PRqstDt_approvedlevel
				,prequestdt.warehouse_code,prequest.project_code as prequestproject_code,prequest.costcent_code as prequestcostcent_code,prequestdt.project_code as project_code,prequestdt.costcent_code as costcent_code
				,ifnull(QtyExists(prequestdt.item_code , '$transferwarehousecode[$i]', prequest.prqst_date, 0, 'PQ', '', ''),0) as qtyexists
				,ifnull(PRqstDt_OQuantity,0) - ifnull(PRqstDt_CQuantity,0) as remainingqty
				from prequest,prequestdt left join items on items.item_code=prequestdt.item_code
				where prequest.prqst_id = prequestdt.prqst_id  
				and ifnull(prequestdt.PRqstDt_status,'a') <> 'c'
				and prequest.prqst_id = $prqstid";
else  if($reqType == 'mr')	
	$query=" select materialreq.MReq_reference as prqst_reference,date_format(materialreq.MReq_date,'%d/%m/%Y') as prqst_date,materialreq.currency_code as currency_code
				,materialreq.MReq_total as prqst_total,materialreqdt.item_code as item_code,items.item_description as item_description,materialreqdt.item_description as item_description1 
				, MReqDt_OQuantity as PRqstDt_OQuantity, MReqDt_CQuantity as PRqstDt_CQuantity, MReqDt_Quantity as PRqstDt_Quantity, MReqDt_id as PRqstDt_id, MReqDt_status as PRqstDt_status,materialreq.MReq_id as PRqst_id,ifnull(MReqDt_approvedlevel,5000) as PRqstDt_approvedlevel
				,materialreqdt.warehouse_code,materialreq.project_code as prequestproject_code,materialreq.costcent_code as prequestcostcent_code,materialreqdt.project_code as project_code,materialreqdt.costcent_code as costcent_code
				,ifnull(QtyExists(materialreqdt.item_code , '$transferwarehousecode[$i]', materialreq.MReq_date, 0, 'MR', '', ''),0) as qtyexists
				,ifnull(MReqDt_OQuantity,0) - ifnull(MReqDt_CQuantity,0) as remainingqty
				from materialreq,materialreqdt left join items on items.item_code=materialreqdt.item_code
				where materialreq.MReq_id = materialreqdt.MReq_id  
				and ifnull(materialreqdt.MReqDt_status,'a') <> 'c'
				and materialreq.MReq_id = $prqstid";
//echo $query;exit;

$result=mysql_query($query,$connection) or die(mysql_error());	
	

$i = 0;

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

				if($ct%2==0)
					$Color="style='background-color:".$grid_color1."'";
				else			
					$Color="style='background-color:".$grid_color2."'";	
					
					
	$xx = 'PRqstDt_Quantity'.$i;
	$$xx = $PRqstDt_Quantity;
	echo "<tr $Color><td>$item_code";
	
	
	$val = 'item_code'.$i;
	$val1 = 'item_description'.$i;
	
	if ($item_code=='')
		echo"<span class='style4'><input type='text'   name='item_code$i' id='item_code$i' value='".$$val."'   
		$KeyDown   class='roundedtext_amortization_small'   onchange=\"setitemcode(this.value,'item_code".$i."','item_description".$i."','','','','','','','',1);\"  style='width:100px'></span>
				<img src='img/scroll-down-1.png' width='20' height='20' id='trqstdtitemcodeimage$i' onmouseover=\"style.cursor='pointer'\"  onclick=\"showsearchpage('itemcode','item_code$i','item_description$i','','','','','800','500','','')\">
					";

	
	echo"</td><td>$item_description
	
	";
	if ($item_description=='')
		echo "<input type='text' value='".$$val."' name='item_description$i' id='item_description$i'>";
	
	echo"</td>";
		
		$trans = 'transferqty'.$i.'';

		$war = 'transferwarehousecode'.$i;
		
		if ($$trans=='')
			$$trans = $PRqstDt_OQuantity;
			//$$trans = $qtyexists;
			
		if ($$war=='')
			$$war = $warehouse_code;//$defaultwarehouse;
			
		echo "<td  colspan=1><span class='style15'>";
		echo"<input type='text'   $KeyDown   class='roundedtext_amortization_medium'   style='width:70px'  name='transferwarehousecode$i' id='transferwarehousecode$i' value='".$$war."' onchange=\"setwarehousecode(this.value,'transferwarehousecode$i','imgwarehousebtn[$i]');SetModRecord('ModRec_G1','$i');\"  > </span>
			<img src='img/scroll-down-1.png' title=' Select Warehouse ' id='imgwarehousebtn[$i]' width='20' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onclick=\"showlistWarehouseqtyexists('warehousecode','transferwarehousecode$i','transferqtyexists$i','800','500','$item_code','$prqst_date') \" />
			";
			
	echo"</span></td>";
	//echo"<td>$warehouse_code</td>";
	
	if ($remainingqty=='')
		$remainingqty = 0;
	
	//echo $qtyexists;exit;
		
echo "<td  colspan=1><span class='style15'>
<input type='text' name='transferqty$i' onchange=\"checkqty($i,$remainingqty)\" id='transferqty$i' value='".$$trans."' style='width:50px'>
</td><td><input type='text' name='transferqtyexists$i'  readonly id='transferqtyexists$i' value='".$qtyexists."' style='width:50px'>

</span></td>";


	//echo"<td><input type='text' name='".$xx."' value='".$$xx."' style='width:70px;text-align:right'></td>
	echo"</tr>";
$i+=1;
}

//echo "<tr height=40><td align=center colspan=5>To Warehouse: <input type='text' name='towarehouse'  id='towarehouse' value='$towarehouse'>
//<img src='img/scroll-down-1.png' title=' Select Warehouse ' id='imgwarehousebtn[$i]' width='20' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onclick=\"showlistWarehouse('towarehouse','towarehouse','800','500') \" />
//</td></tr>";

echo"<tr height=50><td align=center colspan=6><input type='button' name='but'  onmouseover=\"style.cursor='pointer'\"  onclick='savedata()' value='Create Stock Out'></td></tr>";

echo"</table>";


print <<<HERE

</form>
</body>

HERE;

function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

function displayParadoxDate($data){
		return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2);
	}
	
//Return Today's Date in YYYYMMDD format. Supplied Format: DD/MM/YYYY
	function insertDate($data){
		return substr($data, 6, 4) . substr($data, 3, 2) . substr($data, 0, 2);
	}	
?>