<?php

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


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


$querylog="SELECT FI_ReturnGrn as loginaccess 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);
}

if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");

	
$querylog=" Select ifNull(FI_ReturnGrnApp,0) As FI_ReturnGrnApp, ifNull(Login_FastPrint,0) As Login_FastPrint ".
          " 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 Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, 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_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_SerialNo,0) As Module_SerialNo, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(module_grncostprice,0) As Module_grncostprice,".
			 " ifNull(Module_Pack,0) As Module_Pack, ifNull(Module_Heatno,0) As Module_Heatno, ifNull(module_locationGrn,0) As module_locationGrn, ".
			 " ifnull(Module_GRNwithPorder,0) as Module_GRNwithPorder ".
			 " From Module  ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

//Read From PurchaseSetup Table
$queryPurchaseSetup="Select PurchaseTTC, Warehouse As SetupDftWareHouse, ifNull(ShowCostCentLayout,0) As ShowCostCentLayout From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}

$querylog="select ifNull(FI_PurchaseCategory,0) As FI_PurchaseCategory 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);
}

$querydflwh="select default_warehouse_code as defaultwarehouse from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_warehouse_code != '' ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}


$actionmode = $_POST["actionmode"]; if ($actionmode == ""){$actionmode = $_GET["actionmode"];}   
$mainaction = $_POST["mainaction"]; if ($mainaction == ""){$mainaction = $_GET["mainaction"];} 
$mainmode   = $_POST["mainmode"]; if ($mainmode == ""){$mainmode = $_GET["mainmode"];} 
$message 	= $_POST["message"]; if ($message == ""){$message = $_GET["message"];}   
$PrPurId 	= $_POST["PrPurId"]; if ($PrPurId == ""){$PrPurId = $_GET["PrPurId"];}
$PurType 	= $_POST["PurType"]; if ($PurType == ""){$PurType = $_GET["PurType"];}
$QtySerNo 	= $_POST["QtySerNo"]; if ($QtySerNo == ""){$QtySerNo = $_GET["QtySerNo"];}


$txtPurCountDetail 	= $_POST["txtPurCountDetail"]; if ($txtPurCountDetail == ""){$txtPurCountDetail = $_GET["txtPurCountDetail"];} 
$PurId    		= $_POST["txtPurId"]; if ($txtPurId == ""){$txtPurId = $_GET["txtPurId"];} 
$txtRef 			= $_POST["txtRef"]; if ($txtRef == ""){$txtRef = $_GET["txtRef"];} 
$txtDate 			= $_POST["txtDate"]; if ($txtDate == ""){$txtDate = $_GET["txtDate"];} 
$txtMaturityDate   	= $_POST["txtMaturityDate"]; if ($txtMaturityDate == ""){$txtMaturityDate = $_GET["txtMaturityDate"];} 
$txtSupplier 	   	= $_POST["txtSupplier"]; if ($txtSupplier == ""){$txtSupplier = $_GET["txtSupplier"];} 
$txtSupplierName 	= $_POST["txtSupplierName"]; if ($txtSupplierName == ""){$txtSupplierName = $_GET["txtSupplierName"];} 
$txtSupplierVat 	= $_POST["txtSupplierVat"]; if ($txtSupplierVat == ""){$txtSupplierVat = $_GET["txtSupplierVat"];} 
$txtPaymentTerms	= $_POST["txtPaymentTerms"]; if ($txtPaymentTerms == ""){$txtPaymentTerms = $_GET["txtPaymentTerms"];} 
$txtCurr   			= $_POST["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_GET["txtCurr"];} 
$txtPurCategory   	= $_POST["txtPurCategory"]; if ($txtPurCategory == ""){$txtPurCategory = $_GET["txtPurCategory"];} 
$txtRemark  		= $_POST["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_GET["txtRemark"];} 
$txtProjectCode 	= $_POST["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_GET["txtProjectCode"];} 
$txtCostCentCode	= $_POST["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_GET["txtCostCentCode"];} 
$txtInvoiceNo		= $_POST["txtInvoiceNo"]; if ($txtInvoiceNo == ""){$txtInvoiceNo = $_GET["txtInvoiceNo"];} 




if (empty($mainaction))	$mainaction = 'insert';

$message = ereg_replace("'"," ",$message);

$Title = '';
$HeaderTitle = '';

$Title = 'RETURN GOODS RECEIVE NOTE';
$HeaderTitle = ucfirst(strtolower($Title));

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">
<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,'SelectedRec','ModRec_G1','imgSubmit');
			selRecordColor(this,'SelectedRec','SelectedRecColor');
		});
		
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
		//Set Cursor Position After Page Reload
		var NextElement = readCookie('grnr-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('grnr-nextcell');
		
		
		
	});
	
	
</script>

<script type="text/javascript" language="javascript">
function CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost){
  
    x = document.purchase;
	
	var PurDate = x.txtDate.value;
	var PurMaturityDate = x.txtMaturityDate.value;
	var PurSupplier = x.txtSupplier.value;
	var PurCurr = x.txtCurr.value;
	var PurProject = x.txtProjectCode.value;
	var PurCostCenter = x.txtCostCentCode.value;
	
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	if (PurDate=='' )
	{
		alert("Date Column is mandatory!");
		x.txtDate.focus();
		return 0;
	}
	else if (PurMaturityDate=='')
	{
		alert("MaturityDate Column is mandatory!");
		x.txtMaturityDate.focus();
		return 0;
	}
	else if (PurSupplier=='' )
	{
		alert("Supplier Column is mandatory!");
		x.txtSupplier.focus();
		return 0;
	}
	/*else if (PurCurr=='' )
	{
		alert("Currency Column is mandatory!");
		x.txtCurr.focus();
		return 0;
	}*/
	else if (PurProject=='' && ModuleRestProj==1 && ModuleProj==1)
	{
		alert("Project is mandatory!");
		x.txtProjectCode.focus();
		return 0;
	}
	else if (PurCostCenter=='' && ModuleRestCost==1 && ModuleCost==1 && document.getElementById('txtCostCentCode').type == 'text')
	{
		alert("CostCenter is mandatory!");
		x.txtCostCentCode.focus();
		return 0;
	}
			
	
	else
	return 1 ;	
}



