<%@ Language=VBScript %>
<%
'	Module:		Requisition Detail.
'	Owner:		Martin
'	Parameters:	requisitionid and requisitionerprefix
'	Caller(s):	requisition_list.asp
'	Notes:		None.
'	Copyright (c) Baan Company 1999.
'	$Revision: 113 $
%>
<!-- #include file="../../include/General.asp" -->
<!-- #include file = "../../include/UserLib.asp" -->
<!-- #INCLUDE FILE="../../include/EETable.asp" -->
<!-- #INCLUDE FILE="../../include/PageUtil.asp" -->
<!-- #INCLUDE FILE="../../include/Utilities.asp" -->
<!-- #include file = "../../include/DGrid.asp" -->
<!-- #INCLUDE FILE="../../include/Format.asp" -->
<!-- #INCLUDE FILE="../../include/auo.asp" -->
<!-- #INCLUDE FILE="../../include/validate.asp" -->
<!-- #include file="../../include/Labels.asp" -->
<!-- #include file="../include/requisitionbusinessrules.asp" -->
<!-- #include file="../include/requisitionproperties.asp" -->
<!-- #include file="../include/LabelsRequisition.asp" -->
<!-- #include file="../include/RequisitionUtility.asp" -->
<!-- #INCLUDE FILE="../../include/UtilitiesClient.asp" -->
<!-- #include file="../../e-common/include/genericselectiongrid.asp" -->
<!-- #include file="../../e-catalog/include/CatalogUtility.asp" -->
<html>
<head>
</head>
<%
'---------------------------------------------------------------------------------------------------------------------------------------------------
' This page uses the gMode variable to determine which information is displayed and which information is maintained in hidden fields.
' The following modes are supported:
' - edit: in this mode editable visible fields are displayed
' - selectaddress: in this mode the requisition fields are hidden and the address selection grid is displayed
' - selectbusinesspartner: in this mode the requisition fields are hidden and the business partner grid is displayed
' - The add mode has several submodes:
'   - addwellcome: a wellcome page for the add requisition line wizard
'   - addwhat: the product related fields (commodity code, product description, quantity and unit) are displayed, other fields are hidden
'   - addbuy: the buyer and supplier information is displayed
'   - addcost: the financial information is displayed
'   - addwhen: the delivery date and delivery address choice are displayed
' Usage of gRole:
'   - While adding attachments all operations are Role based.
'---------------------------------------------------------------------------------------------------------------------------------------------------

	const mButtonCol1 = 4
	const mCellHeight = -20 ' -23 ' TODO: This should be handled automatically in Page::Table.
	dim Page
	dim gOuterTable
	dim gTable
	dim gPageHeaderTable
	dim gHeaderTable
		' ----------
	Dim gView
	Dim gMode
	Dim gRole
	Dim gRequisitionID
	Dim gRequisitionerPrefix
	Dim gRequisitionLineNumber
	Dim gCurrentHeaderID
	Dim gLineRS
	Dim gHeaderRS
	Dim gCurrency
	Dim gUserComponent
	Dim gSelectedAddressID
	Dim gSelectedBusinessPartnerID
	Dim gFromMode
	Dim gWizardStartTable
	Dim gLinkStr
	Dim gApprovers	'To store the approvers of a requistioin Line, Created in Approval Info and Used in Display File attach. info
	Dim gSourceofrequisition	
	Dim gBuyerassisted	

	'on error resume next
	call Main()
	'if Err.number<>0 then
	'	DisplayErrorInterface(Err)
	'end if
	'on error goto 0

'---------------------------------------------------------------------------------------------------------------------------------------------------