function CheckFieldsDt(PIndex,ItemExpire,ModuleExpireDate,ItemWithSerial,ModuleSerialNo){
  
    x = document.purchase;
	
	var PurDtItem 	   = document.getElementById('itemcode['+PIndex+']').value;
	var PurDtWarehouse = document.getElementById('warehousecode['+PIndex+']').value;
	var PurDtQty       = document.getElementById('purdtquantity['+PIndex+']').value;
	var PurDtQty2	   = document.getElementById('unit2qty['+PIndex+']').value;
	if(document.getElementById('grnqty['+PIndex+']'))
	var AvailableQty   = document.getElementById('grnqty['+PIndex+']').value;
	else var AvailableQty = 0;
	if(document.getElementById('grnref['+PIndex+']'))
	var GrnRef         = document.getElementById('grnref['+PIndex+']').value;
	else var GrnRef = '';
	
	var PurDtExpireDate = document.getElementById('expiredate['+PIndex+']').value;
	var PurDtBatchNo    = document.getElementById('batchno['+PIndex+']').value;
	
	
	var vmode = x.actionmode.value;
	
	if (PurDtQty2 == '')    PurDtQty2 = 0;
	if (PurDtQty == '')     PurDtQty = 0;
	if (AvailableQty == '') AvailableQty = 0;
	
	PurDtQty     = parseFloat(PurDtQty);	
	AvailableQty = parseFloat(AvailableQty);
	
	
	if (PurDtItem=='')
	{
		alert("Item is mandatory!");
		document.getElementById('itemcode['+PIndex+']').focus();
		return 0;
	}	
	else if (PurDtWarehouse=='')
	{
		alert("Warehouse is mandatory!");
		document.getElementById('warehousecode['+PIndex+']').focus();
		return 0;
	}
	else if (PurDtQty*1 != PurDtQty/1 || PurDtQty <= 0  ) {
		alert('Quantity ('+PurDtQty+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('purdtquantity['+PIndex+']').focus();
		return 0;
	}
	else if (PurDtQty > AvailableQty && AvailableQty >= 0 && GrnRef != "") {
		alert('Quantity entered not allowed. Qty must be <= Remaining Grn Qty ['+AvailableQty+'].');
		document.getElementById('purdtquantity['+PIndex+']').focus();
		return 0;
	}
	else if ((PurDtQty2 != '' && PurDtQty2*1 != PurDtQty2/1) ) {
		alert('Item Qty2 should be a NUMERIC value.');
		document.getElementById('unit2qty['+PIndex+']').focus();
		return 0;
	}
	else if (ItemExpire == 1 && ModuleExpireDate==1 && PurDtExpireDate == '' ) {
		alert('Item Expire Date is mandatory.');
		document.getElementById('expiredate['+PIndex+']').focus();
		return 0;
	}
	else if (ItemExpire == 1 && ModuleExpireDate==1 && PurDtBatchNo == '' ) {
		alert('Item Batch No is mandatory.');
		document.getElementById('batchno['+PIndex+']').focus();
		return 0;
	}
	
		
	
	else
	return 1 ;	
}

function ClearPage(){
	x = document.purchase;
	
	if (confirm ( "Are you sure you want to Clear Page?"))
	{
		ClearForm('All');
		x = document.purchase;
		x.mainaction.value='insert';
		x.actionmode.value='';
		x.action='Form_RetGoodRecNote.php';
		x.submit();
	}	
}

function ClearPage1(){
	x = document.purchase;
	var msg = x.message.value;
	
	ClearForm('All');
	
	x.mainaction.value='insert';
	x.actionmode.value='';
	x.message.value=msg;
	x.action='Form_RetGoodRecNote.php';
	x.submit();
}


function CancelRecord(){
	x = document.purchase;
	var vMainMode = x.mainaction.value;
	var PurId     = x.txtPurId.value;
		
	if (confirm ( "Are you sure you want to Delete current pending return GRN permenantly?"))
	{
		x.action="Form_RetGoodRecNote_Actions.php?mode=cancel&mainmode="+vMainMode+"&SPurId="+PurId;
		x.submit();
	}
    
}



function PostChanges(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost) {
	x = document.purchase;
	var PurId  = x.txtPurId.value;
	var vMainMode = x.mainaction.value;
	
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	if (x.QtySerNo.value == 1){
		alert('Please check quantity for items.');
	}	
	else if (x.txtPurCountDetail.value == 0 || x.txtPurCountDetail.value == '') {
		alert('Save not allowed. Please add items.');
	}
	else
	{
		if (result == 1) {
			if (confirm ( "Are you sure you want to Save current return GRN?"))
			{
				//Save Grid Before Posting	
				var vModRec  = document.getElementById('ModRec_G1').value;
				if (vModRec != "") {
					var Obj = document.getElementById('CurRec'+vModRec);
					Obj.style.backgroundColor='#F13A3A';
					alert("Please Submit changes before.");
					
				} else {
					if (document.getElementById('btnPost'))
						x.btnPost.disabled = true;
					if (document.getElementById('btnCancel'))
						x.btnCancel.disabled = true;	
					if (document.getElementById('btnClear'))
						x.btnClear.disabled = true;
					if (document.getElementById('btnAddSerial'))
						x.btnAddSerial.disabled = true;
					if (document.getElementById('btnLoadGrn'))	
						x.btnLoadGrn.disabled = true;
						
					x.actionmode.value='post';
					x.action="Form_RetGoodRecNote_Actions.php?mode=post&mainmode="+vMainMode+"&SPurId="+PurId;
					x.submit();
				}	
			}
		}	
	}
}
	
function DeletePurDt(PurDtId, ItemPackCode, ItemCode) {
	x = document.purchase;
	var PurId  = x.txtPurId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = '';
	
	if (ItemPackCode != '')
	   vDelMsg = "Are you sure you want to Delete Pack Item "+ItemPackCode+" ?";
	else  
	   vDelMsg = "Are you sure you want to Delete Item "+ItemCode+" ?";
	   
	if (confirm ( vDelMsg ))
	{
		x.action="Form_RetGoodRecNote_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SPurId="+PurId+"&SPurDtId="+PurDtId;
		x.submit();
	}

}

function UpdatePurDt(PurDtId, RemainQty) {
    x = document.purchase;
	
	var vPurId   = x.txtPurId.value;
	var vPurDate = x.txtDate.value;
		
	var vMainMode = x.mainaction.value;
	
	win = window.open('Form_RetGoodRecNoteDetail.php?mainaction='+vMainMode+'&actionmode=&PPurId='+vPurId+'&PPurDate='+vPurDate+'&PPurDtId='+PurDtId+'&txtRemainQty='+RemainQty, 'Form_RetGoodRecNoteDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=720,height=300,top=100');		
	win.creator = self;
	win.focus();		

}

function AddSerials() {
	x = document.purchase;

	var vMainMode    = x.mainaction.value;
	var vPurSupplier = x.txtSupplier.value;
	var vPurId       = x.txtPurId.value;
	
	win = window.open('Form_RetGoodRecNoteAddSerial.php?mainaction='+vMainMode+'&actionmode=&PPurId='+vPurId,
					  'Form_RetGoodRecNoteAddSerial', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=780,height=400,top=100,left=50');
	win.creator = self;
	win.focus();		
    
}

function AddSerialNo(PurDtId, RemainQty) {
	x = document.purchase;
	var PurId = x.txtPurId.value;
	
	XPos = (screen.availHeight - 450) / 2;
	YPos = (screen.availWidth - 550) / 2;
    win = window.open('Form_RetGoodRecNoteSerialNo.php?SRPurId='+PurId+'&SRPurDtId='+PurDtId+'&SRRemainQty='+RemainQty, 'Form_RetGoodRecNoteSerialNo', 'titlebar=no,toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,directories=no, width=550,height=450,left='+YPos+',top='+XPos);		
	//win.creator = self;
	//win.focus();		
	
}



//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.purchase;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtPurId.value='';
		x.txtRef.value='';
		x.txtDate.value='';
		x.txtMaturityDate.value='';
		x.txtSupplier.value='';
		x.txtSupplierName.value='';
		x.txtSupplierVat.value='';
		x.txtPaymentTerms.value='';
		x.txtRemark.value='';
		x.txtCurr.value='';
		x.txtProjectCode.value='';
		x.txtCostCentCode.value='';
		x.txtInvoiceNo.value='';
		
				
		x.message.value='';
		x.QtySerNo.value='';
		x.txtPurCountDetail.value='';
		
		x.actionmode.value = '';
		x.mainaction.value = '';
	} 
}