'---------------------------------------------------------------------------------------------------------------------------------------------------
' Main function:
' - reads in global variables
' - set recordsets
' - perform the server actions based on the choice of the user on the page
' - based on the mode displays the correct information
'---------------------------------------------------------------------------------------------------------------------------------------------------
	Sub Main()
	
		Dim lSelectMode ' Submode is used to detect that we are in the mode to select businesspartner or addresses
		Dim lFromMode
	
		gFromMode = cStr(Request.QueryString("mode"))
		gRequisitionID = Request.QueryString("requisitionid")
		gRequisitionerPrefix = Request.QueryString("requisitionerprefix")
		gRequisitionLineNumber = Request.QueryString("requisitionlinenumber")
		gCurrentHeaderID = getCurrentRequisitionHeader(CStr(getprocuser)) 
		gRole = Request.QueryString ("role")
		
		call setPageAttributes()

		gSelectedBusinessPartnerID = 0
		gSelectedAddressID = 0
		
		' correct query.string variable for submode
		if trim(getformValue("selectmode"))<>"" then
			' we are still in the submode so correct
			lFromMode = getformValue("selectmode")
		else
			lFromMode = gFromMode
		end if
		
		if trim(gRequisitionLineNumber)>"0" then
			Set gLineRS = getRecordset("SELECT * FROM REQUISITIONLINE WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)
			'#ST 498.sn
			if gLineRS.EOF then
				call GenerateWarning( I18N(Lbl_RequisitionReference), I18N(Lbl_NotValidSelectedReq))
			end if
			'#ST 498.en

			gSourceofrequisition = gLineRS("SOURCEOFREQUISITION")	
			gBuyerassisted = gLineRS("BUYERASSISTED")				
			gView=I18N(getStateLabel(gLineRS.fields("LINESTATUS")))
			set gLineRS=nothing
		end if
		
		gMode = doServerActions(lFromMode)

		if gMode = "selectwizardbusinesspartner" or gMode = "selectbusinesspartner" or gMode =  "selectwizardaddress" or gMode = "selectaddress" then	
			gEETableForEnduser = False
		else
			gEETableForEnduser = True
		end if

		if trim(gMode)="" or trim(gMode)="exit" then
			' no actions so get out of here
			Exit Sub
		end if

		if gMode = "selectwizardbusinesspartner" or gMode = "selectbusinesspartner" or gMode =  "selectwizardaddress" or gMode = "selectaddress" then
			' store submode in hidden field
			lSelectMode = gMode
		else
			' no submode
			lSelectMode  = ""
		end if

		Dim lUrl: lUrl = getMSCSPage.URL( "E-Requisition/enduser/requisitionline_detail.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "requisitionlinenumber", gRequisitionLineNumber, "mode", gMode, "role", gRole)
		' Perform actions based on buttons pressed and updates the mode (which determines which information is displayed)

		%>
		<form method="post" action="<%=lUrl%>" id=form1 name=form1>
		<%

		Response.Write(formhidden("selectmode", lSelectMode))

		if trim(gRequisitionLineNumber)>"0" then
			Set gLineRS = getRecordset("SELECT * FROM REQUISITIONLINE WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)

			if gLineRS.EOF then
				call GenerateWarning( I18N(Lbl_RequisitionReference), I18N(Lbl_NotValidSelectedReq))
			end if

		end if
		
		if trim(gRequisitionID)>"0" then
			Set gHeaderRS = getRecordset("SELECT * FROM REQUISITIONHEADER WHERE REQUISITIONID=" & gRequisitionID)
			gCurrency = gHeaderRS("CURRENCYCODE")
			' Begin Fix after IT 
			if gRequisitionerPrefix = "" then 
				gRequisitionerPrefix = gHeaderRS("REQUISITIONERPREFIX")
			End if 
			' End Fix after IT 
		else
			gHeaderRS = ""
			gCurrency = ""
		end if
		
		call InitPage()
				
		Select Case gMode
		Case "edit"
			call showrequisitionfields(true)
		Case "selectaddress"
			call showrequisitionfields(False)
			call createselectiongrid(I18N(Lbl_SelectAddressfromGrid), "SELECT ADDRESSID , SHORTDESCRIPTION FROM ADDRESS", "[ADDRESSID]", I18N(Lbl_Description), "[SHORTDESCRIPTION]")
		Case  "selectbusinesspartner"
			call showrequisitionfields(False)
			call createselectiongrid(I18N(Lbl_SelectBusinessPartnerfromGrid), "SELECT BUSINESSPARTNERID , NAME FROM BUSINESSPARTNER", "[BUSINESSPARTNERID]", I18N(Lbl_Description), "[NAME]")
		Case "selectwizardaddress"
			call setWizardHiddenFields()
			call createselectiongrid(I18N(Lbl_SelectAddressfromGrid), "SELECT ADDRESSID , SHORTDESCRIPTION FROM ADDRESS", "[ADDRESSID]", I18N(Lbl_Description), "[SHORTDESCRIPTION]")
		Case  "selectwizardbusinesspartner"
			call setWizardHiddenFields()
			call createselectiongrid(I18N(Lbl_SelectBusinessPartnerfromGrid), "SELECT BUSINESSPARTNERID , NAME FROM BUSINESSPARTNER", "[BUSINESSPARTNERID]", I18N(Lbl_Description), "[NAME]")
		Case "addwellcome"
			call displayWizardWellCome()
		Case "addwhat"
			call displayWizardWhat()
		Case "addwhen"
			call displayWizardWhen()
		Case "addbuy"
			call displayWizardBuy()
		Case "addcost"
			call displayWizardCost()
		Case "addcreate"
			call displayWizardCreate()
		Case "addproperties"
			'call setWizardHiddenFields()
			call displayWizardProperties()
		Case "addattachments"
			call displayAddAttachment()
			call showrequisitionfields(False)
		end select
%>
</form>
<%		' EEMAPI functions do not run within a form
		if Request.QueryString("mailto") <> "" then
			dim gRecipients(0)
			gRecipients(0) = Request.QueryString("mailto")
			if ucase(getBrowser.browser) = "IE" then ' Internet Explorer section
				call buildMessageEEMAPI(buildSubject(Request.QueryString("RequisitionID"), Request.QueryString("RequisitionerPrefix")),_
						buildMailText(getBrowser.browser, Request.QueryString("RequisitionID"), Request.QueryString("RequisitionerPrefix"), Request.QueryString("RequisitionLineNumber")),_
						gRecipients)
			end if
		end if
		set gHeaderRS = Nothing
		set gLineRS = Nothing
	end sub

'---------------------------------------------------------------------------------------------------------------------------------------------------
' doServerActions:
' - Determines which user action has taken place
' - performs actions on the server (like update or send email)
'---------------------------------------------------------------------------------------------------------------------------------------------------

	function doServerActions(iMode)
		dim i
		dim ReqComp
		Dim result
		Dim lHeaderRS

		if isFormButtonPressed("btnAddAttachment") then
			' add attachment action
			call CBR_Insert("REQUISITIONATTACHEDFILE", _
						  Array("REQUISITIONID", "REQUISITIONERPREFIX", "REQUISITIONLINENUMBER", "REQUISITIONFILENAME", "REQUISITIONFILEDESCRIPTION"), _
						  Array(gRequisitionID, gRequisitionerPrefix, gRequisitionLineNumber, getFormValue("REQUISITIONFILENAME"), getFormValue("REQUISITIONFILEDESCRIPTION")), _
						  Array(False, True, False, True, True))
			doServerActions = "edit"
			Exit Function
		end if

		if isFormButtonPressed("btnAddReceipt") then
			' create receipt line
			Dim lQReceived: lQReceived = setVal(getFormValue("txtQtyReceived"))
			Dim lQRejected: lQRejected = setVal(getFormValue("txtQtyRejected"))
			Dim lQBackOrdered: lQBackOrdered = setVal(getFormValue("txtBackOrdered"))
			Dim lInvoiceNum: lInvoiceNum = getFormValue("txtInvoice")
			
			if not isValidFloat(lQReceived) or not isValidFloat(lQRejected) or not isValidCurrency(lValReceived) then
				call GenerateWarning( I18N(Lbl_CanNotInsertUpdate), Array( I18N(Lbl_EnterNumericValue)))
				exit Function
			end if

			Set ReqComp = getcomponent("REQUISITION")
			call ReqComp.InsertReceipt(cLng(gRequisitionID), cStr(gRequisitionerPrefix), cLng(gRequisitionLineNumber), cDbl(lQReceived), _
													 cDate(Date), cDbl(lQRejected), cDbl(0.0), cDbl(lQBackOrdered), cStr(lInvoiceNum))
			doServerActions = "edit"
			set ReqComp = Nothing
			Exit Function
		end if
		
		if isFormButtonPressed("btnSetToCreated") then
			Set ReqComp = getcomponent("REQUISITION")
			call ReqComp.SetLineState(cStr(getprocuser), cLng(gRequisitionID), cStr(gRequisitionerPrefix), cLng(gRequisitionLineNumber),  ERequisition_ERequisitionState_Created)
			doServerActions = "edit"
			set ReqComp = Nothing
			Exit Function
		end if

		if isFormButtonPressed("BtnAssist") then
			if updatevalidate("update") then									'## IT DF 116.n
				Response.Redirect( getMSCSPage.URL(_
					"E-Requisition/enduser/buyerassistance_edit.asp",_
					"requisitionid", cstr(gRequisitionID),_
					"requisitionerprefix",gRequisitionerPrefix,_
					"requisitionlinenumber", cStr(gRequisitionLineNumber)))
			end if																		' ## IT DF 116.n
		end if

		if isFormButtonPressed("BtnSubmitAssist") then
			gBuyerassisted = 0	'Kris.n
			
			Dim lLineRS
			if updatevalidate("update") then								'# IT DF 121.n
				updateAttachments()											'# IT DF 121.n
				Set lHeaderRS = getRecordset("SELECT * FROM REQUISITIONHEADER WHERE REQUISITIONID=" & gRequisitionID)
				Set lLineRS = getRecordset("SELECT * FROM REQUISITIONLINE WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)

				' set line back to created and send email to requisitioner
				Set ReqComp = getcomponent("REQUISITION")
				call ReqComp.SubmitBackToRequisitioner(cStr(lHeaderRS("USERID")), cStr(getprocuser), cLng(gRequisitionID), cStr(gRequisitionerPrefix), cLng(gRequisitionLineNumber), cStr(getValue("ASSISTTEXT")))
				set lHeaderRS = Nothing
				Set lLineRS = Nothing
				call Response.Redirect(getMSCSPage().URL("E-Requisition/Enduser/RequisitionLine_List.asp", "mode", "buyer", "view", "review"))
				doServerActions = "edit"
				Exit Function
			end if																		'# IT DF 121.n
		end if

		if isFormButtonPressed("btnCancelAttachment") then
			doServerActions = "edit"
			Exit Function
		end if
	
		if iMode="new" and Request.Form.Count=0 then
		' page started from requisition header so start add wizard
			doServerActions ="addwellcome"
			exit function
		end if
		
		if isFormButtonPressed("wizardcancel") then
			Response.Redirect(getMSCSPage().URL("E-Requisition/Enduser/Requisition_detail.asp", "requisitionid", gCurrentHeaderID, "requisitionerprefix", "", "mode", "current"))
			doserveractions = "exit"
			Exit function
		elseif isFormButtonPressed("btnAddAttachmentMain") then
		' go to add file attachment
			doServerActions ="addattachments"
			exit function
		elseif isFormButtonPressed("wizardnext") then
			if not updateValidate("validate") then
				doServerActions = "error"
				Exit Function
			end if
			Select Case iMode
			Case "addwellcome"
				doServerActions = "addwhat"
			Case "addwhat"
				if WizardPropsPresent() then
					doServerActions = "addproperties"
				else
					doServerActions = "addwhen"
				end if
			Case "addwhen"
				doServerActions = "addbuy"
			Case "addbuy"
				doServerActions = "addproperties"
			Case "addproperties"
				if WizardPropsPresent() then
					RequisitionProperties_ValidateAllProperties()
					'call UpdateProperties()
				end if
				doServerActions = "addwhen"
				
			end select
			Exit Function			
		elseif isFormButtonPressed("wizardback") then
			Select Case iMode
			Case "addwhat"
				doServerActions = "addwellcome"
			Case "addwhen"
				if WizardPropsPresent() then
					doServerActions = "addproperties"
				else
					doServerActions = "addwhat"
				end if
			Case "addbuy"
				doServerActions = "addwhen"
			Case "addcost"
				doServerActions = "addbuy"
			Case "addproperties"
				doServerActions = "addwhat"
			end select
			Exit Function
		elseif isFormButtonPressed("wizardfinish") then
		'NEW UI: insert RequisitionLine and Optional properties

			'VALIDATE
			if not updateValidate("validate") then
				doServerActions = "error"
				Exit Function
			end if
			'INSERT REQ LINE; REQUISITIONPROPERTIES WILL BE ADDED IN UpdateValidate
			if not updateValidate("add") then
				doServerActions = "error"
				Exit Function
			end if

			'if iMode = "addproperties" then
			'if WizardPropsPresent() then
				'call UpdateProperties()
				Response.Redirect(getMSCSPage().URL("E-Requisition/Enduser/Requisition_detail.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "mode", "edit"))
				doserveractions = "exit"
				Exit Function
			'else			
			'	doServerActions = "addcreate"
			'	Exit Function
			'end if
		end if

'####################################################################################################################################		
'###	THIS CODE CAN PROBABLY BE REMOVED AS There is no submit button present any more   ######
		if isFormButtonPressed("btnsubmit") then
			' Save changes to database and next create properties
			updateAttachments()
			if updateValidate("add") then
					Dim lPropertiesRS
					Set lPropertiesRS = getRecordset("SELECT * FROM REQUISITIONPROPERTIES WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)
					if lPropertiesRS.EOF then
						Response.Redirect(getMSCSPage().URL("E-Requisition/Enduser/Requisition_detail.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix,  "mode", "edit"))
						doserveractions = "exit"
						Exit Function
					else
						doServerActions = "addproperties"
						Exit Function
					end if
					set lPropertiesRS = Nothing
			else				
				Response.Redirect(getMSCSPage().URL("E-Requisition/Enduser/Requisition_detail.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "mode", "edit"))
				doserveractions = "exit"
				Exit Function
			end if
		end if
'########################################################################################		

		if isPressedSelectionGrid(I18N(Lbl_SelectAddressFromGrid)) then
			gSelectedAddressID = ValueSelectionGrid()
			if iMode = "selectwizardaddress" then
				doServerActions = "addwhen"
			else
				doServerActions = "edit"
			end if
			Exit Function
		else
			gSelectedAddressID = 0
		end if
		
		if isPressedSelectionGrid(I18N(Lbl_SelectBusinessPartnerFromGrid)) then
			gSelectedBusinessPartnerID = ValueSelectionGrid()
			if iMode = "selectwizardbusinesspartner" then
				doServerActions = "addbuy"
			else
				doServerActions = "edit"
			end if
			Exit Function
		else
			gSelectedBusinessPartnerID = 0
		end if

		if isFormButtonPressed("buttonselectbusinesspartner") then
			' Select business partner page
			if left(iMode, 3)="add" then
				' pressed in wizard case
				doServerActions = "selectwizardbusinesspartner"
			else
				doServerActions = "selectbusinesspartner"
			end if
			Exit Function
		end if

		if isFormButtonPressed("addressselect") then
		' select address page
			if left(iMode, 3)="add" then
				' pressed in wizard case
				doServerActions = "selectwizardaddress"
			else
				doServerActions = "selectaddress"
			end if
			Exit Function
		end if

		if isFormButtonPressed("lineupdate") then
			' Save changes to database
'			updateAttachments()				'#IT DF 213.o

		'#IT 3.sn
		Dim lWarning 
		Dim lWarningCheck : lWarningCheck = False

		if not IsValidDate(Request.Form("DATEREQUIRED")) then'#ST314.sn
		
					lWarning = I18N(Lbl_NotValidDate)
				    lWarningCheck = True
		
		
		elseif CDate(GetValidDate(Request.Form("DATEREQUIRED"))) < Date() then 'For defects 108685,108690
			lWarning = I18N(Lbl_InCorrectRequiredDate)	
			lWarningCheck = True
		End if '#ST314.en
		'#ST314.so
		'if CDate(Request.Form("DATEREQUIRED")) < Date() then 
		'	lWarning = I18N(Lbl_InCorrectRequiredDate)	
		'	lWarningCheck = True
		'End if
		'#ST314.so
		
		if Request.Form("LINEQUANTITY")<>"" then
			if Cint(Request.Form("LINEQUANTITY")) < 0 then
				'An extra check is necessary to see if there is a warning already present 
				'iF yes then choose the Array format else choose the string format 
				if lWarningCheck then 
					lWarning = Array(lWarning,I18N(Lbl_CanNotOrderQty))
				Else
					lWarning = "Invalid Quantity"
				End if 
				lWarningCheck = True
			End if 
		Else
			'An extra check is necessary to see if there is a warning already present 
			'iF yes then choose the Array format else choose the string format 
			if lWarningCheck then 
				lWarning = Array(lWarning,I18N(Lbl_CanNotOrderQty))
			Else
				lWarning = "Invalid Quantity"
			End if 
			lWarningCheck = True		
		End if 
			
		if lWarningCheck then 
			Call GenerateWarning(I18N(Lbl_CanNotInsertUpdate),lWarning)
			Exit Function 
		End if 
		'#IT 3.en
		Dim lTempLineRS
		Set lTempLineRS = getRecordset("SELECT * FROM REQUISITIONLINE WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)
		if NOT IsNull(lTempLineRS("PRODUCTID")) then 
			requisitionutility_checkLotSize lTempLineRS("PRODUCTID"), Request.Form("LINEQUANTITY") 
		End if 
		set lTempLineRS=nothing
		'#ST.en	
			
			if updateValidate("update") then
				Set lHeaderRS = getRecordset("SELECT * FROM REQUISITIONHEADER WHERE REQUISITIONID=" & gRequisitionID)
				Set gLineRS = getRecordset("SELECT * FROM REQUISITIONLINE WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)
								
				if (gLineRS("LINESTATUS")<>ERequisition_ERequisitionState_UnderReview) then
				
					if getprocuser=lHeaderRS("USERID") then
						Response.Redirect(getMSCSPage().URL("E-Requisition/Enduser/Requisition_detail.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "mode", "edit"))
						doserveractions = "exit"
						Exit Function
					else
						doServerActions = "edit"
						exit function
					end if				
				else																									'#IT DF 213.sn
				'to update the Internal Attachment flag. Only buyer can change the flag
					updateAttachments()																		'#IT DF 213.en
				end if
			end if
	end if

		if isFormButtonPressed("lineremove") then
			' Delete line, response direct to delete line
			 Response.Redirect(getMSCSPage().URL("E-Requisition/Enduser/RequisitionLine_delete.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "requisitionlinefrom", gRequisitionLineNumber, "requisitionlineto", gRequisitionLineNumber, "view", gView))
			doserveractions = "exit"
			Exit Function
		end if

	' loop through all form elements and find the button actions
		for i = 1 to Request.Form.Count
			Dim Name: Name = Request.Form.Key(i)
			Dim Value: Value = Request.Form.Item(i)
			If left(Name, 19) =  "buttondeletereceipt" then
				' Delete receipt line
				Set ReqComp = getcomponent("REQUISITION")
				result = ReqComp.DeleteReceipt(cStr(getprocuser), CLng(gRequisitionID), cStr(gRequisitionerPrefix), CLng(gRequisitionLineNumber), CLng(Replace(left(Name, len(Name)-2), "buttondeletereceipt", "")))			
				doServerActions= "edit"
				set ReqComp = Nothing
				Exit Function
			end if
			If left(Name,22) = "buttondeleteattachment" then
				' Delete attachment
				Set ReqComp = getcomponent("REQUISITION")
				result = ReqComp.DeleteAttachment(cStr(getprocuser), CLng(gRequisitionID), cStr(gRequisitionerPrefix), CLng(gRequisitionLineNumber), CLng(Replace(left(Name, len(Name)-2), "buttondeleteattachment", "")))
				doServerActions= "edit"
				set ReqComp = Nothing
				Exit Function
			end if
		next
		' no actions so return with start mode
		doServerActions = iMode
	end function

private sub InitPage()

	set Page = GetPage()
	Page.OpenDatabaseConnection( "EProcurementConnection" ) ' For DGid's
	'table for wizard layout
	gWizardStartTable = "<TABLE CELLPADDING=""3"" CELLSPACING=""15"" WIDTH=""100%"">"
	set gTable = Page.Table()
	call gTable.SetTableTypeProperty()
	
	' Font size 1 = -20, size 2 = -23

	call gTable.SetColAlign( mButtonCol1, 1 )
	
	call gTable.SetColWidth( 1, 10)
	call gTable.SetColWidth( 2, 80 )
	call gTable.SetColWidth( 3, 50 ) ' To make the middle cols as long as possible.
	call gTable.SetColWidth( 4, 20)
	
	dim lButtonTable: set lButtonTable = Page.Table()
	call lButtonTable.SetTableTypePlain()
	if left(gMode,3)<>"add" and left(gMode,6)<>"select" then
	
		if (gHeaderRS("USERID")=getprocuser or gLineRS("USERID")=getprocuser) and _
		   (gLineRS("LINESTATUS") = ERequisition_ERequisitionState_Created or gLineRS("LINESTATUS") = ERequisition_ERequisitionState_Rejected or gLineRS("LINESTATUS")=ERequisition_ERequisitionState_UnderReview) then
			' allow updates in case of buyers and requisitioners
			call lButtonTable.CellAt( 1, 1, _
				formButton("lineupdate", I18NGif("btnupdateLeft.gif"), I18N(Lbl_UpdateLine) ) )	'IT 100.0
		end if
		if gHeaderRS("USERID")=getprocuser then
		     if gLineRS("LINESTATUS") <> ERequisition_ERequisitionState_Send and gLineRS("LINESTATUS") <> ERequisition_ERequisitionState_Received then		
			call lButtonTable.CellAt( 2, 1, _
			getDeleteButton("lineremove", I18N(Lbl_DeleteLine)) )
		      end if	
		      if gLineRS("LINESTATUS") = ERequisition_ERequisitionState_Created or gLineRS("LINESTATUS") = ERequisition_ERequisitionState_Rejected and not (Trim(gLineRS("USERID")) = "" ) then
				call lButtonTable.CellAt( 3, 1, _
					 formButton("BtnAssist", I18NGif("BtnBuyerAssistanceHeader.gif"), I18N(Lbl_AssistBuyer)))
		      end if
		end if
	end if

	set gOuterTable = Page.Table()
	call gOuterTable.SetTableTypePlain()
	call gOuterTable.SetTableHeight("100%")

	call gOuterTable.SetColWidth( 1, 100 ) ' This forces the left column to extend to the right

	' Place the buttons in a separate table
	set gPageHeaderTable = Page.Table()
	call gPageHeaderTable.SetTableTypePlain()
	call gPageHeaderTable.cellAt( 1, 2, lButtonTable )
	if left(gMode,3)<>"add" and left(gMode,6)<>"select" then
		call gPageHeaderTable.cellAt( 2, 1, "<hr>" )
	end if

	call gOuterTable.CellAt( 1, 1, gPageHeaderTable )
	call gOuterTable.CellAt( 2, 1, gTable )
	
end sub

'---------------------------------------------------------------------------------------------------------------------------------------------------
' Display Functions
' - Display general information
' - Properties
' - Address Information
' - Supplier Information
' - Properties
' - File Attachments
' - Approval entries
' - Receipt statements
'---------------------------------------------------------------------------------------------------------------------------------------------------
	function showrequisitionfields(iVisible)
		if iVisible then
			'call putExplainHeader( I18N(Lbl_ReqLineReqLine),  I18N(Lbl_RequisitionLineDetailHeader))
			call CreatePageHeader()
		end if
		call DisplayAssistInfo(iVisible)
		call DisplayGeneralInfo(iVisible)
		call displayaddressInfo(iVisible)
		call DisplayProperties(iVisible)
		call DisplayFinancialInfo(iVisible)
		call DisplaySupplierInfo(iVisible)
		call DisplayApprovalInfo(iVisible)  '#ST 452.sn
											'Approval data needs to come before attachments 
											'b'coz attachment needs list of approvers.
		call DisplayFileAttachments(iVisible)'#ST DF 452.so

		
		if iVisible then
			' Display Tracking and tracing information in case the requisition has been send out
			call displayTrackInformation()
			if Err.number = 0 and left(gMode,3)<>"add" then
				' In case of wizard then add to page is done in wizarddisplay
				call gHeaderTable.cellAt( 3, 1, gLinkStr)
				call Page.Add( gOuterTable )
			end if 
		end if
	end function

	'---------------------------------------------------------------------------------------------------------
	' CreatePageHeader
	' Sub Creates the pages header with links to information on the page
	'---------------------------------------------------------------------------------------------------------
	Private Sub CreatePageHeader()
		' Place the buttons in a separate table
		set gHeaderTable = Page.Table()
		call gHeaderTable.SetTableTypePlain()
		call gHeaderTable.cellAt( 1, 1, getExplainHeaderWithOnlineHelp(I18N(Lbl_ReqLineReqLine)) )
		call gHeaderTable.cellAt( 2, 1, I18N(Lbl_RequisitionLineDetailHeader) )
		'call gHeaderTable.cellAt( 3, 1, gLinkStr), this cell
		'is added just before page.Add( gOuterTable ), because then we
		'know the links to the headers in this page.

		call gPageHeaderTable.cellAt( 1, 1, gHeaderTable )
	End Sub

	private function getLinks()
		getLinks = "linkje1     linkje2"
	end function

	Function DisplayAssistInfo(iVisible)
		if (trim(gLineRS("ASSISTTEXT"))="" or isnull(gLineRS("ASSISTTEXT"))) and (getprocuser<>gLineRS("USERID") or gLineRS("LINESTATUS")<>ERequisition_ERequisitionState_UnderReview) then
			Response.Write(RSFieldHidden("ASSISTTEXT"))
			Exit Function
		end if
		if iVisible then
		'ToDo: insert a better image.
			if gLineRS("LINESTATUS")=ERequisition_ERequisitionState_UnderReview then
				call doInfoHeaderCell( "../images/Buyerassist.gif", _
									I18N(Lbl_GetBuyerAssist), _
									I18N(Lbl_LeftAssistInfo), _
									I18N(Lbl_GetBuyerAssistLink) )
			else
				call doInfoHeaderCell( "../images/Buyerassist.gif", _
									I18N(Lbl_GetBuyerAssist), _
									"", _
									I18N(Lbl_GetBuyerAssistLink) )
			end if
			call doTableNewRow()
			call setHeaderCellX(iVisible, I18N(Lbl_Remark))
		end if
		call setCellX(iVisible, TextArea("ASSISTTEXT", 10, 80, iVisible))
		if iVisible and gLineRS("LINESTATUS")=ERequisition_ERequisitionState_UnderReview then
			Dim lHTML
			call doTableNewRow()
			call gTable.SetNextCellColSpan(4)
			lHTML = I18N(Lbl_ClickAssistButton) & "&nbsp;&nbsp;" & formButton( "BtnSubmitAssist", I18NGif("btnsubmit.gif"), I18N(Lbl_ClickAssistButtonAlt))
			call doTableCell(lHTML)
			call dotableEnd()
		end if
	End Function

	Function DisplayGeneralInfo(iVisible)
		if iVisible then
			call doInfoHeaderCell( retrieveProductImgLocation(gLineRS("PRODUCTID")), _
									I18N(Lbl_RequirementInformation), _
									I18N(Lbl_LeftGeneralInfo), _
									I18N(Lbl_RequirementInformationLink) )
'			call doTableBeginProp( I18N(Lbl_RequirementInformation) )
			
			' sets the column for the whole page
			call gTable.SetColWidth( 1, "30" )
			
			call doTableNewRow()
'			call placeExplain( putLeftExplain(retrieveProductImgLocation(gLineRS("PRODUCTID")), I18N(Lbl_LeftGeneralInfo)))
			call setHeaderCellX(iVisible, I18N(Lbl_Header))
			call setCellX(iVisible, gRequisitionID & " - " & gRequisitionerPrefix & "&nbsp;" & setHeaderLink(I18N(Lbl_PressHeaderLink)))
			if gMode<>"add" then
				call doTableNewRow()
				call setHeaderCellX(iVisible, I18N(Lbl_LineNumber))
				call setCellX(iVisible, gRequisitionLineNumber)
			end if
		end if
		
		if iVisible then
			call doTableNewRow()
			call setHeaderCellX(iVisible, I18N(Lbl_State))
			call setCellX(iVisible, setStatusField(iVisible))
		end if
		
		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_Description))
		call setCellX(iVisible, setTextBox("ITEMDESCRIPTION", 30, 30, iVisible))

		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_PartNumber))
		call setCellX(iVisible, setTextBox("PARTNUMBERLINE", 30, 30, iVisible))

		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_Quantity))
		call setCellX(iVisible, setTextBox("LINEQUANTITY", 10, 10, iVisible) & "&nbsp;" & setListBox("UNITCODE",  iVisible))

		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_DateRequired))
		call setCellX(iVisible, setTextBox("DATEREQUIRED", 10, 10, iVisible)) 
		
		if getprocuser<>gHeaderRS("USERID") then
		' Display requisitioner if current user is different
			call doTableNewRow()
			call setHeaderCellX(iVisible, I18N(Lbl_Requisitioner))
			call setCellX(iVisible, getProcActualName(gHeaderRS("USERID").Value) & "&nbsp;&nbsp;" & getUserCommunicationLink(gHeaderRS("USERID"), gRequisitionID, gRequisitionerPrefix, gRequisitionLineNumber, getUrl(gHeaderRS("USERID"))))
		end if
		
		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_Commodity))
		call setCellX(iVisible, setListBox("COMMODITYCODE",iVisible))
		
		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_SearchCode))
		call setCellX(iVisible, setTextBox("LINESEARCHCODE", 30, 30, iVisible))

		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_Remark))
		call setCellX(iVisible, TextArea("LINEREMARK", 5, 50, iVisible))
		
		'call doTableEnd()
	End Function

	function DisplayProperties(iVisible)
		Dim lPropertiesRS
		Dim lPropertyComp
	
		Set lPropertiesRS = getRecordset("SELECT * FROM REQUISITIONPROPERTIES WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)
		if lPropertiesRS.EOF then
		' No properties to display
			Exit Function
		end if
		if iVisible then
'			call doTableBeginProp( I18N(Lbl_Properties))
			call doInfoHeaderCell( "../images/properties.gif", _
									I18N(Lbl_Properties), _
									I18N(Lbl_LeftProperties), _
									I18N(Lbl_PropertiesLink) )
		end if
		Set lPropertyComp = Server.CreateObject("ECatalog.Property")
		dim lFirst: lFirst = True
		Do while not lPropertiesRS.EOF
			call doTableNewRow()
'			if lFirst and iVisible then
'				lFirst = false
'				call placeExplain( putLeftExplain("e-requisition/images/properties.gif" , I18N(Lbl_LeftProperties)))
'			end if
			call setHeaderCellX(iVisible, lPropertiesRS("PROPERTYNAME").value)
			call setCellX(iVisible, SetPropertyField(lPropertiesRS("PROPERTYID").value, lPropertiesRS("REQVALUE").value, lPropertyComp.getDataType(lPropertiesRS("PROPERTYID").value ), lPropertiesRS("MANDATORY").value, lPropertiesRS("PROPERTYNAME").value, iVisible ))
			lPropertiesRS.MoveNext
		Loop
		set lPropertyComp = Nothing
		if iVisible then
			doTableEnd()
		end if
	End function

	function displayAddressInfo(iVisible)
		Dim lAddressID
		
		if gSelectedAddressID>0 then
			' address selected so display
			lAddressID = gSelectedAddressID
		else
			if Request.Form("ADDRESSID").Count<>0 then
				lAddressID = Request.Form("ADDRESSID")
			else
				lAddressID = gLineRS("ADDRESSID")
			end if
		end if

		call displayAddressX(lAddressID, allowEdit(gLineRS, "ADDRESSID") and iVisible, iVisible)
		'if iVisible then
			call doTableNewRow()

			call setHeaderCellX(iVisible, I18N(Lbl_ShipToContactInformation))
			call setCellX(iVisible, TextArea("SHIPTOCONTACTINFORMATION", 5, 50, iVisible))
			doTableEnd()
		'end if
	end function
	
	' ------------------------------------
	' DisplayFinancialInfo
	' ------------------------------------
	function DisplayFinancialInfo(iVisible)

		' names follow those of getCost() in RequisitionUtility
		Dim lCost
		Dim lQuan
		Dim lFreightCost
		Dim lUnitCost
		Dim lTax
		Dim lDiscountPercentage
		Dim lDiscountAmount

		lQuan				= CDbl(getValidCost(gLineRS("LINEQUANTITY")))
'		lFreightCost		= CDbl(getValidCost(gLineRS("FREIGHT_COST")))
		lFreightCost		= 0 ' Freight cost is disabled for this release
		lUnitCost			= CDbl(getValidCost(gLineRS("UNITCOST")))
		lTax				= CDbl(getValidCost(gLineRS("TAXPERCENTAGE")))
		lDiscountPercentage	= CDbl(getValidCost(gLineRS("DISCOUNTPERCENTAGE")))
		lDiscountAmount		= CDbl(getValidCost(gLineRS("DISCOUNTAMOUNT")))

		lDiscountPercentage = lDiscountPercentage / 100
		lTax				= lTax / 100

		Dim lTotalDiscountFromAmount
		Dim lTotalDiscountFromPercentage
		Dim lTotalDiscount

		lTotalDiscountFromAmount		= lQuan * lDiscountAmount
		lTotalDiscountFromPercentage	= lQuan * lUnitCost * lDiscountPercentage
		lTotalDiscount					= lTotalDiscountFromAmount + lTotalDiscountFromPercentage

		lCost = lQuan * lUnitCost - lTotalDiscount + lFreightCost
		lTax  = lCost * lTax
		lCost = lCost + lTax

		if iVisible then
			'call doTableBeginProp( I18N(Lbl_FinancialInfo) )
			'call placeExplain(putLeftExplain("e-requisition/images/finance.gif", I18N(Lbl_LeftFinancial)))
			call doInfoHeaderCell( "../images/finance.gif", _
									I18N(Lbl_FinancialInfo), _
									I18N(Lbl_LeftFinancial), _
									I18N(Lbl_FinancialInfoLink) )
			call doTableNewRow()
			call setHeaderCellX(iVisible, I18N(Lbl_CostCenter))
			call setCellX(iVisible, gLineRS("LINECOSTCENTER"))
		end if	
		
		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_ChargeType))
		call setCellX(iVisible, setListBox("CHARGETYPECODE", iVisible))
		
		if iVisible then
			call doTableNewRow()
			call setHeaderCellX(iVisible, I18N(Lbl_Budget))
			call setCellX(iVisible, gLineRS("BUDGETCODE") & " - " & gLineRS("ID"))
		end if
		
		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_Contract))
		call setCellX(iVisible, setListBox("CONTRACTCODE", iVisible))

		' --- second part
		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_UnitCost))
		call setCellX(iVisible, setCostField("UNITCOST", lUnitCost, iVisible))