function DeleteRecordGrid(filepath,formname,transid,PurDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	x = document.purchase;
	var vPurId    = x.txtPurId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = $.parseJSON(xmlhttp.responseText);
					
				var msg = data[0].message;
					
				if (msg != "") {
					$("#Loader").removeClass("ajaxsaving");
					alert(decodeURIComponent(msg));
				} else { 
					$("#Loader").removeClass("ajaxsaving");
					ReloadGrid(filepath,formname,transid,'datagrid',index,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);			
				}
			}
		}

		xmlhttp.open("GET","Form_RetGoodRecNote_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SPurId="+vPurId+"&SPurDtId="+PurDtId);
		xmlhttp.send();
	}	

}


function SubmitRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction,ModuleRestProj,ModuleRestCost,ModuleProj,ModuleCost,ModuleExpireDate,ModuleSerialNo, FIPurchaseCategory) {
	
	x = document.purchase;
	
	var ItemExpire     = document.getElementById('itemexpire['+PIndex+']').value;
	var ItemWithSerial = document.getElementById('itemwithserial['+PIndex+']').value;
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	if (result == 1) {
		result = CheckFieldsDt(PIndex,ItemExpire,ModuleExpireDate,ItemWithSerial,ModuleSerialNo);
	}
	
	var PurDtId   = document.getElementById('purdtid['+PIndex+']').value;
	if (PurDtId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	if (FIPurchaseCategory == 0) {
		for (var i=0; i < x.txtPurCategory.length; i++)
		{
			if (x.txtPurCategory[i].checked)
			{
			  var vPurCategory = x.txtPurCategory[i].value;
			}
		}
	} else {
		var vPurCategory = x.txtPurCategory.value;
	}	
	
	var txtgrncostprice=''
	if(document.getElementById('grncostprice['+PIndex+']'))
			var txtgrncostprice=document.getElementById('grncostprice['+PIndex+']').value;

		
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SPurId='+x.txtPurId.value+
					'&PPurId='+x.txtPurId.value+
					'&PPurCurr='+x.txtCurr.value+
					'&PPurDate='+x.txtDate.value+
					'&PPurMaturityDate='+x.txtMaturityDate.value+
					'&PPurSupplier='+x.txtSupplier.value+
					'&PPurCategory='+vPurCategory+
					'&PPurProjectCode='+x.txtProjectCode.value+
					'&PPurCostCentCode='+x.txtCostCentCode.value+
					'&PPurInvoiceNo='+encodeURIComponent(x.txtInvoiceNo.value)+
					'&PPurRemark='+encodeURIComponent(x.txtRemark.value)+
					'&SPurDtId='+document.getElementById('purdtid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecode['+PIndex+']').value+
					'&txtItemCode='+document.getElementById('itemcode['+PIndex+']').value+
					'&txtPurDtRemark='+document.getElementById('remarkdt['+PIndex+']').value+
					'&txtPurDtQty='+document.getElementById('purdtquantity['+PIndex+']').value+
					'&txtPurDtQty2='+document.getElementById('unit2qty['+PIndex+']').value+
					//'&txtPurDtVolume='+document.getElementById('purdtvolume['+PIndex+']').value+
					'&txtPurDtBatchNo='+document.getElementById('batchno['+PIndex+']').value+
					'&txtPurDtExpireDate='+document.getElementById('expiredate['+PIndex+']').value+
					'&txtProjectCodeDt='+document.getElementById('projectcodedt['+PIndex+']').value+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value+
					'&txtgrncostprice='+txtgrncostprice;
					
					
					
		
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader").addClass("ajaxsaving");
		//$('#datagrid :input').attr('disabled', true);
		
		var SubBtnID = 'imgSubmit['+PIndex+']';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
		
		if(xmlhttp) {
			//xmlhttp.open("POST", "Form_RetGoodRecNote_Actions.php", true);
		
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message;
					
					if (msg != "") {
						$("#Loader").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtPurId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'itemcode['+index+']';
						ReloadGrid(filepath,'GRN-R',transid,'datagrid',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
							document.getElementById('ModRec_G1').value = "";
						});
						
					}
				}
			}
			
			// adds  a header to tell the PHP script to recognize the data as is sent via POST
			//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			//xmlhttp.send(the_data);
			
			xmlhttp.open("GET","Form_RetGoodRecNote_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}
}