' Freight cost is disabled for this release		
'		call doTableNewRow()
'		call setHeaderCellX(iVisible, I18N(Lbl_FreightCost))
'		call setCellX(iVisible, setCostField("FREIGHTCOST", lFreightCost, iVisible))
		
		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_Discount))
		
		if lQuan<>0 then
			' Convert the Discount amount to Discount per Unit 
			call setCellX(iVisible, setCostField("DISCOUNT", (CDbl(lTotalDiscount/lQuan)), iVisible))	'#ST 554.n
		Else
			call setCellX(iVisible, setCostField("DISCOUNT", lTotalDiscount, iVisible))	'#ST 554.n
		End if 


		call doTableNewRow()
		call setHeaderCellX(iVisible, I18N(Lbl_Tax))
		call setCellX(iVisible, setCostField("TAX", lTax, iVisible))

		if iVisible then
			call doTableNewRow()
			call setHeaderCellX(iVisible, I18N(Lbl_TotalCost))
			call setCellX(iVisible, EEFormatCurrency(lCost, gCurrency))
			doTableEnd()
		end if
		
	end function	' DisplayFinancialInfo()
	

	function displaySupplierInfo(iVisible)
		Dim lBusinessPartnerID
		
		if gSelectedBusinessPartnerID>0 then
			lBusinessPartnerID = gSelectedBusinessPartnerID
		else
			lBusinessPartnerID = getValue("BUSINESSPARTNERID")
		end if
		if iVisible then
		'	call doTableBeginProp( I18N(Lbl_SupplierInfo) )
		'	call placeExplain( PutLeftExplain("e-requisition/images/supplier.gif", I18N(Lbl_LeftSupplier)))
			call doInfoHeaderCell( "../images/supplier.gif", _
									I18N(Lbl_SupplierInfo), _
									I18N(Lbl_LeftSupplier), _
									I18N(Lbl_SupplierInfoLink) )
			call doTableNewRow()
		end if

		
		call setHeaderCellX(iVisible, I18N(Lbl_Supplier))

		if iVisible then
			call setCellX(iVisible, getSupplierEmailLink(getBusinessPartnerName(lBusinessPartnerID)))
			if allowEdit(gLineRS, "BUSINESSPARTNERID") then
				call gTable.CellAt( -1, 4, setSelectButton("buttonselectbusinesspartner", I18N(Lbl_SelectSupplier)))
			end if
		end if
		Response.Write( formhidden("BUSINESSPARTNERID", lBusinessPartnerID))

		if iVisible then
			call doTableNewRow()

			call setHeaderCellX(iVisible, I18N(Lbl_Buyer))
			if trim(gLineRS("USERID"))="" or IsNull(gLineRS("USERID")) then
				call setCellX(iVisible, "")
			else
				call setCellX(iVisible, setListBox("USERID", iVisible) & "&nbsp;" & getUserCommunicationLink(gLineRS("USERID").Value, gRequisitionID, gRequisitionerPrefix, gRequisitionLineNumber, getUrl(gLineRS("USERID"))))
			end if
		else
			call setCellX(iVisible, setListBox("USERID", iVisible))
		end if
		call doTableNewRow()

		call setHeaderCellX(iVisible, I18N(Lbl_SupplierPartNumber))
		call setCellX(iVisible, setTextBox("BUYFROMITEMCODE", 30, 50, iVisible))

		if iVisible then
			doTableEnd()
		end if
	end function

	function displayTrackInformation()
		if gLineRS("LINESTATUS") <> ERequisition_ERequisitionState_Send and gLineRS("LINESTATUS") <> ERequisition_ERequisitionState_Closed and gLineRS("LINESTATUS")<> ERequisition_ERequisitionState_Archived then
		' No need to show track information so go away
			Exit Function
		end if

		'call doTableBeginProp( I18N(Lbl_TrackingTracingInfo) )
		'call doTableNewRow()
		'call placeExplain( PutLeftExplain("e-requisition/images/deliver.gif", I18N(Lbl_LeftTrack)))
		call doInfoHeaderCell( "../images/tracing.gif", _
								I18N(Lbl_TrackingTracingInfo), _
								I18N(Lbl_LeftTrack), _
								I18N(Lbl_TrackingTracingInfoLink) )
		call doTableNewRow()
		
		call doTableHeaderCell(I18N(Lbl_DateSend))
		call doTableCell(EEFormatDate(gLineRS("DATESEND").Value))
		call doTableNewRow()
		call doTableHeaderCell(I18N(Lbl_AckDate))
		call doTableCell(EEFormatDate(gLineRS("ACKDATE").Value))
		call doTableNewRow()
		call doTableHeaderCell(I18N(Lbl_AckQuantity))
		call doTableCell(EEFormatFloat(gLineRS("ACKQUAN").Value))
		
		if trim(gLineRS("PURCHASEORDERNUMBER"))<>"" and not IsNull(gLineRS("PURCHASEORDERNUMBER")) then
			call doTableNewRow()
			call doTableHeaderCell(I18N(Lbl_PurchaseOrder))
			call doTableCell(gLineRS("PURCHASEORDERNUMBER") & " - " & gLineRS("PURCHASEORDERLINE"))
		end if
		
		if not isnull(gLineRS("TRACKURL")) then
			Dim lTrUrl
			if not isurl(gLineRS("TRACKURL").Value) then
				lTrUrl = "HTTP://" & gLineRS("TRACKURL").Value
			else
				lTrUrl = gLineRS("TRACKURL").Value
			end if
			call doTableNewRow()
			call gTable.SetNextCellColSpan(4)
			call doTableCell("<A href=""" & lTrUrl & """ TARGET=""_Blank"">" & I18N(Lbl_TrackURL) & "<A>")		
			call doTableNewRow()
		end if

		dim lRS: set lRS = Page.DRecordset()
		dim lTable: set lTable = Page.Table()		' Note the grid is put in a temp table to put it next to the picture, construction is also used elsewhere
		dim lGrid: set lGrid = Page.DGrid( lRS, I18N(Lbl_Receipts), true, lTable )

		' Args for DGrid.Col() <Column title> <Sort field(s)> <Width> <Alignment>
		call lGrid.Col( I18N(Lbl_ReceiptDate), "RECEIPTDATE" )
		call lGrid.Col( I18N(Lbl_Quantity), "QUANTITYRECEIVED") 
		call lGrid.Col( I18N(Lbl_QuantityRejected), "QUANTITYREJECTED") 
		call lGrid.Col( I18N(Lbl_BackOrdered), "BACKORDERED") 
		call lGrid.Col( I18N(Lbl_DeliveryNote), "INVOICENUMBER", , ,1)

		dim lShowDelete: lShowDelete = false
		if (gLineRS("LINESTATUS")=ERequisition_ERequisitionState_send) then
		    lShowDelete = true
			call lGrid.Col( I18N(Lbl_Remove))
		end if

		' Display Receipts Grid
		Dim newSql: newSql = "SELECT * FROM RECEIPTS WHERE REQUISITIONID=" & gLineRS("REQUISITIONID") & " AND REQUISITIONLINENUMBER=" & gLineRS("REQUISITIONLINENUMBER")
		call lRS.OpenRS( _
			newSQL, _
			"REQUISITIONID,REQUISITIONERPREFIX, REQUISITIONLINENUMBER, RECEIPTID" )
		'#ST 501.sn
		dim lTempRS :set lTempRS=Page.DRecordset()
		dim lCount :lCount=0
		dim lLoopVar:lLoopVar=0
		call lTempRS.OpenRS( _
			newSQL, _
			"REQUISITIONID,REQUISITIONERPREFIX, REQUISITIONLINENUMBER, RECEIPTID" )
		do while not lTempRS.eof
			lCount=lCount+1
			call lTempRS.MoveNext()
		loop
		'#ST 501.en
		' Only pput grid on page if there are records to show otherwise strange results
		Dim lSetGrid: lSetGrid = not lRS.EOF
		
		do while not lRS.EOF
			call lGrid.Cell( EEFormatDate(getvaliddate(lRS( "RECEIPTDATE").Value)) )
			call lGrid.Cell( EEFormatFloat(cStr(lRS("QUANTITYRECEIVED" ))))
			call lGrid.Cell( EEFormatFloat(cStr(lRS("QUANTITYREJECTED" ))))
			call lGrid.Cell( EEFormatFloat(cStr(lRS( "BACKORDERED"))))
			call lGrid.Cell( lRS( "INVOICENUMBER" ) )
			If lShowDelete then
			'#ST 501.sn
				lLoopVar=lLoopVar+1
				if lLoopVar=lCount then
			'#ST 501.en
					call lGrid.Cell(getDeleteButton(getdeletereceiptbuttonname(lRS("RECEIPTID")), I18N(Lbl_TipDeleteReceipt)))
				else	'#ST 501.sn
					call lGrid.Cell("")
				end if	'#ST 501.en
			end if
			call lRS.MoveNext()
		loop
		
		if lSetGrid then
			call doTableNewRow()
			call gTable.SetNextCellColSpan(4)
			call doTableCell(lTable)
		end if

' No add to receipt fields are shown to the user as he/she can do th		
'		if getprocuser=trim(gHeaderRS("USERID")) and gLineRS("LINESTATUS")=ERequisition_ERequisitionState_Send and gLineRS("MNTRECEIPTS") then  'ERequisitionState.Send 
'			call doTableNewRow()
'			call gTable.SetNextCellColSpan(4)
'			call doTableCell(getReceiptFields())		
'		end if
		
		call doTableEnd()
	end function

	function getReceiptFields()
		getReceiptFields = "<TABLE><TR><TD colspan=8 algin=left>" & fontBeginFunc()
		getReceiptFields = getReceiptFields & I18N(Lbl_EnterReceipt) & "</TD></TR><TR><TD>" & fontBeginFunc()
		getReceiptFields = getReceiptFields & I18N(Lbl_QuantityReceived) & "</TD><TD>" & formEdit("txtQtyReceived", "", 10, 10, 0) 
		getReceiptFields = getReceiptFields & "</TD><TD>" & fontBeginFunc() & I18N(Lbl_QuantityRejected) & "</TD><TD>" & formEdit("txtQtyRejected",  "", 10, 10, 0)
		getReceiptFields = getReceiptFields & "</TD><TD>" & fontBeginFunc() & I18N(Lbl_BackOrdered) & "</TD><TD>" &  formEdit("txtBackOrdered",  "", 10, 10, 0)
		getReceiptFields = getReceiptFields & "</TD><TD>" & fontBeginFunc() & I18N(Lbl_DeliveryNote) & "</TD><TD>" & formEdit("txtInvoice",  "", 10, 30, 0)
		getReceiptFields = getReceiptFields & "</TD><TD>" & formbutton("btnAddReceipt", I18NGif("btnAdd.gif"), I18N(Lbl_AddReceiptButton))
		getReceiptFields = getReceiptFields & fontEndFunc() & "</TD></TR></TABLE>"
	end function
	
	function CheckRole()
		if gRole = "REQUISITIONER" or _
		   gRole = "BUYER"  or _
		    gRole = "APPROVER"  then
		    CheckRole = true
		else
			CheckRole = False
		end if
	end function

	function displayFileAttachments(iVisible)
                
                Dim lLineStatus
		if not iVisible then
			Exit Function
		end if

		Dim newSql: newSql = "SELECT * FROM REQUISITIONATTACHEDFILE WHERE REQUISITIONID=" & gLineRS("REQUISITIONID") & " AND REQUISITIONLINENUMBER=" & gLineRS("REQUISITIONLINENUMBER")
		
		gRole = getCurrentRole (getprocuser)		

		lLineStatus = gLineRS("LINESTATUS")
		if lLineStatus <> ERequisition_ERequisitionState_Created and lLineStatus <> ERequisition_ERequisitionState_UnderReview and lLineStatus <> ERequisition_ERequisitionState_BeingApproved and lLineStatus <> ERequisition_ERequisitionState_Rejected then


		' check if there are attachments, if not then skip this whole section
			Dim lCheckFiles: set lCheckFiles = getRecordset(newSql)
			if lCheckFiles.EOF then
				' no files so get away
				lcheckFiles.Close
				exit function
			end if
			lCheckFiles.Close
		end if

'		call doTableBeginProp( I18N(Lbl_Attachments) )
'		call placeExplain( putLeftExplain("e-requisition/images/attachment.gif", I18N(Lbl_LeftAttachment)))
		call doInfoHeaderCell( "../images/attachment.gif", _
								I18N(Lbl_Attachments), _
								I18N(Lbl_LeftAttachment), _
								I18N(Lbl_AttachmentsLink) )
		call doTableNewRow()
		
		' Display Attachments Grid
		dim lRS: set lRS = Page.DRecordset()
		dim lTable: set lTable = Page.Table()
		dim lGrid: set lGrid = Page.DGrid( lRS, "", true, lTable ) ' Use the main table for this grid.

		' Args for DGrid.Col() <Column title> <Sort field(s)> <Width> <Alignment>
		call lGrid.Col( I18N(Lbl_Description ), "REQUISITIONFILEDESCRIPTION" )
		call lGrid.Col(I18N(Lbl_InternalAttachment))
		call lGrid.Col( I18N(Lbl_Name), "REQUISITIONFILENAME", , ,2 ) ' Last arg = Colspan.


		call lRS.OpenRS( _
			newSQL, _
			"REQUISITIONID,REQUISITIONERPREFIX, REQUISITIONLINENUMBER, REQUISITIONFILEID" )
		call lGrid.Col( I18N(Lbl_Remove) )	

		' Only pput grid on page if there are records to show otherwise strange results
		Dim lSetGrid: lSetGrid = not lRS.EOF
		
		do while not lRS.EOF

			call lGrid.Cell( getFileLink(Server.HTMLEncode(cstr(lRS("REQUISITIONFILENAME"))), Server.HTMLEncode(cstr(lRS("REQUISITIONFILEDESCRIPTION")))) )
			'Build the checkbox Input tag
			Dim lchkbox: lchkbox = "<input type=checkbox name=""" & "IA" & lRS("REQUISITIONFILEID") & """"
			if lRS("INTERNALATTACHMENT") then
				lchkbox = lchkbox + "  checked"
			end if
			
			if gRole <> "BUYER" then
				lchkbox = lchkbox & " disabled "
			end if
			lchkbox = lchkbox &  " >"
			
			call lGrid.cell(lchkbox)
			call lGrid.Cell( Server.HTMLEncode(cstr(lRS("REQUISITIONFILENAME"))) )
			if CheckRole() and cStr(lRS("USERID")) = cstr(getProcUser) then
				call lGrid.Cell( getDeleteButton( getdeleteattachmentbuttonname( _
					lRS( "REQUISITIONFILEID" ) ), I18N(Lbl_TipDeleteAttachment) ) )
			else
				call lGrid.Cell("")		
			end if
			call lRS.MoveNext()
		loop
		if lSetGrid then
			call gTable.SetNextCellColSpan(4)
			call doTableCell(lTable)
		end if
		
		if Checkrole() then 'created, rejected //TODO : Reqr able to add attach, when the status is Underreview?
			if lSetGrid then
				call doTableNewRow()	
			end if			
			call gTable.SetNextCellAlign( 1 )
'			call doTableCell( I18N(Lbl_PressToAddFile) & " &nbsp;" & formButton( "btnAddAttachmentMain", "btnadd.gif", I18N(Lbl_AddAttachment)))
			call doTableCell( "<A href=""" &getMSCSPage.URL("E-Requisition/Enduser/RequisitionAttachment_Upload.asp", "mode","edit", "requisitionid", getOptionalASPParameter("requisitionid"), "requisitionerprefix", getOptionalASPParameter("requisitionerprefix"), "requisitionlinenumber", getOptionalASPParameter("requisitionlinenumber") ) & """>" &I18N(Lbl_PressToAddFile) &"</A><BR>" & FontBeginColorFunc("red") &I18N(Lbl_FirstSaveChanges) & FontEndFunc())
		end if

		call doTableEnd()
	end function

	function getFileLink(iFileName, iDesc)
		getFileLink = "<A HREF=""" & getMSCSPage().URL("e-requisition/attached files/" & cStr(gRequisitionID) & "_" & cStr(gRequisitionerPrefix) & "_" & cStr(gRequisitionLineNumber) & "/" & trim(cStr(iFileName))) & """ target=""_Blank"">" & iDesc & "<A>"
	end function
	
	function displayAddAttachment()
		call doTableBeginProp( I18N(Lbl_AttachmentInfo) )
		call placeExplain( putleftExplain("e-requisition/images/attachment.gif", I18N(Lbl_LeftAttachment)))
		call doTableHeaderCell(I18N(Lbl_Description))
		call doTableCell(formEdit("REQUISITIONFILEDESCRIPTION",  "", 50, 50, 0))
		call doTableNewRow()
		call doTableHeaderCell(I18N(Lbl_FileName))
		call doTableCell(formTextArea("REQUISITIONFILENAME", "", 5, 50, False))
		call doTableNewRow()
		call doTableHeaderCell("")
		call doTableCell(formButton( "btnAddAttachment", I18NGif("btnadd.gif"), I18N(Lbl_AddAttachment)) & "&nbsp;&nbsp;" & formButton( "btnCancelAttachment", I18NGif("btncancel.gif"), I18N(Lbl_CancelAddAttachment)))
		call doTableEnd()
	End Function

	function displayApprovalInfo(iVisible)
		Dim ApprovalRS
		
		if not iVisible then
			Exit Function
		end if
		
		Set ApprovalRS = getRecordset("SELECT * FROM APPROVALENTRY WHERE REQUISITIONID=" & gRequisitionID & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber)
		set gApprovers = server.CreateObject ("Scripting.Dictionary")
		if ApprovalRS.EOF then
		' No Approval Entries to display
			Exit Function
		end if

		'call doTableBeginProp( I18N(Lbl_Approvals) )
		'call placeExplain(putLeftexplain("e-requisition/images/approval.gif", I18N(Lbl_LeftApproval)))
		call doInfoHeaderCell( "../images/approval.gif", _
								I18N(Lbl_Approvals), _
								I18N(Lbl_LeftApproval), _
								I18N(Lbl_ApprovalsLink) )

		call doTableNewRow()

		' Display Receipts Grid
		Dim newSql: newSql = "SELECT * FROM APPROVALENTRY WHERE REQUISITIONID=" & gLineRS("REQUISITIONID") & " AND REQUISITIONLINENUMBER=" & gLineRS("REQUISITIONLINENUMBER")
			
		dim lRS: set lRS = Page.DRecordset()
		dim lTable: set lTable = Page.Table()
		dim lGrid: set lGrid = Page.DGrid( lRS,  "", true, lTable ) ' Use main table.

		' Args for DGrid.Col() <Column title> <Sort field(s)> <Width> <Alignment>
		call lGrid.Col( I18N(Lbl_Approver),	"USERID" )
		call lGrid.Col( I18N(Lbl_Status) ) 
		call lGrid.Col( I18N(Lbl_Description), "DESCRIPTION", , ,2 ) ' Last arg = Colspan.
	        call lGrid.Col( I18N(Lbl_DetailedDescription)) 
        	call lGrid.Col( I18N(Lbl_Reason))

		call lRS.OpenRS( _
			newSql, _
			"REQUISITIONID, REQUISITIONERPREFIX, REQUISITIONLINENUMBER, APPROVALID" )

		' Only pput grid on page if there are records to show otherwise strange results
		Dim lSetGrid: lSetGrid = not lRS.EOF
		
		Dim ltempusername

		do while not lRS.EOF
		
			ltempusername = lRS("USERID").Value
			gApprovers.Add ltempusername, ltempusername
			call lGrid.Cell( getLink( ltempusername ) )
			
			call lGrid.Cell( getApprovalState( lRS( "APPROVALSTATUS" ).Value ))
			call lGrid.Cell( lRS( "DESCRIPTION" ).Value )
		        call lGrid.Cell( lRS( "DETAILEDDESCRIPTION" ).Value ) 
		 	call lGrid.Cell( lRS( "REASONS" ).Value ) 
			call lRS.MoveNext()
		loop
		
		if lSetGrid then
			call gTable.SetNextCellColSpan(4)
			call doTableCell(lTable)
		end if
		call doTableEnd()

	end function

'---------------------------------------------------------------------------------------------------------------------------------------------------
' The following functions handle the display of the create requisition wizard and its individual steps.
' A wizard consists of three parts: a heading, a picture shown on the left and a main body showing text and input fields.
' On the bottom of the wizard page a small icon is shown together with a back, next, cancel and finish button.
'---------------------------------------------------------------------------------------------------------------------------------------------------

	function displayWizardWellCome()
		Dim ltextStr 
		Dim iHeading
		
		ltextStr = "<OL TYPE=""1"">"		
		ltextStr = ltextStr & "<LI>" & I18N(lbl_Step1)	
		ltextStr = ltextStr &  "<LI>" & I18N(lbl_Step2) & "<BR>"	
		ltextStr = ltextStr &  "<LI>" & I18N(lbl_Step3) & "<BR>"	
		ltextStr = ltextStr &  "<LI>" & I18N(lbl_Step4) & "<BR>"	
		ltextStr = ltextStr &  "<LI>" & I18N(lbl_Step5) & "<BR>"	
		ltextStr = ltextStr &  "<LI>" & I18N(lbl_Step6) & "</OL><BR>"	

'		call displayWizard(I18N(Lbl_WellComeAdd), I18N(Lbl_WellComeText), "AddWellcome.gif", lTextStr)
	
		call setWizardHiddenFields()
		if trim(cStr(gRequisitionID))>"0" then
			iHeading = iHeading & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" & "&nbsp;&nbsp;&nbsp;&nbsp;" & I18N(Lbl_Requisition) & ": " & gRequisitionID & " - " & gRequisitionerPrefix
			if trim(cStr(gRequisitionLineNumber))>"0" then
				iHeading = iHeading & " - " & gRequisitionLineNumber
			end if
		end if
		call gTable.SetTableTypeWizard()
		call doWizardTableBegin( I18N(Lbl_WellComeAdd) )
		
		call doTableNewRow()
		call doWizardTableCell( "<DIV align=""center""><STRONG><BR>" &FontBeginSizeFunc(2) & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" &I18N(Lbl_WellComeText) &"&nbsp;" & FontEndFunc() &"</STRONG></DIV>")
		call doTableNewRow()
		call gTable.setNextCellColSpan(3)
		call doWizardTableCell( displayAllSteps( Array("1.gif","2.gif" ,"3.gif","4.gif"), Array(Lbl_Step1, Lbl_Step6, Lbl_Step2, Lbl_Step3) ))
		call doTableNewRow()
		Dim lBtnNextCancel
		lBtnNextCancel = "<TABLE cellpadding=""5"" cellspacing=""0"" width=""100%"" height=""100%"" background=""" &getMSCSPage().Url(Application("WizardTableTitleBgImage")) &"""><TR>"
		lBtnNextCancel = lBtnNextCancel & "<TD ALIGN=""right"">"
		lBtnNextCancel = lBtnNextCancel & getGreyButton("wizardnext", I18N(Lbl_WizardNext), I18N(Lbl_WizardNextAlt)) & "&nbsp;"
		lBtnNextCancel = lBtnNextCancel & getGreyButton("wizardcancel", I18N(Lbl_Cancel), I18N(Lbl_CancelWizard)) & "&nbsp;"
		lBtnNextCancel = lBtnNextCancel & "</TD></TR></TABLE>"
		
		call doWizardTableCell(lBtnNextCancel)
		call Page.Add( gOuterTable )
		call doTableEnd()
	end function
	
	function displayAllSteps(iImages, iTexts)
		dim lReturnTable, cnt
		lReturnTable = "<TABLE cellpadding=""1"" cellspacing=""10""><TR>"
		for cnt=LBound(iImages) to UBound(iImages)
			lReturnTable = lReturnTable & "<TD align=""left"">" & getImage("e-requisition/images/" &iImages(cnt)) & "</TD>"
		next
		lReturnTable = lReturnTable &"<TR></TR>"
		for cnt=LBound(iTexts) to UBound(iTexts)
			lReturnTable = lReturnTable & "<TD valign=""top"" align=""left"">" & getStepText(iTexts(cnt)) & "</TD>"
		next
		displayAllSteps = lReturnTable &"</TR></TABLE>"
	end function


	function getStepText(iLabel)
		getStepText = FontBeginFunc & I18N(iLabel) & FontEndFunc()
	end function
	
	function displayWizardWhat()
		Dim ltextStr 
		
		ltextStr = gWizardStartTable	
		ltextStr = ltextStr & "<TR>" & internalCell(I18N(Lbl_AddCommodity), true)	& internalCell(setListBox("COMMODITYCODE",  True), false) & "</TR>"
		ltextStr = ltextStr &  "<TR>" & internalCell(I18N(Lbl_AddProduct) &getAsterisk(), true)	& internalCell(setTextBox("ITEMDESCRIPTION", 30, 30, True), false) & "</TR>"
		ltextStr = ltextStr &  "<TR>" & internalCell(I18N(Lbl_AddRemark), true)	& internalCell(TextArea("LINEREMARK", 5, 50, True), false) & "</TR>"
		ltextStr = ltextStr &  "<TR>" & internalCell(I18N(Lbl_AddQuantity), true) & internalCell( setTextBox("LINEQUANTITY", 10, 10, True) & setListBox("UNITCODE",  True), false) & "</TR>"
		ltextStr = ltextStr &  "<TR>" & internalCell("&nbsp;", false) & internalCell( FontbeginColorFunc("red") & "*&nbsp;" & I18N(Lbl_MandatoryField) & FontEndFunc(), false)& "</TR>"
		lTextStr = lTextStr & "</TABLE>"
		
		call displayWizard(I18N(Lbl_AddWhat), I18N(lbl_AddWhatExplain), "cart.gif", lTextStr)
	end function

	function displayWizardWhen()
		Dim ltextStr 
		Dim lAddressID
		
		if gSelectedAddressID>0 then
			' address selected so display
			lAddressID = gSelectedAddressID
		else
			lAddressID = getValue("ADDRESSID")
		end if
		
		ltextStr = I18N(lbl_AddWhenDefault) & "<BR><BR>" & gWizardStartTable	
		ltextStr = ltextStr & "<TR>" & internalCell(I18N(Lbl_AddReceiptDate), true) & internalCell(setTextBox("DATEREQUIRED", 10, 10, True), false) & "</TR>"
		lTextStr = lTextStr & "<TR>" & internalCell(I18N(Lbl_DeliveredToAddress), true) & internalCell( displayAddressBox(lAddressID), false) & "</TR></TABLE>"
		Response.Write(formhidden("ADDRESSID", lAddressID))

		call displayWizard(I18N(Lbl_AddWhen), I18N(lbl_AddWhenExplain), "truck.gif", lTextStr)
	end function

	function displayWizardBuy()
		Dim ltextStr 
		Dim lBusinessPartnerID
		
		if gSelectedBusinessPartnerID>0 then
			lBusinessPartnerID = gSelectedBusinessPartnerID
		else
			lBusinessPartnerID = getValue("BUSINESSPARTNERID")
		end if
		Response.Write(formhidden("BUSINESSPARTNERID", lBusinessPartnerID))

		ltextStr = gWizardStartTable
		lTextStr = lTextStr & "<TR>" & internalCell(I18N(Lbl_Buyer), true) & internalCell(setListBox("USERID", true), false) & "</TR>"
		lTextStr = 	lTextStr & "<TR>" & internalcell(I18N(Lbl_Supplier), true) & internalCell( SupplierSelect( lBusinessPartnerID ),false )
		lTextStr = lTextStr & "</TABLE>"
		
		call displayWizard( I18N(Lbl_AddBuy), I18N(Lbl_AddBuyExplain), "handshake.gif", lTextStr)
	end function

	function SupplierSelect( iBusinessPartnerID )
		Dim lTable
		lTable = "<TABLE cellpadding=""5"" bgcolor=""" & Application( "WizardTableSelectColor" ) &""">"
		if trim(iBusinessPartnerID)<>"" then
			lTable = lTable & "<TR><TD><INPUT type=""text"" size=""30"" value=""" &getBusinessPartnerName(iBusinessPartnerID)&""" disabled>" &"</TD></TR>"
		else
			lTable = lTable & "<TR><TD><INPUT type=""text"" size=""30"" disabled>" &"</TD></TR>"
		end if
		SupplierSelect = lTable & "<TR><TD align=""right"">" & setSelectButton("buttonselectbusinesspartner", I18N(Lbl_SelectSupplier) )& "</TD></TR></TABLE>"
	end function

	function displayWizardCost()
		Dim lTextStr
		
		ltextStr = gWizardStartTable 
		ltextStr = lTextStr & "<TR>" & internalCell(I18N(lbl_AddUnitCost), true) & internalCell(formEdit("UNITCOST", getValue("UNITCOST"), 10, 10, 0) & "&nbsp;" & getValue("CURRENCYCODE"), false) & "</TR>" 
		ltextStr = lTextStr & "<TR>" & internalCell(I18N(lbl_AddChargeType), true) & internalCell(setListBox("CHARGETYPECODE", True), false) & "</TR>"
		ltextStr = lTextStr & "<TR>" & internalCell(I18N(lbl_AddCostCenter), false) & internalCell(getValue("LINECOSTCENTER"), false) & "</TR></TABLE>"
	
		Response.Write(formHidden("LINECOSTCENTER", getValue("LINECOSTCENTER")))	
		
		call displayWizard(I18N(Lbl_AddCost), I18N(lbl_AddCostExplain), "payment.gif", lTextStr)
		
	end function

	function displayWizardCreate()
		Dim lTextStr

		if gRequisitionID<>"" then
			lTextStr = I18N(Lbl_NewRequisitionWizard) & gRequisitionID & " - " & gRequisitionerPrefix & "<BR><BR>"
		else
			lTextStr = lTextStr & I18N(Lbl_NewHeaderWizard) & "<BR><BR>"
		end if		
		lTextStr = lTextStr & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" & formButton("btnsubmit", I18NGif("btnsubmit.gif"), I18N(Lbl_SubmitRequisition)) & "<BR><BR>"
		
		lTextStr = lTextStr & I18N(Lbl_AddCreateExplainNext) & "<BR><BR>"
		lTextStr = lTextStr & I18N(Lbl_AttachAfterFiles)
				
		call displayWizard(I18N(Lbl_AddCreate), I18N(lbl_AddCreateExplain), "AddCreate.gif", lTextStr)
	end function

	function displayWizardProperties()
		'properties are retrieved in getWizardPropertyTable
		call displayWizard(I18N(Lbl_AddProperties), I18N(lbl_AddPropertiesExplain), "specification.gif", getWizardPropertyTable(getFormvalue("COMMODITYCODE")) )
	end function
	
	'this method returns the properties for the selected commoditycode in a table 
	function getWizardPropertyTable(iCommodityCode)
		Dim lTable, lRow
		Dim lProdComp
		Dim lPropDict
		Dim lProperties
		Dim lContainsMandatoryProperties
		Dim i
	
		' First check if properties have to be displayed
		set lProdComp = getcomponent("PRODUCT")
		set lPropDict = lProdComp.GetRequisitionLineProperties(cStr(getprocuser), cStr(iCommodityCode), 0)
		if lPropDict.Count = 0 then
			exit function
		end if
		set lProdComp = Nothing
		lTable = gWizardStartTable  

	    lProperties = lPropDict.Keys
		for i = LBound(lProperties) to UBound(lProperties)
			Dim lCurrentProperty : set lCurrentProperty = lPropDict.Item(lProperties(i))
			lRow = lRow & "<TR>"
			if CBool(lCurrentProperty.Item("MANDATORY")) then 
				lContainsMandatoryProperties = true
				lRow = lRow & internalCell(lCurrentProperty.Item("PROPERTYNAME") & getAsterisk(), true)
			else
				lRow = lRow & internalCell(lCurrentProperty.Item("PROPERTYNAME"), true)
			end if

			lRow = lRow & internalCell(SetPropertyField( lProperties(i), lCurrentProperty.Item("VALUE"), lCurrentProperty.Item("DATATYPE"),  lCurrentProperty.Item("MANDATORY"), lCurrentProperty.Item("PROPERTYNAME"), True), false)
			lRow = lRow & "</TR>"
			lTable = lTable & lRow
			lRow=""
		next

		lRow = lRow & "<TR>"
		lRow = lRow & internalCell( "&nbsp;" , false)
		lRow = lRow & internalCell( FontBeginColorFunc("red") & "*&nbsp;" &I18N(Lbl_Mandatory)& FontEndFunc(), false)
		lRow = lRow & "</TR>"
		lTable = lTable & lRow

		getWizardPropertyTable = lTable & "</TABLE>"
	end function
	
	'depending on iShow this function returns a red colored asterisk (*)
	function getAsterisk()
		getAsterisk = FontBeginColorFunc("red") & "&nbsp;*" & FontEndFunc()
	end function
'---------------------------------------------------------------------------------------------------------------------------------------------------
' The following function is used by the wizard to store the intermediate results in hidden fields.
'---------------------------------------------------------------------------------------------------------------------------------------------------

	Sub setWizardHiddenFields()
	' This function sets all fields hidden initially and prevents double fields by taking into account the mode
	' Note that it is also used to set default values upfront
		if gMode<>"addcost" then
			setWizardHidden("UNITCOST")
			setWizardHidden("CHARGETYPECODE")
			setWizardHidden("LINECOSTCENTER")
		end if
		
		if gMode<>"addwhen" then
			if gMode<>"selectwizardaddress" then
				setWizardHidden("ADDRESSID")
			end if
			setWizardHidden("DATEREQUIRED")
		end if
		if gMode<>"addbuy" then
			if gMode<>"selectwizardbusinesspartner" then
				setWizardHidden("BUSINESSPARTNERID")
			end if
			setWizardHidden("USERID")
		end if
		setWizardHidden("CURRENCYCODE")
		if gMode<>"addwhat" then
			setWizardHidden("ITEMDESCRIPTION")
			setWizardHidden("LINEREMARK")
			setWizardHidden("COMMODITYCODE")
			setWizardHidden("PARTNUMBERLINE")
			setWizardHidden("UNITCODE")
			setWizardHidden("LINEQUANTITY")
		end if
		
		if gMode<>"addproperties" then
			call setPropertyHiddenFields()
		end if
		
	end Sub

	
	Function setPropertyHiddenFields()
		Dim lItem
		
		for each lItem in Request.Form
			if inStr(lItem,"prop")>0 then
				call Response.Write(RSFieldHidden(lItem))
			end if
		Next
	end function


	function setWizardHidden(iField)
		if Request.Form(iField).Count<>0 then
			Response.Write(RSFieldHidden(iField))
		end if
	end Function

	function displayWizard( iTitle, iText, iImage, iContent)
		Dim lContent
		call setWizardHiddenFields()
		if trim(cStr(gRequisitionID))>"0" then
			iTitle = iTitle & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" & "&nbsp;&nbsp;&nbsp;&nbsp;" & I18N(Lbl_Requisition) & ": " & gRequisitionID & " - " & gRequisitionerPrefix
			if trim(cStr(gRequisitionLineNumber))>"0" then
				iTitle = iTitle & " - " & gRequisitionLineNumber
			end if
		end if
		call gTable.SetTableTypeWizard()
		'set the table height to 100% for nice displaying
		call doWizardTableBegin( iTitle )
		
		' These settings are required to make it look nicer
		call gTable.SetColWidth( 1, 20)
		call gTable.SetColWidth( 2, 100)
		call doTableNewRow()
		call doWizardTableCell(HeadingTable(iText, iImage))
		
		call doWizardTableCell("<TABLE><TR><TD >"  & FontBeginFunc() & iContent & FontEndFunc() & "</td></tr></table>")
		call doTableNewRow()
		
		lContent = "<TABLE cellpadding=""5"" cellspacing=""0"" width=""100%"" height=""100%"" background=""" &getMSCSPage().Url(Application("WizardTableTitleBgImage")) &"""><TR>"
		lContent = lContent & "<TD ALIGN=""right"">"
		lContent = lContent & getWizardButtons()
		lContent = lContent & "</TD></TR></TABLE>"
		
		call doWizardTableCell(lContent)
		call Page.Add( gOuterTable )
		call doTableEnd()
	End function		
	
	function getWizardButtons()
		Dim lBtnNext, lBtnBack, lBtnCancel, lBtnFinish
		lBtnNext = getGreyButton("wizardnext", I18N(Lbl_WizardNext), I18N(Lbl_WizardNextAlt)) & "&nbsp;"
		lBtnBack = getGreyButton("wizardback", I18N(Lbl_WizardBack), I18N(Lbl_WizardBackAlt)) & "&nbsp;"
		lBtnCancel = getGreyButton("wizardcancel", I18N(Lbl_Cancel), I18N(Lbl_CancelWizard)) & "&nbsp;"
		lBtnFinish = getGreyButton("wizardfinish", I18N(Lbl_WizardFinish), I18N(Lbl_WizardFinishAlt))
		
		getWizardButtons = ""
		' Different buttons are shown in different modes
		if gMode = "addwellcome" then
			getWizardButtons = getWizardButtons & lBtnNext & lBtnCancel
		elseif gMode = "addwhat" or gMode = "addproperties" or gMode = "addwhen" then
			getWizardButtons = getWizardButtons & lBtnBack & lBtnNext & lBtnCancel
		elseif gMode = "addbuy" then
			getWizardButtons = getWizardButtons & lBtnBack &  lBtnCancel & lBtnFinish
		end if
	end function

	function WizardPropsPresent()
		dim lProdComp
		set lProdComp = getcomponent("PRODUCT")
		WizardPropsPresent = lProdComp.RequisitionCommodityPropertiesPresent( cStr(getFormvalue("COMMODITYCODE")), cStr(getprocuser) )
		set lProdComp = Nothing
	end function
	
	'this function returns a table containing the explanation text,
	' background- and foregroundimage for every step in the wizard
	function HeadingTable(iHeadingText, iHeadingImage)
		HeadingTable = "<TABLE CELLPADDING=""10"" CELLSPACING=""0"" height=""249"" width=""163"">" &_
		"<TR><TD height=""128"" width=""163"" background=""" & getMSCSPage().Url( "E-requisition/images/wizardtextbgimagetop.gif" )&""">" & getImage("e-requisition/images/" & iHeadingImage) & "</TD></TR>" &_
		"<TR><TD height=""121"" width=""163"" background=""" & getMSCSPage().Url( "E-requisition/images/wizardtextbgimagebottom.gif" )&""">" & FontBeginFunc() & iHeadingText & FontEndFunc() & "</TD></TR>" &_
		"</TABLE>"
	end function
	
	function internalCell(iContent, iIsLabel)
		Dim lCellBgColorTag : lCellBgColorTag = ""
		if iIsLabel then
			lCellBgColorTag = "bgcolor=""" & Application( "WizardTablePropColor" ) &""""
		end if
		'Function returns a table cell with the right font and colors set
		internalCell = "<TD valign=""top""" & lCellBgColorTag &">" & fontBeginFunc() &"<B>"& iContent & fontEndFunc() & "</TD>"
	end function

'---------------------------------------------------------------------------------------------------------------------------------------------------
' General functions
'---------------------------------------------------------------------------------------------------------------------------------------------------

	function updateValidate(iAction)
	' Note that the following fields are not assumed to be editable and are therefore not read here:
	' productid, catalogid, freigth_cost, taxpercentage, discountpercentage, discountamount, linestatus,
	' purchaseorder number, purchaseorderline, budgetcode, id
		Dim lFields(26)		'#ST 554.n
		Dim lValues(26)
		Dim lStrings(26)	'#ST 554.n
		Dim cnt
		
		cnt = 0		
		call setArray( "REQUISITIONID", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("REQUISITIONERPREFIX", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("REQUISITIONLINENUMBER", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("BUSINESSPARTNERID", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("ADDRESSID", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("COMMODITYCODE", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("CHARGETYPECODE", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("CONTRACTCODE", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("NUMBER", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("UNITCODE", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("DISCOUNTAMOUNT", false, lValues(cnt), lFields(cnt), lStrings(cnt))	 '#ST 554.n
		cnt =  cnt + 1 '#ST 554.n
		call setArray("TAXPERCENTAGE", false, lValues(cnt), lFields(cnt), lStrings(cnt))	 '#ST 554.n
		cnt =  cnt + 1 '#ST 554.n
		call setArray("PARTNUMBERLINE", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("ITEMDESCRIPTION", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("LINEQUANTITY", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("UNITCOST", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("BUYFROMEMAIL", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("BUYFROMITEMCODE", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("SHIPTOCONTACTINFORMATION", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("LINEREMARK", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("LINESEARCHCODE", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("LINECOSTCENTER", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("DATEREQUIRED", false, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("USERID", True, lValues(cnt), lFields(cnt), lStrings(cnt))
		cnt =  cnt + 1
		call setArray("ASSISTTEXT", True, lValues(cnt), lFields(cnt), lStrings(cnt))
			cnt = cnt + 1
		call setArray("LINESTATUS", False, lValues(cnt), lFields(cnt), lStrings(cnt))'anu.n
		
		If iAction = "add" then		
			lFields(cnt) = "SOURCEOFREQUISITION"
			lValues(cnt) = 2
			lStrings(cnt) = false
			cnt = cnt + 1
			lFields(cnt) = "BUYERASSISTED"
			if fillbuyerassisted(2) then
				lValues(cnt) = 1	'Kris.n	
			else
				lValues(cnt) = 0	'Kris.n
			end if
			lStrings(cnt) = false
			cnt = cnt + 1
		elseif iAction = "update" then
			lFields(cnt) = "SOURCEOFREQUISITION"
			lValues(cnt) = gSourceofrequisition
			lStrings(cnt) = false
			cnt = cnt + 1
		
			lFields(cnt) = "BUYERASSISTED"
			lValues(cnt) = gBuyerassisted
			lStrings(cnt) = false
			cnt = cnt + 1
		end if
	
		Select Case iAction
		Case "add"
			Dim ReqComp
			Dim ReqDict
			
			' We do not use the requisitionbusinessrules here because we need to retrieve the requisition id, prefix and line number
			Set ReqComp =getcomponent("REQUISITION")
			if trim(gRequisitionID)="" then
				gRequisitionID = getCurrentRequisitionHeader(CStr(getprocuser))
				Dim lTmpRS
				set lTmpRS = getRecordset("SELECT REQUISITIONID, REQUISITIONERPREFIX FROM REQUISITIONHEADER WHERE REQUISITIONID=" & gRequisitionId)
				if not lTmpRS.Eof then
					gRequisitionerPrefix = cStr(lTmpRS("REQUISITIONERPREFIX"))
				else
					gRequisitionID = CLng(0)
				end if
				set lTmpRS = Nothing
			end if
			if trim(gRequisitionerPrefix)="" then
				gRequisitionerPrefix = cStr("")
			end if
			if trim(gRequisitionLineNumber)="" then
				gRequisitionLineNumber = CLng(0)
			end if
			
				
			Dim lChargeTypeCode
			Dim lCnt
			
			For lCnt = Lbound(lFields) to UBound(lFields)
				
				if lFields(lCnt) = "COMMODITYCODE" then
					Dim lSql
					Dim lRSChargeType
					
					lSql = "SELECT * FROM COMMODITY WHERE COMMODITYCODE='" & lValues(lCnt) & "'"
					
					set lRSChargeType = getCatalogConnection.Execute(lSql)
					lChargeTypeCode = lRSChargeType("CHARGETYPECODE")
				end if 
				if lFields(lCnt) = "CHARGETYPECODE" then
					lValues(lCnt) = lChargeTypeCode
				End if
				
				if lFields(lCnt) = "BUSINESSPARTNERID" then
					' check if supplier is not specified
					if lValues(lCnt)="" or IsNull(lValues(lCnt)) or IsEmpty(lValues(lCnt)) then
						Dim lFieldName
						Dim lValueCnt
						Dim lLowerValueCnt: lLowerValueCnt = lBound(lFields)
						Dim lUpperValueCnt: lUpperValueCnt = UBound(lFields)
						' if supplier not specified put the requisition under review
						For lValueCnt = lLowerValueCnt to lUpperValueCnt
							if lFields(lValueCnt) = "LINESTATUS" then 
								lValues(lValueCnt) = 3
							End if 
							if lFields(lValueCnt) = "ASSISTTEXT" then 
								lValues(lValueCnt) = I18N(Lbl_SelectBusinessPartnerFromGrid)
							End if 
						Next 
					End if 	
				End if 
				
				
			Next
			
			
			' when a header and line are created then the new values are returned through the global variables
'			Dim i
'			For i = 0 to UBound(lFields)
'				Response.Write lFields(i) & " : "
'				Response.Write lValues(i) & "<BR>"
'			Next 
'			Response.End
			
			set ReqDict = ReqComp.CreateLine(cStr(getprocuser), lFields, lValues, CLng(gRequisitionID), cStr(gRequisitionerPrefix))
			if not (ReqDict is Nothing) then
				updateValidate = True
				'set the new ReqID, Prefix and LineNumber for updating the properties
				gRequisitionID = ReqDict.item("REQUISITIONID")
				gRequisitionerPrefix = ReqDict.item("REQUISITIONERPREFIX")
				gRequisitionLineNumber = ReqDict.item("REQUISITIONLINENUMBER")
				'update properties for this reqline
				call UpdateProperties()
			else
				updateValidate = False
			end if
			set ReqComp = Nothing
		Case "update"
			call UpdateProperties()
			updateValidate =  CBR_Update("REQUISITIONLINE", lFields, lValues, lStrings, Array("REQUISITIONID", "REQUISITIONERPREFIX", "REQUISITIONLINENUMBER"))

		Case "validate"
			if gMode = "addWellCome" then
				updateValidate = True
			else
				updateValidate =  validateWizard()
			end if
		End Select
	end function
	
	function UpdateAttachments()
	'This function will be called only for buyer Role.
	'Updates the Internal Attachment Switch for a Particular Requisition.
	
		Dim lRS : set lRS = Server.CreateObject("ADODB.Recordset")
		Dim lSQL : lSQL = "SELECT * FROM REQUISITIONATTACHEDFILE WHERE REQUISITIONID = " & gRequisitionId & " AND REQUISITIONLINENUMBER=" & gRequisitionLineNumber
		Dim lConnection: lConnection = getConnection()
		Dim lReqFileId
		Dim lIntAttach
	
		lRS.Open lSQL, lConnection, 0 , 3
	
		do while not lRS.EOF
		
			lReqFileId = "IA" & lRS("REQUISITIONFILEID")
			
			if Request.Form (lReqFileId) = "on" then
				lIntAttach = 1
			else
				lIntAttach = 0
			end if
						
			lRS("INTERNALATTACHMENT") = lIntAttach
			
			lRS.moveNext()
		loop
		
		set lRS = nothing
		set lConnection = nothing
		
	end function
	
	Function UpdateProperties()
		Dim item
				
		if not RequisitionProperties_ValidateAllProperties() then
			' Errors so return
			Exit Function
		end if

		For each item in Request.Form
		' Consider each field on the form
			if inStr(item, "property")>0 then
			' If the IDstring is present then it is a correct field
				Dim tmpMandatory
				
				if Request.Form("propman" & getPropID(item)).Item then
					tmpMandatory = 1
				else 
					tmpMandatory = 0
				end if 
			
				call CBR_Update("REQUISITIONPROPERTIES",_
						Array("PROPERTYID", "REQUISITIONID", "REQUISITIONERPREFIX", "REQUISITIONLINENUMBER", "REQVALUE", "MANDATORY", "DATATYPE", "PROPERTYNAME"),_
						Array(getPropID(item), gRequisitionid, gRequisitionerPrefix, gRequisitionLineNumber, cStr(Request.Form(item).Item), tmpMandatory,CLng(Request.Form("propdatatype" & getPropID(item)).item), cStr(Request.Form("propname" & getPropID(item)).item)), _
						Array(False, False, True, False, True, False, False, True),_
						Array("PROPERTYID", "REQUISITIONID", "REQUISITIONERPREFIX", "REQUISITIONLINENUMBER"))
			End If
		Next
	End Function

	function ValidateWizard()
		Dim Warnings(), Counter
		
		Counter = 0
		validateWizard = True
		
		if gFromMode = "addwhat" then
			if IsEmptyStr( getValue( "ITEMDESCRIPTION")) then
				validateWizard = False
				ReDim Warnings(Counter)
				Warnings(Counter) = I18N(Lbl_DescriptionNotEmpty)
				Counter = Counter + 1
			end if
			if IsEmptyStr( getValue( "LINEQUANTITY")) or not IsValidFloat(getValue( "LINEQUANTITY")) then
					validateWizard = False
					ReDim Warnings(Counter)
					Warnings(Counter) = I18N(Lbl_QuantityNotNumber)
					Counter = Counter + 1
			elseif	 getValue( "LINEQUANTITY")<0.0 or getValue( "LINEQUANTITY")>9999999 then
					validateWizard = False
					ReDim Warnings(Counter)
					'Warnings(Counter) = I18N(Lbl_QuantityNotNumber)  '#ST 303.O
					Warnings(Counter) = I18N(Lbl_QtyOutOfRange)		  '#ST 303.N
					Counter = Counter + 1
			end if
		end if
		
		if gFromMode = "addcost" then
			' note that correctCostField is declared in requisitionbusinessrules
			if  not correctCostField(getValue("UNITCOST")) then
				validateWizard = False
				ReDim Warnings(Counter)
				Warnings(Counter) = I18N(Lbl_NotValidCost)
				Counter = Counter + 1
			end if
		end if
		
		if gFromMode = "addwhen" then
			if not IsEmptyStr( getValue( "DATEREQUIRED")) then
				if not IsValidDate(getValue( "DATEREQUIRED")) then
					validateWizard = False
					ReDim Warnings(Counter)
					Warnings(Counter) = I18N(Lbl_NotValidDate)
					Counter = Counter + 1
				end if
			end if
		end if
		if not validateWizard then
			call GenerateWarning( I18N(Lbl_CanNotContinueWizard), Warnings)
			Exit Function
		end if
		validateWizard = true
	end function
	
	function setArray(iFieldName, iString, iValue, iField, iStrings)
		Select Case iFieldName
		Case "CONTRACTCODE"
			iValue = getContractCode("CONTRACTCODE")
		Case "NUMBER"
			iValue = getContractCode("NUMBER")
		Case "REQUISITIONID"
			iValue = gRequisitionID
		Case "REQUISITIONERPREFIX"
			iValue = gRequisitionerPrefix
		Case "REQUISITIONLINENUMBER"
			iValue = gRequisitionLineNumber
		Case "LINEQUANTITY"
			if isvalidfloat(getformvalue(iFieldName)) then
				iValue = getvalidfloat(getFormValue(iFieldName))
			else
				iValue = getFormValue(iFieldName)
			end if
		Case "DATEREQUIRED"
			if isvaliddate(getFormValue(iFieldName)) then
				iValue = EEFormatdate(getvaliddate(getFormValue(iFieldName)))
			else
				iValue = getFormValue(iFieldName)
			end if
		Case "UNITCOST"
			if isvalidcurrency(cStr(getFormValue(iFieldName))) then
				iValue = getvalidcurrency(getFormValue(iFieldName))
			else
				iValue = getFormValue(iFieldName)
			end if
		Case "LINEREMARK"
			if len(getFormValue(iFieldName))>255 then
				iValue = left(getFormValue(iFieldName), 255)
			else
				iValue = getFormValue(iFieldName)
			end if
		 '#ST 554.sn
		Case "DISCOUNTAMOUNT"
			if isvalidcurrency(cStr(getFormValue("DISCOUNT"))) then
				iValue = getvalidcurrency(getFormValue("DISCOUNT"))
			else
				iValue = CDbl("0")
			end if
		Case "TAXPERCENTAGE"
			Dim lCost
			Dim lUnitCost
			Dim lDiscount
			Dim lTax 
			
			if isvalidcurrency(cStr(getFormValue("TAX"))) then
				iValue = getvalidcurrency(getFormValue("TAX"))
			else
				iValue = getFormValue("TAX")
			end if
			
			If "" & getFormValue("UNITCOST") = "" or "" & getFormValue("DISCOUNT")="" or "" & getFormValue("LINEQUANTITY")="" then 
				lCost = CDbl("0")
			Else
				lCost = (CDbl(getFormValue("UNITCOST"))-CDbl(getFormvalue("DISCOUNT")))*CDbl(getFormValue("LINEQUANTITY"))
			End if 
			
			if lCost<>0 then
				iValue = (iValue * 100)/lCost
			Else
				iValue = 0 
			End if 
		'#ST 554.en
		Case Else	
			iValue = getFormValue(iFieldName)
		End Select
		
		if (iFieldName = "BUDGETCODE" or iFieldName = "CONTRACTCODE" or iFieldName = "COMMODITYCODE" or iFieldName = "NUMBER" or iFieldName = "BUSINESSPARTNERID" or iFieldName = "UNITCOST" or iFieldName = "PRODUCTID" or _
		   iFieldName = "ADDRESSID" or iFieldName = "LINEQUANTITY" or iFieldName = "ID" or iFieldName = "DATEREQUIRED" or iFieldName = "ASSISTTEXT") and trim(iValue)="" then
			iValue = Null
		end if
		
		if isEmpty(iValue) then
			iValue = ""
		end if
		
		iField = iFieldName
		iStrings = iString
	end function

	function getContractCode(iField)
		Dim lCodeAndNumber : lCodeAndNumber = split(getFormValue("CONTRACTCODE"), "-")
		if trim(getFormValue("CONTRACTCODE"))="" then
			getContractCode = ""
			Exit Function
		end if
		if iField = "CONTRACTCODE" then
			getContractCode = trim( lCodeAndNumber(0) )
		else
			if isnumeric(trim( lCodeAndNumber(1))) then
				getContractCode = CLng(trim( lCodeAndNumber(1) ))	
			else
				getContractCode = Null
			end if
		end if
	end function

	function getValidCost(iValue)
		if IsNull(iValue) then
			getValidCost = 0
		else 
			if cStr(iValue)="" then
				iValue = 0
			end if
			getValidCost = cDbl(iValue)
		end if
	end function

	'function getLink(iUserID)
	'	getLink = getProcActualName(iUserId) & "&nbsp;" & getUserCommunicationLink(iUserID, gRequisitionID, gRequisitionerPrefix, gRequisitionLineNumber, getUrl(iUserID))
	'end function
	
	function getLink(iUserID)
		if ("" & iUserID) = "" then
			getLink = ""
		else
			getLink = getProcActualName(iUserId) & "&nbsp;" & _
						getUserCommunicationLink(iUserID, gRequisitionID, _
									 gRequisitionerPrefix, _
									 gRequisitionLineNumber, _
									 getUrl(iUserID))
		end if
	end function


	function getdeletereceiptbuttonname(iID)
		getdeletereceiptbuttonname =  "buttondeletereceipt" & iID
	end function
	
	function getdeleteattachmentbuttonname(iID)
		getdeleteattachmentbuttonname =  "buttondeleteattachment" & iID
	end function

 	Function setHeaderlink(iStr)
		setHeaderLink = "<A HREF=""" & getMSCSPage.URL( "E-Requisition/enduser/requisition_detail.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "mode", "edit") & """>" & iStr & "<A>"
	end Function

 	Function setApprovallink(iStr, iID, iUserId)
 		if iUserId = getprocuser and gLineRS("LINESTATUS") = ERequisition_ERequisitionState_BeingApproved then
 			setApprovalLink = iStr & "&nbsp;" & "<A HREF=""" & getMSCSPage.URL( "E-Requisition/enduser/approval_edit.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "requisitionlinenumber", gRequisitionLineNumber, "approvalid", iID) & """>" & I18N(Lbl_ClickLinkToSetState) & "<A>"
		else
			setApprovalLink = iStr
		end if
	end Function

	Function getUserComponent()
		if not IsObject(gUserComponent) then
			set gUserComponent = getcomponent("USER")
		end if
		set getUserComponent = gUserComponent
	end Function

	Function SetPropertyField(iPropID, iValue, iDataType, iMandatory, iName, iVisible)
		' Also hide other values, will save dbase queries
		setPropertyField = formhidden("propman" & iPropID, iMandatory)
		setPropertyField = setPropertyField & formhidden("propdatatype" & iPropID, iDatatype)
		setPropertyField = setPropertyField & formhidden("propname" & iPropID, iName)

		if not iVisible then
			setPropertyField = setPropertyField & formhidden("property" & iPropID, getPropertyValue(iPropID, iValue))
			Exit Function
		end if
		if not allowEdit(gLineRS, "property" & iPropID) then
			setPropertyField = setPropertyField &  getPropertyValue(iPropID, iValue)
			Exit Function
		end if
		if iDataType=ECatalog_Datatype_ENUMPROPERTYTYPE then
			' Create listbox for each enum
			SetPropertyField = setPropertyField & SetPropertyListBox(iPropID, getPropertyValue(iPropID, iValue))
			Exit Function
		elseif iDataType=ECatalog_Datatype_DATEPROPERTYTYPE and trim(getPropertyValue(iPropID, iValue))<>"" then
			setPropertyField = setPropertyField & formEdit("property" & iPropID, EEFormatDate(getPropertyValue(iPropID, iValue)), 30, 30, 0)
		else
			setPropertyField = setPropertyField & formEdit("property" & iPropID, getPropertyValue(iPropID, iValue), 30, 30, 0)
		end if
		
	End Function

	function giveReceiptType(iType)
		if iType=1 then
			giveReceiptType = I18N(Lbl_Quantity)
		else
			giveReceiptType = I18N(Lbl_Value)
		end if
	end function
	
	function getSupplierEmailLink(iName)
		if gLineRS("BUYFROMEMAIL")="" then
			getSUpplierEmailLink = iName
		else
			getSupplierEmailLink = "<A HREF=""mailto:" & getValue("BUYFROMEMAIL") & """>" & iName & "<A>"
		end if
	end function

	Function getDeleteButton(iName, iAltText)
			getDeleteButton = formButton( iName, I18NGif("btnremoveHeader.gif"), iAltText )
	end function
	
	Function setSelectButton(iName, iAltText)
			setSelectButton = formButton( iName, I18NGif("btnselect.gif"), iAltText )
	end function
	
	Function setCostField(iName, iCost, iVisible)
		Dim Disable
		
		if not iVisible then
			setCostField = formhidden(iName, iCost)
			exit function
		end if
		if not allowEdit(gLineRS, iName) then
			Disable = 1
		end if
'		if Disable = 1 or iName <> "UNITCOST" then		'#ST 554.o
		if Disable = 1 or (iName <> "UNITCOST" and iName<>"DISCOUNT" and iName<>"TAX") then	'#ST 554.n
			setCostField = gCurrency & "&nbsp;" & formEdit(iName, EEFormatEditCurrency(iCost, gCurrency), 30, 30, 1)
		else
			setCostField = gCurrency & "&nbsp;" & formEdit(iName, EEFormatEditCurrency(iCost, gCurrency), 30, 30, Disable)
		end if
	end function
	
	function TextArea(iName, iRows, iCols, iVisible)
		if not iVisible then
			TextArea = RSFieldHidden(iName)
			exit function
		end if
		TextArea = formTextArea(iName, getValue(iName), iRows, iCols, not allowEdit(gLineRS, iName))
	end function

	function setListBox(iFieldName, iVisible)
		Dim item
		Dim Dict
	     
	     
		if not iVisible then
			setListBox = RSFieldHidden(iFieldName)
			Exit Function
		end if
		
		if not allowEdit(gLineRS, iFieldName) then
			if iFieldName = "CONTRACTCODE" then
				setListBox = gLineRS(iFieldName) & " -" & gLineRS("NUMBER") & RSFieldHidden(iFieldName)
			elseif iFieldName = "USERID" then
				setListBox = getProcActualName(gLineRS(iFieldName)) & RSFieldHidden(iFieldName)
			else
				setListBox = gLineRS(iFieldName) & RSFieldHidden(iFieldName)
			end if
			Exit Function
		end if
		setListBox = "<SELECT name=""" & iFieldName &""">"
		
		Select Case iFieldName
		Case "UNITCODE"
			Dim CatComp
			
			Set CatComp = Server.CreateObject("ECatalog.Unit")
			Set Dict = CatComp.GetAllUnits()
			set CatComp = Nothing
		Case "COMMODITYCODE"
			Dim ProdComp
		
			Set ProdComp = getcomponent("PRODUCT")
			Set Dict = ProdComp.GetAllCommodities()
			set ProdComp = Nothing
		Case "CHARGETYPECODE"
			Dim BudgetComp
			
			Set BudgetComp = Server.CreateObject("EBudget.Budget")
			set Dict = BudgetComp.GetAllChargeTypes()
			set BudgetComp = Nothing
		Case "CONTRACTCODE"
			Dim ContractComp
			
			Set ContractComp = Server.CreateObject("ECatalog.Contract")
			set Dict = ContractComp.GetAllContracts()
			set ContractComp = Nothing
		Case "USERID"
		
			Dim ComComp
			
			Set ComComp = getcomponent("USER")
			set Dict = ComComp.getAllBuyers()
			set ComComp = Nothing

		end select
		
		if iFieldName<>"USERID" then
		' kris.sn
			if not (iFieldName = "COMMODITYCODE" and (gMode = "addwellcome" or gMode = "addwhat")) then
				setListBox = AddField(setListBox, iFieldName, "", "")
			end if 
		' kris.en
		end if
		
		For each item in Dict
			setListBox = AddField(setListBox, iFieldName, item, item)					
		Next
		
		setListBox = setListBox & "</SELECT>"
	end function

	function AddField(iLB, iField, iValue, iDisplay)
'		if getValue(iField) = iValue then '#ST self.o

		if Trim(getValue(iField)) = Trim(iValue) then		'#ST self.n
			AddField = iLB & "<OPTION value=""" & iValue & """SELECTED >" & iDisplay & "</OPTION>"
		else
			AddField = iLB & "<OPTION value=""" & iValue & """>" & iDisplay & "</OPTION>"
		end if
	end function

	Function AddFields(iRS, iFieldName)
		AddFields = ""
		Do while not iRS.EOF 
			AddFields = AddFields & "<OPTION value=""" & iRS.Fields(iFieldName) & """>" & iRS.Fields(iFieldName) & "</OPTION>"
			iRS.MoveNext
		Loop	
	end Function

	function setTextBox(iName, iLength, iMaxLength, iVisible)
		Dim Disabled
	
		if not iVisible then
			setTextBox = RSFieldHidden(iName)
			exit function
		end if
		if not allowEdit(gLineRS, iName) then
			Disabled = 1
		else
			Disabled = 0
		end if
		if iName="DATEREQUIRED" then
			setTextBox = formEdit(iName,  EEFormatDate(GetValidDate(getValue(iName))), iLength, iMaxLength, Disabled)'For defects 108685,108690,108686
		elseif iName = "LINEQUANTITY" Then
			setTextBox = formEdit(iName, cStr(getValidFloat(getValue(iName))), iLength, iMaxLength, Disabled)
		else
			if iName = "ITEMDESCRIPTION" and gMode = "edit" then
				
				if not isnull(gLineRS("PRODUCTID")) and gLineRS("USERID")<>getprocuser then
				' put a hyperlink to the product_view page, only in case ordered from a catalog and the
				' user is not a buyer
					setTextBox = getProductLink(cStr(getValue(iName)), gLineRS("PRODUCTID"), gLineRS("ITEMDESCRIPTION")) & RSFieldHidden("ITEMDESCRIPTION")
				else
					setTextBox = formEdit(iName, cStr(getValue(iName)), iLength, iMaxLength, Disabled)
				end if
			else
				setTextBox = formEdit(iName, cStr(getValue(iName)), iLength, iMaxLength, Disabled)
			end if
		end if
	end function
	
	function setStatusField(iVisible)
		if iVisible then
			setStatusField = I18N(getStateLabel(gLineRS.fields("LINESTATUS")))
			if gHeaderRS("USERID")=getprocuser and (gLineRS("LINESTATUS") = ERequisition_ERequisitionState_BeingApproved or _
		  	   gLineRS("LINESTATUS") = ERequisition_ERequisitionState_Approved) then
				setStatusField = setStatusField & "&nbsp;&nbsp;" & formButton( "BtnSetToCreated", I18NGif("btnSetToCreated.gif"), I18N(Lbl_BtnSetToCreated))
			end if
			setStatusField = setStatusField & RSFieldHidden("LINESTATUS")
		else
			setStatusField = RSFieldHidden("LINESTATUS")
		end if
	end function
	
	function RSFieldHidden(iFieldName)
		RSFieldHidden = formhidden(iFieldName, getValue(iFieldName))
	end function

	function setVal(iVal)
		if trim(iVal)="" then
			setVal = "0"
		else
			setVal = iVal
		end if
	end function

	Function getValue(iName)
		if Request.Form(iName).Count<>0 and iName<>"USERID" then	'IT 20.o
			getValue = Request.Form(iName)
		else
			if Left(gMode, 3)<>"add" then
				If iName ="CONTRACTCODE" Then
					getValue = gLineRS("CONTRACTCODE") & "-" & gLineRS("NUMBER")
				else
					'#ST 326.sn
					if iName="USERID" and gmode="selectwizardbusinesspartner" then
						getvalue = Request.Form(iName)
					Else
					'#ST 326.en
						'getValue =gLineRS(iName)#ST300.o
						getValue =Trim(gLineRS(iName))'#ST300.n
					End if 
				end if
			else
				' here some default info is filled
				Select Case iName
				Case "CONTRACTCODE"
					getValue = gLineRS("CONTRACTCODE") & " - " & gLineRS("NUMBER")
				Case "UNITCOST" 
					getValue = 1.0
				Case "CURRENCYCODE"
					getValue = getDefaultCurrency()
				Case "CHARGETYPECODE"
					getValue = getDefaultChargeType()
				Case "USERID"
					' getValue = getDefaultBuyer()	'108593.o
					' 108593.sn
					getValue = Request.Form(iName)
				 	if getValue = "" then
						getValue = getDefaultBuyer()
					end if
					' 108593.en
				Case "LINECOSTCENTER"
					' retrieve this from user object
					getValue = getUserComponent().GetCostCenter(getprocuser)		
				Case "DATEREQUIRED"
					getValue =(Date) 
				Case "LINEQUANTITY"
					getValue = "0"
				Case "UNITCOST"
					getValue = gLineRS("UNITCOST").Value
				Case "SHIPTOCONTACTINFORMATION"
					'getValue = gLineRS("SHIPTOCONTACTINFORMATION").Value '#ST300.o
					getValue = Trim(gLineRS("SHIPTOCONTACTINFORMATION").Value)'#ST300.n
				Case else
					getValue = ""
				End Select
			end if
		end if
		if IsNull(getValue) then
			if iName="UNITCOST" then
				getValue="0.0"
			end if 
			getValue = ""
		end if
	end Function

	function getDefaultCurrency()
		if trim(gRequisitionID)<>"" then
		' requisition header is present so retrieve the currency code from there
			getDefaultCurrency = gHeaderRS("CURRENCYCODE")
		else
			Dim lUserComp
			set lUserComp = getUserComponent()
			getDefaultCurrency = lUserComp.GetCurrencyCode(getprocuser)
			set lUserComp = Nothing
		end if
	end function
	
	function getDefaultChargeType()
		if trim(getValue("COMMODITYCODE"))<>"" then
			Dim lCatComp
			set lCatComp = getcomponent("PRODUCT")
			getDefaultChargeType = lCatComp.getChargeType(cStr(getValue("COMMODITYCODE")))
			set lCatComp = Nothing
		else
			getDefaultChargeType = ""
		end if
	end function

	function getDefaultBuyer()
		if trim(getValue("COMMODITYCODE"))<>"" then
			Dim lCatComp
			set lCatComp = getcomponent("PRODUCT")
			getDefaultBuyer = lCatComp.GetBuyerFromCommodity(cStr(getValue("COMMODITYCODE")))
			set lCatComp = Nothing
		else
			getDefaultBuyer = ""
		end if
	end function
	
	function allowEdit(iLineRS, iFieldName)
		allowEdit = True
				
		if left(gMode, 3)="add" then
			allowedit = true
			exit function
		end if
		
		if not ((gHeaderRS("USERID")=getusername() or iLineRS("USERID")=getUserName()) and _
			(iLineRS("LINESTATUS") = ERequisition_ERequisitionState_Created or _
			  iLineRS("LINESTATUS") = ERequisition_ERequisitionState_Rejected or iLineRS("LINESTATUS")=ERequisition_ERequisitionState_UnderReview) )then   
				allowEdit = False
				exit function
		end if
		
		if not IsNull(iLineRS("PRODUCTID")) then
			'#ST 554.sn
			if iFieldName="UNITCOST" or iFieldName="DISCOUNT" or iFIeldName="TAX" then
				allowedit = False
			'#St 554.en
			elseif ilineRS("USERID")=getusername() then
				allowedit=true
			'#ST 554.sn
'			elseif (iFieldName = "UNITCOST" or iFieldname="DISCOUNT" or iFieldName="TAX") and iLineRS("USERID")=getActiveUser().cn then
'				allowedit=true
			'#ST 554.en
			elseif CLng(iLineRS("PRODUCTID"))>0 and _
				(iFieldName = "ITEMDESCRIPTION" or iFieldName="PARTNUMBERLINE" or iFieldName="UNITCODE" or iFieldName="COMMODITYCODE" or iFieldName = "CONTRACTCODE" or _
				 iFieldName = "COST" or iFieldName = "TAX" or iFieldName = "FREIGHTCOST" or iFieldName = "DISCOUNT" or iFieldName = "UNITCOST" or iFieldName = "CHARGETYPECODE" or _
				 iFieldName = "USERID" or iFieldName = "BUSINESSPARTNERID" or iFieldName = "BUYFROMEMAIL" or iFieldName ="BUYFROMITEMCODE") then
				allowEdit = False
			end if
		else
			allowEdit = True
		end if
		
		if iFieldName = "USERID" then
			allowEdit = False
		end if
		
	end function

	function getUrl(iUserID)
		if trim(iUserID)="" or IsNull(iUserID) then
			getUrl = ""
			Exit Function
		end if
		getUrl = getMSCSPage.URL( "E-Requisition/enduser/requisitionline_detail.asp", "requisitionid", gRequisitionID, "requisitionerprefix", gRequisitionerPrefix, "requisitionlinenumber", gRequisitionLineNumber, "mode", gMode, "role", gRole,  "mailto", getComponent("USER").GetEmailAddress(cstr(iUserID)))
	end function

	function getProductLink(iStr, iProductID, iDescription)
		if IsNull(iProductID) then
			' only show link to catalog if there is one
			getProductLink = iStr
			Exit Function
		end if
		if gHeaderRS("REQUISITIONID") = gCurrentHeaderID then
			getProductLink = "<A href=""" & getMSCSPage().URL("E-Catalog/EndUser/Product_View_procurement.asp", "itemno", "", "qty", "", "showaddtoorder", "true", "productid", cStr(iProductID), "nodeids", cStr(iProductID), "nodenames", cStr(iDescription), "nodetypes", "4", "application", "eprocurement") & """>" & iStr & "</A>"
		else
			getProductLink = "<A href=""" & getMSCSPage().URL("E-Catalog/EndUser/Product_View_procurement.asp", "itemno", "", "qty", "", "showaddtoorder", "false", "productid", cStr(iProductID), "nodeids", cStr(iProductID), "nodenames", cStr(iDescription), "nodetypes", "4", "application", "eprocurement") & """>" & iStr & "</A>"
		end if
	end function
	
	Function getCurrentRole(UserName)
	
		Dim Role : 	Role = "OTHERS"
		Dim lLineStatus : lLineStatus = gLineRS("LINESTATUS")
		Dim gUserObject
		set gUserObject = GetCurrentUser()
		
		if gHeaderRS("USERID") = UserName and gUserObject.RequisitionerRole and (lLineStatus  = ERequisition_ERequisitionState_Created or lLineStatus  = ERequisition_ERequisitionState_Rejected ) then
			Role = "REQUISITIONER"
		elseif gLineRS("USERID") = UserName and gUserObject.BuyerRole and lLineStatus  = ERequisition_ERequisitionState_UnderReview then
			Role = "BUYER"
		end if	
		
		if not isEmpty(gapprovers) then
			if gApprovers.Exists(UserName) and gUserObject.ApproverRole and lLineStatus  = ERequisition_ERequisitionState_BeingApproved then 
				Role = "APPROVER"
			end if
		end if
		getCurrentRole = Role
		set gUserObject=nothing
	end function
	
	function getApprovers(Product, requisitioner)
		Dim lRS : set lRS = Server.CreateObject("ADODB.Recordset")
		Dim lSQL : lSQL = "SELECT COMMODITYCODE FROM PRODUCT WHERE PRODUCTID=" & SQLEncode(Product)
		Dim lConnection: lConnection = getCatalogConnection()
		Dim lCommoditycode
		Dim lAdminOffice
		Dim Approvers
		
		set Approvers = server.CreateObject ("Scripting.Dictionary")
		
		lRS.Open lSQL, lConnection ', adOpenForwardOnly, adLockReadOnly
		lCommodityCode = lRS("COMMODITYCODE")
		
		set lConnection = Nothing
		
		lRS.Close
		
		lAdminOffice = getUserFieldByID(requisitioner, "ADMINOFFICE")
		
		lSQL = "SELECT USERID FROM APPROVAL_RULE WHERE (DATEFROM<='" & Date & "' and (DATETO>='" & Date & "' OR DATETO IS NULL)) AND (OFFICEDESCRIPTION IS NULL OR OFFICEDESCRIPTION='" & SQLEncode(lAdminOffice) & "') AND COMMODITYCODE='" & SQLEncode(lCommodityCode) & "'"
		
		lConnection = getConnection()
		lRS.Open lSQL, lConnection ', adOpenForwardOnly, adLockReadOnly
		
		do while not lRS.EOF
			Approvers.Add lRS("USERID"), lRS("USERID")
			Response.Write (lRS("USERID"))
			lRS.MoveNext
		loop
			
		lRS.close
		set lConnection = Nothing
		
		set getApprovers = Approvers
	end function
	
	function fillbuyerassisted(source)
		Dim lRS 
		Dim lSQL 
		Dim lConnection
	
		Dim lCommoditycode
		Dim lAdminOffice
		DIM user	
		'dim lSourceofrequisition
		dim  lstOffices
		set lstOffices = server.CreateObject("EECommon.User")
		if Request.Form("COMMODITYCODE").Count<>0 then	'all change
			lcommoditycode = Request.Form("COMMODITYCODE")
		end if

		user = getProcUser()
		lAdminOffice = lstOffices.GetAdminOffice(user)
						
		'lsourceofrequisition = getValue("SOURCEOFREQUISITION")
		
		set lRS = Server.CreateObject("ADODB.Recordset")
		lSQL = "SELECT * FROM BUYERASSISTRULES,BUYERASSISTEXCEPTIONS WHERE BUYERASSISTEXCEPTIONS.RULEID = BUYERASSISTRULES.RULEID AND ((BUYERASSISTRULES.SOURCEOFREQUISITION IS NULL AND BUYERASSISTEXCEPTIONS.SOURCEOFREQUISITION ='" & source &"') OR (BUYERASSISTRULES.COMMODITYCODE IS NULL AND BUYERASSISTEXCEPTIONS.COMMODITYCODE ='"& lCommoditycode &"') OR (BUYERASSISTRULES.OFFICEDESCRIPTION IS NULL  AND BUYERASSISTEXCEPTIONS.OFFICEDESCRIPTION ='"& lAdminoffice &"')) "
		lConnection = getConnection()
		
		lRS.Open lSQL, lConnection
		if not lRS.EOF then
			set lRS = nothing
			set lConnection = nothing
			fillbuyerassisted = false
		else 
			set lRS = nothing
			set lConnection = nothing
			
			set lRS = Server.CreateObject("ADODB.Recordset")
			lSQL = "SELECT * FROM BUYERASSISTRULES WHERE (BUYERASSISTRULES.SOURCEOFREQUISITION IS NULL OR BUYERASSISTRULES.SOURCEOFREQUISITION = '"& source &"') AND (BUYERASSISTRULES.COMMODITYCODE IS NULL OR BUYERASSISTRULES.COMMODITYCODE = '" &lCommoditycode &"') AND (BUYERASSISTRULES.OFFICEDESCRIPTION IS NULL OR BUYERASSISTRULES.OFFICEDESCRIPTION = '" &lAdminoffice &"') "
			lConnection = getConnection()
			lRS.Open lSQL, lConnection 
		
			if not lRS.EOF then
				set lRS = nothing
				set lConnection = nothing
				fillbuyerassisted = true
				exit function
			else
				set lRS = nothing
				set lConnection = nothing
				fillbuyerassisted = false
			end if
		end if			
	end function	
	
	function DisplayErrorInterface(iErr)	
		dim lErrInfo( 4 )
		lErrInfo( 0 ) = iErr.number
		lErrInfo( 1 ) = iErr.source
		lErrInfo( 2 ) = iErr.description
		lErrInfo( 3 ) = iErr.helpfile
		lErrInfo( 4 ) = iErr.helpcontext
		DisplayErrorInfo(lErrInfo)
	end function 
%>
</body>
</html>