function SearchForRef(){
    //ClearForm('All');
    x = document.purchase;
	win = window.open('Form_RetGoodRecNoteSearch.php', 'Form_RetGoodRecNoteSearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=980,height=620,top=100,left=0');		
	win.creator = self;
	win.focus();		
			
}

function SearchForPending(){
    //ClearForm('All');
    x = document.purchase;
    win = window.open('Form_RetGoodRecNoteSearchPending.php', 'Form_RetGoodRecNoteSearchPending', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=980,height=600,top=100,left=0');		
	win.creator = self;
	win.focus();		
			
}

function LoadGrn(){
	x = document.purchase;
	var vPurSupplier = x.txtSupplier.value;
	var vPurId  	 = x.txtPurId.value;
	
	win = window.open('Form_RetGoodRecNote_LoadGrn.php?PPurId='+vPurId+'&PPurSupplier='+vPurSupplier, 'Form_RetGoodRecNote_LoadGrn', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=980,height=620,top=50,left=50');		
	win.creator = self;
	win.focus();		
	
}

function SetMaturityDate() {
	x = document.purchase;
	var vmode = x.mainaction.value;
	
    
	//if (vmode == 'insert' || vmode == 'edit') {
	    var str   = document.getElementById('txtPaymentTerms').value;
		var str1 = '';
		
		if (str == '') str = 0;
		var sdays = parseInt(str);	
		var sdate = document.getElementById('txtDate').value;
		sdate = ChangeDate(sdate);
		var d = new Date(sdate); 
		
		d.setDate(d.getDate() + sdays); 
		
		str = d.getDate();
		str1 = str.toString();
		
		if (str1.length == 1)
     		str1 = "0"+str1;
			
		str = d.getMonth()+1;
		str2 = str.toString();
		
		if (str2.length == 1)
     		str2 = "0"+str2;	
			
		x.txtMaturityDate.value=(str1 + "/" + str2 + "/" + d.getFullYear()); 
		
	//}  
	
	    
		
}

function ChangeDate(sdate){
	var idate = new String;
	idate = sdate;
      
    dt_array = idate.split("/");
      
    if ((dt_array[0] < 10) && (dt_array[0].length == 1))
		dt_array[0] = "0" + dt_array[0];
        
	if ((dt_array[1] < 10) && (dt_array[1].length == 1))
		dt_array[1] = "0" + dt_array[1];
   	
	//fdate = dt_array[2] + "-" + dt_array[1] + "-" + dt_array[0];
	// "mm/dd/yyyy"
	fdate = dt_array[1] + "/" + dt_array[0] + "/" + dt_array[2];
	
	return fdate;
}





function PrintPurchase(PurId, PurRef) {
	x = document.purchase;
	var str = '';
	
	if (confirm ( "Do you want to Print current Return GRN with reference "+PurRef+" ?"))
	{
		str = 'Form_RetGoodRecNotePreview.php?PurchaseId='+PurId;
		window.open(str);
	}	
}


function showlistSupplier(str){
	var vdate, vcode;
	vdate=document.purchase.txtDate.value;
	vcode=encodeURIComponent(document.purchase.txtSupplier.value);
  
	window.open('List_Supplier.php?item='+str+'&PLedger_number='+vcode+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}
function showlistSupplierName(str) {
	var vdate, vcode;
	vdate=document.purchase.txtDate.value;
	vname=encodeURIComponent(document.purchase.txtSupplierName.value);
  
	window.open('List_Supplier.php?item='+str+'&PLedger_name='+vname+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}


function showlistProject(str){

	vProjectCode = encodeURIComponent(document.getElementById('txtProjectCode').value);
	window.open('List_Project.php?item='+str+'&PProject_Code='+vProjectCode,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(str){

	vCostcentCode = encodeURIComponent(document.getElementById('txtCostCentCode').value);
	window.open('List_Costcenter.php?item='+str+'&PCostcent_Code='+vCostcentCode,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}


function showlistProjectDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vProjectCode = encodeURIComponent(document.getElementById('projectcodedt['+PIndex+']').value);
	
	window.open('List_SorProject.php?frm=25&index='+PIndex+'&item='+str+'&PProject_Code='+vProjectCode,'List_SorProject','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistCostcenterDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vCostcentCode = encodeURIComponent(document.getElementById('costcentcodedt['+PIndex+']').value);
	
	window.open('List_SorCostcenter.php?frm=25&index='+PIndex+'&item='+str+'&PCostcent_Code='+vCostcentCode,'List_SorCostcenter','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistBatchNo(str,PIndex) {
	x = document.purchase;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 580) / 2;
	
	vItemCode = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
	
	window.open('List_BatchNo.php?frm=10&index='+PIndex+'&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 showlistItems(str,PIndex){
	var vDate, vItemCode;
	x = document.purchase;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemCode  = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
  
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&PItem_Code='+vItemCode+'&ItemType=All&TransDate='+vDate,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistItemsDesc(str,PIndex){
	var vDate, vItemCode;
	x = document.purchase;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemDesc  = encodeURIComponent(document.getElementById('itemdescription['+PIndex+']').value);
	
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&PItem_Description='+vItemDesc+'&ItemType=All&TransDate='+vDate,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistWarehouse(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_SorWarehouse.php?frm=2&index='+PIndex+'&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 CalcQty2(ModuleUnit1Method,Option,PIndex) { 
	x = document.purchase;
	var Qty  = document.getElementById('purdtquantity['+PIndex+']').value; 
	var Qty2 = document.getElementById('unit2qty['+PIndex+']').value;
	var UnitCoef = document.getElementById('itemunitcoef['+PIndex+']').value;
	
	if (Qty == '')  Qty = 0;
	if (Qty2 == '') Qty2 = 0;
	
	if(ModuleUnit1Method == 1) {
		if (Qty > 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty*UnitCoef;
		}	
		else if (Qty == 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty and Qty2 Should Be Empty
	else if(ModuleUnit1Method == 0 && Option == 1 && Qty2 == 0) {
		if (Qty > 0 && UnitCoef != 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty/UnitCoef;
		}	
		else if (Qty == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty2 Get Qty
	else if(ModuleUnit1Method == 0 && Option == 2) {
		if (Qty2 > 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('purdtquantity['+PIndex+']').value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('purdtquantity['+PIndex+']').value = '';
		}
	}
}



</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>$HeaderTitle</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>

</head>
<body>
<form name='purchase' method='post'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='QtySerNo' value='$QtySerNo'>
<input type='hidden' name='PurType' value='$PurType'>
<input type='hidden' name='message' value='$message' size='200'>
HERE;

//$message='';

	
//Initializations
	
	
//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 ((empty($txtProjectCode)) && $Module_Project == 1)
	$txtProjectCode = $defaultproject;
if ((empty($txtCostCentCode)) && $Module_CostCenter == 1)
	$txtCostCentCode = $defaultcostcent;	
if (empty($txtCurr))
	$txtCurr = $base1;
if (empty($txtDate))	
	$txtDate = displayToday();
if (empty($txtMaturityDate))	
	$txtMaturityDate = displayToday();
	
if ($FI_PurchaseCategory == 0 || $FI_PurchaseCategory == 1) $txtPurCategory = 0;
else if ($FI_PurchaseCategory == 2) $txtPurCategory = 1;	



if ($txtPurId != '' && $actionmode != "cancel") {
	// Read From Temp Tables For Selected Record				 
	$query = " Select Purchase_ID, Purchase_Reference, Date_Format(Purchase_Date,'%d/%m/%Y') As Purchase_Date, ".
	         " Date_Format(Journaldt_valuedate,'%d/%m/%Y') As Maturity_Date, GrnPurchases.Currency_code, ".
			 " GrnPurchases.Supplier_code As SupplierCode,	Suppliers.Ledger_name As SupplierName, Supplier_PaymentTerms,  ".
			 " Purchase_Remark, Purchase_InvoiceNo, GrnPurchases.Project_Code, GrnPurchases.Costcent_code,  ".
			 " ifNull(Purchase_Import,0) ".
			 " From Temp_GrnPurchases As GrnPurchases ".
			 " Left Join Suppliers on GrnPurchases.Supplier_code = Suppliers.Ledger_Number ".
			 " Left Join Journal on GrnPurchases.Journal_ID = Journal.Journal_ID ".
	         " Where Purchase_ID = '".$txtPurId."' ".
			 " And   GrnPurchases.Journal_Type = 'PR' ";
			 //" And ifNull(Purchase_Grn,0) = 1 ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
			 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	
	$txtPurId        = $rows[0];
	$txtRef          = $rows[1];
	$txtDate         = $rows[2];
	$txtMaturityDate = $rows[3];
	$txtSupplier     = $rows[5];
	$txtSupplierName = $rows[6];
	$txtPaymentTerms = $rows[7];
	$txtRemark       = $rows[8];
	$txtCurr         = $rows[4];
	$txtProjectCode  = $rows[10];
	$txtCostCentCode = $rows[11];
	$txtInvoiceNo    = $rows[9];
	$txtPurCategory  = $rows[12];
	
	
	$query = " Select Count(*) FROM Temp_GrnPurchasesDt ".
			 " WHERE Purchase_id = ".$txtPurId;
	$result = selectData($connection, $query);
	$txtPurCountDetail = $result[0];
	if($txtPurCountDetail == '') $txtPurCountDetail = 0;
	
}




//$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";

echo"<table cellpadding='0' cellspacing='0' border='0'  align='center' class='layout-width'>";
include_once("header.php");
echo" <tr><td  valign='top'>";

include_once("sidemenu.php");
echo"  </td></tr>";


echo" <tr style='height:26px;'>
		<td  valign='top' id='content-top'>
			<table border='0' cellpadding='0' cellspacing='0' style='table-layout:fixed; height:26px;' class='layout-width'>
			<tr style='height:26px;'>
				<td style='width:38px; height:26px;'>&nbsp;</td>
				<td valign='middle' style='width:300px; height:26px;'><span class='title'>$Title</span></td>
				<td class='message' valign='middle' style='height:26px;'>".htmlspecialchars($message, ENT_QUOTES)."</td>
			</tr></table>
		</td>
	  </tr>";

echo"<tr>
		<td  height='34'  valign='top' id='content-top2'>
			<table border='0' cellpadding='0' cellspacing='0' class='layout-width'>
			<tr>
				<td width='30'  height='34'>&nbsp;</td>
				<td valign='middle' height='34' width='720px' align='left'>";
				
	if ($FI_ReturnGrnApp == 1)
	echo" <button type='button' id='btnAddSerial' name='btnAddSerial' onclick='AddSerials();return false;' title='Add Serials'><span><span>Add Serials</span></span></button>";


echo" <button type='button' id='btnClear' name='btnClear' onclick='ClearPage();return false;' title='Clear Page'><span><span>Clear Page</span></span></button>";			


if ($txtPurId != '')
	echo" <button type='button' id='btnCancel' name='btnCancel' onclick='CancelRecord();return false;' title='Cancel Changes'><span><span>Cancel</span></span></button>";	

	
if ($txtPurId != '')
	echo" <button type='button' id='btnPost' name='btnPost' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter);return false;' title='Save Changes'><span><span>Save</span></span></button>";


if ($txtPurId == '')
		echo" <button type='button' id='btnSearch' name='btnSearch' onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";	


if ($txtPurId == '')
	echo" <button type='button' id='btnPending' name='btnPending' onclick='SearchForPending();return false;' title='Pending Goods Receive Note'><span><span>Pending</span></span></button>";	


if ($FI_ReturnGrnApp == 1)
	echo" <button type='button' id='btnLoadGrn' name='btnLoadGrn' onclick='LoadGrn();return false;' title='Search Grn'><span><span>Load Grn</span></span></button>";
	
	
echo"	</td></tr></table>";
echo"</td></tr>";				

		
echo"<tr><td id='content-body'>
<table border='0'  align='center' valign='top' width=100% class='tablecontent'>
   <tr bgcolor='#F7F7F7'><td valign='top' align='left' colspan='10'>";				
				
print <<<HERE

		<table border="0" style='table-layout:fixed'>
		  <col width=80>
		  <col width=100>
		  <col width=50>
		  <col width=130>
		  <col width=70>
		  <col width=160>
		  <col width=100>
		  <col width=150>
		  <col width=240>

		<tr bgcolor="#F7F7F7" height='30'>
          <td valign="center" align='left' ><span class="style1">Reference&nbsp;<span class="style16">*</span></span></td>
		  <td><font face='Verdana' size='2'><b>&nbsp;$txtRef</b></font>
			  <input type='hidden' name='txtPurCountDetail' value='$txtPurCountDetail' >
			  <input type='hidden' name='txtPurId' value='$txtPurId' size='10'>
			  <input type="hidden" name="txtRef" value="$txtRef" size='10' >
			  <input type="hidden" name="txtCurr" value="$txtCurr" size='10' >
		  </td>
		  <td align="left"><span class="style1">Date&nbsp;<span class="style16">*</span></span></td>
		  <td><input type='text' name='txtDate' value='$txtDate' onchange='SetMaturityDate();' maxlength='10' style='width:85px;' >
		      <A HREF="#" onClick="displayCalendar(document.purchase.txtDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A>
		  </td>
          <td align='left' ><span class='style1'>&nbsp;</span></td>
          <td ><input type='hidden' name='txtMaturityDate' value='$txtMaturityDate' maxlength='10' style='width:85px;' ></td>
		  <td colspan='3'>&nbsp;</td>
		</tr>
HERE;

//<td align='left' ><span class='style1'>Maturity&nbsp;<span class="style16">*</span></span></td>
//<A HREF="#" onClick="displayCalendar(document.purchase.txtMaturityDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A>

echo"   <tr bgcolor='#F7F7F7'  height='30'>
		  <td align='left' ><span class='style1'>Supplier&nbsp;<span class='style16'>*</span></span></td>";
echo"     <td colspan='5' ><span class='style1'>";
echo"     	<input type='text' name='txtSupplier' id='txtSupplier' value='$txtSupplier' onBlur='SetMaturityDate();'  style='width:120px;' maxlength='10' onchange=\"CheckLookup('chkcodeexists','suppliers','ledger_number',this.value,'lstSupplierCodeH'); \" />
			<input type='text' name='txtSupplierName' id='txtSupplierName' value='$txtSupplierName' style='width:320px;' onchange=\"CheckLookup('chkcodeexists','suppliers','ledger_name',this.value,'lstSupplierNameH');\" />
			<label><span class='style1'><img src='img/btnopen.jpg' title=' Select Supplier ' id='lstSupplierCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSupplier(1); ' /> </span></label>
			<label><img src='img/btnopen.jpg' title='Select Supplier' id='lstSupplierNameH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSupplierName(1);' style='display:none;' /></label>
			<input type='hidden' name='txtSupplierVat' id='txtSupplierVat' value='$txtSupplierVat' />
          </span>
          </td>";

//echo"     <td align='left' ><span class='style1'>Payment Terms</span></td>";
//echo"     <td ><font face='Verdana' size='2'><b>&nbsp;$txtPaymentTerms</b></font><span class='style1'><input type='hidden' name='txtPaymentTerms' value='$txtPaymentTerms' style='width:100px;' readonly /></span></td>";
echo"     <td>&nbsp;</td>";
echo"     <td>&nbsp;<span class='style1'><input type='hidden' name='txtPaymentTerms' value='$txtPaymentTerms' style='width:100px;' readonly /></span></td>";
echo"     <td>&nbsp;</td>";
echo"   </tr>";

echo"   <tr bgcolor='#F7F7F7'  height='30'>
		  <td align='left' ><span class='style1'>Remark</span></td><td colspan='5' > <span class='style1'>
			<input type='text' name='txtRemark' value='".htmlspecialchars($txtRemark, ENT_QUOTES)."'  style='width:445px;' maxlength='100' >
		  </td>";

echo"     <td align='left' ><span class='style1'>Waybill No.</span></td>";
echo"     <td ><span class='style1'><input type='text' name='txtInvoiceNo' value='".htmlspecialchars($txtInvoiceNo, ENT_QUOTES)."' style='width:130px;' maxlength='25'  /></span></td>";
echo"     <td>&nbsp;</td>";
echo"   </tr>";		  
		
echo"   <tr bgcolor='#F7F7F7'>";

if ($Module_Project == 1) {
	echo" <td align='left' ><span class='style1'>Project&nbsp;<span class='style16'>*</span></span></td>
	      <td align='left' colspan='2'> <span class='style1'>
		    <input type='text' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' style='width:100px;' maxlength='15' onchange=\"CheckLookup('chkcodeexists','project','project_code',this.value,'lstProjectCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Project ' id='lstProjectCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
} else {
	echo" <td align='left' colspan='3'><input type='hidden' name='txtProjectCode' id='txtProjectCode' value='' /></td>";

}			

if ($Module_CostCenter == 1 && $ShowCostCentLayout == 1) {		  
	echo" <td align='right' ><span class='style1'>Costcenter&nbsp;<span class='style16'>*</span></span></td>		
		  <td align='left' colspan='2'><span class='style1'>
		    <input type='text' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' style='width:160px;' maxlength='15' onchange=\"CheckLookup('chkcodeexists','costcent','costcent_code',this.value,'lstCostCentCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Costcenter ' id='lstCostCentCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
} else {
	echo" <td align='left' colspan='3'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='' /></td>";

}

if ($FI_PurchaseCategory == 0) {
	echo" <td align='left' ><span class='style1'>Category</span></td>
		  <td align='left'> <span class='style1'>";
	echo" <input type='radio' name='txtPurCategory' id='txtPurCategory' value='0' "; if($txtPurCategory==0 || $txtPurCategory=='') echo "checked />"; else echo " />";  echo " Local";
	echo" <input type='radio' name='txtPurCategory' id='txtPurCategory' value='1' "; if($txtPurCategory==1) echo "checked />"; else echo " />";  echo " Import";
       echo"</span></td>";
} else {
	echo" <td align='left' colspan='2' >&nbsp;<input type='hidden' name='txtPurCategory' id='txtPurCategory' value='$txtPurCategory' /></td>";
}	

echo"     <td>&nbsp;</td>";	
echo"   </tr>";


echo"   <tr bgcolor='#F7F7F7' height='20'><td colspan='9' align='center'>&nbsp;</td></tr>";
		  
		  
/*
echo"   <tr><td colspan='9' valign='top'>";
echo"	<div style='overflow:scroll; height:180px; width:975px;' >";
echo"     <table border='0' cellspacing='2' style='table-layout:fixed'>
          <col width=20>
		  <col width=20>
		  <col width=20>";
		  
if ($Module_DoubleUnit == 1) {
	echo" <col width=120>
		  <col width=120>
		  <col width=200>
		  <col width=70>
		  <col width=60>
		  <col width=70>
		  <col width=40>
		  <col width=75>
		  <col width=40>
		  <col width=70>
		  <col width=60>
		  <col width=70>";
		  
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
	if ($Module_ExpireDate == 1) {
		echo"<col width=80>";
		echo"<col width=80>";
	}	  	  
} else {
	echo" <col width=120>
		  <col width=120>
		  <col width=220>
		  <col width=80>
		  <col width=70>
		  <col width=75>
		  <col width=75>
		  <col width=75>
		  <col width=80>";
		  
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
	if ($Module_ExpireDate == 1) {
		echo"<col width=80>";
		echo"<col width=80>";
	}	  	  
}		  
		  
		echo"<tr height='25'>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
   		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item Code Packed</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Description</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>WH</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Grn Ref</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Rem. Grn Qty</span></td>";
		
		if ($Module_DoubleUnit == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit1</span></td>";
			
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Return Qty</span></td>";
		
		if ($Module_DoubleUnit == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2 Qty</span></td>";
		}
		
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>S/N Bal</span></td>";
		echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Volume</span></td>";
		
		if ($Module_ProjectDt == 1)	
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Project</span></td>";
		if ($Module_CostCenterDt == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>CostCenter</span></td>";
		if ($Module_ExpireDate == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Batch No</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Expire Date</span></td>";
		}
		
        echo"</tr>";
		  
		if ($txtPurId != '' ) {
		      
			  
			  //Checking For Difference Btw Qty and Count SerialNo
			  $QtySerNoCheck = 0;
			  echo '<script type="text/javascript" language="javascript">';
			  echo ' x = document.purchase; ';
  			  echo ' x.QtySerNo.value=0; ';
			  echo '</script>';
			  
			  
			$querydt = " Select GrnPurchasesDt.PurchaseDt_ID, GrnPurchasesDt.Item_CodePacked, GrnPurchasesDt.Item_code, Item_Description, ".
					   " GrnPurchasesDt.Warehouse_Code, Purchasedt_Remark, PurchaseDt_Quantity, PurchaseDt_Volume, ".
					   " Count(SerialNo_Code) As CountSerialNo, ifNull(item_withserialno,0) As ItemWithSerialNo, ".
					   " GrnPurchasesDt.Related_Ref, GrnPurchasesDt.RelatedDt_Id, GrnPurchasesDt.Item_Unit2Qty, Item_UnitPurchaseDesc, Item_UnitSalesDesc, ".
					   " Date_Format(PurchaseDt_ExpireDate,'%d/%m/%Y') As PurchaseDt_ExpireDate, PurchaseDt_BatchNo, GrnPurchasesDt.Project_code, GrnPurchasesDt.CostCent_Code ".
					   " From Temp_GrnPurchasesDt As GrnPurchasesDt Left Join Items on GrnPurchasesDt.Item_code = Items.Item_code ".
					   " Left Join Temp_Purchasesserialno on GrnPurchasesDt.PurchaseDt_ID = Temp_Purchasesserialno.GrnDt_ID ".
					   " And Temp_Purchasesserialno.Journal_Type = 'PR' ".
					   " Where GrnPurchasesDt.Purchase_ID = '".$txtPurId."' ".
					   " Group By GrnPurchasesDt.PurchaseDt_ID ".
					   " Order By GrnPurchasesDt.PurchaseDt_ID Desc ";
			//echo $querydt;
			$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){
			    
				$ct+=1;

				if($ct%2==0)
					$Color="style='background-color:".$grid_color1."'";
				else			
					$Color="style='background-color:".$grid_color2."'";	
				
				
				$vDeliveryDtId   = $rowsdt[11];
				$vRemainQty      = 999999;
				$vRemainQtyDisp  = 0;
				
				if (!empty($vDeliveryDtId) && $vDeliveryDtId != '') {
					$sub_query = " Select ifNull(GrnPurchasesDt.PurchaseDt_Quantity,0) - ifNull(Sum(ifNull(ReturnGrnPurchasesDt.PurchaseDt_Quantity,0)),0) ".
								 " From GrnPurchasesDt, GrnPurchasesDt As ReturnGrnPurchasesDt ".
								 " Where GrnPurchasesDt.PurchaseDt_ID = '".$vDeliveryDtId."' ".
								 " And GrnPurchasesDt.Journal_Type = 'PI' ".
								 " And ReturnGrnPurchasesDt.Journal_Type = 'PR' ".
								 //" And ReturnGrnPurchasesDt.PurchaseDt_ID != '".$rowsdt[0]."' ".
								 " And ReturnGrnPurchasesDt.RelatedDt_Id = GrnPurchasesDt.PurchaseDt_ID ";

					$sub_result = selectData($connection, $sub_query);
					$vRemainQty = $sub_result[0];
					if ($vRemainQty == '') $vRemainQty = 0;
					
					$vRemainQtyDisp  = $vRemainQty;
				}	
				
						
				echo "<tr ".$Color." >";
				
				// If ItemWithSerialNo True And ModuleSerialNo True	
				if ($rowsdt[9] == 1 && $Module_SerialNo == 1) 
					echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_addserial.png' onMouseOver=\"style.cursor='hand'\" onclick=AddSerialNo('".$rowsdt[0]."','".$vRemainQty."') title='Add Serial Nos'  ></span></td>";
				else
					echo "	<td align='center' valign='center'>&nbsp;</td>";
					
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_edit.png'  onMouseOver=\"style.cursor='hand'\" onclick=UpdatePurDt('".$rowsdt[0]."','".$vRemainQty."') title='Edit Record'  ></span></td>";
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/c_delete.png'  onMouseOver=\"style.cursor='hand'\" onclick=\"DeletePurDt('".$rowsdt[0]."','".htmlentities($rowsdt[1])."','".htmlentities($rowsdt[2])."')\" title='Delete Record'  ></span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[1]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[2]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[3]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[4]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[10]."</span></td>";
				echo "	<td align='right'><span class='style15'>".$vRemainQtyDisp."</span></td>";
				
				if ($Module_DoubleUnit == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[14]."</span></td>";
				
				// if Total Quantity Differs From Total SerialNos And
				// If ItemWithSerialNo True And ModuleSerialNo True	
				if (($rowsdt[6] != $rowsdt[8] && $rowsdt[9] != 0 && $Module_SerialNo == 1) || ($rowsdt[6] == 0 && $rowsdt[9] != 0 && $Module_SerialNo == 1)) {
				    if ($QtySerNoCheck == 0) {
						$QtySerNoCheck = 1;
						
						echo '<script type="text/javascript" language="javascript">';
						echo ' x = document.purchase; ';
						echo ' x.QtySerNo.value=1; ';
						echo '</script>';
					}					
						
					//echo "	<td align='right' style='background-color:#FF0000' ><span class='style28' style='text-decoration:underline;'>".$rowsdt[6]."</span></a></td>";	
					echo "	<td align='right' style='background-color:#FF0000' ><span class='style28' style='text-decoration:underline;'>".$rowsdt[6]."</span></td>";
					
				} else	
					echo "	<td align='right'><span class='style15'>".$rowsdt[6]."</span></td>";
				
				if ($Module_DoubleUnit == 1) { 
					echo "	<td align='left'><span class='style15'>".$rowsdt[13]."</span></td>";	
					echo "	<td align='right'><span class='style15'>".$rowsdt[12]."</span></td>";	
				}
				
				echo "	<td align='right'><span class='style15'>".$rowsdt[8]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[7]."</span></td>";
				
				if ($Module_ProjectDt == 1)	
					echo "	<td align='left'><span class='style15'>".$rowsdt[17]."</span></td>";
				if ($Module_CostCenterDt == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[18]."</span></td>";
				if ($Module_ExpireDate == 1) {
					echo "	<td align='left'><span class='style15'>".$rowsdt[16]."</span></td>";
					echo "	<td align='left'><span class='style15'>".$rowsdt[15]."</span></td>";
				}	
				
				echo "</tr>";
						
					
								
			}
			
			
		 }
		
		echo "</table></div>"; 

echo"   </td></tr>";
*/
/*
echo"   <tr bgcolor='#D8D8D8' height='30'><td colspan='9' align='center'>";

if ($FI_ReturnGrnApp == 1)
	echo"	<input type='button' id='btnAddSerial' name='btnAddSerial' value='Add Serials'  onclick='AddSerials()' $style title='Add Serials'>";
	
echo"		<input type='button' id='btnClear' name='btnClear' value='Clear Page'   onclick='ClearPage();' $style title='Clear Page'>";

if ($txtPurId != '')
	echo"   <input type='button' name='btnCancel' id='btnCancel' value='Cancel' onclick='CancelRecord();' $style title='Cancel Changes'>";
	
if ($txtPurId != '')
	echo"   <input type='button' name='btnPost' id='btnPost' value='Save' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter);' $style	title='Save Changes' />";

if ($txtPurId == '')
	echo"   <input name='btnSearch' type='button' id='btnSearch' value='Search' onclick='SearchForRef();' $style title='Search By Reference' />";

if ($txtPurId == '')
	echo"   <input name='btnPending' type='button' id='btnPending' value='Pending' onclick='SearchForPending();' $style title='Pending Goods Receive Note'  />";

if ($FI_ReturnGrnApp == 1)
	echo"  <input type='button' name='btnLoadGrn' id='btnLoadGrn' value='Load Grn' onclick='LoadGrn();' $style style='width: 100px;' title='Search Grn' /> ";

echo"   </td></tr>";	*/


$Parameters = array();
$Parameters['Module_Unit1Method'] = $Module_Unit1Method;
$Parameters['Module_Pack'] = $Module_Pack;
$Parameters['Module_DoubleUnit'] = $Module_DoubleUnit;
$Parameters['Module_Project'] = $Module_Project;
$Parameters['Module_CostCenter'] = $Module_CostCenter;
$Parameters['Module_ProjectDt'] = $Module_ProjectDt;
$Parameters['Module_CostCenterDt'] = $Module_CostCenterDt;
$Parameters['Module_RestrictProjCost'] = $Module_RestrictProjCost;
$Parameters['Module_RestrictCost'] = $Module_RestrictCost;
$Parameters['ShowCostCentLayout'] = $ShowCostCentLayout;
$Parameters['Module_SerialNo'] = $Module_SerialNo;
$Parameters['Module_ExpireDate'] = $Module_ExpireDate;
$Parameters['FI_PurchaseCategory'] = $FI_PurchaseCategory;


$Parameters['SetupDftWareHouse'] = $SetupDftWareHouse;
$Parameters['defaultwarehouse']  = $defaultwarehouse;

$Parameters['txtDate'] 		   = $txtDate;
$Parameters['txtSupplierCode'] = $txtSupplier;
$Parameters['module_grncostprice']= $Module_grncostprice;


$_SESSION['ggrnr_parameters']  = $Parameters;



echo"   <tr bgcolor='#ffffff'><td colspan='11' valign='top'>";
echo"	<div id='datagrid' class='grid' style='width:1090px;' >";

//Show Items Grid
ShowReturnGoodRecNoteDtGrid($connection,'GRN-R',$txtPurId,$_SESSION['ggrnr_parameters'],$_SESSION['ggrnr_arrayaccess'],'GrnPurchasesDt.PurchaseDt_ID');

echo"	  </div>"; 
echo"   </td></tr>"; 
echo"   </table></td></tr>"; 
 echo"   </table></td></tr><tr height='30'><td align='center' id='content-bottom' ></td></tr>";  
echo"   </table></td></tr>"; 

echo" </table>  ";//end of last table menu
	
if ($actionmode == "post" && $PrPurId != '') {
	echo '<script type="text/javascript" language="javascript">';
	
	if ($Login_FastPrint == 1) 
		echo ' PrintPurchase(\''.$PrPurId.'\', \''.$PrPurRef.'\'); ';
		
	echo ' ClearPage1(); ';
	echo '</script>';

}

print <<<HERE
</form>
</body>

HERE;

?>