'*****************************************************
' Subversion Information:
' $Rev: 269 $:     Revision of last commit
' $Author: a.buellesbach $:  Author of last commit
' $Date: 2016-01-23 20:56:33 +0100 (Sa, 23 Jan 2016) $:    Date of last commit
'*****************************************************

Const QM_CONFIG_PREFIXES = "Controlled_Documents_"
Const QM_WF_INVALIDATION = "Document Invalidation"
Const QM_WF_TEMPLATE_INVALIDATION = "Template Invalidation"
Const QM_WF_CHECK_REVISION = "Check Revision"
Const QM_WF_REVISION = "Document Creation / Revision"
Const QM_WF_MODIFY_RECIPIENTS = "Modify Training Recipients"
Const QM_WF_MODIFY_AUTHOR = "Modify Author"
Const QM_WF_MODIFY_RESPONSIBLES = "Modify Training Responsibles"
Const QM_WF_MODIFY_PARTICIPANTS = "Modify Participants"
Const QM_WF_MANAGE_TRAINEES = "Manage trainees"
Const QM_TM_TRAINING_TITLE_PREFIX = "Training:  " 'Prefix of the title of a generated training survey
Const QM_TM_MODULE_NAME = "Controlled Documents / SOP" 'Name of the module for reference in training survey
Const QM_TM_CABINET_INTERNAL_NAME = "fTrainingSurvey" 'Internal name of the training survey cabinet
Const QM_LANGUAGES = "deu|eng" 'Languages implemented

IncludeScript recCommon.sScriptPath.Value & "Global_InternalNames.vbs"
IncludeScript recCommon.sScriptPath.Value & "customerFunctions.vbs"

'**********************************************************
' Class ControlledPrinting
' @description: Provides access to function for controlled printing
'**********************************************************
Class ControlledPrinting
    
	
	Function initControlledPrinting

		if thisprocess.WFFile.FileObjects.Count = 0 then 'no object in the wffile
			wfvariables.sError.Value = "StandardWF;;;OnlyOneDocument;;;Sie mssen genau eine Dokument an diesen Workflow bergeben."
			wfvariables.bCorrect.Value = 1
			Exit Function
		end If
		'check if the object is already in a Controlled Printout Workflow
		bIsAlreadyInProcess = isObjectInProcess (wfvariables.recStructure.iDocumentID.Value, "Controlled Printout")
		If bIsAlreadyInProcess = True Then
			wfvariables.sError.Value = "StandardWF;;;ControlledPrintoutActive;;;Ein Workflow zum Erzeugen der Ausdrucke ist bereits aktiv. Bitte versuchen Sie es spter erneut."
			wfvariables.bCorrect.Value = 1
			Exit Function
		End If	
	End Function
	
	Function initInformalPrinting

		if thisprocess.WFFile.FileObjects.Count = 0 then 'no object in the wffile
			wfvariables.sError.Value = "StandardWF;;;OnlyOneDocument;;;Sie mssen genau eine Dokument an diesen Workflow bergeben."
			wfvariables.bCorrect.Value = 1
			Exit Function
		end If
	End Function	
	
    Function enableMultiSelection
    	wfvariables.recPrintouts.MultiSelect = True
    End Function
    
    Function disableMultiSelection
    	wfvariables.recPrintouts.MultiSelect = False
    End Function	
    
  
    '**********************************************************
    ' loadPrintouts
    ' @description: determines the controlled printouts from the controlled document - the user can only see printouts created by himself. 
    '				users who are member of the supervisor role (defined in the configuration file) can see all printouts
    ' @param: Nothing
    ' @return: Nothing
    '**********************************************************
    Function loadPrintouts
        sXMLPath = getObjectDetails (wfvariables.recStructure.iDocumentID.value, "", "")
        
        Dim dom, oXmlDoc
        
        'read the supervisor role from the configuration file
        Set oXmlDoc = CreateObject("Msxml2.DOMDocument") 		
        oXmlDoc.load( wfvariables.recCommon.sConfigurationFile.Value) 
        Dim xpath : xpath = "//config/WorkflowType[@type='" & wfvariables.recCommon.sWorkflowModel.Value & "' ]/SupervisorRole"
        Set oSupervisorNode = oXmlDoc.selectSingleNode(xpath)  
        wfvariables.sSupervisorRole.Value = oSupervisorNode.text
        debug2file "SupervisorRole from configuration file: " & wfvariables.sSupervisorRole.Value
        Set oXmlDoc = Nothing
        
        
        Set dom = CreateObject("Msxml2.DOMDocument") 
        
        dom.load(sXMLPath)
        
        
        Set oColumns = dom.selectNodes("/DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='rManagedCopies']/Columns/Column")
        Dim colCreatorIndex, colResponsibleIndex, colDateIndex, colReturnDateIndex, colReturnedIndex, colLocationIndex, colCommentIndex
        
        'get the index for each column	
        For c = 0 To oColumns.length - 1
            If oColumns.item(c).attributes.getNamedItem("internal_name").text = "sCreator" Then
                colCreatorIndex = c
            End If
            If oColumns.item(c).attributes.getNamedItem("internal_name").text = "sResponsible" Then
                colResponsibleIndex = c
            End If
            If oColumns.item(c).attributes.getNamedItem("internal_name").text = "dDate" Then
                colDateIndex = c
            End If
            If oColumns.item(c).attributes.getNamedItem("internal_name").text = "dReturnDate" Then
                colReturnDateIndex = c
            End If
            If oColumns.item(c).attributes.getNamedItem("internal_name").text = "sReturned" Then
                colReturnedIndex = c
            End If	
            If oColumns.item(c).attributes.getNamedItem("internal_name").text = "sLocation" Then
                colLocationIndex = c
            End If	
            If oColumns.item(c).attributes.getNamedItem("internal_name").text = "sComment" Then
                colCommentIndex = c
            End If	        								
        Next
        
        
        Dim sCreator, sResponsible, sResponsibleGUID, sDate, sReturnDate, sReturned, sLocation, sComment
        
        Set oNodes = dom.selectNodes("/DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='rManagedCopies']/Row")	
        'wfvariables.iLogEntries.value = CLng(oNodes.length)
        For i = 0 To oNodes.length - 1
            iRowID = oNodes.item(i).attributes.getNamedItem("id").text
            Set oValues = dom.selectNodes("/DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='rManagedCopies']/Row[@id='" & iRowID & "']/Value")      
            For v = 0  To oValues.length - 1
                If v = colCreatorIndex Then
                    sCreator = oValues.item(v).text
                End If
                If v = colResponsibleIndex Then
                    sResponsible = oValues.item(v).text
                    'get the guid of the responsible person
                    For z = 0 To wforganisation.GetOrgObjectsByName(sResponsible).Count - 1
                        If wforganisation.GetOrgObjectsByName(sResponsible).Item(z).OrgClass.Name = "Person" Then
                            sResponsibleGUID = wforganisation.GetOrgObjectsByName(sResponsible).Item(z).ID
                        End If
                    Next        		
                End If
                If v = colDateIndex Then
                    sDate = convertOSDateToLocalDate(oValues.item(v).text)	'CR - Support English / Multilanguage - CC-000240
                End If
                If v = colReturnDateIndex Then
                    sReturnDate = convertOSDateToLocalDate(oValues.item(v).text) 'CR - Support English / Multilanguage - CC-000240
                End If
                If v = colReturnedIndex Then
                    sReturned = oValues.item(v).text
                End If
                If v = colLocationIndex Then
                    sLocation = oValues.item(v).text
                End If
                If v = colCommentIndex Then
                    sComment = oValues.item(v).text
                End If        	        	    	
            Next
            
            'load the printouts to the workflow table
            Set oEntry = wfvariables.recPrintouts.CreateListItem
            oEntry.Item("sCreator").Value = sCreator
            oEntry.Item("sResponsible").Value = sResponsible
            If sDate <> "" Then
            	oEntry.Item("dCreatedOn").Value = sDate
            End If
            If sReturnDate <> "" Then
            	oEntry.Item("dDestroyedOn").Value = sReturnDate
            End If
            oEntry.Item("sDestroyed").Value = sReturned
            oEntry.Item("sLocation").Value = sLocation
            oEntry.Item("sComment").Value = sComment
            oEntry.Item("sResponsibleGUID").Value = sResponsibleGUID
            oEntry.Item("iLocked").Value = 1 'indicated that this entry is readonly
            wfvariables.recPrintouts.AddListItem oEntry	
            
        Next
        
        Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
        If oFSO.FileExists (sXMLPath) = True Then 'delete the file
            oFSO.DeleteFile sXMLPath
        End If
        'Clean up
        Set oFSO = Nothing	
    End Function
    
    
    '**********************************************************
    ' addToWFTray
    ' @description: adds a file to the wf file
    ' @param: 	sPath (String) - the file path of the object which should be added
    '			iTableIndex (Integer) - the index in the table of the current file (needed to write back the object id to the table)
    ' @return: Nothing
    '**********************************************************	
    Function addToWFTray (sPath, iTableIndex)
        debug2file "start addToWFTray (" & sPath & ")"
        Dim RC 
        Set RC = RunningContext 
        Set PrmIn = RC.NewJobsParams 
        Set PrmOut = RC.NewJobsParams
        
        xmlStr = "" &_
        "<DMSData>" &_
        "<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
        "<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
        "<Object>" &_
        "<Fields>" &_
        "<Field internal_name='" & getInternalName_Document_DocumentNumber & "'>" & convertToValidXML(wfvariables.sDocumentNumber.Value) & "</Field>" &_
        "<Field internal_name='" & getInternalName_Document_DocumentTitle & "'>" & convertToValidXML(wfvariables.sTitle.Value) & "</Field>" &_
        "<Field internal_name='" & getInternalName_Document_DocumentVersion & "'>" & convertToValidXML(wfvariables.sVersion.Value) & "</Field>" &_
        "<Field internal_name='" & getInternalName_Document_DocumentStatus & "'>" & 1 & "</Field>" &_
        "</Fields>" &_				
        "</Object>" &_
        "</ObjectType>" &_
        "</Archive>" &_
        "</DMSData>"
        
        debug2file xmlStr
        Set dom = CreateObject("MSXML.DOMDocument") 
        
        dom.loadXML(xmlStr)
        
        PrmIn.Clear() 
        PrmIn.Value("Flags") = 16
        PrmIn.Value("Options") = "CHECKREADONLY=0;CHECKCATALOGUE=0;CHECKOBLIGATION=0;CHECKKEYFIELDS=0;INWFTRAY=1" 
        PrmIn.Value("$Job$Files$" ) = sPath
        PrmIn.Value("XML" ) = dom
        PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
        
        iRet = RC.Jobs.DMS.XMLInsert(PrmIn, PrmOut)
        If iRet = 0 Then	
            debug2file "Objekt-ID " & PrmOut.Value("ObjectID")
            debug2file "Objekt-Typ " & PrmOut.Value("ObjectType")
            wfvariables.recPrintouts.Item(iTableIndex).Item("sPrintObjectID").Value = PrmOut.Value("ObjectID")
            wfvariables.recPrintouts.Item(iTableIndex).Item("sPrintObjectType").Value = PrmOut.Value("ObjectType")
        End If
        
        bRet = thisprocess.WFFile.AddFileObject(PrmOut.Value("ObjectID"),PrmOut.Value("ObjectType"),False,2)
        debug2file bRet
        
        debug2file "Result: " & iRet
        debug2file "end addToWFTray"
    End Function
    
    '**********************************************************
    ' createPrintouts
    ' @description: creates printouts with watermarks and adds them to the wffile. stores the information on the controlled document
    ' @param: Nothing
    ' @return: Nothing
    '**********************************************************
    Function createPrintouts
        Dim iRet
        For i = 0 To wfvariables.recPrintouts.Count - 1
        	If wfvariables.recPrintouts.item(i).item("sDestroyed").Value <> "ja / yes" Then 'don't create a printout for a already destroyed entry
	        	If wfvariables.recPrintouts.item(i).item("iLocked").Value <> "" Then 'a locked entry is an old one and was already printed, so we don't create another printout
	        		If wfvariables.recPrintouts.item(i).item("iLocked").Value <> 1 Then        	
			            sPath = storeObjectInCacheByID (wfvariables.recStructure.iDocumentID.Value, 1)
			            iRet = CreateWatermarks (sPath, sPath & ".pdf", i)
			            debug2File "PATH: " & sPath
			            If iRet <> 0 Then
			            	wfvariables.sHint.value = "Es ist ein Fehler aufgetreten. Womglich lsst sich das Dokument nicht in ein PDF-Dokument konvertieren."
			            Else
			            	addToWFTray sPath, i
			            End If            
					End If
				End If
			End If            
        Next
        If iRet = 0 Then	'only update the document table, if the watermarks could be created
        	updateDocumentPrintTable False
        End If
        
    End Function
    
    '**********************************************************
    ' createAttachmentPrintouts
    ' @description: creates printouts with watermarks and adds them to the wffile. Does not store the information on the controlled document (informal printout)
    ' @param: Nothing
    ' @return: Nothing
    '**********************************************************	
    Function createAttachmentPrintouts
        Dim iRet
        For i = 0 To wfvariables.recPrintouts.Count - 1
            sPath = storeObjectInCacheByID (wfvariables.recStructure.iDocumentID.Value , 1)
            iRet = CreateWatermarks (sPath, sPath & ".pdf", i)
            If iRet <> 0 Then
            	wfvariables.sHint.value = "Es ist ein Fehler aufgetreten. Womglich lsst sich das Dokument nicht in ein PDF-Dokument konvertieren."
            Else
            	addToWFTray sPath, i
            End If
        Next
        
    End Function
    
    '**********************************************************
    ' getAmountOfControlledPrintouts
    ' @description: gets the amount of controlled printouts and stores the number in the variable iLogEntries
    '				this can be used to print (watermark) a printout counter on the document
    ' @param: Nothing
    ' @return: Nothing
    '**********************************************************		
    Function getAmountOfControlledPrintouts
        
        sXMLPath = getObjectDetails (wfvariables.recStructure.iDocumentID.value, "", "")
        
        Set dom = CreateObject("MSXML.DOMDocument") 
        dom.load(sXMLPath)
        Set oNodes = dom.selectNodes("/DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='rManagedCopies']/Row")	
        wfvariables.iLogEntries.value = CLng(oNodes.length)
        
        Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
        If oFSO.FileExists (sXMLPath) = True Then 'delete the file
            oFSO.DeleteFile sXMLPath
        End If
        'Clean up
        Set oFSO = Nothing	
        
    End Function
    
    Function getAmountOfInformalPrintouts
    End Function
    
    '**********************************************************
    ' deleteWFFileObjects
    ' @description: deletes the created files from the wf file
    ' @param: Nothing
    ' @return: Nothing
    '**********************************************************
    Function deleteWFFileObjects
        For i=0 To thisprocess.WFFile.FileObjects.Count-1 
            thisprocess.WFFile.DeleteFileObject thisprocess.WFFile.FileObjects(i).Id	
        Next
    End Function
    
    '**********************************************************
    ' updateDocumentPrintTable
    ' @description: updates the Printout table of the controlled document (stores the new printouts on the table)
    ' @param: bReplaceTableFields - true if the tablefields should be replaced, false if the fields should be added
    ' @return: Nothing
    '**********************************************************	
    Function updateDocumentPrintTable (bReplaceTableFields)
        Dim RC 
        Set RC = RunningContext 
        Set PrmIn = RC.NewJobsParams 
        Set PrmOut = RC.NewJobsParams
        
        Dim sTableFields : sTableFields = ""
        For i = 0 To wfvariables.recPrintouts.Count - 1
        	'if we replace the table fields we write all information back
       		If bReplaceTableFields = True Or wfvariables.recPrintouts.item(i).item("iLocked").value <> 1 Then 'a locked entry is an old one and was already printed, so we don't store these entry again
	            sTableFields = sTableFields & "<Row>"
	            sTableFields = sTableFields & "<Field internal_name='" & "sCreator" & "'>" & convertToValidXML(wfvariables.recPrintouts.Item(i).Item("sCreator").value) & "</Field>"
	            sTableFields = sTableFields & "<Field internal_name='" & "sResponsible" & "'>" & convertToValidXML(wfvariables.recPrintouts.Item(i).Item("sResponsible").value) & "</Field>"
	            sTableFields = sTableFields & "<Field internal_name='" & "dDate" & "'>" & convertToOSDate(wfvariables.recPrintouts.Item(i).Item("dCreatedOn").value) & "</Field>"     'CR - Support English / Multilanguage - CC-000240       
	            sTableFields = sTableFields & "<Field internal_name='" & "dReturnDate" & "'>" & convertToOSDate(wfvariables.recPrintouts.Item(i).Item("dDestroyedOn").value) & "</Field>" 'CR - Support English / Multilanguage - CC-000240
	            sTableFields = sTableFields & "<Field internal_name='" & "sReturned" & "'>" & convertToValidXML(wfvariables.recPrintouts.Item(i).Item("sDestroyed").value) & "</Field>"
	            sTableFields = sTableFields & "<Field internal_name='" & "sLocation" & "'>" & convertToValidXML(wfvariables.recPrintouts.Item(i).Item("sLocation").value) & "</Field>"
	            sTableFields = sTableFields & "<Field internal_name='" & "sComment" & "'>" & convertToValidXML(wfvariables.recPrintouts.Item(i).Item("sComment").value) & "</Field>"
	            sTableFields = sTableFields & "</Row>"
	        End If
        Next
        
        
        Dim sXML
        sXML = "" &_
        "<DMSData>" &_
        "<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
        "<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
        "<Object object_id='" & wfvariables.recStructure.iDocumentID.value & "'>" &_
        "<TableFields>" &_
        "<TableField internal_name='" & "rManagedCopies" & "'>" &_
        sTableFields &_
        "</TableField>" &_
        "</TableFields>" &_
        "</Object>" &_
        "</ObjectType>" &_
        "</Archive>" &_
        "</DMSData>"
        debug2file sXML
        Set dom = CreateObject("MSXML.DOMDocument") 
        
        dom.loadXML(sXML) 
        PrmIn.Value("Flags") = 0
        If bReplaceTableFields = True Then
        	PrmIn.Value("Options") ="CHECKREADONLY=0;REPLACETABLEFIELDS=1"
        Else
			PrmIn.Value("Options") ="CHECKREADONLY=0;REPLACETABLEFIELDS=0"        
        End If

        PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
        PrmIn.Value("XML")=dom 
        
        
        iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
        If iRet = 0 Then 
            debug2File vbTab & "updateDocumentPrintTable successful..."
        Else
            debug2File vbTab & "ERROR: updateDocumentPrintTable failed..."
        End If
    End Function
    
   
    '**********************************************************
    ' CreateWatermarks
    ' @description: validates if at least one printout is created
    ' @param: 	path (String) - the path of the source file
    '			pathout (String) - the path of the destination file
    '			iTableIndex (Integer) - the if of the file in the printout table of the workflow mask
    ' @return: pathout (String) - the path of the destination file
    '**********************************************************	
    Function CreateWatermarks (path , pathout, iTableIndex )

        pathout = pathout & iTableIndex & ".pdf"
        debug2file "CreateWatermarks<==" & path
        Dim sPosX, sPosy, sColor, sFont, sFontSize, sValue, sPage, sRotate
        Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")	
        oXmlDoc.load( wfvariables.recCommon.sConfigurationFile.Value) 
        debug2file "CreateWatermarks readxml" 
        Dim xpath : xpath = "//config/WorkflowType[@type='" & wfvariables.recCommon.sWorkflowModel.Value & "' ]/Watermarks/Watermark"
        Dim oWatermarks : Set oWatermarks = oXmlDoc.selectNodes( xpath )
        debug2file "CreateWatermarks " &	oWatermarks.length
        
        
        debug2file "CreateWatermarks Neevia.docConverter" 
        
        
        debug2file "CreateWatermarks Read Parameter " & oWatermarks.length
        For i=0 To oWatermarks.length-1
            Dim DC : Set DC = CreateObject("Neevia.docConverter")
            debug2file "CreateWatermarks Read Values" 		
            Dim sValueType
            Set oValues=oWatermarks(i).selectNodes("Value")
            For ipar=0 To oValues.length-1
                
                sValueType=oValues(ipar).GetAttribute("type")
                debug2file "CreateWatermarks " & sValueType & "=" & sValue
                sValue=oValues(ipar).text			
                'sValue=ReplaceArchivefields(sValue)
                sValue=ReplaceWorkflowfields(sValue, iTableIndex)
                sValue=ReplaceSpecialfields(sValue)			
                debug2file "CreateWatermarks " & sValueType & "=" & sValue
                DC.setParameter sValueType, sValue
                
            Next
            
            
            
            Dim sParameterType, sParameterValue
            Set oParameters=oWatermarks(i).selectNodes("Parameter")
            debug2file "CreateWatermarks  Parameter " & oParameters.length
            For ipar=0 To oParameters.length-1
                sParameterType=oParameters(ipar).GetAttribute("type")
                sParameterValue=oParameters(ipar).text
                debug2file "CreateWatermarks " & sParameterType & "=" & sParameterValue
                DC.setParameter sParameterType, sParameterValue
            Next
         
            Dim RVal : RVal =-1
            
            RVal=DC.stampPDF(path, pathout)	            
            path=pathout
            Set DC = Nothing	
            If RVal=0 Then
                debug2file "CreateWatermarks Done !!!"
                CreateWatermarks = 0
            Else
                debug2file "CreateWatermarks There was an error stamping the document !!!"
                CreateWatermarks = -1
            End If			
        
        Next
        If oWatermarks.length=0 Then
            Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
            FSO.CopyFile path , pathout
        End If
        
        debug2file "CreateWatermarks==>" & pathout
    End Function
    
    
    '**********************************************************
    ' ReplaceSpecialfields
    ' @description: substitutes placeholder for the createWatermark function
    ' @param: 	sValue (String)  - the value which should be replaced
    ' @return: the replaced value
    '**********************************************************		
    Function ReplaceSpecialfields(sValue)
        debug2file "ReplaceSpecialfields<==" & sValue
        sValue=ReplaceN(sValue , "#Date#", Date)
        sValue=ReplaceN(sValue , "#DateCAAG#", Date)
        sValue=ReplaceN(sValue , "#Now#", Now)
        sValue=ReplaceN(sValue , "#vbnewline#", vbNewLine)
        ReplaceSpecialfields=sValue
        debug2file "ReplaceSpecialfields==>" & sValue
    End Function
    
    Function ReplaceN(sString,sPattern,sValue)
        debug2file "ReplaceN<==" & sString & " " & sPattern & " " & sValue & " " 
        Dim ir
        
        For ir=0 To 10
            Dim sValueLocal
            'sValueLocal=sValue
            If InStr(sString, sPattern & "##")=0 Then Exit For
            Startindex=InStr(sString,sPattern & "##")+Len(sPattern & "##")
            Endindex=InStr(Startindex,sString,"#")
            'msgbox Startindex & " " & Endindex & " " & Endindex-Startindex
            sNumber=Mid(sString,Startindex,Endindex-Startindex)
            
            If IsNumeric(sValue) Then sValueLocal=CLng(sValue)+CLng(sNumber)
            If IsDate(sValue) Then sValueLocal=DateAdd("d" ,CLng(sNumber), sValue)
            'msgbox sPattern & "##" & sNumber & "#" & " " & sValue	
            
            
            If sPattern="#DateCAAG#" Then sValueLocal=formatDateCAAG(sValueLocal)
            
            
            sString=Replace(sString,sPattern & "##" & sNumber & "#" , sValueLocal)
        Next
        If sPattern="#DateCAAG#" Then sValue=formatDateCAAG(sValue)
        sString=Replace(sString,sPattern , sValue)
        ReplaceN=sString
        debug2file "ReplaceN==>" & sString
    End Function
    
    Function ReplaceArchivefields
        'tbd
    End Function
    
    '**********************************************************
    ' ReplaceWorkflowfields
    ' @description: substitutes placeholder for the createWatermark function with values from the workflow variables
    ' @param: 	sValue (String)  - the value which should be replace
    '			iTableIndex (Integer) - the index of the table, if a variable of the table should be used
    ' @return: the replaced value
    '**********************************************************		
    Function ReplaceWorkflowfields(sValue, iTableIndex)
        debug2file "ReplaceWorkflowfields<==" & sValue
        
        If sValue <> ""  Then
            Dim bFound : bFound = False
            If InStr(sValue, "#WF#") > 0 Then
                bFound = True
            End If
            Do While bFound = True
                If InStr(sValue, "#WF#") > 0 Then
                    nPos = InStr(sValue, "#WF#")
                    nPos = nPos +4 'the end of the #WF# tag -> the begin of the variable name
                    nNextPos = InStr(nPos,sValue,"#") 'the end of the variable name
                    sVariablename = Mid(sValue,nPos,nNextPos-nPos)
                    'check if the variable is the counter element. if this is the case increase the counter
                    If sVariablename = "iLogEntries" Then
                        wfvariables.iLogEntries.value = wfvariables.iLogEntries.value + 1
                    End If
                    debug2file "ReplaceWorkflowfields " & sVariablename & " ; " & wfvariables.Item(sVariablename).Value
                    sValue=ReplaceN(sValue, "#WF#" & sVariablename & "#" ,wfvariables.Item(sVariablename).Value)
                Else
                    bFound = False
                End If		
            Loop
            'Table Fields
            bFound = False
            If InStr(sValue, "#WF-Table#") > 0 Then
                bFound = True
            End If
            Do While bFound = True
                If InStr(sValue, "#WF-Table#") > 0 Then
                    nPos = InStr(sValue, "#WF-Table#")
                    nPos = nPos + 10 'the end of the #WF-Table# tag -> the begin of the variable name
                    nNextPos = InStr(nPos,sValue,"#") 'the end of the variable name
                    sVariablename = Mid(sValue,nPos,nNextPos-nPos)		
                    debug2file sVariablename
                    debug2file "ReplaceWorkflowfields " & sVariablename & " ; " & wfvariables.recPrintouts.Item(CLng(iTableIndex)).Item(sVariablename).value
                    sValue=ReplaceN(sValue, "#WF-Table#" & sVariablename & "#" ,wfvariables.recPrintouts.Item(CLng(iTableIndex)).Item(sVariablename).value)
                Else
                    bFound = False
                End If		
            Loop
            
        End If
        
        
        ReplaceWorkflowfields = sValue
        debug2file "ReplaceWorkflowfields==>" & sValue
    End Function
    
    '**********************************************************
    ' setHistoryEntry
    ' @description: creates an comment entry in the object history which indicates that an informal printout was created
    ' @param: nothing
    ' @return: nothing
    '**********************************************************		
    Function setHistoryEntry ()
        Dim RC 
        Set RC = RunningContext 
        Set PrmIn = RC.NewJobsParams 
        Set PrmOut = RC.NewJobsParams
        
        
        
        PrmIn.Value("Flags") = 0
        PrmIn.Value("sInfo") = "Ein informeller Ausdruck wurde erstellt."
        'PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("AUTHOR").Item(0).GetAttributeValueByName("UserId") 
        PrmIn.Value("JobUserGUID") = thisprocess.creator
        PrmIn.Value("dwObjectID")=wfvariables.recStructure.iDocumentID.Value
        PrmIn.Value("dwObjectType")=wfvariables.recStructure.iDocumentType.Value
        
        
        iRet = RC.Jobs.STD.SetHistory(PrmIn, PrmOut)
        
    End Function
    
    
    '**********************************************************
    ' FillLocationList
    ' @description: fills the location list
    ' @param: nothing
    ' @return: nothing
    '**********************************************************		
    '	Function FillLocationList ()
    
    'get the dropdownmenu
    '	    Set Maskfield = wfMaskfields.Item(0).CtrlPages.Item(0).Fields.Item(1).WFListColumns.Item(1) 
    '	    MySectionName = Maskfield.WFFieldValues.SectionName
    '	    Set MaskfieldList = Maskfield.WFFieldValues
    
    
    '	    nCounter = 0
    '	    For x = 0 To UBound(arrReviewer)
    'write a new entry to the dropdown menu
    '	        MyPropertyName = "Zeile" & nCounter
    '	        nCounter=nCounter+1
    '	        MyNewValue = arrReviewer(x)
    '	        MaskfieldList.WriteStringValue MySectionName, MyPropertyName,MyNewValue  
    
    '	    Next	
    '	End Function
    

    
    Public Function formatDateCAAG( xDate ) 
        debug2file "formatDateCAAG  ==>" & xDate
        If InStr(CStr(xDate),"-")>1 Then
            xDate=Replace(xDate,"Okt","Oct")
            xDate=Replace(xDate,"Dez","Dec")
            xDate=Replace(xDate,"Mrz","Mar")
            xDate=Replace(xDate,"Mai","May")
            formatDateCAAG=xDate
            Exit Function
        End If
        
        '	Dim sDay : sDay = DatePart("d", xDate)
        '	
        '	If Len(sDay) < 2 Then
        '		sDay = "0" & sDay
        '	End If
        '	Dim sMonth : sMonth = DatePart("m", xDate)
        '
        '	If Len(sMonth) < 2 Then
        '		sMonth = "0" & sMonth
        '	End If
        '	Dim sYear : sYear = DatePart("yyyy", xDate)
        '	formatDate = sDay & "." & sMonth & "." & sYear
        
        If InStr(CStr(xDate),".")>1 Then
            formatDateCAAG=xDate
            aDate=Split(xdate,".")
            sDay=aDate(0)
            sYear=aDate(2)
            Select Case aDate(1)
                Case "01"
                sMonth= "Jan"
                Case "02"
                sMonth= "Feb"
                Case "03"
                sMonth= "Mrz"
                Case "04" 
                sMonth="Apr"
                Case "05" 
                sMonth="Mai"
                Case "06"
                sMonth= "Jun"
                Case "07" 
                sMonth= "Jul"
                Case "08" 
                sMonth= "Aug"
                Case  "09"
                sMonth= "Sep"
                Case   "10"
                sMonth= "Okt"
                Case "11"
                sMonth= "Nov" 
                Case  "12"	
                sMonth= "Dez"
                Case Else 
                sMonth="Jan"
            End Select
            sMonth=Replace(sMonth,"Okt","Oct")
            sMonth=Replace(sMonth,"Dez","Dec")
            sMonth=Replace(sMonth,"Mrz","Mar")
            sMonth=Replace(sMonth,"Mai","May")
            formatDateCAAG = sDay & "-" & sMonth & "-" & sYear		
        End If
    End Function
End Class
'**************************************************************************************************
'End Class
'**************************************************************************************************

Function TestFunction
	
	Set oServer = CreateObject("OxSvrSpt.Server") 
	'create a session with an encrypted password
	Set createSession = oServer.Login(wfvariables.recSession.sTechUser.Value, wfvariables.recSession.sTechPwd.Value, wfvariables.recSession.sOSCom.Value, wfvariables.recSession.iOSPort.Value, 1)
	Set oJob = createSession.NewJob("DMS.GetObjectDetails")
	oJob.InputParameters.AddNewIntegerParameter "ObjectID", ObjectID
	oJob.InputParameters.AddNewIntegerParameter "ObjectType", ObjectType
	oJob.InputParameters.AddNewIntegerParameter "Flags", 16
	oJob.InputParameters.AddNewStringParameter "SystemFields" ,SystemFields
	
	iRet = oJob.Execute
	If iRet = 0 Then
		sfile = oJob.OutputFileParameters.Item(1).FileName	
		Set getObjectDetails = sfile
	Else
		Set getObjectDetails = -1
	End If
End Function

'**********************************************************
' createHistoryDocument
' @description: creates a history document below the version register
' @param: nothing
' @return: nothing
'**********************************************************
Function createHistoryDocument

	debug2File "start createHistoryDocument"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	sXML = "" &_
	"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sVersionHistoryInternalName.Value & "' type='DOCUMENT'>" &_
				"<Object folder_id='" & CLng(wfvariables.recStructure.iFolderID.Value) & "' register_id='" & CLng(wfvariables.recStructure.iRegisterID.Value) & "'>" &_
					"<Fields>" &_
						"<Field internal_name='" & getInternalName_VersionHistory_DocumentNumber & "'>" & convertToValidXML(wfvariables.sDocumentNumber.Value) & "</Field>" &_
						"<Field internal_name='" & getInternalName_VersionHistory_DocumentVersion & "'>" & convertToValidXML(wfvariables.sVersion.Value) & "</Field>" &_
					"</Fields>" &_
				"</Object>" &_
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSData>"

	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("XML") = dom 
	PrmIn.Value("$Job$Files$" )  = getHistoryDocumentTemplate
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	
	iRet = RC.Jobs.DMS.XMLInsert(PrmIn, PrmOut)
	If iRet = 0 Then
		debug2File vbTab & "createHistoryDocument XmlInsert successfull..."
		VersionHistoryObjectID = PrmOut.Value("ObjectID")
		VersionHistoryObjectType = PrmOut.Value("ObjectType")
	
		syncedFile = SynchronizeData (VersionHistoryObjectID, VersionHistoryObjectType)
		
		'now replace (XmlUpdate) the document with the synced one	
		sXML = "" &_
		"<DMSData>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
				"<ObjectType internal_name='" & wfvariables.recStructure.sVersionHistoryInternalName.Value & "' type='DOCUMENT'>" &_
					"<Object object_id='" & VersionHistoryObjectID & "'>" &_
					"</Object>" &_
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSData>"
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		
		dom.loadXML(sXML) 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") = "CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		PrmIn.Value("$Job$Files$")  = syncedFile
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		If iRet = 0 Then 
			debug2File vbTab & "createHistoryDocument XmlUpdate successful..."
		Else
			debug2File vbTab & "ERROR: createHistoryDocument XmlUpdate failed..."
		End If
		
		'now delete the syncedFile
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		If oFSO.FileExists (syncedFile) = True Then 'delete the xmlFile
			oFSO.DeleteFile syncedFile
		End If		
	Else
		debug2File vbTab & "ERROR: createHistoryDocument XmlInsert failed..."
	End If
	debug2File "end createHistoryDocument"

End Function

'**********************************************************
' getHistoryDocumentTemplate
' @description: gets the template for the document history
' @param: nothing
' @return: the filename of the template for the history document
'**********************************************************
Function getHistoryDocumentTemplate
	debug2File "start getHistoryDocumentTemplate"
	Dim RC 
	Set RC = RunningContext 

	sVersionHistoryTemplate = wfvariables.recCommon.sScriptPath.Value & "docs\versionhistory.docx"

	Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
	Dim sNewFile
	'copy the template	
	sNewFile = oFSO.GetParentFolderName(sVersionHistoryTemplate) & Replace( thisprocess.ProcessName, "/", "") & ".docx"


	oFSO.CopyFile sVersionHistoryTemplate, sNewFile
	
	'return the new file
	getHistoryDocumentTemplate = sNewFile
	debug2File vbTab & "getHistoryDocumentTemplate: " & getHistoryDocumentTemplate
	debug2File "start getHistoryDocumentTemplate"
End Function

'**********************************************************
' deleteAttachments
' @description: deletes all attachments with the column "sDeleted" = "Ja / Yes"
' @param: nothing
' @return: nothing
'**********************************************************
Function deleteAttachments
	Dim sToDelete : sToDelete = ""
	Dim i
	For i=0 To wfvariables.recAttachments.Count - 1 
		If wfvariables.recAttachments.Item(i).Item("sDeleted").Value = "Ja / Yes" Then
			iObjectID = CLng( wfvariables.recAttachments.Item(i).Item("sObjectID").Value )
			'deleteDocument iObjectID, wfvariables.recStructure.sAttachmentInternalName.Value
			deleteObjectInWFFile iObjectID, wfvariables.recStructure.sAttachmentInternalName.Value
			If CInt( wfvariables.recAttachments.Item(i).Item("bPersisted").Value ) = 0 Then
				If sToDelete <> "" Then
					sToDelete = sToDelete & "|"
				End If
				sToDelete = sToDelete & wfvariables.recAttachments.Item(i).ListItemId
			Else
				wfvariables.recAttachments.Item(i).Item("sObjectId").Value = 0
			End If
		End If
	Next
	If sToDelete <> "" Then
		Dim aToDelete : aToDelete = Split( sToDelete, "|" )
		For i=0 To UBound( aToDelete )
			wfvariables.recAttachments.RemoveListItem aToDelete( i )
		Next
	End If
End Function

'**********************************************************
' sendMail 
' @description: send an email
' @param: sMailReceiver	- the email of the receiver
' @param: sMailSender - the email of the sender
' @param: sMailSubject - the subject
' @param: sMailBody the body
' @param: sAttachments - filepath to attachment
' @return: nothing
'**********************************************************
Function sendMail (sMailReceiver, sMailSender, sMailSubject, sMailBody, sAttachments)
debug2File "start sendMail"
	Dim RC : Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	PrmIn.Clear()
	PrmIn.Value("Flags") = 0
	PrmIn.Value("Receiver") = sMailReceiver
	PrmIn.Value("Sender") = sMailSender
	PrmIn.Value("Subject") = sMailSubject
	PrmIn.Value("Text") = sMailBody
	PrmIn.Value("Attachments") = sAttachments
	
	iRet = RC.Jobs.KRN.SendMail(PrmIn, PrmOut)
	If iRet = 0 Then
		debug2File vbTab & "sendMail successfull..."
	Else
		debug2File vbTab & "sendMail failed..."
	End If
debug2File "end sendMail"
End Function


'**********************************************************
' getAttachmentsBelowVersionRegister 
' @description: reads all attachments below the version register and initialize the workflow attachment record
' @param: registerID (Integer) - the object id of the version register
' @return: a list of all objectIds separated by '#'
'**********************************************************
Function getAttachmentsBelowVersionRegister (registerID)
debug2File "start getAttachmentsBelowVersionRegister (" & registerID & ")"
	getAttachmentsBelowVersionRegister = "-1"
	
	If (wfvariables.recStructure.sAttachmentInternalName.Value <> "") Then
	
		Dim RC : Set RC = RunningContext
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
	
		Dim sXML
		sXML = "" &_
		"<DMSQuery request_type='HOL'>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
				"<ObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
					"<Fields field_schema='MIN'/>" &_
					"<ChildObjects>" &_
						"<ChildObjectType internal_name='" & wfvariables.recStructure.sAttachmentInternalName.Value & "' type='DOCUMENT'>" &_
							"<Fields field_schema='MAX'/>" &_				
						"</ChildObjectType>" &_			
					"</ChildObjects>" &_								
					"<Conditions>" &_
						"<ObjectID>" & registerID & "</ObjectID>" &_
					"</Conditions>" &_					
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSQuery>"
	
		Set dom = CreateObject("MSXML.DOMDocument") 
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 16
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML") = dom 
		
		iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
		debug2File "iRet = " & iRet
		
		If iRet = 0 Then
			
			sfile = PrmOut.Value("$Job$Files$")
			debug2File "sfile = " & sfile
			sfile = Mid(sfile,2,Len(sfile)-2)
			Dim oNodes
			Dim oNodeField
			Dim sObjectIds
			Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
			'debug2File "Load sfile = " & sfile
			If oXmlDoc.load(sfile) = True Then 
				'debug2File oXmlDoc.xml
				Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/ChildObjects/ObjectType/ObjectList/Object"
				Set oNodes = oXmlDoc.selectNodes(xpath)
				'debug2File "oNodes.length = " & oNodes.length
				For y = 0 To oNodes.length - 1
					If sObjectIds <> "" then
						sObjectIds = sObjectIds & "#" 
					End If
					sObjectIds = sObjectIds & oNodes.item(y).attributes.getNamedItem("id").text
				Next
			End If
			
			getAttachmentsBelowVersionRegister = sObjectIds
			
			Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
			
			If oFSO.FileExists (sfile) = True Then 'delete the file
				oFSO.DeleteFile sfile
			End If
			
			'clean up
			Set oXmlDoc = Nothing
			Set oFSO = Nothing
		Else
			debug2file	"getAttachmentsBelowVersionRegister failed"
		End If
	End if
debug2File "end getAttachmentsBelowVersionRegister"	
End Function


'**********************************************************
' ReplaceDocument
' @description: replaces a document and deletes the source file (sDocumentFilePath)
' @param: ObjectID (Integer) - objectID of the object which should be replaced
'		  sDocumentFilePath (String) - the new document
' @return: 
'**********************************************************
Function ReplaceDocument(objectID, sDocumentFilePath)
	debug2File "start ReplaceDocument (" & objectID & "," & sDocumentFilePath & ")"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXML
	sXML = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
	"<Object object_id='" & objectID & "'>" &_
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	
	dom.loadXML(sXML) 
	PrmIn.Value("Flags") = 0
	PrmIn.Value("Options") ="CHECKREADONLY=0"
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	PrmIn.Value("$Job$Files$")  = sDocumentFilePath
	
	iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
	If iRet = 0 Then 
		debug2File vbTab & "ReplaceDocument successful..."
	Else
		debug2File vbTab & "ERROR: ReplaceDocument failed..."
	End If
	
	Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists (sDocumentFilePath) = True Then 'delete the xmlFile
		debug2File "Synced File: " & sDocumentFilePath
		oFSO.DeleteFile sDocumentFilePath
	End If
	
	Set oxmlDoc = Nothing
	debug2File "end ReplaceDocument (" & objectID & "," & sDocumentFilePath & ")"
End Function


'**********************************************************
' checkRevisionForLinkedDocuments
' @description: checks for each linked document if the revision value is "ja / yes" and starts the Check Revision Workflow if this is the case
' @param: none
' @return: nothing
'**********************************************************
Function checkRevisionForLinkedDocuments()
debug2File "start checkRevisionForLinkedDocuments"
	For v = 0 To wfvariables.recLinkedDocuments.Count - 1 

		linkedDocumentNumber = wfvariables.recLinkedDocuments.Item(v).Item("sLinkNumber").Value
		linkDocument = wfvariables.recLinkedDocuments.Item(v).Item("sLinkRevision").Value
		linkedDocumentID = ""
		
		debug2File vbTab & "Check document number: " & linkedDocumentNumber
		
		If linkDocument = "ja / yes" Then
			'1) Step 1: get the current valid document with the linked document number
			linkedDocumentID = getValidDocumentObjectID (linkedDocumentNumber)
			linkedDocumentType = wfvariables.recStructure.iDocumentType.Value
			startCheckRevisionForLinkedDocumentsWorkflow "StandardWF;;;LinkedRevision;;;Ein Dokument, dass auf dieses Dokument verweist wurde revisioniert. Daher soll berprft werden, ob dieses Dokument ebenfalls revisioniert werden soll.", linkedDocumentID, linkedDocumentType 'Der String wird ;;;-getrennt fr getMessageText verwendet -> MultiLanguageSupport
		End If

	Next
debug2File "end checkRevisionForLinkedDocuments"	
End Function


'**********************************************************
' getValidDocumentObjectID
' @description: gets the object id of a document with the status "valid" from a given document number
' @param: DocumentNumber (string) - the number of a document
' @return: objectID
'**********************************************************
Function getValidDocumentObjectID (DocumentNumber)
debug2File "start getValidDocumentObjectID (" & DocumentNumber & ")"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
				"<Fields field_schema='MIN'/>" &_
				"<Conditions>" &_
					"<ConditionObject internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
						"<FieldCondition internal_name='" & getInternalName_Document_DocumentNumber & "' operator='='>" &_
							"<Value>" & DocumentNumber & "</Value>" &_
						"</FieldCondition>" &_
						"<FieldCondition internal_name='" & getInternalName_Document_DocumentStatus & "' operator='='>" &_
							"<Value>" & "1" & "</Value>" &_
						"</FieldCondition>" &_
					"</ConditionObject>" &_		
				"</Conditions>" &_					
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"
	
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	debug2File sXML
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("Variants") = 1
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")  'wforganisation.GetOrgObjectsByName("osservice").Item(0).Id
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		debug2File "Filename: " & sfile
		
		Dim oNode
		Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oXmlDoc.load(sfile) = True Then 

			
			'Dim oFSO2 : Set oFSO2 = CreateObject("Scripting.FileSystemObject")
			'Dim sNewFile 'copy the file, cause the file will be deleted if the job ends
			'sNewFile = sfile & ".tmp." & oFSO2.GetExtensionName(sfile) 'the file should be deleted by the calling function
			'oFSO2.CopyFile sfile, sNewFile			
			
			Dim xpath
			xpath = "/DMSContent/Archive/ObjectType/ObjectList/Object"
			Set oNode = oXmlDoc.selectSingleNode (xpath)
			If Not oNode Is Nothing Then
				debug2File "Objekt ID des verbundenen Dokuments: " & oNode.attributes.getNamedItem("id").text
				objectID = oNode.attributes.getNamedItem("id").text
				getValidDocumentObjectID = objectID
			End If
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oXmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"ERROR: getValidDocumentObjectID GetResultList failed..."
	End If
debug2File "end getValidDocumentObjectID (" & DocumentNumber & ")"
End Function

'**********************************************************
' SynchronizeData
' @description: runs the synchronizeData job - the return file should be deleted by the calling function
' @param: ObjectID (Integer) - objectID of the object which should be replaced
'		  ObjectType (Integer) - objecttyoe of the object
' @return: sDocumentFilePath (String) - the new document
'**********************************************************
Function SynchronizeData (objectID, objectType)
debug2File "start SynchronizeData (" & objectID & "," & objectType & ")"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	PrmIn.Value("Flags") = 0
	PrmIn.Value("ObjectType") = objectType
	PrmIn.Value("ObjectID") = objectID
'	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("$$$SwitchContextUserGUID$$$")=	wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") ' Wirft im Gegensatz zur JobUserGUID keine Fehler zu SERVER_ROOT_3

	iRet = RC.Jobs.DTR.SynchronizeData(PrmIn, PrmOut)
	
	If iRet = 0 Then
		debug2File vbTab & "SynchronizeData successfull..."
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		Dim sNewFile 'copy the file, cause the file will be deleted if the job ends
		sNewFile = sfile & ".tmp." & oFSO.GetExtensionName(sfile) 'the file should be deleted by the calling function
		oFSO.CopyFile sfile, sNewFile
		debug2File "Synchronized file: " & sNewFile
		SynchronizeData = sNewFile
		
		'clean up
		Set oFSO = Nothing
	Else
		debug2File vbTab & "ERROR: SynchronizeData failed..."
	End If
debug2File "end SynchronizeData (" & objectID & "," & objectType & ")"	
End Function



'**********************************************************
' readConfiguration
' @description
' @param: internalName - internalName or an empty string for no internalName
' @return: -1 if no workflowType is found for the param 'ObjectType', otherwise the funtion returns 0
'**********************************************************
Function readConfiguration (internalName)
	debug2file "start - readConfiguration internalName(" & internalName & ")"
	
	readConfiguration = 0
	
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	debug2File "Versuche das ConfigurationFile zu laden: " & wfvariables.recCommon.sConfigurationFile.Value
	
	If True = oXmlDoc.load( wfvariables.recCommon.sConfigurationFile.Value ) Then
		debug2file "Geladenes ConfigurationFile: " & wfvariables.recCommon.sConfigurationFile.Value
		
		Dim xpath
		Dim oNode
		Dim oNodes
		Dim xpathDocumentType
		
		wfvariables.recConfigStructureFields.ClearList	'remove all items of the list of internal archive fields
		
		'read the data about the technical user
		xpath = "config/TechnicalUser/Username"
		debug2File "Reading the name of the technical user..."
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then			
			wfvariables.recSession.sTechUser.Value = oNode.text
			debug2File "Technical user: " & wfvariables.recSession.sTechUser.Value
		Else
			throwError "Failed to read the username of the technical user"
		End If

		xpath = "config/TechnicalUser/Password"
		debug2File "Reading the password of the technical user..."
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then			
			wfvariables.recSession.sTechPwd.Value = oNode.text
			debug2File "Technical password: " & wfvariables.recSession.sTechPwd.Value
		Else
			throwError "Failed to read the password of the technical user"			
		End If
		
		
		'read Systemattributes		
		xpath = "config/SystemAttributesType/Folder"
		debug2File "Reading SystemAttributes"
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then			
			'read SystemAttribute Folder ObjectId (this folder stores information about the next available document number)
			wfvariables.recStructure.iSystemAttributesID.Value = oNode.attributes.getNamedItem("objectID").text
			debug2File "SystemAttributes Folder Object Id: " & wfvariables.recStructure.iSystemAttributesID.Value
			wfvariables.recStructure.sSystemAttributesInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File "SystemAttributes Internal Name: " & wfvariables.recStructure.sSystemAttributesInternalName.Value
		Else
			throwError "Failed to read the SystemAttributesFolder"
		End If
		
		'read SystemAttribute Fields
		xpath = "config/SystemAttributesType/Folder/Fields/Field"
		fillStructureFields oXmlDoc, xpath, "SystemAttributes"
		
		
		'read TemplatesType
		'Templates Folder
		xpath = "config/TemplatesType/Folder"
		debug2File "Reading TemplatesFolder"
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then			
			wfvariables.recStructure.sTemplatesFolderInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File "Templates Folder Internal Name: " & wfvariables.recStructure.sTemplatesFolderInternalName.Value
		Else
			throwError "Failed to read the TemplatesFolder"
		End If
		
		'read Templates Folder Fields
		xpath = "config/TemplatesType/Folder/Fields/Field"
		fillStructureFields oXmlDoc, xpath, "TemplatesFolder"
		
		'Templates Register
		xpath = "config/TemplatesType/Register"
		debug2File "Reading TemplatesRegister"
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then			
			wfvariables.recStructure.sTemplatesRegisterInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File "Templates Register Internal Name: " & wfvariables.recStructure.sTemplatesRegisterInternalName.Value
		Else
			throwError "Failed to read the TemplatesRegister"
		End If
		
		'read Templates Register Fields
		xpath = "config/TemplatesType/Register/Fields/Field"
		fillStructureFields oXmlDoc, xpath, "TemplatesRegister"
		
		'Templates Document
		xpath = "config/TemplatesType/Document"
		debug2File "Reading TemplatesDocument"
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then			
			wfvariables.recStructure.sTemplatesDocumentInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File "Templates Document Internal Name: " & wfvariables.recStructure.sTemplatesDocumentInternalName.Value
		Else
			throwError "Failed to read the TemplatesDocument"
		End If
		
		'read Templates Document Fields
		xpath = "config/TemplatesType/Document/Fields/Field"
		fillStructureFields oXmlDoc, xpath, "TemplatesDocument"
		
		'DocumentType
		If internalName = "" Then 'lookup for a DocumentType with an empty internalName attribute
			xpathDocumentType = "config/DocumentType[not(@type)]" 
		Else
			xpathDocumentType = "config/DocumentType[@internal_name='" & internalName & "']"
			debug2File xpathDocumentType
			debug2File "Reading document type"
			Set oNode = oXmlDoc.selectSingleNode(xpathDocumentType)
			If Not oNode Is Nothing Then
				debug2File "DocumentType Internal Name: " & oNode.attributes.getNamedItem("internal_name").text
			Else
				throwError "Failed to read the document type"
				readConfiguration = -1 'no workflowType was found for the given internalName - so stop reading the configuration and throw an error
				Exit Function
			End If			
		End If
		
		
		'Folder object type
		xpath = xpathDocumentType & "/Folder"
		debug2File "Reading folder type"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sFolderInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the folder: " & wfvariables.recStructure.sFolderInternalName.Value
		Else
			debug2File vbTab & "no folder type found"
		End If
		'FolderFields
		xpath = xpathDocumentType & "/Folder/Fields/Field"
		debug2File "Reading folder fields"
		fillStructureFields oXmlDoc, xpath, "Folder"
		
		'History table - in fact it's an table control at the folder, but to keep it simple we handle it in the configuration file like an OS-Object
		'Folder object type
		xpath = xpathDocumentType & "/HistoryTable"
		debug2File "Reading history table"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sHistoryTableInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the history table: " & wfvariables.recStructure.sHistoryTableInternalName.Value
		Else
			debug2File vbTab & "no history table found"
		End If
		'FolderFields
		xpath = xpathDocumentType & "/HistoryTable/Fields/Field" 'Table fields
		debug2File "Reading history table fields"
		fillStructureFields oXmlDoc, xpath, "HistoryTable"				
		
		
		'Register object type
		xpath = xpathDocumentType & "/Register"
		debug2File "Reading register type"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sRegisterInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the register: " & wfvariables.recStructure.sRegisterInternalName.Value
		Else
			debug2File vbTab & "no register type found"
		End If		
		'RegisterFields
		xpath = xpathDocumentType & "/Register/Fields/Field" 
		debug2File "Reading register fields"
		fillStructureFields oXmlDoc, xpath, "Register"
		
		'ProtocolRegister object type
		xpath = xpathDocumentType & "/ProtocolRegister"
		debug2File "Reading protocol register type"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sProtocolRegisterInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the protocol register: " & wfvariables.recStructure.sProtocolRegisterInternalName.Value
		Else
			debug2File vbTab & "no protocol register type found"
		End If		
		'RegisterFields
		xpath = xpathDocumentType & "/ProtocolRegister/Fields/Field" 
		debug2File "Reading protocol register fields"
		fillStructureFields oXmlDoc, xpath, "ProtocolRegister"
		
		'ProtocolDocument object type
		xpath = xpathDocumentType & "/ProtocolDocument"
		debug2File "Reading protocol document type"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sProtocolDocumentInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the protocol document: " & wfvariables.recStructure.sProtocolDocumentInternalName.Value
		Else
			debug2File vbTab & "no protocol document type found"
		End If		
		'RegisterFields
		xpath = xpathDocumentType & "/ProtocolDocument/Fields/Field" 
		debug2File "Reading protocol document fields"
		fillStructureFields oXmlDoc, xpath, "ProtocolDocument"		
		
		
		'Document object type
		xpath = xpathDocumentType & "/Document"
		debug2File "Reading document type"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sDocumentInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the document: " & wfvariables.recStructure.sDocumentInternalName.Value
			'wfvariables.recStructure.iDocumentType.Value = oNode.attributes.getNamedItem("objectType").text
			'debug2File vbTab & "Object Type of the document: " & wfvariables.recStructure.iDocumentType.Value 
		Else
			debug2File vbTab & "no document type found"
		End If	
		'DocumentFields
		'xpath = "config/DocumentType/Document/Fields/Field" 
		xpath = xpathDocumentType & "/Document/Fields/Field" 
		debug2File "Reading document fields"
		fillStructureFields oXmlDoc, xpath, "Document"
		
		'Linked document table - in fact it's an table control at the document, but to keep it simple we handle it in the configuration file like an OS-Object
		xpath = xpathDocumentType & "/LinkedDocumentsTable"
		debug2File "Reading LinkedDocuments table"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sLinkedDocumentsInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the LinkedDocuments table: " & wfvariables.recStructure.sLinkedDocumentsInternalName.Value
		Else
			debug2File vbTab & "no LinkedDocuments table found"
		End If
		'LinkedTableFields
		xpath = xpathDocumentType & "/LinkedDocumentsTable/Fields/Field" 'Table fields
		debug2File "Reading LinkedDocuments table fields"
		fillStructureFields oXmlDoc, xpath, "LinkedDocumentsTable"			
		
		'Participants table - in fact it's a table control at the document, but to keep it simple we handle it in the configuration file like an OS-Object
		xpath = xpathDocumentType & "/ParticipantsTable"
		debug2File "Reading participants table"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sParticipantsInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the Participants table: " & wfvariables.recStructure.sParticipantsInternalName.Value
		Else
			debug2File vbTab & "no attachments found"
		End If
		'ParticipantsTableFields
		xpath = xpathDocumentType & "/ParticipantsTable/Fields/Field" 'Table fields
		debug2File "Reading Participantstable table fields"
		fillStructureFields oXmlDoc, xpath, "ParticipantsTable"			
		

		'Training Responsibles table - in fact it's a table control at the document, but to keep it simple we handle it in the configuration file like an OS-Object
		xpath = xpathDocumentType & "/ResponsibleDocumentsTable"
		debug2File "Reading participants table"
'		Set oNode = oXmlDoc.selectSingleNode (xpath)
'		If Not oNode Is Nothing Then
'			wfvariables.recStructure.sParticipantsInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
'			debug2File vbTab & "Internal name of the Participants table: " & wfvariables.recStructure.sParticipantsInternalName.Value
'		Else
'			debug2File vbTab & "no attachments found"
'		End If
		'ParticipantsTableFields
		xpath = xpathDocumentType & "/ResponsibleDocumentsTable/Fields/Field" 'Table fields
		debug2File "Reading Participantstable table fields"
		fillStructureFields oXmlDoc, xpath, "ResponsibleDocumentsTable"	

		'Versionhistory document
		xpath = xpathDocumentType & "/VersionHistory"
		debug2File "Reading version history document"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sVersionHistoryInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the VersionHistory: " & wfvariables.recStructure.sVersionHistoryInternalName.Value
		Else
			debug2File vbTab & "no attachments found"
		End If
		'Versionhistory fields
		xpath = xpathDocumentType & "/VersionHistory/Fields/Field" 'fields
		debug2File "Reading version history fields"
		fillStructureFields oXmlDoc, xpath, "VersionHistory"	

		
		'Attachment document
		xpath = xpathDocumentType & "/Attachment"
		debug2File "Reading attachment document"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sAttachmentInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the Attachment: " & wfvariables.recStructure.sAttachmentInternalName.Value
		Else
			debug2File vbTab & "no attachments found"
		End If
		'AttachmentFields
		xpath = xpathDocumentType & "/Attachment/Fields/Field" 'fields
		debug2File "Reading attachment fields"
		fillStructureFields oXmlDoc, xpath, "Attachment"	
		
		'Attachments table - in fact it's a table control at the document, but to keep it simple we handle it in the configuration file like an OS-Object
		xpath = xpathDocumentType & "/AttachmentsTable"
		debug2File "Reading attachments table"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sAttachmentsTableInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the attachments table: " & wfvariables.recStructure.sAttachmentsTableInternalName.Value
		Else
			debug2File vbTab & "no attachments table found"
		End If
		'AttachmentsTableFields
		xpath = xpathDocumentType & "/AttachmentsTable/Fields/Field" 'Table fields
		debug2File "Reading attachments table fields"
		fillStructureFields oXmlDoc, xpath, "AttachmentsTable"			
		
		
		'DistributionRegister
		xpath = xpathDocumentType & "/DistributionRegister"
		debug2File "Reading DistributionRegister"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sDistributionRegisterInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the DistributionRegister: " & wfvariables.recStructure.sDistributionRegisterInternalName.Value
		Else
			debug2File vbTab & "no DistributionRegister found"
		End If
		'DistributionRegister Fields
		xpath = xpathDocumentType & "/DistributionRegister/Fields/Field" 'Table fields
		debug2File "Reading DistributionRegister fields"
		fillStructureFields oXmlDoc, xpath, "DistributionRegister"	
		
		'DistributionRegisterResponsibleTable
		xpath = xpathDocumentType & "/DistributionResponsibleTable"
		debug2File "Reading DistributionResponsibleTable"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			wfvariables.recStructure.sDistributionObjectResponsibleTableInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the DistributionResponsibleTable: " & wfvariables.recStructure.sDistributionObjectResponsibleTableInternalName.Value
		Else
			debug2File vbTab & "no DistributionResponsibleTable found"
		End If
		'DistributionResponsibleTable Fields
		xpath = xpathDocumentType & "/DistributionResponsibleTable/Fields/Field" 'Table fields
		debug2File "Reading DistributionResponsibleTable fields"
		fillStructureFields oXmlDoc, xpath, "DistributionResponsibleTable"	
		
		'DistributionParticipantsTable
		xpath = xpathDocumentType & "/DistributionRecipientsTable"
		debug2File "Reading DistributionRecipientsTable"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then 
			wfvariables.recStructure.sDistributionObjectRecipientsTableInternalName.Value = oNode.attributes.getNamedItem("internal_name").text
			debug2File vbTab & "Internal name of the DistributionRecipientsTable: " & wfvariables.recStructure.sDistributionObjectRecipientsTableInternalName.Value
		Else
			debug2File vbTab & "no DistributionRecipientsTable found"
		End If
		'DistributionParticipantsTable Fields
		xpath = xpathDocumentType & "/DistributionRecipientsTable/Fields/Field" 'Table fields
		debug2File "Reading DistributionRecipientsTable fields"
		fillStructureFields oXmlDoc, xpath, "DistributionRecipientsTable"	
		
		'WorkflowType
		xpath = xpathDocumentType & "/WorkflowType"
		debug2File "Reading WorkflowType for the given ObjectType"
		Set oNode = oXmlDoc.selectSingleNode (xpath)
		If Not oNode Is Nothing Then
			debug2File "WorkflowType: " & oNode.attributes.getNamedItem("type").text
			wfvariables.recCommon.sWorkflowModel.Value = oNode.attributes.getNamedItem("type").text 'save the workflowType for future use/information
			
			xpath = "config/WorkflowType[@type='" & wfvariables.recCommon.sWorkflowModel.Value &"']"
			debug2File "Reading workflowType configuration"
			Set oNode = oXmlDoc.selectSingleNode(xpath)
			If Not oNode Is Nothing Then
				debug2File "WorkflowType: " & oNode.attributes.getNamedItem("type").text
			Else
				throwError "Failed to read the workflowType configuration"
			End If
			'Read StartActivity
			xpath = "config/WorkflowType[@type='" & wfvariables.recCommon.sWorkflowModel.Value &"']/StartActivity"
			debug2File "Reading start activity"
			Set oNode = oXmlDoc.selectSingleNode(xpath)
			If Not oNode Is Nothing Then
				debug2File "StartActivity name: " & oNode.attributes.getNamedItem("Name").text
				wfvariables.sNextActivity.Value = oNode.attributes.getNamedItem("Name").text
			Else
				throwError "Failed to read the start activity"
			End If
			
		Else
			throwError "Failed to read a workflow configuration for the ObjectType"
		End If
		
		
		'WorkflowFeatures
		xpath = "config/WorkflowType[@type='" & wfvariables.recCommon.sWorkflowModel.Value &"']/WorkflowFeatures/Feature"
		debug2File "Reading workflow features"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If Not oNodes Is Nothing Then
			wfvariables.recConfigWorkflowFeatures.ClearList
			For i = 0 To oNodes.length - 1
				Dim currentFeature : currentFeature = oNodes(i).attributes.getNamedItem("Name").text
				Dim FeatureEvent : FeatureEvent = oNodes(i).attributes.getNamedItem("Event").text
				Dim FeatureConditionVariable : FeatureConditionVariable = ""
				Dim FeatureConditionValue : FeatureConditionValue = ""
				
				debug2File vbTab & vbTab & "Feature name: " & currentFeature
				debug2File vbTab & vbTab & "Feature event: " & FeatureEvent
				
				
				'add feature to internal structure
				Set oEntry = wfvariables.recConfigWorkflowFeatures.CreateListItem
				oEntry.Item("sName").Value = currentFeature
				oEntry.Item("sEvent").Value = FeatureEvent
				
				xpath = "config/WorkflowType[@type='" & wfvariables.recCommon.sWorkflowModel.Value &"']/WorkflowFeatures/Feature[@Name='" & currentFeature & "']/Condition"
				Dim oCondition				
				Set oCondition = oXmlDoc.selectSingleNode(xpath)
				If Not oCondition Is Nothing Then
					debug2File vbTab & vbTab & "Condition: " & oCondition.text
					If Trim( oCondition.text ) <> "" Then
						oEntry.Item("sCondition").Value = oCondition.text
					End If
				End If
				
									
				wfvariables.recConfigWorkflowFeatures.AddListItem oEntry								
			Next			
		Else
			throwError "Failed to read workflow features"
		End If
		
		
	Else
		throwError "Failed to read the configuration file: " & oXmlDoc.parseError.reason
	End If
	debug2File "end - readConfiguration"		
End Function


'**********************************************************
' fillStructureFields
' @description: fill the internal record with structure fields
' @param: oXmlDoc (initialized MSXML object), xpath (string), sArchiveObject (string) - e.g. "TemplatesFolder"
' @return nothing
'**********************************************************
Function fillStructureFields (oXmlDoc, xpath, sArchiveObject)
	
	debug2File vbTab & "Reading " & sArchiveObject & " fields"
	Set oNodes = oXmlDoc.selectNodes(xpath)
	If Not oNodes Is Nothing Then
		For i = 0 To oNodes.length - 1
			debug2File vbTab & vbTab & sArchiveObject & " Field Internal Name: " & oNodes(i).attributes.getNamedItem("internal_name").text
			debug2File vbTab & vbTab & sArchiveObject & " Field Variable Name: " & oNodes(i).attributes.getNamedItem("variablename").text
			debug2File vbTab & vbTab & sArchiveObject & " Field MapToArchive Value: " & oNodes(i).attributes.getNamedItem("mapToArchive").text
			debug2File vbTab & vbTab & sArchiveObject & " Field Value: " & oNodes(i).text
			Set oEntry = wfvariables.recConfigStructureFields.CreateListItem
			oEntry.Item("sArchiveObject").Value = sArchiveObject
			oEntry.Item("sInternalName").Value = oNodes(i).attributes.getNamedItem("internal_name").text
			oEntry.Item("sVariableName").Value = oNodes(i).attributes.getNamedItem("variablename").text
			oEntry.Item("iMapToArchive").Value = oNodes(i).attributes.getNamedItem("mapToArchive").text				
			wfvariables.recConfigStructureFields.AddListItem oEntry		
		Next
	Else
		throwError "Failed to read " & sArchiveObject & " fields"			
	End If
	
End Function

'**********************************************************
' initFromArchive
' @description: initalizes workflow variables from corresponding archive fields (configuration file, attribute mapToArchive)
' @param: objectID (Integer) - the object with which the workflow variables should be initialized
' @return nothing
'**********************************************************
Function initFromArchive (objectID)
	debug2File "start initFromArchive (" & objectID & ")"
	Dim xmlFile
	xmlFile = getObjectDetails(objectID,"","")
	
	'MapToArchive = 0 - kein Datenaustausch
	'MapToArchive = 1 - init und zurckschreiben
	'MapToArchive = 2 - init
	'MapToArchive = 3 - zurckschreiben
	
	Dim oNode, oNodesRows, oNodesValues
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	If True = oXmlDoc.load(xmlFile) Then
	
		For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for document fields
			If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "Document" Then
				recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
				If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 2) Then
					'check if there is a corresponding field in the xmlFile
					xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/Fields/Field[@internal_name='" & recInternalName & "']"
					Set oNode = oXmlDoc.selectSingleNode (xpath)
					If Not oNode Is Nothing Then
						variableName = wfvariables.recConfigStructureFields.Item(a).Item("sVariableName").Value
						debug2File vbTab & vbTab & "initFromArchive:... initialize '" & variableName & "' with '" & oNode.text & "'"
						wfvariables.Item(variableName).Value = oNode.text	'initializes the wfvariable from the archive field
					End If
				End If
			End If
		Next
		
		'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 2
		Dim bInitAttachmentsTable : bInitAttachmentsTable = False
		For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for AttachmentsTable fields
			If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "AttachmentsTable" Then
				recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
				If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 2) Then
					bInitAttachmentsTable = True
				End If
			End If
		Next
		
		debug2File "initFromArchive: bInitAttachmentsTable = " & bInitAttachmentsTable
		
		If bInitAttachmentsTable = True Then
			'Clear the list before adding new entries
			wfvariables.recAttachments.ClearList
					
			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sAttachmentsTableInternalName.Value & "']/Row" 
			debug2File "initFromArchive: xpath = " & xpath
			Set oNodesRows = oXmlDoc.selectNodes(xpath)
			If Not oNodesRows Is Nothing Then
				For b = 0 To oNodesRows.length - 1
					rowID = oNodesRows.item(b).attributes.getNamedItem("id").text
					'ToDo: Read first the columns to determine the correct order of the row values
					xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sAttachmentsTableInternalName.Value & "']/Row[@id='" & rowID & "']/Value"
					debug2File "initFromArchive: xpath = " & xpath
					Set oNodesValues = oXmlDoc.selectNodes(xpath)
					If Not oNodesValues Is Nothing Then
						Set oEntry = wfvariables.recAttachments.CreateListItem
						oEntry.Item("sAttNr").Value = oNodesValues.item(0).text
						oEntry.Item("sTitle").Value = oNodesValues.item(1).text
						oEntry.Item("sCreator").Value = oNodesValues.item(2).text
						oEntry.Item("dCreatedOn").Value = oNodesValues.item(3).text
						oEntry.Item("sDeleted").Value = oNodesValues.item(4).text
						oEntry.Item("sObjectId").Value = oNodesValues.item(5).text
						debug2File vbtab & "sAttNr: " & oNodesValues.item(0).text
						debug2File vbtab & "sTitle: " & oNodesValues.item(1).text
						debug2File vbtab & "sCreator: " & oNodesValues.item(2).text
						debug2File vbtab & "dCreatedOn: " & oNodesValues.item(3).text
						debug2File vbtab & "sDeleted: " & oNodesValues.item(4).text
						debug2File vbtab & "sObjectId: " & oNodesValues.item(4).text
						wfvariables.recAttachments.AddListItem oEntry
					End If
				Next
			End If
		End If
		
		'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 2
		Dim bInitLinkedTable : bInitLinkedTable = False
		For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for LinkedTable fields
			If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "LinkedDocumentsTable" Then
				recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
				If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 2) Then
					bInitLinkedTable = True
				End If
			End If
		Next
		
		debug2File "initFromArchive: bInitLinkedTable = " & bInitLinkedTable
		
		If bInitLinkedTable = True Then
			'Clear the list before adding new entries
			wfvariables.recLinkedDocuments.ClearList	
				
			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sLinkedDocumentsInternalName.Value & "']/Row" 
			debug2File "initFromArchive: xpath = " & xpath
			Set oNodesRows = oXmlDoc.selectNodes(xpath)
			If Not oNodesRows Is Nothing Then
				For b = 0 To oNodesRows.length - 1
					rowID = oNodesRows.item(b).attributes.getNamedItem("id").text
					'ToDo: Read first the columns to determine the correct order of the row values
					xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sLinkedDocumentsInternalName.Value & "']/Row[@id='" & rowID & "']/Value"
					debug2File "initFromArchive: xpath = " & xpath
					Set oNodesValues = oXmlDoc.selectNodes(xpath)
					If Not oNodesValues Is Nothing Then
						Set oEntry = wfvariables.recLinkedDocuments.CreateListItem
						oEntry.Item("sLinkNumber").Value = oNodesValues.item(0).text
						oEntry.Item("sLinkTitle").Value = oNodesValues.item(1).text
						oEntry.Item("sLinkType").Value = oNodesValues.item(2).text
						oEntry.Item("sLinkRevision").Value = oNodesValues.item(3).text
						oEntry.Item("sLinkRelation").Value = oNodesValues.item(4).text						
						oEntry.Item("sLinkID").Value = oNodesValues.item(5).text					
						wfvariables.recLinkedDocuments.AddListItem oEntry
					End If
				Next
			End If
		End If
		
		'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 2
		Dim bInitParticipantsTable : bInitParticipantsTable  = False
		For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for Participants fields
			If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "ParticipantsTable" Then
				recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
				If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 2) Then
					bInitParticipantsTable = True
				End If
			End If
		Next
		
		debug2File "initFromArchive: bInitParticipantsTable = " & bInitParticipantsTable
		
		If bInitParticipantsTable = True Then
			'Clear the list before adding new entries
			wfvariables.recUsers.ClearList
			
			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sParticipantsInternalName.Value & "']/Columns/Column"
			
			debug2File "initFromArchive: xpath = " & xpath
debug2File getInternalName_Participants_Username
			Set oNodesRows = oXmlDoc.selectNodes(xpath)			
			
			'these are the column indexes
			Dim icolIndex_Participants_Activity : icolIndex_Participants_Activity = -1
			Dim icolIndex_Participants_Username : icolIndex_Participants_Username = -1
			Dim icolIndex_Participants_Rolename : icolIndex_Participants_Rolename = -1
			Dim icolIndex_Participants_UserGuid : icolIndex_Participants_UserGuid = -1
			Dim icolIndex_Participants_RoleGuid : icolIndex_Participants_RoleGuid = -1	
			
			For b = 0 To oNodesRows.length - 1
				Dim sColInternalName : sColInternalName = oNodesRows.item(b).attributes.getNamedItem("internal_name").text
				Select Case sColInternalName
				    Case getInternalName_Participants_Activity
				    	icolIndex_Participants_Activity = b
				    	debug2File "Checking getInternalName_Participants_Activity = " & getInternalName_Participants_Activity
				    Case getInternalName_Participants_Username
				    	icolIndex_Participants_Username = b
				    	debug2File "Checking getInternalName_Participants_Username = " & getInternalName_Participants_Username
				    Case getInternalName_Participants_RoleName
				    	icolIndex_Participants_Rolename = b
				    	debug2File "Checking getInternalName_Participants_RoleName = " & getInternalName_Participants_RoleName
				    Case getInternalName_Participants_UserGuid
				    	icolIndex_Participants_UserGuid = b
				    	debug2File "Checking getInternalName_Participants_UserGuid = " & getInternalName_Participants_UserGuid
				    Case getInternalName_Participants_RoleGuid
				    	icolIndex_Participants_RoleGuid = b				    					    				
				    	debug2File "Checking getInternalName_Participants_RoleGuid = " & getInternalName_Participants_RoleGuid
				End Select
				
			Next		
			
			debug2File vbTab & vbTab & "initFromArchive:... icolIndex_Participants_Activity set to " & icolIndex_Participants_Activity			
			debug2File vbTab & vbTab & "initFromArchive:... icolIndex_Participants_Username set to " & icolIndex_Participants_Username
			debug2File vbTab & vbTab & "initFromArchive:... icolIndex_Participants_Rolename set to " & icolIndex_Participants_Rolename
			debug2File vbTab & vbTab & "initFromArchive:... icolIndex_Participants_UserGuid set to " & icolIndex_Participants_UserGuid
			debug2File vbTab & vbTab & "initFromArchive:... icolIndex_Participants_RoleGuid set to " & icolIndex_Participants_RoleGuid
			
			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sParticipantsInternalName.Value & "']/Row" 
			debug2File "initFromArchive: xpath = " & xpath
			Set oNodesRows = oXmlDoc.selectNodes(xpath)			
			
			If Not oNodesRows Is Nothing Then
				For b = 0 To oNodesRows.length - 1
					rowID = oNodesRows.item(b).attributes.getNamedItem("id").text
					'ToDo: Read first the columns to determine the correct order of the row values
					xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sParticipantsInternalName.Value & "']/Row[@id='" & rowID & "']/Value"
					debug2File "initFromArchive: xpath = " & xpath
					Set oNodesValues = oXmlDoc.selectNodes(xpath)
					If Not oNodesValues Is Nothing Then
						Set oEntry = wfvariables.recUsers.CreateListItem
						If icolIndex_Participants_Activity > -1 Then
							oEntry.Item("sActivity").Value = oNodesValues.item( icolIndex_Participants_Activity ).text
							debug2File vbTab & vbTab & "initFromArchive:... initialize ParticipantsTable '" & "sActivity" & "' with '" & oEntry.Item("sActivity").Value & "'"							
						End If
						If icolIndex_Participants_Username > -1 Then
							oEntry.Item("sUsername").Value = oNodesValues.item( icolIndex_Participants_Username ).text
							debug2File vbTab & vbTab & "initFromArchive:... initialize ParticipantsTable '" & "sUsername" & "' with '" & oEntry.Item("sUsername").Value & "'"							
						End If
						If icolIndex_Participants_Rolename > -1 Then
							oEntry.Item("sRoleName").Value = oNodesValues.item( icolIndex_Participants_Rolename ).text
							debug2File vbTab & vbTab & "initFromArchive:... initialize ParticipantsTable '" & "sRoleName" & "' with '" & oEntry.Item("sRoleName").Value & "'"							
						End If
						oEntry.Item("sPerformedBy").Value = ""
						oEntry.Item("dPerformedAt").Value = ""
						oEntry.Item("sDecision").Value = ""
						If icolIndex_Participants_UserGuid > -1 Then
							oEntry.Item("sUserGuid").Value = oNodesValues.item( icolIndex_Participants_UserGuid ).text					
							debug2File vbTab & vbTab & "initFromArchive:... initialize ParticipantsTable '" & "sUserGuid" & "' with '" & oEntry.Item("sUserGuid").Value & "'"							
						End If
						If icolIndex_Participants_RoleGuid > -1 Then
							oEntry.Item("sRoleGuid").Value = oNodesValues.item( icolIndex_Participants_RoleGuid ).text
							debug2File vbTab & vbTab & "initFromArchive:... initialize ParticipantsTable '" & "sRoleGuid" & "' with '" & oEntry.Item("sRoleGuid").Value & "'"							
						End If							
						wfvariables.recUsers.AddListItem oEntry
					End If
				Next
			End If
		End If
		
		
		'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 2
		Dim bInitResponsibleTable : bInitResponsibleTable = False
		For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for LinkedTable fields
			If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "ResponsibleDocumentsTable" Then
				recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
				If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 2) Then
					bInitResponsibleTable = True
				End If
			End If
		Next
		
		debug2File "initFromArchive: bInitResponsibleTable = " & bInitResponsibleTable
		
		If bInitResponsibleTable = True Then
			'Clear the list before adding new entries
			wfvariables.TrainingResponsible.ClearList
			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & "m_doc_responsible" & "']/Row" 
			debug2File "initFromArchive: xpath = " & xpath
			Set oNodesRows = oXmlDoc.selectNodes(xpath)
			If Not oNodesRows Is Nothing Then
				For b = 0 To oNodesRows.length - 1
					rowID = oNodesRows.item(b).attributes.getNamedItem("id").text
					'ToDo: Read first the columns to determine the correct order of the row values
					xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & "m_doc_responsible" & "']/Row[@id='" & rowID & "']/Value" 			
					debug2File "initFromArchive: xpath = " & xpath
					Set oNodesValues = oXmlDoc.selectNodes(xpath)
					If Not oNodesValues Is Nothing Then
						Set oEntry = wfvariables.TrainingResponsible.CreateListItem
						oEntry.Item("Guid").Value = oNodesValues.item(0).text
						oEntry.Item("Name").Value = oNodesValues.item(1).text
						wfvariables.TrainingResponsible.AddListItem oEntry
					End If
				Next
			End If
		End If		
		
				
	End If
	
	wfvariables.sTitle2.Value = wfvariables.sTitle.Value 'we got two title fields, we use the title also for the header of the mask
	
	Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists (xmlFile) = True Then 'delete the xmlFile
		oFSO.DeleteFile xmlFile
	End If
	
	'clean up
	Set oFSO = Nothing
	
	debug2File "end initFromArchive (" & objectID & ")"	
End Function

'**********************************************************
' updateHistoryTable
' @description: writes back the document history to the folder object (configuration file)
' @param: objectID (Integer) - the folder object
' @return nothing
'**********************************************************
Function updateHistoryTable (objectID)
	debug2File "start updateHistoryTable (" & objectID & ")"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXMLFile  
	sXMLFile = getObjectDetails(objectID,"","")
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	If True = oXmlDoc.load(sXMLFile) Then
		Dim xpath
		Dim oNodesRows
		Dim oNodesValues
		Dim sRows : sRows = ""
		
		'first add the new entry to the string
		sRows = "<Row>" &_
		"<Field internal_name='" & getInternalName_HistoryTable_Author & "'>" & convertToValidXML(wfvariables.sCreatorName.Value) & "</Field>" &_
		"<Field internal_name='" & getInternalName_HistoryTable_ChangeReason & "'>" & convertToValidXML(wfvariables.sChangeReason.Value) & "</Field>"	&_				
		"<Field internal_name='" & getInternalName_HistoryTable_Date & "'>" & convertToValidXML(wfvariables.dCreatorDate.Value) & "</Field>"	&_
		"<Field internal_name='" & getInternalName_HistoryTable_Version & "'>" & convertToValidXML(wfvariables.sVersion.Value) & "</Field>"	&_		
		"<Field internal_name='" & getInternalName_HistoryTable_ChangeDetails & "'>" & convertToValidXML(wfvariables.sChangeDetails.Value) & "</Field>"	&_		
		"</Row>"


		'now iterate over existing entries and add them to the new entry
		xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField/Row"
		Set oNodesRows = oXmlDoc.selectNodes (xpath)
		If Not oNodesRows Is Nothing Then
			For i = 0 To oNodesRows.length - 1
				rowID = oNodesRows.item(i).attributes.getNamedItem("id").text
				sRows = sRows & "<Row>" & vbCrLf
				xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField/Row[@id='" & rowID & "']/Value"
				Set oNodesValues = oXmlDoc.selectNodes(xpath)
				If Not oNodesValues Is Nothing Then
					For z = 0 To oNodesValues.length - 1
						If z = 0 Then
							sRows = sRows & "<Field internal_name='" & getInternalName_HistoryTable_Date & "'>" & convertToValidXML(oNodesValues.item(z).text) & "</Field>" & vbCrLf
						End If
						If z = 1 Then
							sRows = sRows & "<Field internal_name='" & getInternalName_HistoryTable_Version & "'>" & convertToValidXML(oNodesValues.item(z).text) & "</Field>"	& vbCrLf
						End If
						If z = 2 Then
							sRows = sRows & "<Field internal_name='" & getInternalName_HistoryTable_ChangeReason & "'>" & convertToValidXML(oNodesValues.item(z).text) & "</Field>" & vbCrLf
						End If
						If z = 3 Then
							sRows = sRows & "<Field internal_name='" & getInternalName_HistoryTable_Author & "'>" & convertToValidXML(oNodesValues.item(z).text) & "</Field>" & vbCrLf
						End If	
						If z = 4 Then
							sRows = sRows & "<Field internal_name='" & getInternalName_HistoryTable_ChangeDetails & "'>" & convertToValidXML(oNodesValues.item(z).text) & "</Field>" & vbCrLf
						End If																						
					Next
				End If
				sRows = sRows & "</Row>" & vbCrLf
			Next
		End If
		
		Dim sXML
		
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "' type='FOLDER'>" &_
		"<Object object_id='" & objectID & "'>" &_
		"<Fields>" &_
		"</Fields>" &_	
		"<TableFields>" &_
		"<TableField internal_name='" & wfvariables.recStructure.sHistoryTableInternalName.Value & "'>" &_
		sRows &_
		"</TableField>" &_
		"</TableFields>" &_
		"</Object>" &_
		"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		
		dom.loadXML(sXML) 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0;REPLACETABLEFIELDS=1"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		If iRet = 0 Then
			debug2File "UpdateHistoryTable successful..."
			wfvariables.iHistoryTableAlreadyUpdated.Value = 1
		Else
			debug2File "UpdateHistoryTable failed..."
		End If
		
		Set oxmlDoc = Nothing
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists(sXMLFile) Then
			debug2File "Delete " & sXMLFile
			oFSO.DeleteFile(sXMLFile)
		End If
		
	End If
	debug2File "end updateHistoryTable (" & objectID & ")"
End Function

'**********************************************************
' mapToArchive
' @description: writes back workflow variables to corresponding archive fields (configuration file)
' @param: objectID (Integer) - the object for which the workflow variables should be archived
' @return nothing
'**********************************************************
Function mapToArchive (objectID)
	debug2File "start mapToArchive (" & objectID & ")"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	'MapToArchive = 0 - kein Datenaustausch
	'MapToArchive = 1 - init und zurckschreiben
	'MapToArchive = 2 - init
	'MapToArchive = 3 - zurckschreiben
	
	'Updates fields for the folder
	For i = 0 To wfvariables.recConfigStructureFields.Count - 1 	
		If wfvariables.recConfigStructureFields.Item(i).Item("sArchiveObject").Value = "Folder" Then
			internalName = wfvariables.recConfigStructureFields.Item(i).Item("sInternalName").Value
			If (wfvariables.recConfigStructureFields.Item(i).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(i).Item("iMapToArchive").Value = 3) Then
				variable = wfvariables.recConfigStructureFields.Item(i).Item("sVariableName").Value
				debug2file vbTab & vbTab & "mapToArchive -> mapped internalName = " & internalName & " to variable = " & variable & "(" & wfvariables.Item(variable).Value & ")"
				updateField wfvariables.recStructure.sFolderInternalName.Value, "FOLDER", wfvariables.recStructure.sFolderInternalName.Value, wfvariables.recStructure.iFolderID.Value, internalName, CStr(wfvariables.Item(variable).Value)
			End If
		End If
	Next
	
	'Updates fields for the register
	For i = 0 To wfvariables.recConfigStructureFields.Count - 1 	
		If wfvariables.recConfigStructureFields.Item(i).Item("sArchiveObject").Value = "Register" Then
			internalName = wfvariables.recConfigStructureFields.Item(i).Item("sInternalName").Value
			If (wfvariables.recConfigStructureFields.Item(i).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(i).Item("iMapToArchive").Value = 3) Then
				variable = wfvariables.recConfigStructureFields.Item(i).Item("sVariableName").Value
				debug2file vbTab & vbTab & "mapToArchive -> mapped internalName = " & internalName & " to variable = " & variable & "(" & wfvariables.Item(variable).Value & ")"
				updateField wfvariables.recStructure.sFolderInternalName.Value, "REGISTER", wfvariables.recStructure.sRegisterInternalName.Value, wfvariables.recStructure.iRegisterID.Value, internalName, CStr(wfvariables.Item(variable).Value)
			End If
		End If
	Next	
	
	wfvariables.sTitle2.Value = wfvariables.sTitle.Value 'we got two title fields, we use the title also for the header of the mask
	
	'get all document fields to write them back to the archive object
	Dim sFields
	For i = 0 To wfvariables.recConfigStructureFields.Count - 1 	
		If wfvariables.recConfigStructureFields.Item(i).Item("sArchiveObject").Value = "Document" Then
			internalName = wfvariables.recConfigStructureFields.Item(i).Item("sInternalName").Value
			If (wfvariables.recConfigStructureFields.Item(i).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(i).Item("iMapToArchive").Value = 3) Then
				variable = wfvariables.recConfigStructureFields.Item(i).Item("sVariableName").Value
				debug2file vbTab & vbTab & "mapToArchive -> mapped internalName = " & internalName & " to variable = " & variable & "(" & wfvariables.Item(variable).Value & ")"
				sFields = sFields & vbCrLf &_
				"<Field internal_name='" & internalName & "'>" & convertToValidXML(CStr(wfvariables.Item(variable).Value)) & "</Field>"
			End If
		End If
	Next
	
	
	'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 3
	Dim bInitAttachmentsTable : bInitAttachmentsTable = False
	For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for AttachmentsTable fields
		If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "AttachmentsTable" Then
			recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
			If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 3) Then
				bInitAttachmentsTable = True
			End If
		End If
	Next
	
	debug2File "mapToArchive -> bInitAttachmentsTable = " & bInitAttachmentsTable
	
	If bInitAttachmentsTable = True Then
		'get all attachmentes table fields to write them back to the archive object
		Dim sRowsAttachments : sRowsAttachments = ""	
		'iterate over all rows
		For v = 0 To wfvariables.recAttachments.Count - 1 
			sRowsAttachments = sRowsAttachments & "<Row>" &_
			"<Field internal_name='" & getInternalName_AttachmentsTable_No & "'>" & convertToValidXML(wfvariables.recAttachments.Item(v).Item("sAttNr").Value) & "</Field>" &_
			"<Field internal_name='" & getInternalName_AttachmentsTable_Title & "'>" & convertToValidXML(wfvariables.recAttachments.Item(v).Item("sTitle").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_AttachmentsTable_Creator & "'>" & convertToValidXML(wfvariables.recAttachments.Item(v).Item("sCreator").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_AttachmentsTable_CreatedOn & "'>" & convertToValidXML(wfvariables.recAttachments.Item(v).Item("dCreatedOn").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_AttachmentsTable_Deleted & "'>" & convertToValidXML(wfvariables.recAttachments.Item(v).Item("sDeleted").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_AttachmentsTable_ObjectId & "'>" & convertToValidXML(wfvariables.recAttachments.Item(v).Item("sObjectId").Value) & "</Field>"	&_
			"</Row>"
		Next
		debug2file "mapToArchive -> mapped attachments!"		
	End If
	
	'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 3
	Dim bInitLinkedTable : bInitLinkedTable = False
	For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for LinkedTable fields
		If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "LinkedDocumentsTable" Then
			recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
			If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 3) Then
				bInitLinkedTable = True
			End If
		End If
	Next
	
	debug2File "mapToArchive -> bInitLinkedTable = " & bInitLinkedTable
	
	If bInitLinkedTable = True Then
		'get all linkeddocument table fields to write them back to the archive object
		Dim sRowsLinked : sRowsLinked = ""	
		'iterate over all rows
		For v = 0 To wfvariables.recLinkedDocuments.Count - 1 
			sRowsLinked = sRowsLinked & "<Row>" &_
			"<Field internal_name='" & getInternalName_LinkedDocuments_Number & "'>" & convertToValidXML(wfvariables.recLinkedDocuments.Item(v).Item("sLinkNumber").Value) & "</Field>" &_
			"<Field internal_name='" & getInternalName_LinkedDocuments_Title & "'>" & convertToValidXML(wfvariables.recLinkedDocuments.Item(v).Item("sLinkTitle").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_LinkedDocuments_Type & "'>" & convertToValidXML(wfvariables.recLinkedDocuments.Item(v).Item("sLinkType").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_LinkedDocuments_Relation & "'>" & convertToValidXML(wfvariables.recLinkedDocuments.Item(v).Item("sLinkRelation").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_LinkedDocuments_Revision & "'>" & convertToValidXML(wfvariables.recLinkedDocuments.Item(v).Item("sLinkRevision").Value) & "</Field>"	&_	
			"<Field internal_name='" & getInternalName_LinkedDocuments_ID & "'>" & convertToValidXML(wfvariables.recLinkedDocuments.Item(v).Item("sLinkID").Value) & "</Field>"	&_	
			"</Row>"
		Next
		debug2file "mapToArchive -> mapped linked documents!"		
	End If
	
	'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 3
	Dim bInitParticipantsTable : bInitParticipantsTable  = False
	For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for Participants fields
		If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "ParticipantsTable" Then
			recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
			If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 3) Then
				bInitParticipantsTable = True
			End If
		End If
	Next
	
	debug2File "mapToArchive -> bInitParticipantsTable = " & bInitParticipantsTable
	
	If bInitParticipantsTable = True Then	
		'get all participants table fields to write them back to the archive object
		Dim sRowsParticipants : sRowsParticipants = ""	
		'iterate over all rows
		For v = 0 To wfvariables.recUsersSorted.Count - 1 'recUsers
			sRowsParticipants = sRowsParticipants & "<Row>" &_
			"<Field internal_name='" & getInternalName_Participants_Activity & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("sActivity").Value) & "</Field>" &_
			"<Field internal_name='" & getInternalName_Participants_Username & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("sUsername").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_Participants_RoleName & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("sRoleName").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_Participants_PerformedBy & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("sPerformedBy").Value) & "</Field>"	&_
			"<Field internal_name='" & getInternalName_Participants_PerformedAt & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("dPerformedAt").Value) & "</Field>"	&_	
			"<Field internal_name='" & getInternalName_Participants_Decision & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("sDecision").Value) & "</Field>"	&_	
			"<Field internal_name='" & getInternalName_Participants_UserGuid & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("sUserGuid").Value) & "</Field>"	&_	
			"<Field internal_name='" & getInternalName_Participants_RoleGuid & "'>" & convertToValidXML(wfvariables.recUsersSorted.Item(v).Item("sRoleGuid").Value) & "</Field>"	&_	
			"</Row>"
		Next
		debug2file "mapToArchive -> mapped participants!"		
	End If	
	
	
	
	'map the COMPLETE table if at least 1 column has the attribute mapToArchive = 1 or 3
	Dim bInitResponsibleTable : bInitResponsibleTable = False
	For a = 0 To wfvariables.recConfigStructureFields.Count - 1 'iterate over the structure fields and look for LinkedTable fields
		If wfvariables.recConfigStructureFields.Item(a).Item("sArchiveObject").Value = "ResponsibleDocumentsTable" Then
			recInternalName = wfvariables.recConfigStructureFields.Item(a).Item("sInternalName").Value
			If (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 1) Or (wfvariables.recConfigStructureFields.Item(a).Item("iMapToArchive").Value = 3) Then
				bInitResponsibleTable = True
			End If
		End If
	Next
	
	debug2File "mapToArchive -> bInitResponsibleTable = " & bInitResponsibleTable
	
	If bInitResponsibleTable = True Then
		'get all linkeddocument table fields to write them back to the archive object
		Dim sRowsResponsible : sRowsResponsible = ""	
		'iterate over all rows
		For v = 0 To wfvariables.TrainingResponsible.Count - 1  
			sRowsResponsible = sRowsResponsible & "<Row>" &_
			"<Field internal_name='" & "Guid" & "'>" & convertToValidXML(wfvariables.TrainingResponsible.Item(v).Item("Guid").Value) & "</Field>" &_
			"<Field internal_name='" & "Name" & "'>" & convertToValidXML(wfvariables.TrainingResponsible.Item(v).Item("Name").Value) & "</Field>" &_
			"</Row>"
		Next
		debug2file "mapToArchive -> mapped linked documents!"		
	End If

	
	Dim sXML
	sXML = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
	"<Object object_id='" & objectID & "'>" &_
	"<Fields>" &_
	sFields &_
	"</Fields>" &_				
	"<TableFields>"
	If bInitAttachmentsTable = True Then
		sXML = sXML &_
		"<TableField internal_name='" & wfvariables.recStructure.sAttachmentsTableInternalName.Value & "'>" &_
		sRowsAttachments &_
		"</TableField>"
	End If
	If bInitLinkedTable = True Then
		sXML = sXML &_
		"<TableField internal_name='" & wfvariables.recStructure.sLinkedDocumentsInternalName.Value & "'>" &_
		sRowsLinked &_
		"</TableField>"
	End If
	If bInitParticipantsTable = True Then
		sXML = sXML &_
		"<TableField internal_name='" & wfvariables.recStructure.sParticipantsInternalName.Value & "'>" &_
		sRowsParticipants &_
		"</TableField>"
	End If
	If bInitResponsibleTable = True Then 'm_doc_responsible
		sXML = sXML &_
		"<TableField internal_name='" & "m_doc_responsible" & "'>" &_
		sRowsResponsible &_
		"</TableField>"
	End If	
	sXML = sXML &_
	"</TableFields>" &_			
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	'debug2file "mapToArchive XML:" 
	'debug2File sXML
	dom.loadXML(sXML) 
	PrmIn.Value("Flags") = 0
	PrmIn.Value("Options") ="CHECKREADONLY=0;REPLACETABLEFIELDS=1"
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
	If iRet = 0 Then
		debug2File vbTab & "mapToArchive successful..."
	Else
		debug2File vbTab & "Error: mapToArchive failed..."
	End If
	
	Set oxmlDoc = Nothing
	debug2File "end mapToArchive (" & objectID & ")"
End Function

'**********************************************************
' getVisibleActivities
' @description: returns an array (";" separated string) with all as visible=1 defined activities from the configuration file
' @param
' @return
'**********************************************************
Function getVisibleActivities()
	debug2File "start - getVisibleActivities"
	
	Dim sRet : sRet = ""
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	If True = oXmlDoc.load(wfvariables.recCommon.sConfigurationFile.Value) Then
		Dim xpath
		Dim oNodes
		
		'get Activities
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity"
		
		debug2File xpath
		Set oNodes = oXmlDoc.selectNodes (xpath)
		If Not oNodes Is Nothing Then
			For i = 0 To oNodes.length - 1
				visible = oNodes.item(i).attributes.getNamedItem("visible").text
				If CLng(visible) = 1 Then
					sRet = sRet & oNodes.item(i).attributes.getNamedItem("Name").text & ";"
				End If
			Next
		End If
	End If
	
	If sRet <> "" Then 'if sRet = "", no activity should be visible
		'remove last separator
		sRet = Left(sRet, (Len(sRet)-1))
	End If
	debug2File "getVisibleActivities -> " & sRet
	getVisibleActivities = sRet
	
	debug2File "end - getVisibleActivities"
End Function


'**********************************************************
' readActivityStartConfiguration
' @description
' @param
' @return
'**********************************************************
Function readActivityStartConfiguration (activityName)
	debug2File "start - readActivityStartConfiguration"
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	If True = oXmlDoc.load(wfvariables.recCommon.sConfigurationFile.Value) Then
		Dim xpath
		Dim oNode
		Dim oNodes
		
		'Templates
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Templates"
		debug2File "Reading template informations"
		Set oNode = oXmlDoc.selectSingleNode(xpath)		
		If Not oNode Is Nothing Then
			debug2File "Template Request: " 
			debug2File vbTab & vbTab & vbTab & oNode.text
			wfvariables.sTemplateRequest.value = oNode.text	'assign the request string to an internal variable (TODO: better way to do this? maybe like wffields?)
		Else
			throwError "Failed to read template informations of the activity " & activityName
		End If
		
		'AttachmentTemplates
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/AttachmentTemplates"
		debug2File "Reading attachment template informations"
		Set oNode = oXmlDoc.selectSingleNode(xpath)		
		If Not oNode Is Nothing Then
			debug2File "Attachment Template Request: " 
			debug2File vbTab & vbTab & vbTab & oNode.text
			wfvariables.sTemplateAttachmentRequest.value = oNode.text	'assign the request string to an internal variable (TODO: better way to do this? maybe like wffields?)
		Else
			throwError "Failed to read attachement template informations of the activity " & activityName
		End If
		
		'ConversionType
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/ConversionType"
		debug2File "Reading conversion type informations (0 means OS; 1 means Neevia)"
		Set oNode = oXmlDoc.selectSingleNode(xpath)		
		If Not oNode Is Nothing Then
			debug2File "Conversion Type: " 
			debug2File vbTab & vbTab & vbTab & oNode.text
			wfvariables.iConversionType.value = oNode.text	
		Else
			throwError "Failed to read the conversion type of the activity " & activityName
		End If		
		
		
		'Activity name		
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']"
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then
			debug2File "Activity nameDE: " & oNode.attributes.getNamedItem("nameDE").text
			debug2File "Activity nameEN: " & oNode.attributes.getNamedItem("nameEN").text
		Else
			throwError "Failed to read the activity " & activityName
		End If
		'Activity WorkflowFields
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/WorkflowFields/Field" 
		debug2File "Reading workflow fields"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If Not oNodes Is Nothing Then
			wfvariables.recConfigWFFields.ClearList
			For i = 0 To oNodes.length - 1
				debug2File vbTab & "Field Variable Name: " & oNodes(i).attributes.getNamedItem("variablename").text
				debug2File vbTab & vbTab & "Field Enabled: " & oNodes(i).attributes.getNamedItem("enabled").text
				debug2File vbTab & vbTab & "Field Visible: " & oNodes(i).attributes.getNamedItem("visible").text
				debug2File vbTab & vbTab & "Field ListType: " & oNodes(i).attributes.getNamedItem("listtype").text
				debug2File vbTab & vbTab & "Field Mandatory: " & oNodes(i).attributes.getNamedItem("mandatory").text
				Dim content : content = ""
				If oNodes(i).attributes.getNamedItem("listtype").text = "2" Then
					debug2File vbTab & vbTab & "Listtype values: " & oNodes(i).text
					content = getObjectDefListValues (oNodes(i).text)
				Else 
					If oNodes(i).attributes.getNamedItem("listtype").text = "1" Then
						debug2File vbTab & vbTab & "Listtype values: " & oNodes(i).text
						content = oNodes(i).text
					Else
						debug2File vbTab & vbTab & "Field Value: " & oNodes(i).text
						content = oNodes(i).text
					End If
				End If
				
				'add configuration wffields to internal record structure
				'this record will be read in different events to initialize wffields / controls				
				Set oEntry = wfvariables.recConfigWFFields.CreateListItem
				oEntry.Item("sVariableName").Value = oNodes(i).attributes.getNamedItem("variablename").text
				oEntry.Item("iEnabled").Value = oNodes(i).attributes.getNamedItem("enabled").text
				oEntry.Item("iVisible").Value = oNodes(i).attributes.getNamedItem("visible").text
				oEntry.Item("iListType").Value = oNodes(i).attributes.getNamedItem("listtype").text
				oEntry.Item("iMandatory").Value = oNodes(i).attributes.getNamedItem("mandatory").text
				oEntry.Item("sContent").Value = content
				wfvariables.recConfigWFFields.AddListItem oEntry
				
			Next			
		Else
			throwError "Failed to read fields"
		End If
		'Activity Buttons
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/Buttons/Button" 
		debug2File "Reading buttons configuration"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If Not oNodes Is Nothing Then
			wfvariables.recConfigButtons.ClearList
			For i = 0 To oNodes.length - 1
				debug2File vbTab & "Button name: " & oNodes(i).text
				debug2File vbTab & vbTab & "Button Enabled: " & oNodes(i).attributes.getNamedItem("enabled").text
				debug2File vbTab & vbTab & "Button Visible: " & oNodes(i).attributes.getNamedItem("visible").text
				debug2File vbTab & vbTab & "Button Function: " & oNodes(i).attributes.getNamedItem("function").text
				
				'add configuration buttons to internal record structure
				'this record will be read in the beforeOpen event to initialize the buttons
				Set oEntry = wfvariables.recConfigButtons.CreateListItem
				oEntry.Item("iEnabled").Value = oNodes(i).attributes.getNamedItem("enabled").text
				oEntry.Item("iVisible").Value = oNodes(i).attributes.getNamedItem("visible").text
				oEntry.Item("sFunction").Value = oNodes(i).attributes.getNamedItem("function").text
				oEntry.Item("sName").Value = oNodes(i).text
				wfvariables.recConfigButtons.AddListItem oEntry
				
			Next			
		Else
			throwError "Failed to read fields"
		End If
		'RecipientRoles
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/StandardRecipientRoles/Role"
		debug2File xpath
		debug2File "Reading StandardRecipientRoles"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If Not oNodes Is Nothing Then
			wfvariables.recConfigRecipients.ClearList
			For i = 0 To oNodes.length - 1
				debug2File vbTab & vbTab & "Role / user: " & oNodes(i).text
				debug2File vbTab & vbTab & "addressRoles: " & oNodes(i).attributes.getNamedItem("addressRoles").text
				debug2File vbTab & vbTab & "addressUsers: " & oNodes(i).attributes.getNamedItem("addressUsers").text
				debug2File vbTab & vbTab & "Multiinstance: " & oNodes(i).attributes.getNamedItem("multiinstance").text
				
				'add recipients to internal record structure
				Set oEntry = wfvariables.recConfigRecipients.CreateListItem
				oEntry.Item("iAddressRoles").Value = oNodes(i).attributes.getNamedItem("addressRoles").text
				oEntry.Item("iAddressUsers").Value = oNodes(i).attributes.getNamedItem("addressUsers").text
				oEntry.Item("iMultiinstance").Value = oNodes(i).attributes.getNamedItem("multiinstance").text
				oEntry.Item("sRecipient").Value = oNodes(i).text
				wfvariables.recConfigRecipients.AddListItem oEntry				
			Next			
		Else
			throwError "Failed to read StandardRecipientRoles"
		End If
		
		'ActivityFeatures
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/Features/Feature"
		debug2File "Reading Features"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If Not oNodes Is Nothing Then
			wfvariables.recConfigActivityFeatures.ClearList
			For i = 0 To oNodes.length - 1
				Dim currentFeature : currentFeature = oNodes(i).attributes.getNamedItem("Name").text
				Dim FeatureEvent : FeatureEvent = oNodes(i).attributes.getNamedItem("Event").text
				Dim FeatureConditionVariable : FeatureConditionVariable = ""
				Dim FeatureConditionValue : FeatureConditionValue = ""
				
				debug2File vbTab & vbTab & "Feature name: " & currentFeature
				debug2File vbTab & vbTab & "Feature event: " & FeatureEvent
				
				
				
				'add feature to internal structure
				Set oEntry = wfvariables.recConfigActivityFeatures.CreateListItem
				oEntry.Item("sName").Value = currentFeature
				oEntry.Item("sEvent").Value = FeatureEvent
				
							
				xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/Features/Feature[@Name='" & currentFeature & "']/Condition"
				Dim oCondition				
				Set oCondition = oXmlDoc.selectSingleNode(xpath)
				If Not oCondition Is Nothing Then
					debug2File vbTab & vbTab & "Condition: " & oCondition.text
					If Trim( oCondition.text ) <> "" Then
						oEntry.Item("sCondition").Value = oCondition.text
					End If
				End If
				
				
				wfvariables.recConfigActivityFeatures.AddListItem oEntry								
			Next			
		Else
			throwError "Failed to read Features"
		End If		
		
	Else
		throwError "Failed to read the configuration file"
	End If
	debug2File "end - readActivityStartConfiguration"
End Function



'**********************************************************
' readActivityEndConfiguration
' @description
' @param
' @return
'**********************************************************
Function readActivityEndConfiguration (activityName)
	debug2File "start - readActivityEndConfiguration"
	
	Dim xpath
	Dim oNode
	Dim oNodes
	Dim oConditionFields
	
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	If True = oXmlDoc.load(wfvariables.recCommon.sConfigurationFile.Value) Then
		
		'NextActivity
		debug2File "Current activity: " & activityName
		xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/NextActivity"
		debug2File "Reading Next Activity"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If Not oNodes Is Nothing Then
			recConfigNextActivityConditions.ClearList
			For i = 0 To oNodes.length - 1
				debug2File vbTab & "Next Activity name: " & oNodes(i).attributes.getNamedItem("Name").text
				Dim nextActivityName : nextActivityName = oNodes(i).attributes.getNamedItem("Name").text
				
				xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/NextActivity[@Name='" & nextActivityName & "']/Condition"
				Dim oCondition				
				Set oCondition = oXmlDoc.selectSingleNode(xpath)
				If Not oCondition Is Nothing Then
					debug2File vbTab & vbTab & "Condition: " & oCondition.text
					
					Set oEntry = wfvariables.recConfigNextActivityConditions.CreateListItem
					oEntry.Item("sNextActivity").Value = nextActivityName
					oEntry.Item("sCondition").Value = oCondition.text
					wfvariables.recConfigNextActivityConditions.AddListItem oEntry						
					
					
					'				xpath = "config/WorkflowType[@type='" & recCommon.sWorkflowModel.Value & "']/Activity[@Name='" & activityName & "']/NextActivity[@Name='" & nextActivityName & "']/Condition/Field"
					'				debug2File vbTab & "Reading conditions"
					'				Set oConditionFields = oXmlDoc.selectNodes(xpath)
					'				If Not oConditionFields Is Nothing And (oConditionFields.length > 0) Then
					'					For n = 0 To oConditionFields.length - 1
					'						debug2File vbTab & vbTab & "ConditionField: " & oConditionFields(n).attributes.getNamedItem("Name").text
					'						Dim conditionFieldName : conditionFieldName = oConditionFields(n).attributes.getNamedItem("Name").text
					'						debug2File vbTab & vbTab & "Condition: " & oConditionFields(n).text
					'						Dim conditionFieldValue : conditionFieldValue = oConditionFields(n).text
					'						debug2File vbTab & "------"
					
					'add condition for next activity to internal record structure
					'this record will be read in the BeforeForward-Event to define the next activity
					'						Set oEntry = wfvariables.recConfigNextActivityConditions.CreateListItem
					'						oEntry.Item("sNextActivity").Value = nextActivityName
					'						oEntry.Item("sVariableName").Value = conditionFieldName
					'						oEntry.Item("sValue").Value = conditionFieldValue
					'						wfvariables.recConfigNextActivityConditions.AddListItem oEntry						
					'			Next			
				Else 'no condition found -> use this activity as nextActivity
					debug2File vbTab & vbTab & "no conditionsFields available -> NextActivity is " & nextActivityName
					wfVariables.sNextActivity.Value = nextActivityName
					'Exit For
				End If 
			Next
		Else
			throwError "Failed to read Next Activtiy"
		End If			
	Else
		throwError "Failed to read the configuration file"
	End If
	debug2File "end - readActivityEndConfiguration"
End Function

'**********************************************************
' setActivityName
' @description
' @param
' @return
'**********************************************************
Function setActivityName
	If wfvariables.sNextActivity.Value <> "" Then
		debug2File "Current ActivityName: " & wfvariables.sNextActivity.Value
		wfvariables.sCurrentActivity.Value = wfvariables.sNextActivity.Value 'helper variable to get the name of the current activity in client events
		thisprocess.CurrentActivity.Name = wfvariables.sNextActivity.Value
	Else
		throwError "Failed to read the next activity"	
	End If
End Function

'**********************************************************
' ManipulateUsersTableForRevision
' @description manipulates the present user's table for revision
' @param Nothing
' @return Nothing
'**********************************************************
Sub ManipulateUsersTableForRevision
	debug2File "Start - ManipulateUsersTableForRevision"
	Dim dcMappings : Set dcMappings = CreateObject( "Scripting.Dictionary" )
	Dim aOldRecUsers : aOldRecUsers = Array(wfvariables.recUsers.Count -1, 7)
	dcMappings.Add "Create", "Revise"
	'Create an image of recUsers in aOldRecUsers. The mapping will already be executed
	Dim a
	debug2File "Copy recUsers - ManipulateUsersTableForRevision, " & wfvariables.recUsers.Count & " entries."
	For a = 0 To wfvariables.recUsers.Count - 1	
		debug2File vbTab & a
		For Each key In dcMappings
			If wfvariables.recUsers.Item(a).Item("sActivity").Value = key Then
				wfvariables.recUsers.Item(a).Item("sActivity").Value = dcMappings(key)
			End If
		Next
'		aOldRecUsers(a,0) 		= wfvariables.recUsers.Item(a).Item("sActivity").Value
'		aOldRecUsers(a,1)		= wfvariables.recUsers.Item(a).Item("sUserGuid").Value
'		aOldRecUsers(a,2)		= wfvariables.recUsers.Item(a).Item("sUserName").Value
'		aOldRecUsers(a,3)		= wfvariables.recUsers.Item(a).Item("sRoleGuid").Value
'		aOldRecUsers(a,4)		= wfvariables.recUsers.Item(a).Item("sRoleName").Value			
'		aOldRecUsers(a,5)		= wfvariables.recUsers.Item(a).Item("sPerformedBy").Value
'		aOldRecUsers(a,6)		= wfvariables.recUsers.Item(a).Item("sDecision").Value
'		aOldRecUsers(a,7)		= wfvariables.recUsers.Item(a).Item("dPerformedAt").Value
	Next
'	wfvariables.recUsers.ClearList 'Clear recUsers to rebuild
'	debug2File "Rebuild recUsers - ManipulateUsersTableForRevision"
'	Dim b
'	For b = 0 To aOldRecUsers.Count -1 ' rebuild recUsers
'		wfvariables.recUsers.Item(b).Item("sActivity").Value		= aOldRecUsers(b,0)
'		wfvariables.recUsers.Item(b).Item("sUserGuid").Value		= aOldRecUsers(b,1) 
'		wfvariables.recUsers.Item(b).Item("sUserName").Value		= aOldRecUsers(b,2) 
'		wfvariables.recUsers.Item(b).Item("sRoleGuid").Value		= aOldRecUsers(b,3) 
'		wfvariables.recUsers.Item(b).Item("sRoleName").Value		= aOldRecUsers(b,4) 
'		wfvariables.recUsers.Item(b).Item("sPerformedBy").Value		= aOldRecUsers(b,5) 
'		wfvariables.recUsers.Item(b).Item("sDecision").Value		= aOldRecUsers(b,6) 
'		wfvariables.recUsers.Item(b).Item("dPerformedAt").Value		= aOldRecUsers(b,7) 
'	Next 
	debug2File "End - ManipulateUsersTableForRevision"
End Sub


'**********************************************************
' addNewPerformerToUserTable
' @description writes all selected participants back to the record which will be mappped with the archive. 
'              This function will be used, from the "modifiy participants" workflow which updates all participants for imported documents.
' @param 
' @return Nothing
'**********************************************************
Sub addNewPerformerToUserTable
For a = 0 To wfvariables.recUsers.Count - 1	
	Set oEntry = wfvariables.recUsersSorted.CreateListItem
	oEntry.Item("sActivity").Value = wfvariables.recUsers.Item(a).Item("sActivity").Value
	oEntry.Item("sUserGuid").Value = wfvariables.recUsers.Item(a).Item("sUserGuid").Value
	oEntry.Item("sUserName").Value = wfvariables.recUsers.Item(a).Item("sUserName").Value
	oEntry.Item("sRoleGuid").Value = wfvariables.recUsers.Item(a).Item("sRoleGuid").Value
	oEntry.Item("sRoleName").Value = wfvariables.recUsers.Item(a).Item("sRoleName").Value			
	wfvariables.recUsersSorted.AddListItem oEntry
	debug2File "addNewPerformerToUserTable (" & sActivity & ") => Updated recUsersSorted"	
Next
End Sub

'**********************************************************
' addPerformerToUserTable
' @description adds the author to the user's table if not present
' @param sActivity the current activity's name
' @return Nothing
'**********************************************************
Sub addPerformerToUserTable(sActivity)
	debug2File "Start - addPerformerToUserTable (" & sActivity & ")"
	Dim sCurrentUserGuid : sCurrentUserGuid = getCurrentActivityPerformerId
	If sCurrentUserGuid = "" Then
		debug2File "addPerformerToUserTable (" & sActivity & ") => No User Guid"	
		Exit Sub
	End If
	
	'get the complete (firstname + lastname) username

	Dim sCurrentUserName : sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).GetAttributeValueByName("Vorname") & " " & wforganisation.GetOrgObjectById(sCurrentUserGuid).GetAttributeValueByName("Nachname")
	If Trim(sCurrentUserName) = "" Then 'use the LogIn Name if no complete name is defined
		sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).Name
	End If
	debug2File "addPerformerToUserTable (" & sActivity & ") => sCurrentUserGuid = " & sCurrentUserGuid & ", sCurrentUserName = " & sCurrentUserName 		
	
	'this could occur if the create activity was performed and forwarded to collaboration. if the the collaboration item is finshed the create wf-item appears again. 
	'in this case we don't want to have 2 Create entries in the user table
	For a = 0 To wfvariables.recUsersSorted.Count - 1	
		debug2File "Activity: " & wfvariables.recUsersSorted.Item(a).Item("sActivity").Value & " = " & sActivity & "   -   PerformedBy " &  wfvariables.recUsersSorted.Item(a).Item("sPerformedBy").Value & " = " & sCurrentUserName & " - PerformedAt: " & wfvariables.recUsersSorted.Item(a).Item("dPerformedAt").Value
		If wfvariables.recUsersSorted.Item(a).Item("sActivity").Value = sActivity And wfvariables.recUsersSorted.Item(a).Item("sPerformedBy").Value = sCurrentUserName And wfvariables.recUsersSorted.Item(a).Item("dPerformedAt").Value <> "" Then				
			debug2File vbTab &  " -> Exit and don't add the user again to the usertable"
			'the activity was already performed, so don't add another activity
			Exit sub							
		End If
	Next

	Dim oEntry
	Dim a
	Dim b
	debug2File "addPerformerToUserTable (" & sActivity & ") => check " & wfvariables.recUsers.Count & " present users"
	For a = 0 To wfvariables.recUsers.Count - 1	
		Dim sPlannedPerformerId : sPlannedPerformerId = wfvariables.sPlannedPerformerID.Value
		debug2File "addPerformerToUserTable (" & sActivity & ") => check activity " & wfvariables.recUsers.Item(a).Item("sActivity").Value & " = " & sActivity
		debug2File "addPerformerToUserTable (" & sActivity & ") => check sUserGuid " & wfvariables.recUsers.Item(a).Item("sUserGuid").Value & " = " & sPlannedPerformerId
		If wfvariables.recUsers.Item(a).Item("sActivity").Value = sActivity And wfvariables.recUsers.Item(a).Item("sUserGuid").Value = sPlannedPerformerId Then 'user are assigned in the table
			debug2File "addPerformerToUserTable (" & sActivity & ") => record " & sActivity & " found!"
			wfvariables.recUsers.Item(a).Item("sPerformedBy").Value = sCurrentUserName
			wfvariables.recUsers.Item(a).Item("dPerformedAt").Value = Date()
			wfvariables.recUsers.Item(a).Item("sDecision").Value = wfvariables.sOptions.Value
			debug2File "addPerformerToUserTable (" & sActivity & ") => record " & sActivity & " updated with username " & sCurrentUserName

			Set oEntry = wfvariables.recUsersSorted.CreateListItem
			oEntry.Item("sActivity").Value = sActivity
			oEntry.Item("sUserGuid").Value = wfvariables.recUsers.Item(a).Item("sUserGuid").Value
			oEntry.Item("sUserName").Value = wfvariables.recUsers.Item(a).Item("sUserName").Value
			oEntry.Item("sRoleGuid").Value = wfvariables.recUsers.Item(a).Item("sRoleGuid").Value
			oEntry.Item("sRoleName").Value = wfvariables.recUsers.Item(a).Item("sRoleName").Value			
			oEntry.Item("sPerformedBy").Value = sCurrentUserName
			oEntry.Item("sDecision").Value = wfvariables.sOptions.Value
			oEntry.Item("dPerformedAt").Value = Date()	
			wfvariables.recUsersSorted.AddListItem oEntry
			debug2File "addPerformerToUserTable (" & sActivity & ") => Updated recUsersSorted"			
			'exit the sub if found an according activity			
			Exit Sub
		End If
	Next



	'Das kann durchaus sein, wenn nmlich fr eine Prfaktivitt nicht ein Performer konfiguriert ist, sondern eine feste Rolle genommen wird
	debug2File "addPerformerToUserTable (" & sActivity & ") => no record found!"
	Dim oRecord : Set oRecord = wfvariables.recUsers.CreateListItem
	oRecord.Item("sActivity").Value = sActivity
	oRecord.Item("sUserGuid").Value = sCurrentUserGuid
	oRecord.Item("sUserName").Value = sCurrentUserName
	oRecord.Item("sPerformedBy").Value = sCurrentUserName
	oRecord.Item("sDecision").Value = wfvariables.sOptions.Value
	oRecord.Item("dPerformedAt").Value = Date()	
	wfvariables.recUsers.AddListItem oRecord
	
	debug2File "addPerformerToUserTable (" & sActivity & ") => record created!"	

	'Insert into sorted record
	Set oEntry = wfvariables.recUsersSorted.CreateListItem
	oEntry.Item("sActivity").Value = sActivity
	oEntry.Item("sUserGuid").Value = sCurrentUserGuid
	oEntry.Item("sUserName").Value = sCurrentUserName
	oEntry.Item("sPerformedBy").Value = sCurrentUserName
	oEntry.Item("sDecision").Value = wfvariables.sOptions.Value
	oEntry.Item("dPerformedAt").Value = Date()	
	wfvariables.recUsersSorted.AddListItem oEntry	
	
	debug2File "addPerformerToUserTable (" & sActivity & ") => Updated recUsers..."	
	debug2File "End - addPerformerToUserTable (" & sActivity & ")"	
End Sub

'**********************************************************
' getPerformerFromUserTable
' @description: returns all user workflow guids (separated by ',') from the usertable (recUsers) for the given activity
' @param: sActivity (String) - the name of the activity for which the users should be returned
' @return: a comma seprated list of users (e.g. "1324564646798601blabla,edhjgflksfer47897632423908")
'**********************************************************
Function getPerformerFromUserTable(sActivity)
	debug2File "Start - getPerformerFromUserTable (" & sActivity & ")"
	Dim sUsers : sUsers = ""	
	For a = 0 To wfvariables.recUsers.Count - 1
		If wfvariables.recUsers.Item(a).Item("sActivity").Value = sActivity Then 'user are assigned in the table
			sUsers = sUsers & wfvariables.recUsers.Item(a).Item("sUserGuid").Value & ","
		End If			
	Next
	If sUsers <> "" Then 'the usertable could be empty at the beginning
		sUsers = Left(sUsers,Len(sUsers)-1) 'remove the last ',' from the string
	End If
	getPerformerFromUserTable = sUsers
	
	If sUsers = "" Then
		debug2File vbTab & "INFO: In the user table are no user defined for the activity '" & sActivity & "'."
	End If
	debug2File "End - getPerformerFromUserTable() => " & getPerformerFromUserTable	
End Function

'**********************************************************
' getCurrentActivityPerformerId
' @description gets the last performer of an activity or multiinstance activity
' @param Nothing
' @return the guid of the last performer or an empty string if none or system user
'**********************************************************
Private Function getCurrentActivityPerformerId()
	debug2file "start getCurrentActivityPerformerId()"
	Dim sperformerId : sperformerId = ""
	Dim ix4
	If thisprocess.CurrentActivity.IsMultiActivity = True Then
		debug2file "getCurrentActivityPerformerId() => check multiinstances"
		For ix4=0 To thisprocess.CurrentActivity.MultiInstances.Count - 1
			debug2file "getCurrentActivityPerformerId() => check " & thisprocess.CurrentActivity.MultiInstances.Item(ix4).RActivityId & " = " & thisprocess.CurrentActivity.RActivityId
			If thisprocess.CurrentActivity.MultiInstances.Item(ix4).RActivityId = thisprocess.CurrentActivity.RActivityId Then
				sperformerId = thisprocess.CurrentActivity.MultiInstances.Item(ix4).PerformerId
			End If
		Next
	Else
		debug2file "getCurrentActivityPerformerId() => check single instance"
		sperformerId = thisprocess.CurrentActivity.PerformerId
	End If
	If Left( sperformerId, 20 ) = "00000000000000000000" Then
		sperformerId = ""
	End If	
	debug2file "end getCurrentActivityPerformerId() => " & sperformerId
	getCurrentActivityPerformerId = sperformerId
End Function

'**********************************************************
' setProcessStarterGuid
' @description: sets the current activity perfomer id to the internal variable sProcessStarterGuid
' @param: nothing
' @return nothing
'**********************************************************
Private Function setProcessStarterGuid
	wfvariables.sProcessStarterGuid.Value = getCurrentActivityPerformerId
End Function

'**********************************************************
' ClearPerformedValuesFromUserTable
' @description: removes all entries in the columns "PerformedBy" and "PerformedAt" from the UserTable
' @param: nothing
' @return nothing
'**********************************************************
Sub ClearPerformedValuesFromUserTable
	debug2File "start - ClearPerformedValuesFromUserTable"
	For i = 0 To wfvariables.recUsers.Count - 1
		wfvariables.recUsers.Item(i).Item("sPerformedBy").Value = ""
		wfvariables.recUsers.Item(i).Item("dPerformedAt").Value = ""
		wfvariables.recUsers.Item(i).Item("sDecision").Value = ""
	Next
	'clear the sorted userlist
	wfvariables.recUsersSorted.ClearList
	debug2File "end - ClearPerformedValuesFromUserTable"	
End Sub

'**********************************************************
' EvaluateOptionResults
' @description: evaluates the different result options
' @param: nothing
' @return 0 if a negative option was selected (e.g. "No approval" or "No release") otherwise a integer value higher than 0
'**********************************************************
Function EvaluateOptionResults
	debug2File "start - EvaluateOptionResults"
	'check the options
	Dim iResult : iResult = 1
	debug2File "Anzahl der Optionen: " & wfvariables.recOptionResults.Count
	For i=0 To wfvariables.recOptionResults.Count - 1
		value = wfvariables.recOptionResults.Item(i).Item("iResultValue").Value
		debug2File vbTab & wfvariables.recOptionResults.Item(i).Item("sResultString").Value
		debug2File vbTab & "Wert: " & value
		iResult = iResult * value	'if one option gots the value 0 the complete 
	Next
	debug2File "EvaluateOptionResults -> " & iResult
	EvaluateOptionResults = iResult
	debug2File "end - EvaluateOptionResults"
End Function





'********************************************************************************************************************
' This class includes all features to handle the access for objects
' Author: A.Buellesbach
'********************************************************************************************************************
Class AccessRights

	'**********************************************************
	' DeleteWriteAccess
	' @description: Deletes the write access for a document
	' @param: sActivity - the name of the current activity
	' @return nothing
	'**********************************************************
	Public Function DeleteWriteAccess(sActivity)
		debug2File "start - DeleteWriteAccess(" & sActivity & ")"
		
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_WriteRights()
		
		If CLng(sObjectId) > 0 Then	
			'Delete write access
			updateField sArchiveName, "DOCUMENT", sObjectName,sObjectId,sFieldName, ""
			
			'get all attachments for current register
'removed for V1.6
'			Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
'			debug2File "DeleteWriteAccess (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
'			If sAttachmentIds <> -1	Then 'in this case we got no attachments defined in the xml configuration file
'				Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
'				Dim ix
'				For ix = 0 To Ubound(aAttachmentIds)
'					sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
'					sFieldName = getInternalName_Attachment_WriteRights()
'					sObjectId = aAttachmentIds(ix)
'					updateField sArchiveName, "DOCUMENT", sObjectName,sObjectId,sFieldName, ""
'				Next
'			End If
					
			'set workflow variable for new documents
			wfvariables.sWriteRights.Value = ""
		
		Else
			debug2File "WARNING: DeleteWriteAccess - document does not exist"
		End If
		
		debug2File "DeleteWriteAccess (" & sActivity & ") to user " & wfvariables.sWriteRights.Value	
		debug2File "end - DeleteWriteAccess(" & sActivity & ")"
	End Function
	
	'**********************************************************
	' DeleteWriteIndexDataAccess
	' @description: Deletes the write access for indexdata for a document
	' @param: sActivity - the name of the current activity
	' @return nothing
	'**********************************************************
	Public Function DeleteWriteIndexDataAccess(sActivity)
		debug2File "start - DeleteWriteIndexDataAccess(" & sActivity & ")"
		
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_WriteIndexDataRights()
		
		If CLng(sObjectId) > 0 Then	
			'Delete write access
			updateField sArchiveName, "DOCUMENT", sObjectName,sObjectId,sFieldName, ""
			
			'get all attachments for current register
			Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
			debug2File "DeleteWriteIndexDataAccess (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
			If CStr(sAttachmentIds) <> CStr(-1)	Then 'in this case we got no attachments defined in the xml configuration file
				Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
				Dim ix
				For ix = 0 To Ubound(aAttachmentIds)
					sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
					sFieldName = getInternalName_Attachment_WriteIndexDataRights()
					sObjectId = aAttachmentIds(ix)
					updateField sArchiveName, "DOCUMENT", sObjectName,sObjectId,sFieldName, ""
				Next
			End If
					
			'set workflow variable for new documents
			wfvariables.sWriteIndexDataRights.Value = ""
		
		Else
			debug2File "WARNING: DeleteWriteIndexDataAccess - document does not exist"
		End If
		
		debug2File "DeleteWriteIndexDataAccess (" & sActivity & ") to user " & wfvariables.sWriteIndexDataRights.Value	
		debug2File "end - DeleteWriteIndexDataAccess(" & sActivity & ")"
	End Function
	
	'**********************************************************
	' SetReadAccess
	' @description: Sets the read access for a documents and attachments to the current user (adds user to write access)
	' @param: sActivity - the name of the current activity
	' @return nothing
	'**********************************************************
	Public Function SetReadAccess(sActivity)
		debug2File "start - SetReadAccess(" & sActivity & ")"
		Dim sCurrentUserGuid : sCurrentUserGuid = thisprocess.CurrentActivity.OwnerId
		If sCurrentUserGuid = "" Then
			debug2File "SetReadAccess (" & sActivity & ") => No User Guid"	
		End If
	
		'Get loginname of user
		Dim sCurrentUser : sCurrentUser = wforganisation.GetOrgObjectById(sCurrentUserGuid).GetAttributeValueByName("Login") & "(u)"
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_ReadRights()
		
		AddToField sArchiveName,"DOCUMENT",sObjectName,sObjectId,sFieldName,sCurrentUser,";"
		
		'get all attachments for current register
		Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
		debug2File "SetReadAccess (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
		If CStr(sAttachmentIds) <> CStr(-1)	Then 'in this case we got no attachments defined in the xml configuration file
			Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
			Dim ix
			For ix = 0 To Ubound(aAttachmentIds)
				sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
				sFieldName = getInternalName_Attachment_ReadRights()
				sObjectId = aAttachmentIds(ix)
				AddToField sArchiveName,"DOCUMENT",sObjectName,sObjectId,sFieldName,sCurrentUser,";"
			Next
		End If
		
		'set workflow variable for new documents: add current user if it is not part of wfvariable
		If (InStr(wfvariables.sReadRights.Value,sCurrentUser) <= 0) Then
			if wfvariables.sReadRights.Value <> "" then
				wfvariables.sReadRights.Value = wfvariables.sReadRights.Value & ";"
			end if
			wfvariables.sReadRights.Value = wfvariables.sReadRights.Value  & sCurrentUser
			debug2File "Current User Added to wfvariables.sReadRights.Value"
		End if
		
		debug2File "SetReadAccess (" & sActivity & ") to user " & wfvariables.sReadRights.Value
		debug2File "end - SetReadAccess(" & sActivity & ")"
	End Function

	'**********************************************************
	' DeleteReadAccess
	' @description: Deletes the read access for a document
	' @param: sActivity - the name of the current activity
	' @return nothing
	'**********************************************************
	Public Function DeleteReadAccess(sActivity)
		debug2File "start - DeleteReadAccess(" & sActivity & ")"
		
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_ReadRights()
		If CLng(sObjectId) > 0 Then
		
			'Delete write access
			updateField sArchiveName, "DOCUMENT", sObjectName,sObjectId,sFieldName, ""
			
			'get all attachments for current register
			Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
			debug2File "DeleteReadAccess (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
			If CStr(sAttachmentIds) <> CStr(-1)	Then 'in this case we got no attachments defined in the xml configuration file
				Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
				Dim ix
				For ix = 0 To Ubound(aAttachmentIds)
					sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
					sFieldName = getInternalName_Attachment_ReadRights()
					sObjectId = aAttachmentIds(ix)
					updateField sArchiveName, "DOCUMENT", sObjectName,sObjectId,sFieldName, ""
				Next
			End If
			
			'set workflow variable for new documents
			wfvariables.sReadRights.Value = ""
		Else
			debug2File "WARNING: DeleteReadAccess - document does not exist"
		End If
		debug2File "DeleteReadAccess (" & sActivity & ") to user " & wfvariables.sReadRights.Value	
		debug2File "end - DeleteReadAccess(" & sActivity & ")"
	End Function

	'**********************************************************
	' SetWriteAccess
	' @description: Sets the write access for documents to the current user (adds user to write access if the user is not in list)
	' @param: sActivity - the name of the current activity
	' @return nothing
	'**********************************************************
	Public Function SetWriteAccess(sActivity)
		debug2File "start - SetWriteAccess(" & sActivity & ")"
		Dim sCurrentUserGuid : sCurrentUserGuid = thisprocess.CurrentActivity.OwnerId
		If sCurrentUserGuid = "" Then
			debug2File "SetWriteAccess (" & sActivity & ") => No User Guid"	
		End If
	
		'Get loginname of user
		Dim sCurrentUser : sCurrentUser = wforganisation.GetOrgObjectById(sCurrentUserGuid).GetAttributeValueByName("Login") & "(u)"
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_WriteRights()
		
		AddToField sArchiveName,"DOCUMENT",sObjectName,sObjectId,sFieldName,sCurrentUser,";"
		
		'get all attachments for current register
'@removed for V 1.6
'		Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
'		debug2File "SetWriteAccess (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
'		If sAttachmentIds <> -1	Then 'in this case we got no attachments defined in the xml configuration file
'			Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
'			Dim ix
'			For ix = 0 To Ubound(aAttachmentIds)
'				sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
'				sFieldName = getInternalName_Attachment_WriteRights()
'				sObjectId = aAttachmentIds(ix)
'				AddToField sArchiveName,"DOCUMENT",sObjectName,sObjectId,sFieldName,sCurrentUser,";"
'			Next
'		End If
			
		'set workflow variable for new documents: add current user if it is not part of wfvariable
		If (InStr(wfvariables.sWriteRights.Value,sCurrentUser) <= 0) Then
			if wfvariables.sWriteRights.Value <> "" then
				wfvariables.sWriteRights.Value = wfvariables.sWriteRights.Value & ";"
			end if
			wfvariables.sWriteRights.Value = wfvariables.sWriteRights.Value  & sCurrentUser
			debug2File "Current User Added to wfvariables.sWriteRights.Value"
		End if
		
		debug2File "SetWriteAccess (" & sActivity & ") to user " & wfvariables.sWriteRights.Value
		debug2File "end - SetWriteAccess(" & sActivity & ")"
	End Function
	
	
	
	'**********************************************************
	' DeleteWriteAccessAttachments
	' @description: Deletes the write access for a document
	' @param: sActivity - the name of the current activity
	' @return nothing
	'**********************************************************
	Public Function DeleteWriteAccessAttachments(sActivity)
		debug2File "start - DeleteWriteAccessAttachments(" & sActivity & ")"
		
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_WriteRights()
		
		If CLng(sObjectId) > 0 Then	
			
			'get all attachments for current register
			Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
			debug2File "DeleteWriteAccessAttachments (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
			If CStr(sAttachmentIds) <> CStr(-1)	Then 'in this case we got no attachments defined in the xml configuration file
				Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
				Dim ix
				For ix = 0 To Ubound(aAttachmentIds)
					sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
					sFieldName = getInternalName_Attachment_WriteRights()
					sObjectId = aAttachmentIds(ix)
					updateField sArchiveName, "DOCUMENT", sObjectName,sObjectId,sFieldName, ""
				Next
			End If
		Else
			debug2File "WARNING: DeleteWriteAccessAttachments - document does not exist"
		End If
		
		debug2File "DeleteWriteAccessAttachments (" & sActivity & ") to user " & wfvariables.sWriteRights.Value	
		debug2File "end - DeleteWriteAccessAttachments(" & sActivity & ")"
	End Function

	'**********************************************************
	' SetWriteAccessAttachments
	' @description: Sets the write access for attachments to the current user (adds user to write access if the user is not in list)
	' @param: sActivity - the name of the current activity
	' @return nothing
	'**********************************************************	
	Public Function SetWriteAccessAttachments (sActivity)
		debug2File "start - SetWriteAccessAttachments(" & sActivity & ")"
		Dim sCurrentUserGuid : sCurrentUserGuid = thisprocess.CurrentActivity.OwnerId
		If sCurrentUserGuid = "" Then
			debug2File "SetWriteAccessAttachments (" & sActivity & ") => No User Guid"	
		End If
	
		'Get loginname of user
		Dim sCurrentUser : sCurrentUser = wforganisation.GetOrgObjectById(sCurrentUserGuid).GetAttributeValueByName("Login") & "(u)"
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_WriteRights()
		
		'get all attachments for current register
		Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
		debug2File "SetWriteAccessAttachments (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
		If CStr(sAttachmentIds) <> CStr(-1)	Then 'in this case we got no attachments defined in the xml configuration file
			Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
			Dim ix
			For ix = 0 To Ubound(aAttachmentIds)
				sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
				sFieldName = getInternalName_Attachment_WriteRights()
				sObjectId = aAttachmentIds(ix)
				AddToField sArchiveName,"DOCUMENT",sObjectName,sObjectId,sFieldName,sCurrentUser,";"
			Next
		End If
			
		debug2File "SetWriteAccessAttachments (" & sActivity & ") to user " & wfvariables.sWriteRights.Value
		debug2File "end - SetWriteAccessAttachments(" & sActivity & ")"
	End Function
	
	'**********************************************************
	' SetWriteIndexDataAccess
	' @description: Sets the write access for indexdata of documents and attachments to the current user (adds user to write access if the user is not in list)
	' @param: nothing
	' @return nothing
	'**********************************************************
	Public Function SetWriteIndexDataAccess(sActivity)
		debug2File "start - SetWriteIndexDataAccess(" & sActivity & ")"
		Dim sCurrentUserGuid : sCurrentUserGuid = thisprocess.CurrentActivity.OwnerId
		If sCurrentUserGuid = "" Then
			debug2File "SetWriteIndexDataAccess (" & sActivity & ") => No User Guid"	
		End If
	
		'Get loginname of user
		Dim sCurrentUser : sCurrentUser = wforganisation.GetOrgObjectById(sCurrentUserGuid).GetAttributeValueByName("Login") & "(u)"
		Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
		Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
		Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
		Dim sFieldName : sFieldName = getInternalName_Document_WriteIndexDataRights()
		
		AddToField sArchiveName,"DOCUMENT",sObjectName,sObjectId,sFieldName,sCurrentUser,";"
		
		'get all attachments for current register
		Dim sAttachmentIds : sAttachmentIds = getAttachmentsBelowVersionRegister(wfvariables.recStructure.iRegisterID.Value) 
		debug2File "SetWriteIndexDataAccess (" & sActivity & ") sAttachmentIds = " &  sAttachmentIds
		If CStr(sAttachmentIds) <> CStr(-1)	Then 'in this case we got no attachments defined in the xml configuration file
			Dim aAttachmentIds : aAttachmentIds = Split(sAttachmentIds,"#")
			Dim ix
			For ix = 0 To Ubound(aAttachmentIds)
				sObjectName = wfvariables.recStructure.sAttachmentInternalName.Value
				sFieldName = getInternalName_Attachment_WriteIndexDataRights()
				sObjectId = aAttachmentIds(ix)
				AddToField sArchiveName,"DOCUMENT",sObjectName,sObjectId,sFieldName,sCurrentUser,";"
			Next
		End If
			
		'set workflow variable for new documents: add current user if it is not part of wfvariable
		If (InStr(wfvariables.sWriteIndexDataRights.Value,sCurrentUser) <= 0) Then
			if wfvariables.sWriteIndexDataRights.Value <> "" then
				wfvariables.sWriteIndexDataRights.Value = wfvariables.sWriteIndexDataRights.Value & ";"
			end if
			wfvariables.sWriteIndexDataRights.Value = wfvariables.sWriteIndexDataRights.Value  & sCurrentUser
			debug2File "Current User Added to wfvariables.sWriteIndexDataRights.Value"
		End if
		
		debug2File "SetWriteIndexDataAccess (" & sActivity & ") to user " & wfvariables.sWriteIndexDataRights.Value
		debug2File "end - SetWriteIndexDataAccess(" & sActivity & ")"
	End Function
End Class



'**********************************************************
' SetDocumentProtectionFlag
' @description: sets the internal flag, to enable document protection (only allows to review and commentate the document)
'**********************************************************
Sub SetDocumentProtectionFlag
	wfvariables.iProtectDocument.Value = 1
End Sub

'**********************************************************
' AddToField
' @description: Adds a fieldvalue to an existing field if the fiels is not part of the string already
' @param: sArchiveName Internal name of archive
' @param: sObjectType Kind of object, e.g. 'DOCUMENT'
' @param: sObjectName Internal Object name
' @param: sObjectId object id
' @param: sFieldName Internal name of return field which should be updated.
' @param: sAddValue Internal name of return field which should be updated.
' @param: sSeparator Separator which will be added between old and new value
' @return "Value1|Value2|..." String with values of the returnfields, separated by pipe. Returns empty string in case no value is found or an error occurs.
'**********************************************************
Sub AddToField(sArchiveName,sObjectType,sObjectName,sObjectId,sFieldName,sAddValue,sSeparator)
	debug2File "start - AddToField(" & sArchiveName & "," & sObjectType & "," & sObjectName & "," & sObjectId &"," & sFieldName & "," & sAddValue & "," & sSeparator & ")"
	'Set writerights for document
	Dim sValue : sValue = ""
	If sObjectId <> 0 Then
		sValue = getObjectFields(sArchiveName,sObjectType,sObjectName,sObjectId,sFieldName)	
		debug2File "AddToField Existing Value = " &  sValue
		'check if sAddValue is part of sValue already
		If (InStr(sValue,sAddValue) <= 0) Then
			debug2File "AddToField Existing sAddValue = " &  sAddValue
			If sValue <> "" Then
				sValue = sValue & sSeparator 
			End If
			sValue = sValue & sAddValue
			updateField sArchiveName, sObjectType, sObjectName,sObjectId,sFieldName, sValue
		Else
			debug2File "AddToField Value is part of string "
		End If
	Else
		debug2File "AddToField Field not updated because ObjectId was 0"
	End If
	debug2File "end - AddToField"
End Sub





'**********************************************************
' checkActivityFeatures
' @description: checks if a feature should be activated
' @param: Event (String) - should be "Start" for StartActivity or "End" for EndActivity
' @return
'**********************************************************
Function checkActivityFeatures (sEvent)
	debug2File "start - checkActivityFeatures"
	For ux = 0 To wfvariables.recConfigActivityFeatures.Count - 1
		debug2File "Event: " & wfvariables.recConfigActivityFeatures.Item(ux).Item("sEvent").Value & " Name: " & wfvariables.recConfigActivityFeatures.Item(ux).Item("sName").Value			   
	Next
	
	For xi = 0 To wfvariables.recConfigActivityFeatures.Count - 1
		If LCase( wfvariables.recConfigActivityFeatures.Item(xi).Item("sEvent").Value ) = LCase( sEvent ) Then 'only check the features for the current event
			debug2File vbTab & "Check Feature " & wfvariables.recConfigActivityFeatures.Item(xi).Item("sName").Value & " for a condition"
			'feature found, now check if a condition exists (the feature + the condition is defined as CDATA code in the configuration file
			If wfvariables.recConfigActivityFeatures.Item(xi).Item("sCondition").Value <> "" Then
				Execute wfvariables.recConfigActivityFeatures.Item(xi).Item("sCondition").Value
			Else
				Execute "activateFeature """ & wfvariables.recConfigActivityFeatures.Item(xi).Item("sName").Value & """"
			End If			
		End If
	Next
	debug2File "end - checkActivityFeatures"	
End Function

'**********************************************************
' checkWorkflowFeatures
' @description: checks if a feature should be activated
' @param: Event (String) - should be "Start" for StartActivity or "End" for EndActivity
' @return
'**********************************************************
Function checkWorkflowFeatures (sEvent)
	debug2File "start - checkWorkflowFeatures"
	For i = 0 To wfvariables.recConfigWorkflowFeatures.Count - 1		   
		If LCase( wfvariables.recConfigWorkflowFeatures.Item(i).Item("sEvent").Value ) = LCase( sEvent ) Then 'only check the features for the current event
			debug2File vbTab & "Check Feature " & wfvariables.recConfigWorkflowFeatures.Item(i).Item("sName").Value & " for a condition"
			'feature found, now check if an condition exists
			If wfvariables.recConfigWorkflowFeatures.Item(i).Item("sCondition").Value <> "" Then
				Execute wfvariables.recConfigWorkflowFeatures.Item(i).Item("sCondition").Value
			Else
				Execute "activateFeature """ & wfvariables.recConfigWorkflowFeatures.Item(i).Item("sName").Value & """"
			End If
		End If
	Next
	debug2File "end - checkWorkflowFeatures"	
End Function 

'**********************************************************
' activateFeature
' @description: activates a feature
' @param: sFeatureName (String) name of the feature
' @return: nothing
'**********************************************************
Function activateFeature (sFeatureName)
debug2File vbTab & vbTab & "activating..."
Dim rights 'class AccessRights

	If LCase(sFeatureName) = LCase("updateNextAuthorField") Then
		debug2File vbTab & vbTab & "activate updateNextAuthorField"
		updateNextAuthorField
	End If
	If LCase(sFeatureName) = LCase("createHistoryDocument") Then
		debug2File vbTab & vbTab & "activate createHistoryDocument"
		createHistoryDocument
	End If
	If sFeatureName = "ManipulateUsersTableForRevision" Then
		debug2File vbTab & vbTab & "activate ManipulateUsersTableForRevision"
		ManipulateUsersTableForRevision
	End If
	If sFeatureName = "MapToArchive" Then
		debug2File vbTab & vbTab & "activate MapToArchive"
		mapToArchive wfvariables.recStructure.iDocumentID.Value
	End If
	If sFeatureName = "UpdateHistoryTable" Then
		debug2File vbTab & vbTab & "activate UpdateHistoryTable"
		updateHistoryTable wfvariables.recStructure.iFolderID.Value
	End If	
	If sFeatureName = "Authentication" Then
		debug2File vbTab & vbTab & "activate Authentication"
		wfvariables.bAuthentication.Value = True
	End If
	If sFeatureName = "SetWriteAccess" Then
		debug2File vbTab & vbTab & "activate SetWriteAccess"
		Set rights = New AccessRights
		rights.SetWriteAccess wfvariables.sCurrentActivity.Value
	End If
	If sFeatureName = "DeleteWriteAccess" Then
		debug2File vbTab & vbTab & "activate DeleteWriteAccess"
		Set rights = New AccessRights
		rights.DeleteWriteAccess wfvariables.sCurrentActivity.Value		
	End If
	If sFeatureName = "SetReadAccess" Then
		debug2File vbTab & vbTab & "activate SetReadAccess"
		Set rights = New AccessRights
		rights.SetReadAccess wfvariables.sCurrentActivity.Value		
	End If
	If sFeatureName = "DeleteReadAccess" Then
		debug2File vbTab & vbTab & "activate DeleteReadAccess"		
		Set rights = New AccessRights
		rights.DeleteReadAccess wfvariables.sCurrentActivity.Value				
	End If
	If sFeatureName = "SetWriteIndexDataAccess" Then
		debug2File vbTab & vbTab & "activate SetWriteIndexDataAccess"
		Set rights = New AccessRights
		rights.SetWriteIndexDataAccess wfvariables.sCurrentActivity.Value		
	End If
	If sFeatureName = "DeleteWriteIndexDataAccess" Then
		debug2File vbTab & vbTab & "activate SetWriteIndexDataAccess"
		Set rights = New AccessRights
		rights.DeleteWriteIndexDataAccess wfvariables.sCurrentActivity.Value				
	End If
	If sFeatureName = "SetWriteAccessAttachments" Then
		debug2File vbTab & vbTab & "activate SetWriteAccessAttachments"
		Set rights = New AccessRights
		rights.SetWriteAccessAttachments wfvariables.sCurrentActivity.Value				
	End If
	If sFeatureName = "DeleteWriteAccessAttachments" Then
		debug2File vbTab & vbTab & "activate DeleteWriteAccessAttachments"
		Set rights = New AccessRights
		rights.DeleteWriteAccessAttachments wfvariables.sCurrentActivity.Value				
	End If		
	If sFeatureName = "setDocumentStatus_0" Then
		debug2File vbTab & vbTab & "activate setDocumentStatus_0"
		setDocumentStatus_0
	End If
	If sFeatureName = "setDocumentStatus_1" Then
		debug2File vbTab & vbTab & "activate setDocumentStatus_1"
		setDocumentStatus_1
	End If
	If sFeatureName = "setDocumentStatus_2" Then
		debug2File vbTab & vbTab & "activate setDocumentStatus_2"
		setDocumentStatus_2
	End If
	If sFeatureName = "setDocumentStatus_3" Then
		debug2File vbTab & vbTab & "activate setDocumentStatus_3"
		setDocumentStatus_3
	End If
	If sFeatureName = "setDocumentStatus_4" Then
		debug2File vbTab & vbTab & "activate setDocumentStatus_4"
		setDocumentStatus_4
	End If
	If sFeatureName = "setPreviousDocumentStatus_0" Then
		debug2File vbTab & vbTab & "activate setPreviousDocumentStatus_0"
		setPreviousDocumentStatus_0
	End If
	If sFeatureName = "setPreviousDocumentStatus_1" Then
		debug2File vbTab & vbTab & "activate setPreviousDocumentStatus_1"
		setPreviousDocumentStatus_1
	End If
	If sFeatureName = "setPreviousDocumentStatus_2" Then
		debug2File vbTab & vbTab & "activate setPreviousDocumentStatus_2"
		setPreviousDocumentStatus_2
	End If
	If sFeatureName = "setPreviousDocumentStatus_3" Then
		debug2File vbTab & vbTab & "activate setPreviousDocumentStatus_3"
		setPreviousDocumentStatus_3
	End If
	If sFeatureName = "setPreviousDocumentStatus_4" Then
		debug2File vbTab & vbTab & "activate setPreviousDocumentStatus_4"
		setPreviousDocumentStatus_4
	End If
	If sFeatureName = "setPreviousDocumentInvalidationDate" Then
		debug2File vbTab & vbTab & "activate setPreviousDocumentInvalidationDate"
		setPreviousDocumentInvalidationDate
	End If	
	If sFeatureName = "ConvertToPDF" Then
		debug2File vbTab & vbTab & "activate ConvertToPDF"
		
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		Dim sFile : sFile = ""
		'converts the document to pdf
		If wfvariables.iConversionType.Value = 1 Then
			'Neevia
			sTempFile = storeObjectInCacheByID (wfvariables.recStructure.iDocumentID.Value, 0)
			sTempFile2 = oFSO.getParentFolderName( sTempFile) & "\" & oFSO.GetTempName & "." & oFSO.GetExtensionName( sTempFile )
			oFSO.CopyFile sTempFile, sTempFile2
			debug2file "convert Neevia DOC: " & sTempFile2		
			
			sPDFType = "PDFA"
			Dim sTempFile3 : sTempFile3 = convertWithDocuConverter( sTempFile2, sPDFType )
			
			debug2file "convert Neevia PDF: " & sTempFile3
			sTempFile2 = sTempFile3 & ".pdf"
			
			oFSO.CopyFile sTempFile3, sTempFile2
			debug2file "convert Neevia PDF: " & sTempFile2
			sFile = sTempFile2
			
		Else 'default conversion should be the os conversion
			sFile = storeObjectInCacheByID (wfvariables.recStructure.iDocumentID.Value, 1)
		End If
		
		'add a new variant
		addActiveVariant wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, sFile
		
		If oFSO.FileExists (sTempFile) = True Then 'delete the sTempFile
			oFSO.DeleteFile sTempFile
		End If
		If oFSO.FileExists (sTempFile2) = True Then 'delete the sTempFile2
			oFSO.DeleteFile sTempFile2
		End If
		If oFSO.FileExists (sTempFile3) = True Then 'delete the sTempFile3
			oFSO.DeleteFile sTempFile3
		End If				
		If oFSO.FileExists (sFile) = True Then 'delete the file
			oFSO.DeleteFile sFile
		End If
		Set oFSO = Nothing
	End If
	If sFeatureName = "ExitWorkflowLoop" Then
		debug2File vbTab & vbTab & "activate ExitWorkflowLoop"
		wfvariables.bCorrect.Value = 2
	End If
	If sFeatureName = "CreateRevision" Then
		debug2File vbTab & vbTab & "activate CreateRevision"
		CreateRevision()
	End If	
	If sFeatureName = "CreateTemplateRevision" Then
		debug2File vbTab & vbTab & "activate CreateRevision"
		CreateTemplateRevision()
	End If		
	If sFeatureName = "InitFromArchive" Then
		debug2File vbTab & vbTab & "activate InitFromArchive"
		initFromArchive wfvariables.recStructure.iDocumentID.Value
	End If
	If sFeatureName = "addPerformerToUserTable" Then
		debug2File vbTab & vbTab & "activate addPerformerToUserTable"
		addPerformerToUserTable wfvariables.sCurrentActivity.Value
	End If	
	If sFeatureName = "Debug2File" Then 'a test feature ;-)
		debug2File vbTab & vbTab & "activate Debug2File"
		debug2File vbTab & vbTab & "*************************DEBUG2FILE***************************"
		debug2File vbTab & vbTab & "*************************DEBUG2FILE***************************"
		debug2File vbTab & vbTab & "*************************DEBUG2FILE***************************"
		debug2File vbTab & vbTab & "*************************DEBUG2FILE***************************"
		debug2File vbTab & vbTab & "*************************DEBUG2FILE***************************"
	End If
	If sFeatureName = "DeleteActiveVariant" Then
		debug2File vbTab & vbTab & "activate DeleteActiveVariant, iPDFID: " & wfvariables.recStructure.iPDFID.Value & ", iOldDocumentID: " & wfvariables.recStructure.iOldDocumentID.Value
		
		processID = thisprocess.ProcessId
		ExecuteSQL "update oswfdrel set object_id = 0 where object_id = " & wfvariables.recStructure.iPDFID.Value & " and processid = '" & processID & "'"
		
		'setActiveVariant wfvariables.recStructure.iPDFID.Value, wfvariables.recStructure.iOldDocumentID.Value, wfvariables.recStructure.iDocumentType.Value
		
		
		
		deleteDocument wfvariables.recStructure.iPDFID.Value , wfvariables.recStructure.sDocumentInternalName.Value
		
		ExecuteSQL "delete from oswfdrel where object_id = 0 and processid = '" & processID & "'"
		
		'STDdeleteDocumentVariant wfvariables.recStructure.iPDFID.Value, wfvariables.recStructure.iDocumentType.Value, wfvariables.recStructure.iOldDocumentID.Value
		'remember pdf variant
		wfvariables.recStructure.iPDFID.Value = 0
	End If
	If sFeatureName = "UpdateAttachmentTable" Then
		debug2File vbTab & vbTab & "activate UpdateAttachmentTable"
		updateAttachmentTable 
	End If
	If sFeatureName = "setInvalidation" Then
		debug2File vbTab & vbTab & "activate setInvalidation"
		setInvalidation 
	End If	
	If sFeatureName = "DeleteAttachments" Then
		debug2File vbTab & vbTab & "activate DeleteAttachments"
		deleteAttachments
	End If
	If sFeatureName = "InitializeDistribute" Then
		debug2File vbTab & vbTab & "activate InitializeDistribute"
		InitializeDistribute
	End If	
	If sFeatureName = "InitializeInvalidation" Then
		debug2File vbTab & vbTab & "activate InitializeInvalidation"
		InitializeInvalidation
	End If
	If sFeatureName = "InitializeTemplateInvalidation" Then
		debug2File vbTab & vbTab & "activate InitializeTemplateInvalidation"
		InitializeTemplateInvalidation
	End If
	If LCase(sFeatureName) = LCase("InitializeModifyParticipants") Then
		debug2File vbTab & vbTab & "activate InitializeModifyParticipants"
		InitializeModifyParticipants
	End If		
	If sFeatureName = "startInvalidationWorkflow" Then
		debug2File vbTab & vbTab & "activate startInvalidationWorkflow"
		startInvalidationWorkflow
	End If
	If LCase(sFeatureName) = LCase("InitializeModifyAuthor") Then
		debug2File vbTab & vbTab & "activate InitializeModifyAuthor"
		InitializeModifyAuthor
	End If		
	If LCase(sFeatureName) = LCase("startModifyAuthorWorkflow") Then
		debug2File vbTab & vbTab & "activate startModifyAuthorWorkflow"
		startModifyAuthorWorkflow
	End If	
	If sFeatureName = "startRevisionWorkflow" Then
		debug2File vbTab & vbTab & "activate startRevisionWorkflow"
		startRevisionWorkflow
	End If
	If sFeatureName = "startTrainerWorkflow" Then
		debug2File vbTab & vbTab & "activate startTrainerWorkflow"
		startTrainerWorkflow
	End If		
	If sFeatureName = "startCheckRevisionWorkflow" Then
		debug2File vbTab & vbTab & "activate startCheckRevisionWorkflow"
		startCheckRevisionWorkflow
	End If		
	If sFeatureName = "startModifyRecipientsWorkflow" Then
		debug2File vbTab & vbTab & "activate startModifyRecipientsWorkflow"
		startModifyRecipientsWorkflow
	End If		
	If sFeatureName = "startModifyParticipantsWorkflow" Then
		debug2File vbTab & vbTab & "activate startModifyParticipantsWorkflow"
		startModifyParticipantsWorkflow
	End If		
	If sFeatureName = "InitializeCheckRevision" Then
		debug2File vbTab & vbTab & "activate InitializeCheckRevision"
		InitializeCheckRevision
	End If
	If sFeatureName = "renewRevisionDate" Then
		debug2File vbTab & vbTab & "activate renewRevisionDate"
		renewRevisionDate
	End If
	If sFeatureName = "executeCode" Then
		debug2File vbTab & vbTab & "activate executeCode"
	End If
	If sFeatureName = "InitializeModifyResponsibles" Then
		debug2File vbTab & vbTab & "activate InitializeModifyResponsibles"
		InitializeModifyResponsibles
	End If
	If sFeatureName = "InitializeModifyRecipients" Then
		debug2File vbTab & vbTab & "activate InitializeModifyRecipients"
		InitializeModifyRecipients
	End If	
	If sFeatureName = "SynchronizeData" Then
		debug2File vbTab & vbTab & "activate SynchronizeData"
		If wfvariables.recStructure.iDocumentID.Value > 0 Then
			syncedFile = SynchronizeData (wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value)
			If syncedFile <> "" Then	'Bugfix: e.g. for *.dotx documents the synchronizedata job does not work
				ReplaceDocument wfvariables.recStructure.iDocumentID.Value, syncedFile
			End If
		Else
			debug2File vbTab & vbTab & "Warning: no document available to perform a data synchronization"
		End If
	End If
	If sFeatureName = "getUpdatedDistributionRegisters" Then
		debug2File vbTab & vbTab & "activate getUpdatedDistributionRegisters"
		getUpdatedDistributionRegisters
	End If
	If sFeatureName = "getAccordingDistributionObject" Then
		debug2File vbTab & vbTab & "activate getAccordingDistributionObject"
		getAccordingDistributionObject
	End If
	If sFeatureName = "updateDistributionRecipients" Then
		debug2File vbTab & vbTab & "activate updateDistributionRecipients"
		updateDistributionRecipients wfvariables.iDistributionObjectID.Value
	End If		
	If sFeatureName = "createTrainingSurvey" Then
		debug2File vbTab & vbTab & "activate createTrainingSurvey"
		createTrainingSurvey
	End If
'	If sFeatureName = "loadAttachments" Then
'		debug2File vbTab & vbTab & "activate loadAttachments"
'		loadAttachments
'	End If	
	If sFeatureName = "setPersonRegister" Then 'Distribute: Schreibt den Schulungsstatus und Kommentar zurck auf das Personenregister in der Schulungsbersicht
		debug2File vbTab & vbTab & "activate setPersonRegister"
		setPersonRegister
	End If	
	If sFeatureName = "addNewPerformerToUserTable" Then
		debug2File vbTab & vbTab & "activate addNewPerformerToUserTable"
		addNewPerformerToUserTable
	End If
	If sFeatureName = "InitializeArchiveStructure" Then
		debug2File vbTab & vbTab & "activate InitializeArchiveStructure"
		InitializeArchiveStructure
	End If	
	If sFeatureName = "setTrainingStatus" Then
		debug2File vbTab & vbTab & "activate setTrainingStatus"
		setTrainingStatus
	End If
	If sFeatureName = "checkRevisionForLinkedDocuments" Then
		debug2File vbTab & vbTab & "activate checkRevisionForLinkedDocuments"
		checkRevisionForLinkedDocuments
	End If
	If sFeatureName = "setProcessStarterGuid" Then
		debug2File vbTab & vbTab & "activate setProcessStarterGuid"
		setProcessStarterGuid
	End If	
	If sFeatureName = "setDocumentProtection" Then
		debug2File vbTab & vbTab & "activate setDocumentProtection"
		Set oUtil = New OfficeUtilities
		oUtil.setDocumentProtection
	End If
	If sFeatureName = "removeDocumentProtection" Then
		debug2File vbTab & vbTab & "activate removeDocumentProtection"
		Set oUtil = New OfficeUtilities
		oUtil.removeDocumentProtection
	End If
	If sFeatureName = "CheckForDocumentRevisions" Then
		debug2File vbTab & vbTab & "activate CheckForDocumentRevisions"
		Set oUtil = New OfficeUtilities
		oUtil.CheckForDocumentRevisions
	End If
	If sFeatureName = "ResetHint" Then
		debug2File vbTab & vbTab & "activate ResetHint"
		wfvariables.sHint.Value = ""
	End If
	If sFeatureName = "sendEmailToCurrentPerformer" Then
		debug2File vbTab & vbTab & "activate sendEmailToCurrentPerformer"
		sendEmailToCurrentPerformer	
	End If
	If sFeatureName = "sendEmailToTrainer" Then
		debug2File vbTab & vbTab & "activate sendEmailToTrainer"
		sendEmailToTrainer	
	End If	
	If sFeatureName = "CalculateNextTrainingDate" Then
		debug2File vbTab & vbTab & "activate CalculateNextTrainingDate"
		CalculateNextTrainingDate	
	End If		
End Function

'**********************************************************
' getObjectFields
' @description: Reads the field values from an object. All field and object names are internal names.
' @param: sReturnFields Internal name of return field (separated by semicolon).
' @param: sObjectName Internal Object name
' @param: sObjecttypeName Kind of object, e.g. 'DOCUMENT'
' @param: sArchiveName Internal name of archive
' @return "Value1|Value2|..." String with values of the returnfields, separated by pipe. Returns empty string in case no value is found or an error occurs.
'**********************************************************
Function getObjectFields (sArchiveName, sObjecttypeName, sObjectName, sObjectId, sReturnFields)
	debug2file "start - getObjectFields ( " & sArchiveName & "," & sObjecttypeName & "," & sObjectName & "," & sObjectId & "," & sReturnFields & ")" 
	getObjectFields = ""
	

	Dim sXML : sXML = "" 
	sXML = sXML & "<DMSQuery request_type='HOL'>" 
	sXML = sXML & "<Archive internal_name='" & sArchiveName & "'>" 
	sXML = sXML & "<ObjectType internal_name='" & sObjectName & "' type='" & sObjecttypeName & "'>" 
	sXML = sXML & "	<Fields field_schema='DEF'>" 
	aReturnFields=Split(sReturnFields,"|")
	for i=0 to Ubound (aReturnFields)
			sXML = sXML & "		<Field internal_name='" & aReturnFields(i) & "'/>"		
	Next
	sXML = sXML & "	</Fields>"
	sXML = sXML & "<Conditions>"
	sXML = sXML & "<ObjectID>" & sObjectId & "</ObjectID>"
	sXML = sXML & "</Conditions>"
	sXML = sXML & "</ObjectType>" 
	sXML = sXML & "</Archive>" 
	sXML = sXML & "</DMSQuery>"
		
'	oJob.AddInParam "Flags", 16, 2
'	oJob.AddInParam "XML", xmlStr, 6
'	Dim iRet : iRet = oJob.Execute()

	Dim RC : Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams	

	Dim dom: Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML") = dom 
	
	Dim iRet : iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	debug2file "getObjectFields() iRet =" & iRet
	
	If iRet = 0 Then
		'Dim sFileName : sFileName = Split(oJob.GetOutFiles,";") (0)
		Dim sFileName : sFileName = PrmOut.Value("$Job$Files$")
		debug2file "getObjectFields() => sFileName: " & sFileName
		sFileName = Mid(sFileName,2,Len(sFileName)-2)
		debug2file "getObjectFields() => sFileName: " & sFileName
		
		Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		
		Dim values : values = ""		
		If True = oXmlDoc.load(sFileName)  Then
			xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/Fields"
			Dim oNode : Set oNode = oXmlDoc.selectSingleNode(xpath)	
			for j=0 to Ubound(aReturnFields)
				if values <> "" then 
					values = values & "|"
				end if 
				debug2file "aReturnFields(j) = " & aReturnFields(j)
				sField = oNode.selectSingleNode( "Field[@internal_name='" & aReturnFields(j) & "']" ).Text
				values = values & sField
				iFound = iFound + 1									
			next		
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sFileName) = True Then 'delete the file
			oFSO.DeleteFile sFileName
		End If
		
		'clean up
		Set oFSO = Nothing		
		
		getObjectFields=values	
		Set oXmlDoc = Nothing	
	End If	
	debug2file "end - getObjectFields = " & getObjectFields		
End Function

'**********************************************************
' CalculateNextTrainingDate
' @description: calculates the next training date depending
' @param: nothing
' @return -
'**********************************************************
Function CalculateNextTrainingDate
	Dim today
	today = Date
	nextDate = DateAdd(wfvariables.sTrainingUnit.value, wfvariables.sTrainingInterval.value, today)
	wfvariables.sTrainingNextDate.Value = nextDate
End Function

'**********************************************************
' updateField
' @description: Updates the field values from an object. All field and object names are internal names.
' @param: sArchiveName Internal name of archive.
' @param: sObjectName Internal name of object.
' @param: sObjectId ObjectId.
' @param: sFieldName Internal name of field.
' @param: sFieldValue Field value.
' @return -
'**********************************************************
Public Sub updateField(sArchiveName, sObjectKind, sObjectName, sObjectId, sFieldName, sFieldValue)
	debug2file "start - updateField("& sArchiveName & "," & sObjectKind & "," & sObjectName & "," & sObjectId & "," & sFieldName & "," & sFieldValue & ")"
	
	Dim xmlStr : xmlStr = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & sArchiveName & "'>" &_
	"<ObjectType internal_name='" & sObjectName & "' type='"& sObjectKind &"'>" &_
	"<Object object_id='" & sObjectId & "'>" &_
	"<Fields>" &_
	"<Field internal_name='" &sFieldName& "'>" & convertToValidXML(sFieldValue) & "</Field>" &_
	"</Fields>" &_
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
	
	Dim RC : Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
'	oJob.AddInParam "Options", "CHECKREADONLY=0;REPLACETABLEFIELDS=1;CHECKCATALOGUE=0;TRUNCATEVALUES=1", 1
'	oJob.AddInParam "Flags", 16, 2
'	oJob.AddInParam "XML", xmlStr, 6
'	Dim iRet : iRet = oJob.Execute()

	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams	
	
	Dim dom : Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(xmlStr) 	
	PrmIn.Value("Flags") = 16
	debug2file "UserId: " & wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	PrmIn.Value("Options") = "CHECKREADONLY=0;REPLACETABLEFIELDS=1;CHECKCATALOGUE=0;TRUNCATEVALUES=1"
	
	Dim iRet : iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
	debug2file vbTab & "updateValues() iRet =" & iRet
	
	debug2file "end - updateField()"
End Sub

'**********************************************************
' updateNextAuthorField
' @description: updates the field 'next author'
' @param: none
' @return: nothing
'**********************************************************
Function updateNextAuthorField
	Dim sArchiveName : sArchiveName = wfvariables.recStructure.sFolderInternalName.Value
	Dim sObjectName : sObjectName = wfvariables.recStructure.sDocumentInternalName.Value
	Dim sObjectId : sObjectId = wfvariables.recStructure.iDocumentID.Value
	Dim sFieldName : sFieldName = getInternalName_Document_NextAuthor
	
	Dim sFieldValue : sFieldValue = ""
	sFieldValue = wfvariables.oNextAuthor.Item(0).Item("Name").value
	
	updateField sArchiveName, "DOCUMENT", sObjectName, sObjectId, sFieldName, sFieldValue
End Function


'**********************************************************
' getWorkflowID
' @description: gets the FamilyID of the given workflowname
' @param: sWorkflowName (String) - the name of the workflow for which the FamiliyID should be returned
' @return: the FamilyID (string)
'**********************************************************
Function getWorkflowID(sWorkflowName)
	debug2File "start - getWorkflowID"
	
	Dim RC : Set RC = RunningContext
	
	Dim PrmIn : Set PrmIn = RC.NewJobsParams
	Dim PrmOut : Set PrmOut = RC.NewJobsParams
	PrmIn.Value("Flags") = 48
	PrmIn.Value("OrganisationId") = wforganisation.id
	PrmIn.Value("UserId") = wforganisation.GetOrgObjectsByName("osservice").Item(0).Id 'wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("ClientTypeId") = "DB928B6631304CFC8D30B1B4FE67679B"
	
	lRet = RC.Jobs.wfm.GetWorkflowList(PrmIn, PrmOut)
	
	If lRet = 0 Then
		Dim oDOMDocument : Set oDOMDocument = CreateObject("MSXML2.DOMDocument")
		oDOMDocument.load(PrmOut.Value("Workflows"))

		Set oNodes = oDOMDocument.selectNodes("Workflows/Workflow")

		For i=0 To oNodes.length - 1
			sModelName = oNodes.item(i).attributes.getNamedItem("ModelName").text
			If Left(sModelName, Len(sWorkflowName)) = sWorkflowName Then
				debug2File vbTab & "getWorkflowID successful..." 
				debug2File vbTab & "Return: " & oNodes.item(i).attributes.getNamedItem("FamilyId").text
				getWorkflowID = oNodes.item(i).attributes.getNamedItem("FamilyId").text
				Exit For
			End If								
		Next
	Else
		debug2file "Error: getWorkflowID failed..."
	End If
	debug2File "end -  getWorkflowID"
End Function

'**********************************************************
' completeWorkItem (not finalized)
' @description: completes the work item and forwards the workitem
' @param: 
' @return: 
'**********************************************************
Function completeWorkItem(workItemId, documentID, documentType)
	debug2File "start - completeWorkItem"
	
'	Dim RC : Set RC = RunningContext
	
'	Dim PrmIn : Set PrmIn = RC.NewJobsParams
'	Dim PrmOut : Set PrmOut = RC.NewJobsParams
	
'	PrmIn.Value("UserId") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")  'wforganisation.GetOrgObjectsByName("osservice").Item(0).Id
'	PrmIn.Value("WorkItemId") = workItemId
'	PrmIn.Value("ActionType") = "SEND_BUTTON"
'	PrmIn.Value("SendTo") = ""
'	PrmIn.Value("ClientTypeId") = "DB928B6631304CFC8D30B1B4FE67679B"
'	PrmIn.Value("Flags") = 48
'	PrmIn.Value("OrganisationId") = wforganisation.id
	
	
'    Dim xmlStr : xmlStr = "<File><Docs>"
'    xmlStr = xmlStr & "<Doc Id=""" & documentID & """ Type=""" & documentType & """ Workspace=""1"" Location=""1"" Moveable=""0"" Deleteable=""0""/>"     
'    xmlStr = xmlStr & "</Docs></File>"
    
'    Dim xmlStrPara : xmlStrPara = "<Parameters>"
'    xmlStrPara = xmlStrPara & "<Parameter DataField="/>"     
'    xmlStrPara = xmlStrPara & "</Parameters>"
	
'	Set dom = CreateObject("MSXML.DOMDocument")
'    dom.loadXML(xmlStr)
'    PrmIn.Value("File") = dom
    
'    Set dom2 = CreateObject("MSXML.DOMDocument")
'    dom2.loadXML(xmlStrPara)
'    PrmIn.Value("Parameters") = dom2
    
    

	debug2File "end -  completeWorkItem"
End Function

'**********************************************************
' AdminSuspendProcess 
' @description: suspends a process
' @param: processId - the id of the process which should be suspended
' @return: nothing
'**********************************************************
Function AdminSuspendProcess (processId)
debug2File "start -  AdminSuspendProcess(" & processId & ")"
	
	Dim RC : Set RC = RunningContext
	
	Dim PrmIn : Set PrmIn = RC.NewJobsParams
	Dim PrmOut : Set PrmOut = RC.NewJobsParams
	
	PrmIn.Value("UserId") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")  'wforganisation.GetOrgObjectsByName("osservice").Item(0).Id
	PrmIn.Value("ProcessId") = processId

	lRet = RC.Jobs.wfm.AdminSuspendProcess(PrmIn, PrmOut)
	debug2File vbTab & "Returnvalue: " & lRet
	
debug2File "end -  AdminSuspendProcess"	
End Function

Function AdminDeleteProcesses (processId)
debug2File "start -  AdminDeleteProcesses(" & processId & ")"
	
	Dim RC : Set RC = RunningContext
	
	Dim PrmIn : Set PrmIn = RC.NewJobsParams
	Dim PrmOut : Set PrmOut = RC.NewJobsParams
	
	PrmIn.Value("OrganisationId") = wforganisation.id
	PrmIn.Value("Processes") = processId

	lRet = RC.Jobs.wfm.AdminDeleteProcesses(PrmIn, PrmOut)
	debug2File vbTab & "Returnvalue: " & lRet
	
debug2File "end -  AdminDeleteProcesses"	
End Function

'**********************************************************
' AdminTerminateProcess 
' @description: terminates a process
' @param: processId - the id of the process which should be terminated
' @return: nothing
'**********************************************************
Function AdminTerminateProcess (processId)
debug2File "start -  AdminTerminateProcess(" & processId & ")"
	
	Dim RC : Set RC = RunningContext
	
	Dim PrmIn : Set PrmIn = RC.NewJobsParams
	Dim PrmOut : Set PrmOut = RC.NewJobsParams
	
	PrmIn.Value("UserId") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")  'wforganisation.GetOrgObjectsByName("osservice").Item(0).Id
	PrmIn.Value("ProcessId") = processId

	RC.Jobs.wfm.AdminTerminateProcess PrmIn, PrmOut
		
debug2File "end -  AdminTerminateProcess"	
End Function

'**********************************************************
' AdminTerminateProcess 
' @description: terminates an activity
' @param: RActivityID - the id of the activity
' @return: nothing
'**********************************************************
Function AdminTerminateActivity (RActivityID)
debug2File "start -  AdminTerminateActivity(" & RActivityID & ")"
	
	Dim RC : Set RC = RunningContext
	
	Dim PrmIn : Set PrmIn = RC.NewJobsParams
	Dim PrmOut : Set PrmOut = RC.NewJobsParams
	
	PrmIn.Value("UserId") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")  'wforganisation.GetOrgObjectsByName("osservice").Item(0).Id
	PrmIn.Value("RActivityID") = RActivityID

	iRet = RC.Jobs.wfm.AdminTerminateActivity (PrmIn, PrmOut)
	debug2File vbTab & "Result: " & iRet
		
debug2File "end -  AdminTerminateActivity"	
End Function

'**********************************************************
' startInvalidationWorkflow
' @description: starts the invalidation workflow
' @param:   nothing
' @return: nothing
'**********************************************************
Function startInvalidationWorkflow
	sGUID = getCurrentActivityPerformerId
	If sGUID = "" Then
		sGUID = wforganisation.GetOrgObjectsByName("Controlled_Documents_QM").Item(0).Id
		debug2File "Found no valid assignee. Assign the invalidation to the default QM (" & sGUID & ") role." 
	End If
	startWorkflow QM_WF_INVALIDATION, "sActivityUserGuids", sGUID, wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value	
End Function

'**********************************************************
' startCheckRevisionWorkflow
' @description: starts the check revision workflow
' @param:   nothing
' @return: nothing
'**********************************************************
Function startCheckRevisionWorkflow
	startWorkflow QM_WF_CHECK_REVISION, "", "", wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value
End Function

'**********************************************************
' startCheckRevisionForLinkedDocumentsWorkflow
' @description: starts the check revision workflow
' @param:   sHint (String) - a note, that will be displayed in the check revision workflow
' @param:   iDocumentID (String) - the ID of the document which should be checked
' @param:   iDocumentType (String) - the Type of the document which should be checked
' @return: nothing
'**********************************************************
Function startCheckRevisionForLinkedDocumentsWorkflow (sHint, iDocumentID, iDocumentType)
	startWorkflow QM_WF_CHECK_REVISION, "sHint", sHint, iDocumentID, iDocumentType
End Function

'**********************************************************
' startRevisionWorkflow
' @description: starts the revision workflow
' @param: nothing
' @return: nothing
'**********************************************************
Function startRevisionWorkflow
	startWorkflow QM_WF_REVISION, "sHint", "StandardWF;;;StartedByCheckRevision;;;Dieser Workflow wurde durch den Prozess 'Revisionierung berprfen' gestartet.", wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value
End Function

'**********************************************************
' startTrainerWorkflow
' @description: starts a workflow for each trainer
' @param: nothing
' @return: nothing
'**********************************************************
Function startTrainerWorkflow
	startWorkflow QM_WF_MANAGE_TRAINEES, "sTrainer", wfvariables.sTrainingTrainer.Item(0).Item("Name").Value, wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value
End Function

'**********************************************************
' startModifyParticipantsWorkflow
' @description: starts the workflow to modify the participants
' @param: nothing
' @return: nothing
'**********************************************************
Function startModifyParticipantsWorkflow
	startWorkflow QM_WF_MODIFY_PARTICIPANTS, "", "", wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value
End Function

'**********************************************************
' startModifyAuthorWorkflow
' @description: starts the workflow to modify the author for the QM-Role
' @param: nothing
' @return: nothing
'**********************************************************
Function startModifyAuthorWorkflow
	sGUID = wforganisation.GetOrgObjectsByName("Controlled_Documents_QM").Item(0).Id
	debug2File "Found no valid assignee. Assign the invalidation to the default QM (" & sGUID & ") role." 	
	startWorkflow QM_WF_MODIFY_AUTHOR, "sActivityUserGuids", sGUID, wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value
End Function

'**********************************************************
' startModifyRecipientsWorkflow
' @description: starts a modify recipients workflow for each responsible person
' @param: nothing
' @return: nothing
'**********************************************************
Function startModifyRecipientsWorkflow
	Dim i
	For i = 0 To wfvariables.TrainingResponsible.count - 1
		distributionObject = getAccordingDistributionObject (wfvariables.TrainingResponsible.Item(i).Item("Guid").Value)
		arrTmp = Split (distributionObject, "#")
		debug2File "Starte startModifyRecipientsWorkflow fr Rolle: " & wfvariables.TrainingResponsible.Item(i).Item("Guid").Value
		startWorkflow QM_WF_MODIFY_RECIPIENTS, "sActivityUserGuids", wfvariables.TrainingResponsible.Item(i).Item("Guid").Value, arrTmp(0), arrTmp(1)
	Next
End Function


'**********************************************************
' getAccordingDistributionObject
' @description: searchs for the distributionobject of the training responsible
' @param:   wfOrgObjectGUID - the Guid of the training responsible
' @return: the distributionObject (String) in following format: objectID#objectType
'**********************************************************
Function getAccordingDistributionObject(wfOrgObjectGUID)
debug2File "start getAccordingDistributionObject (" & wfOrgObjectGUID & ")"
	
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" &_
				"<Fields field_schema='MIN'/>" &_
				"<Conditions>" &_
					"<ConditionObject internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" &_
						"<FieldCondition internal_name='" & getInternalName_DistributionObject_Version & "' operator='='>" &_
							"<Value>" & wfvariables.sVersion.Value & "</Value>" &_
						"</FieldCondition>" &_
						"<FieldCondition internal_name='" & getInternalName_DistributionObject_DocumentNumber & "' operator='='>" &_
							"<Value>" & wfvariables.sDocumentNumber.Value & "</Value>" &_
						"</FieldCondition>" &_
						"<TableCondition internal_name='" & "m_r_responsible" & "'>" &_
							"<TableColumn name='Guid' operator='='>" &_
								"<Value>" & wfOrgObjectGUID & "</Value>" &_
							"</TableColumn>" &_
						"</TableCondition>" &_
					"</ConditionObject>" &_		
				"</Conditions>" &_					
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"
	
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	debug2File sXML
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("Variants") = 1
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")  'wforganisation.GetOrgObjectsByName("osservice").Item(0).Id
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		debug2File "Filename: " & sfile
		
		Dim oNode
		Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oXmlDoc.load(sfile) = True Then 

			
			'Dim oFSO2 : Set oFSO2 = CreateObject("Scripting.FileSystemObject")
			'Dim sNewFile 'copy the file, cause the file will be deleted if the job ends
			'sNewFile = sfile & ".tmp." & oFSO2.GetExtensionName(sfile) 'the file should be deleted by the calling function
			'oFSO2.CopyFile sfile, sNewFile			
			
			Dim xpath
			xpath = "/DMSContent/Archive/ObjectType/ObjectList/Object"
			Set oNode = oXmlDoc.selectSingleNode (xpath)
			If Not oNode Is Nothing Then
				debug2File "Verteiler Objekt ID: " & oNode.attributes.getNamedItem("id").text
				objectID = oNode.attributes.getNamedItem("id").text
				
				'now get the objectType
				xpath = "/DMSContent/Archive/ObjectType"
				Set oNode = oXmlDoc.selectSingleNode (xpath)
				objectType = oNode.attributes.getNamedItem("id").text
				
				getAccordingDistributionObject = objectID & "#" & objectType
			End If
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oXmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"ERROR: getAccordingDistributionObject GetResultList failed..."
	End If
	
debug2File "end getAccordingDistributionObject"
End Function

'**********************************************************
' startWorkflow
' @description: starts the workflow (sWorkflowName) with the given parameter as osservice user
' @param:   documentID - the document with which the workflow should be started
' @param:	documentType - the type of the document
' @param:	svarNames (String) - a string with pipes ("|") as separator for the single names; the names will be split in this function
' @param:	svarValues (String) - a string with pipes ("|") as separator for the single values; the values will be split in this function
' @return: nothing
'**********************************************************
Function startWorkflow (sWorkflowName,svarNames,svarValues, documentID, documentType)
debug2File "start startWorkflow (" & sWorkflowName & "," & svarNames & "," & svarValues & "," & documentID & "," & documentType & ")"
 
 	Dim RC : Set RC = RunningContext
 	Dim workflowID : workflowID = ""
 	Dim processID : processID = ""
 
   	'at first get the FamilyID of the Workflow
	workflowID = getWorkflowID (sWorkflowName)
	
    Dim sStr : sStr = ""
    
    Dim PrmIn : Set PrmIn = RC.NewJobsParams
    Dim PrmOut : Set PrmOut = RC.NewJobsParams
    
    'now get the process instance
    PrmIn.Clear()
    
    PrmIn.Value("UserId") = wforganisation.GetOrgObjectsByName("osservice").Item(0).Id 'wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("OrganisationId") = wforganisation.Id
	PrmIn.Value("ClientTypeId") = "DB928B6631304CFC8D30B1B4FE67679B"
	PrmIn.Value("WorkflowId") = workflowID
	
	iRet = RC.Jobs.wfm.CreateProcessInstance(PrmIn, PrmOut)
	If iRet = 0 Then
		processID = PrmOut.Value("ProcessId")
		debug2File vbTab & "ProcessId: " & processID

		PrmIn.Clear()
	    PrmIn.Value("UserId") = wforganisation.GetOrgObjectsByName("osservice").Item(0).Id 'wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	    PrmIn.Value("OrganisationId") = wforganisation.Id      
	    PrmIn.Value("WorkflowId") = workflowID
	    PrmIn.Value("ProcessId") = processID
	    PrmIn.Value("ClientTypeId") = "DB928B6631304CFC8D30B1B4FE67679B"
	
	    Dim xmlStr : xmlStr = "<Workspace><Docs>"
	    xmlStr = xmlStr & "<Doc Id=""" & documentID & """ Type=""" & documentType & """ Workspace=""1"" Location=""1"" Moveable=""0"" Deleteable=""0""/>"     
	    xmlStr = xmlStr & "</Docs></Workspace>"
	    
	    
	    Set dom = CreateObject("MSXML.DOMDocument")
	    dom.loadXML(xmlStr)
	    PrmIn.Value("Workspace") = dom    
	
	    xmlStr = "<DataFields>"                              
	    avarNames=Split(svarNames,"|")
	    avarValues=Split(svarValues,"|")
	    Dim i : i = 0
	    for i=0 to ubound(avarNames)
	                   xmlStr = xmlStr & "<DataField Id='" & avarNames(i) & "'>"
	                   xmlStr = xmlStr & "<![CDATA[<WFVar><String>" & avarValues(i) & "</String></WFVar>]]>"
	                   xmlStr = xmlStr & "</DataField>"                            
	    next
	    xmlStr = xmlStr & "</DataFields>"
	    Set dom2 = CreateObject("MSXML.DOMDocument")
	    dom2.loadXML(xmlStr)
	    PrmIn.Value("DataFields")=dom2
	
	
	    iRet = RC.Jobs.wfm.StartProcess(PrmIn, PrmOut)
	    If iRet = 0 Then
	        debug2File vbTab & "startWorkflow successful..."	
	    Else
		   	debug2File vbTab & "Error: startWorkflow failed..."
	    End If
	    startWorkflow = iRet
	    
	    'clean up
	    Set dom = Nothing
	    Set dom2 = Nothing
	Else
		debug2File vbTab & "Error: createProcessInstance failed..."		
	End If
	
   
debug2File "end startWorkflow"
end Function



'**********************************************************
' throwError
' @description
' @param
' @return
'**********************************************************
Function throwError (msg)
	
	debug2File "ERROR --> " & msg
	
End Function

'**********************************************************
' debug2File
' @description: write a debugfile
' @param str (string)
' @return nothing
'**********************************************************
Public Sub debug2File(str)
	Dim fso, File
	Dim RC : Set RC = RunningContext
	
	If (recCommon.bDebug.Value = 1) Then
		Set fso = CreateObject("Scripting.FileSystemObject")
		'Set File = fso.OpenTextFile(RC.ServerData.TempDir & Replace( thisprocess.ProcessName, "/", "") & "_debug.txt", 8, True)
		
		If fso.Folderexists(RC.ServerData.LogDir & recCommon.sProductName.Value) = False Then 
			fso.CreateFolder(RC.ServerData.LogDir & recCommon.sProductName.Value) 
		End If
		
		Set File = fso.OpenTextFile(RC.ServerData.LogDir & recCommon.sProductName.Value & "\" & Replace( thisprocess.ProcessName, "/", "") & "_debug.txt", 8, True)
		File.Write Now & vbTab & str & vbCrLf
		File.Close
		Set fso = Nothing
		Set File = Nothing
	End If
End Sub

'**********************************************************
' setPreviousDocumentInvalidationDate
' @description: updates the field invalidation date of the previous document with the validdate of the new document
' @param: 
' @return: nothing
'**********************************************************
Function setPreviousDocumentInvalidationDate ()
	sFieldValues = "<Field internal_name='" & getInternalName_Document_DocumentInvalidationDate & "'>" & convertToValidXML(wfvariables.dValiddate.Value) & "</Field>"

	setDocumentFieldValues sFieldValues, wfvariables.recStructure.iPreviousDocumentID.Value
End Function

'**********************************************************
' setPreviousDocumentStatus_0
' @description: updates the status of the document and the register with 0 
' @param 
' @return: nothing
'**********************************************************
Function setPreviousDocumentStatus_0
	setDocumentStatus "0", wfvariables.recStructure.iPreviousDocumentID.Value
	'always update the register the same way
	setRegisterStatus "0", wfvariables.recStructure.iPreviousRegisterID.Value
End Function

'**********************************************************
' setPreviousDocumentStatus_1
' @description: updates the status of the document and the register with 1
' @param 
' @return: nothing
'**********************************************************
Function setPreviousDocumentStatus_1
	setDocumentStatus "1", wfvariables.recStructure.iPreviousDocumentID.Value
	'always update the register the same way
	setRegisterStatus "1", wfvariables.recStructure.iPreviousRegisterID.Value	
End Function

'**********************************************************
' setPreviousDocumentStatus_2
' @description: updates the status of the document and the register with 2
' @param 
' @return: nothing
'**********************************************************
Function setPreviousDocumentStatus_2
	setDocumentStatus "2", wfvariables.recStructure.iPreviousDocumentID.Value
	'always update the register the same way
	setRegisterStatus "2", wfvariables.recStructure.iPreviousRegisterID.Value	
End Function

'**********************************************************
' setPreviousDocumentStatus_3
' @description: updates the status of the document and the register with 3
' @param 
' @return: nothing
'**********************************************************
Function setPreviousDocumentStatus_3
	setDocumentStatus "3", wfvariables.recStructure.iPreviousDocumentID.Value
	'always update the register the same way
	setRegisterStatus "3", wfvariables.recStructure.iPreviousRegisterID.Value
End Function

'**********************************************************
' setPreviousDocumentStatus_4
' @description: updates the status of the document and the register with 4
' @param 
' @return: nothing
'**********************************************************
Function setPreviousDocumentStatus_4
	setDocumentStatus "4", wfvariables.recStructure.iPreviousDocumentID.Value
	'always update the register the same way
	setRegisterStatus "4", wfvariables.recStructure.iPreviousRegisterID.Value
End Function

'**********************************************************
' setDocumentStatus_0
' @description: updates the status of the document and the register with 0 
' @param 
' @return: nothing
'**********************************************************
Function setDocumentStatus_0
	iRet = setDocumentStatus ("0", wfvariables.recStructure.iDocumentID.Value)
	if iRet = 0 Then
		wfvariables.sStatus.Value = "0"
	End If
	'always update the register the same way
	If wfvariables.recStructure.iDocumentID.Value > 0 Then
		setRegisterStatus "0", wfvariables.recStructure.iRegisterID.Value
	End If
End Function

'**********************************************************
' setDocumentStatus_1
' @description: updates the status of the document and the register with 1
' @param 
' @return: nothing
'**********************************************************
Function setDocumentStatus_1
	iRet = setDocumentStatus ("1", wfvariables.recStructure.iDocumentID.Value)
	if iRet = 0 Then
		wfvariables.sStatus.Value = "1"
	End If	
	'always update the register the same way
	If wfvariables.recStructure.iDocumentID.Value > 0 Then
		setRegisterStatus "1", wfvariables.recStructure.iRegisterID.Value	
	End If
End Function

'**********************************************************
' setDocumentStatus_2
' @description: updates the status of the document and the register with 2
' @param 
' @return: nothing
'**********************************************************
Function setDocumentStatus_2
	iRet = setDocumentStatus ("2", wfvariables.recStructure.iDocumentID.Value)
	if iRet = 0 Then
		wfvariables.sStatus.Value = "2"
	End If	
	'always update the register the same way
	If wfvariables.recStructure.iDocumentID.Value > 0 Then
		setRegisterStatus "2", wfvariables.recStructure.iRegisterID.Value	
	End If
End Function

'**********************************************************
' setDocumentStatus_3
' @description: updates the status of the document and the register with 3
' @param 
' @return: nothing
'**********************************************************
Function setDocumentStatus_3
	iRet = setDocumentStatus ("3", wfvariables.recStructure.iDocumentID.Value)
	if iRet = 0 Then
		wfvariables.sStatus.Value = "3"
	End If	
	'always update the register the same way
	If wfvariables.recStructure.iDocumentID.Value > 0 Then
		setRegisterStatus "3", wfvariables.recStructure.iRegisterID.Value
	End If
End Function

'**********************************************************
' setDocumentStatus_4
' @description: updates the status of the document and the register with 4
' @param 
' @return: nothing
'**********************************************************
Function setDocumentStatus_4
	iRet = setDocumentStatus ("4", wfvariables.recStructure.iDocumentID.Value)
	if iRet = 0 Then
		wfvariables.sStatus.Value = "4"
	End If	
	'always update the register the same way
	If wfvariables.recStructure.iDocumentID.Value > 0 Then
		setRegisterStatus "4", wfvariables.recStructure.iRegisterID.Value
	End If
End Function



Function setFolderStatus (status, folderObjectID)
	debug2File "start setFolderStatus (" & status & ", " & folderObjectID & ")"
	
	If folderObjectID = 0 Then
		folderObjectID = getDocumentFolderID (wfvariables.recStructure.iDocumentID.Value)
	End If
	If folderObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "' type='FOLDER'>" &_
		"<Object object_id='" & CLng(folderObjectID) & "'>" &_
		"<Fields>" &_
		"<Field internal_name='" & getInternalName_Folder_DocumentStatus & "'>" & convertToValidXML(status) & "</Field>" &_
		"</Fields>" &_
		"</Object>" &_
		"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No Register available"	
	End If
	
	
	debug2File "end setFolderStatus"
End Function

'**********************************************************
' setRegisterStatus
' @description: updates the status of the register
' @param: status (string), registerObjectID (Integer)
' @return: nothing
'**********************************************************
Function setRegisterStatus (status, registerObjectID)
	debug2File "start setRegisterStatus (" & status & "," & registerObjectID & ")"
	
	If registerObjectID = 0 Then
		registerObjectID = getDocumentRegisterID (wfvariables.recStructure.iDocumentID.Value)
	End If
	If registerObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
				"<ObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
					"<Object object_id='" & CLng(registerObjectID) & "'>" &_
						"<Fields>" &_
							"<Field internal_name='" & getInternalName_Register_DocumentStatus & "'>" & convertToValidXML(status) & "</Field>" &_
						"</Fields>" &_
					"</Object>" &_
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		If iRet = 0 Then
			debug2File vbTab & "setRegisterStatus successful..."
		Else
			debug2File vbTab & "ERROR: setRegisterStatus failed..."
		End If		
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No Register available"	
	End If
	debug2File "end setRegisterStatus (" & status & "," & registerObjectID & ")"
End Function

'**********************************************************
' setRegisterVersion
' @description: updates the status of the register
' @param: status (string), registerObjectID (Integer)
' @return: nothing
'**********************************************************
Function setRegisterVersion (version, registerObjectID)
	debug2File "start setRegisterVersion (" & version & "," & registerObjectID & ")"
	If registerObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
		"<Object object_id='" & CLng(registerObjectID) & "'>" &_
		"<Fields>" &_
		"<Field internal_name='" & getInternalName_Register_DocumentVersion & "'>" & convertToValidXML(version) & "</Field>" &_
		"</Fields>" &_
		"</Object>" &_
		"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No Register available"	
	End If
	debug2File "end setRegisterVersion (" & version & "," & registerObjectID & ")"
End Function

Function setDocumentFieldValues (sFieldValues, documentObjectID)
	
	debug2File "start setDocumentFieldValues (" & sFieldValues & "," & documentObjectID & ")"
	If documentObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
				"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
					"<Object object_id='" & CLng(documentObjectID) & "'>" &_
						"<Fields>" &_
							sFieldValues &_			
						"</Fields>" &_
					"</Object>" &_
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		setDocumentFieldValues = iRet
		If iRet = 0 Then
			debug2File vbTab & "setDocumentFieldValues successful..."			
		Else
			debug2File vbTab & "ERROR: setDocumentFieldValues failed..."
		End If
		
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No document available"	
	End If
	debug2File "end setDocumentFieldValues (" & sFieldValues & "," & documentObjectID & ")"
	
End Function

Function setFieldValues (sArchiveInternalName, sObjectInternalName, sObjectType, sFieldValues, documentObjectID)
	
	debug2File "start setFieldValues (" & sArchiveInternalName & "," & sObjectInternalName & "," & sObjectType & "," & sFieldValues & "," & documentObjectID & ")"
	If documentObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
			"<Archive internal_name='" & sArchiveInternalName & "'>" &_
				"<ObjectType internal_name='" & sObjectInternalName & "' type='" & sObjectType & "'>" &_
					"<Object object_id='" & CLng(documentObjectID) & "'>" &_
						"<Fields>" &_
							sFieldValues &_			
						"</Fields>" &_
					"</Object>" &_
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		debug2File vbTab & "setFieldValues.request: " & dom.xml
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		setFieldValues = iRet
		If iRet = 0 Then
			debug2File vbTab & "setFieldValues successful..."			
		Else
			debug2File vbTab & "ERROR: setFieldValues failed..."
		End If
		
		
		Set oxmlDoc = Nothing
	Else
		debug2File "setFieldValues: No document available"	
	End If
	debug2File "end setFieldValues (" & sFieldValues & "," & documentObjectID & ")"
	
End Function
'**********************************************************
' setDocumentStatus
' @description: updates the status of the document
' @param: status (string), documentObjectID (Integer)
' @return: nothing
'**********************************************************
Function setDocumentStatus (status, documentObjectID)
	debug2File "start setDocumentStatus (" & status & "," & documentObjectID & ")"
	If documentObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
				"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
					"<Object object_id='" & CLng(documentObjectID) & "'>" &_
						"<Fields>" &_
							"<Field internal_name='" & getInternalName_Document_DocumentStatus & "'>" & convertToValidXML(status) & "</Field>" &_
						"</Fields>" &_
					"</Object>" &_
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		setDocumentStatus = iRet
		If iRet = 0 Then
			debug2File vbTab & "setDocumentStatus successful..."			
		Else
			debug2File vbTab & "ERROR: setDocumentStatus failed..."
		End If
		
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No document available"	
	End If
	'get the statusinformation of the document (the descriptive text, e.g. the status "0" means "in Arbeit / in progress"
	'the function is implemented in the customer functions, cause the descriptive text could differ for each customer
	sDescriptiveStatus = getStatusInformation (status)	
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value, wfvariables.recStructure.iDocumentID.Value, getInternalName_Document_DocumentStatusInfo, sDescriptiveStatus
	

	debug2File "end setDocumentStatus (" & status & ")"
End Function

'**********************************************************
' getStatusInformation
' @description: gets the status information according to the status value (e.g. status value = 1 means statusinformation = "in Arbeit / in Progress"
' @param:   sStatusValue (String)
' @return: descriptive statusinformation as function return value (String)
'**********************************************************
Function getStatusInformation (sStatusValue)
	If sStatusValue = "0" Then
		getStatusInformation = getMessageText ( "V1-6", "DescriptiveStatus_InProgress", "in Arbeit / in progress", "deu" ) '"in Arbeit / in progress"
	End If
	If sStatusValue = "1" Then
		getStatusInformation = getMessageText ( "V1-6", "DescriptiveStatus_Valid", "gltig / valid", "deu" ) '"gltig / valid"
	End If
	If sStatusValue = "2" Then
		getStatusInformation = getMessageText ( "V1-6", "DescriptiveStatus_InTraining", "in Schulung / in Training", "deu" ) '"in Schulung / in Training"
	End If
	If sStatusValue = "3" Then
		getStatusInformation = getMessageText ( "V1-6", "DescriptiveStatus_Invalid", "ungltig / invalid", "deu" ) '"ungltig / invalid"
	End If
	If sStatusValue = "4" Then
		getStatusInformation = getMessageText ( "V1-6", "DescriptiveStatus_Canceled", "verworfen / canceled", "deu" ) '"verworfen / canceled"
	End If
End Function

'**********************************************************
' setDocumentVersion
' @description: updates the version of the document
' @param: version (string), documentObjectID (Integer)
' @return: nothing
'**********************************************************
Function setDocumentVersion (version, documentObjectID)
	debug2File "start setDocumentVersion (" & version & ")"
	If documentObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
		"<Object object_id='" & CLng(documentObjectID) & "'>" &_
		"<Fields>" &_
		"<Field internal_name='" & getInternalName_Document_DocumentVersion & "'>" & convertToValidXML(version) & "</Field>" &_
		"</Fields>" &_
		"</Object>" &_
		"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		If iRet = 0 Then
			debug2File vbTab & "setDocumentVersion successful..."
		Else	
			debug2File vbTab & "ERROR: setDocumentVersion failed..."
		End If
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No document available"	
	End If
	debug2File "end setDocumentVersion (" & version & ")"
End Function

'**********************************************************
' setAttachmentVersion
' @description: updates the version of the attachment
' @param: version (string), attachmentObjectID (Integer)
' @return: nothing
'**********************************************************
Function setAttachmentVersion (version, attachmentObjectID)
	debug2File "start setAttachmentVersion (" & version & ")"
	If attachmentObjectID > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType internal_name='" & wfvariables.recStructure.sAttachmentInternalName.Value & "' type='DOCUMENT'>" &_
		"<Object object_id='" & CLng(attachmentObjectID) & "'>" &_
		"<Fields>" &_
		"<Field internal_name='" & getInternalName_Attachment_Version & "'>" & convertToValidXML(version) & "</Field>" &_
		"</Fields>" &_
		"</Object>" &_
		"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="CHECKREADONLY=0"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		If iRet = 0 Then
			debug2File vbTab & "setAttachmentVersion successful..."
		Else	
			debug2File vbTab & "ERROR: setAttachmentVersion failed..."
		End If
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No attachment available"	
	End If
	debug2File "end setAttachmentVersion (" & version & ")"
End Function


'**********************************************************
' InitializeInvalidation
' @description: initialize all values for a invalidation and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeInvalidation	
debug2File "start InitializeInvalidation"
	InitializeArchiveStructure
	
	'check if the document status is valid
	
	If wfvariables.sStatus.Value <> "1" Then
		wfvariables.sError.Value = "StandardWF;;;StatusValidNecessary;;;Das Dokument muss den Status 'gltig' aufweisen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If
	
	'check if the object is already in a Invalidation Workflow
	bIsAlreadyInProcess = isObjectInProcess (wfvariables.recStructure.iDocumentID.Value, QM_WF_INVALIDATION)
	If bIsAlreadyInProcess = True Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyInvalidating;;;Ein Auerkraftsetzen-Workflow ist fr dieses Dokument bereits aktiv."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If	
	
	'check if participants are defined (e.g. imported documents could not have participants, in this case we hat to exit the workflow)	
	If wfvariables.recUsers.Count = 0 Then 'the variable recUsers will be initialized by the "InitializeArchiveStructure" function, which is called a few lines above
		wfvariables.sError.Value = "StandardWF;;;NoParticipants;;;Es existiert kein Umlauf (z.B. Autor) fr dieses Dokument. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken, wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet."
		wfvariables.bCorrect.Value = 3
		addProtocolEntry "The revision workflow was canceled by the system, because of missing or incorrect participant information.", "INFO", "SYSTEM", False
		addProtocolEntry "Details", "ERROR", "SYSTEM", True
		updateXMLProtocol wfvariables.recStructure.iFolderID.Value,wfvariables.recStructure.iProtocolRegisterID.Value
		Exit Function 'no revision			
	End If
	
	'check if all user still exist
	For a = 0 To wfvariables.recUsers.Count -1 
		sGUID = wfvariables.recUsers.Item(a).Item("sUserGuid").Value
		debug2File "Prfe, ob ein User mit der GUID " & sGUID & " existiert..."
		On Error Resume Next		
		Err.Clear
		Set oOrgObject = wforganisation.GetOrgObjectById(sGUID)
		debug2File "Ergebnis: " & wforganisation.GetOrgObjectById(sGUID).Name
		If  Err.Number <> 0  then  
			debug2File "ERROR: Fr die GUID " & sGUID & " konnte kein User ermittelt werden... - " & wfvariables.recUsers.Item(a).Item("sUserName").Value
			wfvariables.sError.Value = "StandardWF;;;NoParticipant;;;Mindestens ein Anwender aus dem Umlauf exisitiert nicht mehr in der Organisation. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken, wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet. Betroffen:;;;" & wfvariables.recUsers.Item(a).Item("sUserName").Value
			wfvariables.bCorrect.Value = 3
			addProtocolEntry "The revision workflow was canceled by the system, because of incorrect participant information. The user " & wfvariables.recUsers.Item(a).Item("sUserName").Value & " does not exist.", "INFO", "SYSTEM", False
			addProtocolEntry "Details", "ERROR", "SYSTEM", True
			updateXMLProtocol wfvariables.recStructure.iFolderID.Value,wfvariables.recStructure.iProtocolRegisterID.Value
			Exit Function 'no revision							
		End If		
	Next
debug2File "end InitializeInvalidation"		
End Function

'**********************************************************
' InitializeTemplateInvalidation
' @description: initialize all values for a invalidation and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeTemplateInvalidation	
debug2File "start InitializeTemplateInvalidation"

	If thisprocess.WFFile.FileObjects.Count <> 1 Then
		wfvariables.sError.Value = "StandardWF;;;OnlyOneTemplate;;;Sie mssen genau eine Vorlage an diesen Workflow bergeben."
		wfvariables.bCorrect.Value = 1
		Exit Function 
	End If

	InitializeArchiveStructure
	
	'check if the document status is valid
	
	If wfvariables.sStatus.Value <> "1" Then
		wfvariables.sError.Value = "StandardWF;;;DocumentHasToBeValid;;;Das Dokument muss den Status 'gltig' aufweisen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If
	
	'check if the object is already in a Invalidation Workflow
	bIsAlreadyInProcess = isObjectInProcess (wfvariables.recStructure.iDocumentID.Value, QM_WF_TEMPLATE_INVALIDATION)
	If bIsAlreadyInProcess = True Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyInvalidatingTemplate;;;Ein Auerkraftsetzen Workflow ist fr diese Vorlage bereits aktiv."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If	
	
debug2File "end InitializeTemplateInvalidation"		
End Function


'**********************************************************
' InitializeDistribute
' @description: initialize all values for distribute and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
' @description: Reads the field values from an object. All field and object names are internal names.
' @param: sReturnFields Internal name of return field (separated by semicolon).
' @param: sObjectName Internal Object name
' @param: sObjecttypeName Kind of object, e.g. 'DOCUMENT'
' @param: sArchiveName Internal name of archive
' @return "Value1|Value2|..." String with values of the returnfields, separated by pipe. Returns empty string in case no value is found or an error occurs.
'**********************************************************
'Function getObjectFields (sArchiveName, sObjecttypeName, sObjectName, sObjectId, sReturnFields)
Function InitializeDistribute
'	updateField "fTrainingSurvey", "REGISTER", "rPerson", wfvariables.sPersonRegisterID.Value, "sProcessID", thisprocess.ProcessId
	'InitializeArchiveStructure	
	Dim DistName : DistName = getObjectFields ("fTrainingSurvey", "REGISTER", "rPerson", wfvariables.sPersonRegisterID.Value, "sName")
	If DistName <> "" Then
		wfvariables.sHint.Value = "StandardWF;;;ReadReceipt;;;Lesebesttigung fr;;;" & DistName
	Else
		wfvariables.sHint.Value = "StandardWF;;;ReadReceipt;;;Lesebesttigung fr;;;" & getObjectFields ("fTrainingSurvey", "REGISTER", "rPerson", wfvariables.sPersonRegisterID.Value, "sLogin")
	End If 	
End Function


'**********************************************************
' InitalizeModifyResponsibles
' @description: initialize all values for a modify responsible workflow and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeModifyResponsibles	
	InitializeArchiveStructure
	
	'check if the document status is valid
	
	If wfvariables.sStatus.Value <> "1" And  wfvariables.sStatus.Value <> "2" Then
		wfvariables.sError.Value = "StandardWF;;;DocumentValidOrTraining;;;Das Dokument muss den Status 'gltig' oder 'in Schulung' aufweisen, um einen zugehrigen Verteilern anzupassen."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If

	'check if the object is already in a Modify responsibles Workflow
	bIsAlreadyInProcess = isObjectInProcess (wfvariables.recStructure.iDocumentID.Value, QM_WF_MODIFY_RESPONSIBLES)
	If bIsAlreadyInProcess = True Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyModifyingResponsible;;;Ein Workflow zur Anpassung der Schulungsverantwortlichen ist fr dieses Dokument bereits aktiv."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If		
	
End Function

'**********************************************************
' InitalizeModifyAuthor
' @description: initialize all values for a modify author workflow and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeModifyAuthor

	If thisprocess.WFFile.FileObjects.Count <> 1 Then
		wfvariables.sError.Value = "StandardWF;;;OnlyOneDocument;;;Sie mssen genau eine Dokument an diesen Workflow bergeben."
		wfvariables.bCorrect.Value = 1
		Exit Function 
	End If

	InitializeArchiveStructure
	
	'check if the document status is valid
	
	If wfvariables.sStatus.Value <> "1" Then
		wfvariables.sError.Value = "StandardWF;;;DocumentHasToBeValid;;;Das Dokument muss den Status 'gltig' aufweisen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If	
	
	'check if the object is already in a Modify author Workflow
	bIsAlreadyInProcess = isObjectInProcess (wfvariables.recStructure.iDocumentID.Value, QM_WF_MODIFY_AUTHOR)
	If bIsAlreadyInProcess = True Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyModifyingAuthor;;;Ein Workflow zur Anpassung des Autors ist fr dieses Dokument bereits aktiv."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If
	
End Function

'**********************************************************
' InitializeModifyParticipants
' @description: initialize all values for a modify author workflow and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeModifyParticipants
	If thisprocess.WFFile.FileObjects.Count <> 1 Then
		wfvariables.sError.Value = "StandardWF;;;OnlyOneDocument;;;Sie mssen genau eine Dokument an diesen Workflow bergeben."
		wfvariables.bCorrect.Value = 1
		Exit Function 
	End If

	InitializeArchiveStructure
	
	'check if the document status is valid
	
	If wfvariables.sStatus.Value <> "1" Then
		wfvariables.sError.Value = "StandardWF;;;DocumentHasToBeValid;;;Das Dokument muss den Status 'gltig' aufweisen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no workflow start
	End If	
	
	'check if the object is already in a Modify responsibles Workflow
	bIsAlreadyInProcess = isObjectInProcess (wfvariables.recStructure.iDocumentID.Value, QM_WF_MODIFY_PARTICIPANTS)
	If bIsAlreadyInProcess = True Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyModifyingParticipants;;;Ein Workflow zur Anpassung des Umlaufs ist fr dieses Dokument bereits aktiv."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If
	
End Function

'**********************************************************
' InitalizeModifyRecipients
' @description: initialize all values for a modify responsible workflow and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeModifyRecipients
	'the workflow will be started with an distribution object
	'so at first we need to get the correct object id of the controlled document according to the distribution object
	wfvariables.iDistributionObjectID.Value = wfvariables.recStructure.iDocumentID.Value
	
	'get the training responsible role from the distribution object
	sXMLFile = getObjectDetails (wfvariables.iDistributionObjectID.Value, "", "")
	Dim oXmlDoc : Set oXmlDoc = CreateObject("MSXML2.DOMDocument")
	If oXmlDoc.load(sXMLFile) = True Then 
		debug2File oXmlDoc.xml
		'at first check if the distributionobject got the flag 'deleted'. in this case we don't need run the workflow.
		Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/Fields/Field[@internal_name='m_r_deleted']"	'ToDo: m_r_deleted durch Variable ersetzen
		Dim oNode
		Set oNode = oXmlDoc.selectSingleNode(xpath)
		If Not oNode Is Nothing Then
			If oNode.text = "1" Then
				debug2File "Das Verteilerobjekt hat den Status Gelscht = 1"
				wfvariables.sError.Value = "StandardWF;;;DistListInactive;;;Der Verteiler wurde bereits gelscht. Sie knnen keine inaktiven Verteiler anpassen."
				wfvariables.bCorrect.Value = 1
				Exit Function				
			End If
		End If
				
		xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sDistributionObjectResponsibleTableInternalName.Value & "']/Row[@id=1]/Value"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		wfvariables.sPossibleTrainingRecipients.value = ""
						
		If oNodes.length > 1 Then
			debug2File "GUID der Rolle des aktuellen Schulungsverantwortlichen: " & oNodes.item(0).text			
			TrainingResponsibleGUID = oNodes.item(0).text			
			TraininingResponsibleName = wforganisation.getorgobjectbyid(TrainingResponsibleGUID).Name
			debug2File "Name des Verantw. " & TraininingResponsibleName
			'now check if the process creator is member of the training responsible role
			Set ListOrgObjectSuccessorPersons = wforganisation.getorgobjectbyid(TrainingResponsibleGUID).GetSuccessorsByClassName("Person")
			Dim bProcessCreatorIsMemberOfTrainingResponsibles : bProcessCreatorIsMemberOfTrainingResponsibles = 0
			For u = 0 To ListOrgObjectSuccessorPersons.Count -1
				debug2File "Mitglied der Rolle " & TraininingResponsibleName & ": " & ListOrgObjectSuccessorPersons.item(u).Name
				If thisprocess.Creator = ListOrgObjectSuccessorPersons.item(u).Id Then
					bProcessCreatorIsMemberOfTrainingResponsibles = 1
				End If
			Next
debug2File "hier: " & LCase(wforganisation.getorgobjectbyid(thisprocess.Creator).Name)
			If bProcessCreatorIsMemberOfTrainingResponsibles = 0 And (LCase(wforganisation.getorgobjectbyid(thisprocess.Creator).Name) <> "osservice") Then	'the technical user osservice must be able to start the workflow (that's necessary, if the workflow is started by the document creation/revision workflow)
				wfvariables.sError.Value = "StandardWF;;;NotResponsible;;;Sie gehren nicht zu den Schulungsverantwortlichen Personen, daher knnen Sie den Verteiler nicht anpassen."
				wfvariables.bCorrect.Value = 1
				Exit Function 'no revisions
			End If
			
			'now determine all roles on the same level and below the level of the training responsible role
			Set ListOrgObjectPredecessors = wforganisation.GetOrgObjectById(TrainingResponsibleGUID).AllPredecessors
			debug2File "Anzahl der Vorgnger des Schulungsverantwortlichen: " & ListOrgObjectPredecessors.Count
			'debug2File ListOrgObjectPredecessors.item(0).Name
			Set ListOrgObjectSuccessor = ListOrgObjectPredecessors.item(0).GetSuccessorsByClassName("Rolle") '.AllSuccessors
			For z = 0 To ListOrgObjectSuccessor.Count - 1 
				wfvariables.sPossibleTrainingRecipients.value = wfvariables.sPossibleTrainingRecipients.value & ListOrgObjectSuccessor.item(z).Id & ";"
			Next
		End If
		
		If Len(wfvariables.sPossibleTrainingRecipients.value) > 1 Then
			wfvariables.sPossibleTrainingRecipients.value = Left(wfvariables.sPossibleTrainingRecipients.value, Len(wfvariables.sPossibleTrainingRecipients.value)-1)
		End If
		debug2File "Mgliche Rollen fr Schulungsteilnehmer: " & wfvariables.sPossibleTrainingRecipients.value
	End If
	
	Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists (sXMLFile) = True Then 'delete the file from the getObjectDetails Function
		oFSO.DeleteFile sXMLFile
	End If
	'clean up
	Set oFSO = Nothing
	
	registerID = getDistributionObjectParentRegister (wfvariables.iDistributionObjectID.Value)
	
	'reset the current document id
	wfvariables.recStructure.iDocumentID.Value = getDocumentIdFromVersionRegister (registerID)
	
	'reset the current document type
	wfvariables.recStructure.iDocumentType.Value = getObjectTypeByID (wfvariables.recStructure.iDocumentID.Value)

	'add the document to the wffile
	thisprocess.WFFile.AddFileObject wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, True, 1

	InitializeArchiveStructure
	
	'check if the document status is valid
	
	If wfvariables.sStatus.Value <> "1" And  wfvariables.sStatus.Value <> "2" Then
		wfvariables.sError.Value = "StandardWF;;;DocumentValidOrTraining;;;Das Dokument muss den Status 'gltig' oder 'in Schulung' aufweisen, um einen zugehrigen Verteilern anzupassen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If
	
	
	
	'check if the object is in another workflow
	'bIsAlreadyInProcess = isOnlyDistributionObjectInProcess(wfvariables.iDistributionObjectID.Value)	'old function
	bIsAlreadyInProcess = isObjectInProcess (wfvariables.iDistributionObjectID.Value, "")
	If bIsAlreadyInProcess = True Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyModifyingDistList;;;Der Verteiler befindet sich bereits in einem Workflow in Bearbeitung."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If
End Function


'**********************************************************
' isObjectInProcess
' @description: checks if an object is already in a process
' @param: objectID - objectID of the object which should be checked
' @param: Processname - name of the process which should be checked (e.g. "Modify training recipients")
'			If the Processname is an empty string, the function returns TRUE if the object is in any process
' @return: TRUE if the object is already in use in the given process
'**********************************************************
Function isObjectInProcess(objectID, Processname)

'Comment: The job is not used in running context, cause the running context implementation raises an error

debug2File "start isObjectInProcess (" & objectID & ", " & Processname & ")"
	
	Set oSession = createSession()	
	Set oJob = oSession.NewJob("wfm.GetProcessListByObject")
	oJob.InputParameters.AddNewIntegerParameter "ObjectId", objectID
	oJob.InputParameters.AddNewStringParameter "OrganisationId", wforganisation.id
	iRet = oJob.Execute		
	Dim oXmlDoc : Set oXmlDoc = CreateObject("MSXML2.DOMDocument")
    isObjectInProcess = False
    Dim numberOfWorkflows : numberOfWorkflows = 0
    
    myXml = oJob.OutputParameters.item(1).XML     
	If oXmlDoc.loadXML(myXml) = True Then 
		Dim xpath : xpath = "//Processes/Process"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If oNodes.length > 1 Then
			If Processname = "" Then	'it's only necessary to know, if the object is in a process (no matter which process)
				debug2File vbTab & "isObjectInProcess = TRUE"
				isObjectInProcess = True
				Exit Function		
			End If
			For i = 0 To oNodes.length - 1			
				name = oNodes.item(i).attributes.getNamedItem("Name").text
				If LCase(Left(name,Len(Processname))) = LCase(Processname) Then
					numberOfWorkflows = numberOfWorkflows + 1 
					If numberOfWorkflows > 1 Then
						debug2File vbTab & "isObjectInProcess = TRUE"
						isObjectInProcess = True
						Exit Function
					End If
				End If
			Next
		Else
			debug2File vbTab & "isObjectInProcess = FALSE"
			isObjectInProcess = False
		End If
	End If
	
	
	
'	Set PrmIn = RC.NewJobsParams 
'	Set PrmOut = RC.NewJobsParams
		
'	PrmIn.Value("OrganisationId") = wforganisation.id
'	PrmIn.Value("ObjectId") = distributionObjectID
	
'	iRet = RC.Jobs.WFM.GetProcessListByObject (PrmIn, PrmOut)
	
'	Dim oXmlDoc : Set oXmlDoc = CreateObject("MSXML2.DOMDocument")
    
    
'	If oXmlDoc.load(PrmOut.Value("Processes")) = True Then 
			
'		Dim xpath : xpath = "//Processes/Process"
'		Set oNodes = oXmlDoc.selectNodes(xpath)
'		If oNodes.length > 1 Then
'			isOnlyDistributionObjectInProcess = False
'		Else
'			isOnlyDistributionObjectInProcess = True
'		End If
'	End If
	
'	Set oXmlDoc = Nothing
	
debug2File "end isObjectInProcess"


End Function

'**********************************************************
' isOnlyDistributionObjectInProcess
' @description: checks if a distribution object is already in a wffile. in this case we don't start the workflow.
' @param: distributionObjectID - objectID of the distribution object
' @return: TRUE if the distributionObject is already in use - otherwise false
'**********************************************************
Function isOnlyDistributionObjectInProcess (distributionObjectID)

'Comment: The job is not used in running context, cause the running context implementation raises an error

debug2File "start isOnlyDistributionObjectInProcess (" & distributionObjectID & ")"
	
	Set oSession = createSession()	
	Set oJob = oSession.NewJob("wfm.GetProcessListByObject")
	oJob.InputParameters.AddNewIntegerParameter "ObjectId", distributionObjectID
	oJob.InputParameters.AddNewStringParameter "OrganisationId", wforganisation.id
	iRet = oJob.Execute		
	Dim oXmlDoc : Set oXmlDoc = CreateObject("MSXML2.DOMDocument")
    
    myXml = oJob.OutputParameters.item(1).XML     
	If oXmlDoc.loadXML(myXml) = True Then 
		Dim xpath : xpath = "//Processes/Process"
		Set oNodes = oXmlDoc.selectNodes(xpath)
		If oNodes.length > 1 Then
			debug2File vbTab & "isOnlyDistributionObjectInProcess = TRUE"
			isOnlyDistributionObjectInProcess = TRUE
		Else
			debug2File vbTab & "isOnlyDistributionObjectInProcess = FALSE"
			isOnlyDistributionObjectInProcess = FALSE
		End If
	End If
	
	
	
'	Set PrmIn = RC.NewJobsParams 
'	Set PrmOut = RC.NewJobsParams
		
'	PrmIn.Value("OrganisationId") = wforganisation.id
'	PrmIn.Value("ObjectId") = distributionObjectID
	
'	iRet = RC.Jobs.WFM.GetProcessListByObject (PrmIn, PrmOut)
	
'	Dim oXmlDoc : Set oXmlDoc = CreateObject("MSXML2.DOMDocument")
    
    
'	If oXmlDoc.load(PrmOut.Value("Processes")) = True Then 
			
'		Dim xpath : xpath = "//Processes/Process"
'		Set oNodes = oXmlDoc.selectNodes(xpath)
'		If oNodes.length > 1 Then
'			isOnlyDistributionObjectInProcess = False
'		Else
'			isOnlyDistributionObjectInProcess = True
'		End If
'	End If
	
'	Set oXmlDoc = Nothing
	
debug2File "end isOnlyDistributionObjectInProcess"

End Function 

'**********************************************************
' getDistributionObjectParentRegister
' @description: returns the id of the controlled document below the version register
' @param: registerID (Integer) - the object id of the version register
' @return: object id of the controlled document
'**********************************************************
Function getDocumentIdFromVersionRegister (registerID)
debug2File "start getDocumentIdFromVersionRegister (" & registerID & ")"
	getDocumentIdFromVersionRegister = "-1"
	
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams

	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
				"<Fields field_schema='MIN'/>" &_
				"<ChildObjects>" &_
					"<ChildObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
						"<Fields field_schema='MIN'/>" &_				
					"</ChildObjectType>" &_			
				"</ChildObjects>" &_								
				"<Conditions>" &_
					"<ObjectID>" & registerID & "</ObjectID>" &_
				"</Conditions>" &_					
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"
	debug2File sXML
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML") = dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		Dim oNode
		Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oXmlDoc.load(sfile) = True Then 
			Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/ChildObjects/ObjectType/ObjectList/Object"
			Set oNode = oXmlDoc.selectSingleNode(xpath)
			
			debug2File "Object ID of the controlled document: " & oNode.attributes.getNamedItem("id").text

			getDocumentIdFromVersionRegister = oNode.attributes.getNamedItem("id").text
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oXmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"getDocumentIdFromVersionRegister failed"
	End If
debug2File "end getDocumentIdFromVersionRegister"	
End Function

'**********************************************************
' getDistributionObjectParentRegister
' @description: returns the id of the version register of a distribution object
' @param: distributionObjectID (Integer) - the object id of the distribution object
' @return: object id of the version register
'**********************************************************
Function getDistributionObjectParentRegister (distributionObjectID)

debug2File "start getDistributionObjectParentRegister (" & distributionObjectID & ")"
	getDistributionObjectParentRegister = "-1"
	
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams

	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" &_
				"<Fields field_schema='MIN'/>" &_
				"<ParentObjects>" &_
					"<ParentObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
						"<Fields field_schema='MIN'/>" &_				
					"</ParentObjectType>" &_			
				"</ParentObjects>" &_								
				"<Conditions>" &_
					"<ObjectID>" & distributionObjectID & "</ObjectID>" &_
				"</Conditions>" &_					
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"
	debug2File sXML
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML") = dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		Dim oNode
		Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oXmlDoc.load(sfile) = True Then 
			Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/ChildObjects/ObjectType/ObjectList/Object"
			Set oNode = oXmlDoc.selectSingleNode(xpath)
			
			debug2File "Object ID of the version register: " & oNode.attributes.getNamedItem("id").text

			getDistributionObjectParentRegister = oNode.attributes.getNamedItem("id").text
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oXmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"getDistributionObjectParentRegister failed"
	End If
	
End Function


'**********************************************************
' InitializeCheckRevision
' @description: initialize all values for a "check revision" workflow and checks if all necessary conditions are satisfied
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeCheckRevision
	
	If thisprocess.WFFile.FileObjects.Count <> 1 Then
		wfvariables.sError.Value = "StandardWF;;;OnlyOneDocument;;;Sie mssen genau eine Dokument an diesen Workflow bergeben."
		wfvariables.bCorrect.Value = 1
		Exit Function 
	End If
	
	InitializeArchiveStructure
	
	'check if the document status is valid
	
	If wfvariables.sStatus.Value <> "1" Then
		wfvariables.sError.Value = "StandardWF;;;DocumentHasToBeValid;;;Das Dokument muss den Status 'gltig' aufweisen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If	
	
	'check if the object is already in a Check Revision Workflow
	bIsAlreadyInProcess = isObjectInProcess (wfvariables.recStructure.iDocumentID.Value, QM_WF_CHECK_REVISION)
	If bIsAlreadyInProcess = True Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyCheckingRevision;;;Ein Revisionieren berprfen Workflow ist fr dieses Dokument bereits aktiv."
		wfvariables.bCorrect.Value = 1
		Exit Function
	End If		
	
	'check if participants are defined (e.g. imported documents could not have participants, in this case we hat to exit the workflow)	
	If wfvariables.recUsers.Count = 0 Then 'the variable recUsers will be initialized by the "InitializeArchiveStructure" function, which is called a few lines above
		debug2File "Es existiert kein Umlauf (z.B. Autor) fr dieses Dokument. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet."
		wfvariables.sError.Value = "StandardWF;;;NoParticipants;;;Es existiert kein Umlauf (z.B. Autor) fr dieses Dokument. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken, wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet."
		wfvariables.bCorrect.Value = 3
		addProtocolEntry "The revision workflow was canceled by the system, because of missing or incorrect participant information.", "INFO", "SYSTEM", False
		addProtocolEntry "Details", "ERROR", "SYSTEM", True
		updateXMLProtocol wfvariables.recStructure.iFolderID.Value,wfvariables.recStructure.iProtocolRegisterID.Value

		Exit Function 'no revision			
	End If

	'check if the author still exists
	If wfvariables.sNextAuthor.value = "" Then
		sGUID = wfvariables.recUsers.Item(0).Item("sUserGuid").Value
		debug2File "Prfe, ob der Autor mit der GUID " & sGUID & " existiert..."
		On Error Resume Next		
		Err.Clear
		Set oOrgObject = wforganisation.GetOrgObjectById(sGUID)
		debug2File "Ergebnis: " & wforganisation.GetOrgObjectById(sGUID).Name
		If  Err.Number <> 0  then  
			debug2File "ERROR: Fr die GUID " & sGUID & " konnte kein User ermittelt werden..."
			wfvariables.sError.Value = "StandardWF;;;NoParticipants;;;Mindestens ein Anwender aus dem Umlauf exisitiert nicht mehr in der Organisation. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken, wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet."
			wfvariables.bCorrect.Value = 3
			addProtocolEntry "The revision workflow was canceled by the system, because of incorrect participant information. The user " & wfvariables.recUsers.Item(0).Item("sUserName").Value & " does not exist.", "INFO", "SYSTEM", False
			addProtocolEntry "Details", "ERROR", "SYSTEM", True
			updateXMLProtocol wfvariables.recStructure.iFolderID.Value,wfvariables.recStructure.iProtocolRegisterID.Value
		
			Exit Function 'no revision							
		End If
	End If

	
	'check if all user still exist
'	For a = 0 To wfvariables.recUsers.Count -1 
'		sGUID = wfvariables.recUsers.Item(a).Item("sUserGuid").Value
'		debug2File "Prfe, ob ein User mit der GUID " & sGUID & " existiert..."
'		On Error Resume Next		
'		Err.Clear
'		Set oOrgObject = wforganisation.GetOrgObjectById(sGUID)
'		debug2File "Ergebnis: " & wforganisation.GetOrgObjectById(sGUID).Name
'		If  Err.Number <> 0  then  
'			debug2File "ERROR: Fr die GUID " & sGUID & " konnte kein User ermittelt werden..."
'			wfvariables.sError.Value = "StandardWF;;;NoParticipant;;;Mindestens ein Anwender aus dem Umlauf exisitiert nicht mehr in der Organisation. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken, wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet. Betroffen:;;;" & wfvariables.recUsers.Item(a).Item("sUserName").Value
'			wfvariables.bCorrect.Value = 3
'			addProtocolEntry "The revision workflow was canceled by the system, because of incorrect participant information. The user " & wfvariables.recUsers.Item(a).Item("sUserName").Value & " does not exist.", "INFO", "SYSTEM", False
'			addProtocolEntry "Details", "ERROR", "SYSTEM", True
'			updateXMLProtocol wfvariables.recStructure.iFolderID.Value,wfvariables.recStructure.iProtocolRegisterID.Value
		
'			Exit Function 'no revision							
'		End If		
'	Next
	
End Function

'**********************************************************
' InitializeArchiveStructure
' @description: initializes the archive structure (creates a protocol register if not already existent)
' @param: nothing
' @return: nothing
'**********************************************************
Function InitializeArchiveStructure
debug2File "start InitializeArchiveStructure"
	initFromArchive wfvariables.recStructure.iDocumentID.Value 'initialize variables from archive fields (e.g. version information)
	

	wfvariables.sTitle2.Value = wfvariables.sTitle.Value 'we got two title fields, we use the title also for the header of the mask
	folderID = getDocumentFolderID (wfvariables.recStructure.iDocumentID.Value) 'get the folderID of the current document
	wfvariables.recStructure.iFolderID.Value = folderID
	registerID = getDocumentRegisterID (wfvariables.recStructure.iDocumentID.Value) 'get the registerID of the current document
	wfvariables.recStructure.iRegisterID.Value = registerID
	
	'get the protocol register ID
	protocolRegisterID = getProtocolRegisterID (registerID)
	If protocolRegisterID = -1 Then 'a protocol register is not defined
		sProtocolRegister = CreateProtocolRegister (folderID, registerID) 'create a protocol register
		sProtocolRegister = Split(sProtocolRegister,",") 'the result is the objectId and the objectType in a comma separated string
		wfvariables.recStructure.iProtocolRegisterID.Value = sProtocolRegister(0)
		wfvariables.recStructure.iProtocolRegisterType.Value = sProtocolRegister(1)	
	Else
		wfvariables.recStructure.iProtocolRegisterID.Value = protocolRegisterID
	End If
	
debug2File "end InitializeArchiveStructure"
End Function

'**********************************************************
' CreateRevision
' @description: creates a new revision of a document 
'				creates a new register and a new document. both with status 0.
' @param: 
' @return: nothing
'**********************************************************
Function CreateRevision()
	debug2File "start CreateRevision"
	
	Dim bOnlyDocumentInRevision
	Dim bNewestDocumentForRevision
	
	initFromArchive wfvariables.recStructure.iDocumentID.Value 'initialize variables from archive fields (e.g. version information)
	
	'check if the document status is valid	
	If wfvariables.sStatus.Value <> "1" Then
		wfvariables.sError.Value = "StandardWF;;;DocumentHasToBeValid;;;Das Dokument muss den Status 'gltig' aufweisen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If	
	
	'check if there is a further document in revision - if this is the case we can't create a new revision
	bOnlyDocumentInRevision = isOnlyDocumentInRevision(wfvariables.sDocumentNumber.Value)
	If bOnlyDocumentInRevision = False Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyRevisioning;;;Es befindet sich bereits ein Dokument in der Revisionierung."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If
	
	'check if there is a document with a higher version number - if this is the case, we can't revise an old document
	bNewestDocumentForRevision = isNewestDocumentForRevision(wfvariables.sDocumentNumber.Value, wfvariables.sVersion.Value)
	If bNewestDocumentForRevision = False Then
		wfvariables.sError.Value = "StandardWF;;;HigherVersionExists;;;Es existiert ein Dokument mit einer hheren Version. Sie knnen kein altes Dokument revisionieren."
		wfvariables.bCorrect.Value = 3
		Exit Function 'no revision		
	End If
	
	'check if participants are defined (e.g. imported documents could not have participants, in this case we hat to exit the workflow)	
	If wfvariables.recUsers.Count = 0 And wfvariables.sNextAuthor.value = "" Then 'the variable recUsers will be initialized by the "initFromArchive" function, which is called a few lines above
		wfvariables.sError.Value = "StandardWF;;;ParticipantsError;;;Es existiert kein Umlauf (z.B. Autor) fr dieses Dokument, oder ein Teilnehmer exisitiert nicht mehr in der Organisation. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet."
		wfvariables.bCorrect.Value = 3
		Exit Function 'no revision	
	End If
	
	'check if the author still exists
	If wfvariables.sNextAuthor.value = "" Then
		sGUID = wfvariables.recUsers.Item(0).Item("sUserGuid").Value
		debug2File "Prfe, ob der Autor mit der GUID " & sGUID & " existiert..."
		On Error Resume Next		
		Err.Clear
		Set oOrgObject = wforganisation.GetOrgObjectById(sGUID)
		debug2File "Ergebnis: " & wforganisation.GetOrgObjectById(sGUID).Name
		If  Err.Number <> 0  then  
			debug2File "ERROR: Fr die GUID " & sGUID & " konnte kein User ermittelt werden..."
			wfvariables.sError.Value = "StandardWF;;;NoParticipants;;;Mindestens ein Anwender aus dem Umlauf exisitiert nicht mehr in der Organisation. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken, wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet." 
			wfvariables.bCorrect.Value = 3
			addProtocolEntry "The revision workflow was canceled by the system, because of incorrect participant information. The user " & wfvariables.recUsers.Item(0).Item("sUserName").Value & " does not exist.", "INFO", "SYSTEM", False
			addProtocolEntry "Details", "ERROR", "SYSTEM", True
			updateXMLProtocol wfvariables.recStructure.iFolderID.Value,wfvariables.recStructure.iProtocolRegisterID.Value
		
			Exit Function 'no revision							
		End If
	End If
	
	'check if all user still exist
'	For a = 0 To wfvariables.recUsers.Count -1 
'		sGUID = wfvariables.recUsers.Item(a).Item("sUserGuid").Value
'		debug2File "Prfe, ob ein User mit der GUID " & sGUID & " existiert..."
'		On Error Resume Next		
'		Err.Clear
'		Set oOrgObject = wforganisation.GetOrgObjectById(sGUID)
'		debug2File "Ergebnis: " & wforganisation.GetOrgObjectById(sGUID).Name
'		If  Err.Number <> 0  then  
'			debug2File "ERROR: Fr die GUID " & sGUID & " konnte kein User ermittelt werden..."
'			wfvariables.sError.Value = "NoParticipant=Mindestens ein Anwender aus dem Umlauf exisitiert nicht mehr in der Organisation. Wenn Sie die Meldung besttigen indem Sie [Weiterleiten] klicken, wird automatisch der Workflow zur Anpassung des Umlaufs fr die Rolle 'QM' gestartet. Betroffen:;;;" & wfvariables.recUsers.Item(a).Item("sUserName").Value
'			wfvariables.bCorrect.Value = 3
'			addProtocolEntry "The revision workflow was canceled by the system, because of incorrect participant information. The user " & wfvariables.recUsers.Item(a).Item("sUserName").Value & " does not exist.", "INFO", "SYSTEM", False
'			addProtocolEntry "Details", "ERROR", "SYSTEM", True
'			updateXMLProtocol wfvariables.recStructure.iFolderID.Value,wfvariables.recStructure.iProtocolRegisterID.Value
'			Exit Function 'no revision							
'		End If		
'	Next
	
	wfvariables.sTitle2.Value = wfvariables.sTitle.Value 'we got two title fields, we use the title also for the header of the mask
	folderID = getDocumentFolderID (wfvariables.recStructure.iDocumentID.Value) 'get the folderID of the current document
	wfvariables.recStructure.iFolderID.Value = folderID
	registerID = getDocumentRegisterID (wfvariables.recStructure.iDocumentID.Value) 'get the registerID of the current document
	wfvariables.recStructure.iRegisterID.Value = registerID
	
	newRegisterID = copyRegister (folderID, registerID) 'copy the register
	setRegisterStatus 0, newRegisterID 'set the new status for the new register
	setRegisterVersion CLng(wfvariables.sVersion.Value) + 1, newRegisterID 'increase the version for the new register
	originalDocumentID = getDocumentOriginalVariant (wfvariables.recStructure.iDocumentID.Value) 'get the object id of the original word document
	Dim bVariants
	If originalDocumentID = wfvariables.recStructure.iDocumentID.Value Then 'we got no variants for this document
		bVariants = False
	Else
		bVariants = True
	End If
	
	sProtocolRegister = CreateProtocolRegister (folderID, newRegisterID) 'create a protocol register
	sProtocolRegister = Split(sProtocolRegister,",") 'the result is the objectId and the objectType in a comma separated string
	wfvariables.recStructure.iProtocolRegisterID.Value = sProtocolRegister(0)
	wfvariables.recStructure.iProtocolRegisterType.Value = sProtocolRegister(1)	
	
	
	'cause it is an inactive variant, we can't copy the document file
	'so at first we need to temporaly activate the inactive variant	'TODO: better way ? storeObjectInCacheByID (sFile = storeObjectInCacheByID (documentID, 0))does not work correctly
	If bVariants = True Then
		iRet = setActiveVariant (wfvariables.recStructure.iDocumentID.Value, originalDocumentID, wfvariables.recStructure.iDocumentType.Value)
	End If
	
	newDocumentID = copyDocument (folderID, newRegisterID, originalDocumentID, wfvariables.recStructure.sDocumentInternalName.value)
	wfvariables.sStatus.Value = "0"

	'get the statusinformation of the document (the descriptive text, e.g. the status "0" means "in Arbeit / in progress"
	'the function is implemented in the customer functions, cause the descriptive text could differ for each customer
	sDescriptiveStatus = getStatusInformation (wfvariables.sStatus.Value)	
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value, newDocumentID, getInternalName_Document_DocumentStatusInfo, sDescriptiveStatus	
	'set write access of new variant to defined variable
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value, newDocumentID, getInternalName_Document_WriteRights(), wfvariables.sWriteRights.Value
	'set read access of new variant to defined variable
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value, newDocumentID, getInternalName_Document_ReadRights(), wfvariables.sReadRights.Value
	'clear the content of the index field 'next author'																								 
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value, newDocumentID, getInternalName_Document_NextAuthor(), ""
	'clear the field "valid from"
	wfvariables.dValiddate.value = ""	
	'clear the field "valid to"	
	wfvariables.dNextRevisionDate.value = ""

	'get the guid for the next author and assign it to the variable sActivityUserGuids (this variable will be checked first in the start activity, if this variable is set, the activity will be assigned to this user)
	'we deleted the field "next author" already on the archive object a few line above. but we still have the value in the internal variable
	If wfvariables.sNextAuthor.value <> "" Then
		wfvariables.sActivityUserGuids.value = wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).Id
		'now overwrite the performers-table for first activity (e.g. Revise)
		'1. get the full username
		sUserName = wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).GetAttributeValueByName("Vorname") & " " & wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).GetAttributeValueByName("Nachname")
		If Len(Trim(sUserName)) = 0 Then
			sUserName = wfvariables.sNextAuthor.value 'use the login name, if no user name is defined
		End If
		If wfvariables.recUsers.Count > 0 Then	'Bugfix for imported documents where it's possible to find an empty recUsers table
			wfvariables.recUsers.Item(0).Item("sUserName").Value = sUserName
			wfvariables.recUsers.Item(0).Item("sUserGuid").Value = wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).Id
		End If		
'		For a = 0 To wfvariables.recUsers.Count - 1
'			If wfvariables.recUsers.Item(a).Item("sActivity").Value = sActivity Then 'user are assigned in the table
'				sUsers = sUsers & wfvariables.recUsers.Item(a).Item("sUserGuid").Value & ","
'			End If			
'		Next
		
	End If

	'now activate the temporaly inactive variant again
	If bVariants = True Then
		iRet = setActiveVariant (originalDocumentID, wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value)
	End If
	
	'copy all attachments of the old document to the new version register
	copyAttachmentsAndIncreaseVersion wfvariables.recStructure.iDocumentID.Value, newRegisterID
	

	'now we created all objects in the next version, so increase the version variable
	wfvariables.sVersion.Value = wfvariables.sVersion.Value + 1
	
	'move the base version to the 'Info Bereich' in the wffile
	'first delete the base version from wffile
	thisprocess.WFFile.DeleteFileObject wfvariables.recStructure.iDocumentID.Value
	'now add the base version to info
	thisprocess.WFFile.AddFileObject wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, False, 1
	
	'add the new document to the workflow file			
	thisprocess.WFFile.AddFileObject newDocumentID, wfvariables.recStructure.iDocumentType.Value, True, 1
	For i=0 To thisprocess.WFFile.FileObjects.Count - 1
		If thisprocess.WFFile.FileObjects.Item(i).ID = objectId Then
			thisprocess.WFFile.FileObjects.Item(i).Moveable = False
			thisprocess.WFFile.FileObjects.Item(i).Deleteable = False
			Exit For
		End If
	Next
	'now assign the new document id to the internal variable and store the previous version
	wfvariables.recStructure.iPreviousDocumentID.Value = wfvariables.recStructure.iDocumentID.Value
	wfvariables.recStructure.iDocumentID.Value = newDocumentID
	'now assign the new register id to the internal variable and store the previous version
	wfvariables.recStructure.iPreviousRegisterID.Value = wfvariables.recStructure.iRegisterID.Value
	wfvariables.recStructure.iRegisterID.Value = newRegisterID
	
	wfvariables.dCreatorDate.Value = Date	'set the creation date
	
	'set the author
	Dim sCurrentUserGuid : sCurrentUserGuid = getCurrentActivityPerformerId
	'sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).Name
	wfvariables.sCreatorName.Value = sCurrentUserName

	'get the complete (firstname + lastname) username
	Dim sCurrentUserName : sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).GetAttributeValueByName("Vorname") & " " & wforganisation.GetOrgObjectById(sCurrentUserGuid).GetAttributeValueByName("Nachname")
	If sCurrentUserName <> "" Then 'use the fullname if existing
		wfvariables.sCreatorName.Value = sCurrentUserName
	End If
	
	
	'write back all data to the new document
	'nice effect:
		'cause of this mapToArchive the participants table will be empty on the datasheet of the document.
		'in mapToArchive we write back the recUsersSorted record, which is empty at this time	
	mapToArchive wfvariables.recStructure.iDocumentID.Value
	
	'sync the new document
	syncedFile = SynchronizeData (wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value)
	'replace the old document with the synced document
	If syncedFile <> "" Then
		ReplaceDocument wfvariables.recStructure.iDocumentID.Value, syncedFile
	End If	
	debug2File "end CreateRevision"
End Function

'**********************************************************
' CreateRevisionImport
' @description: creates a new revision of a document for imported documents with the state "in progress" and sets the status of the previous version to "invalid"
'				creates a new register and a new document. both with status 0.
' @param: 
' @return: nothing
'**********************************************************
Function CreateRevisionImport()
	debug2File "start CreateRevisionImport"
	
	Dim bOnlyDocumentInRevision
	Dim bNewestDocumentForRevision
	
	initFromArchive wfvariables.recStructure.iDocumentID.Value 'initialize variables from archive fields (e.g. version information)
		
	
	wfvariables.sTitle2.Value = wfvariables.sTitle.Value 'we got two title fields, we use the title also for the header of the mask
	folderID = getDocumentFolderID (wfvariables.recStructure.iDocumentID.Value) 'get the folderID of the current document
	wfvariables.recStructure.iFolderID.Value = folderID
	registerID = getDocumentRegisterID (wfvariables.recStructure.iDocumentID.Value) 'get the registerID of the current document
	wfvariables.recStructure.iRegisterID.Value = registerID
	
	newRegisterID = copyRegister (folderID, registerID) 'copy the register
	setRegisterStatus 0, newRegisterID 'set the new status for the new register
	setRegisterVersion CLng(wfvariables.sVersion.Value) + 1, newRegisterID 'increase the version for the new register
	originalDocumentID = getDocumentOriginalVariant (wfvariables.recStructure.iDocumentID.Value) 'get the object id of the original word document
	Dim bVariants
	If originalDocumentID = wfvariables.recStructure.iDocumentID.Value Then 'we got no variants for this document
		bVariants = False
	Else
		bVariants = True
	End If
	
	sProtocolRegister = CreateProtocolRegister (folderID, newRegisterID) 'create a protocol register
	sProtocolRegister = Split(sProtocolRegister,",") 'the result is the objectId and the objectType in a comma separated string
	wfvariables.recStructure.iProtocolRegisterID.Value = sProtocolRegister(0)
	wfvariables.recStructure.iProtocolRegisterType.Value = sProtocolRegister(1)	
	
	
	'cause it is an inactive variant, we can't copy the document file
	'so at first we need to temporaly activate the inactive variant	'TODO: better way ? storeObjectInCacheByID (sFile = storeObjectInCacheByID (documentID, 0))does not work correctly
	If bVariants = True Then
		iRet = setActiveVariant (wfvariables.recStructure.iDocumentID.Value, originalDocumentID, wfvariables.recStructure.iDocumentType.Value)
	End If
	
	newDocumentID = copyDocument (folderID, newRegisterID, originalDocumentID, wfvariables.recStructure.sDocumentInternalName.value)
	wfvariables.sStatus.Value = "0"
	'set write access of new variant to defined variable
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value,newDocumentID,getInternalName_Document_WriteRights(), wfvariables.sWriteRights.Value
	'set read access of new variant to defined variable
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value,newDocumentID,getInternalName_Document_ReadRights(), wfvariables.sReadRights.Value

	'now activate the temporaly inactive variant again
	If bVariants = True Then
		iRet = setActiveVariant (originalDocumentID, wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value)
	End If
	
	'copy all attachments of the old document to the new version register
	copyAttachmentsAndIncreaseVersion wfvariables.recStructure.iDocumentID.Value, newRegisterID
	

	'now we created all objects in the next version, so increase the version variable
	wfvariables.sVersion.Value = wfvariables.sVersion.Value + 1
	
	'move the base version to the 'Info Bereich' in the wffile
	'first delete the base version from wffile
	thisprocess.WFFile.DeleteFileObject wfvariables.recStructure.iDocumentID.Value
	'now add the base version to info
	thisprocess.WFFile.AddFileObject wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, False, 1
	
	'add the new document to the workflow file			
	thisprocess.WFFile.AddFileObject newDocumentID, wfvariables.recStructure.iDocumentType.Value, True, 1
	For i=0 To thisprocess.WFFile.FileObjects.Count - 1
		If thisprocess.WFFile.FileObjects.Item(i).ID = objectId Then
			thisprocess.WFFile.FileObjects.Item(i).Moveable = False
			thisprocess.WFFile.FileObjects.Item(i).Deleteable = False
			Exit For
		End If
	Next
	'now assign the new document id to the internal variable and store the previous version
	wfvariables.recStructure.iPreviousDocumentID.Value = wfvariables.recStructure.iDocumentID.Value
	wfvariables.recStructure.iDocumentID.Value = newDocumentID
	
	'invalid the previous version
	setDocumentStatus_3 wfvariables.recStructure.iPreviousDocumentID.Value
	
	'now assign the new register id to the internal variable and store the previous version
	wfvariables.recStructure.iPreviousRegisterID.Value = wfvariables.recStructure.iRegisterID.Value
	wfvariables.recStructure.iRegisterID.Value = newRegisterID
	
	wfvariables.dCreatorDate.Value = Date	'set the creation date
	
	'set the author
	Dim sCurrentUserGuid : sCurrentUserGuid = getCurrentActivityPerformerId
	sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).Name
	wfvariables.sCreatorName.Value = sCurrentUserName
	
	
	'write back all data to the new document
	'nice effect:
		'cause of this mapToArchive the participants table will be empty on the datasheet of the document.
		'in mapToArchive we write back the recUsersSorted record, which is empty at this time	
	mapToArchive wfvariables.recStructure.iDocumentID.Value
	
	'sync the new document
	syncedFile = SynchronizeData (wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value)
	'replace the old document with the synced document
	ReplaceDocument wfvariables.recStructure.iDocumentID.Value, syncedFile
	
	debug2File "end CreateRevisionImport"
End Function

'**********************************************************
' CreateTemplateRevision
' @description: creates a new revision of a template 
'				creates a new register and a new template. both with status 0.
' @param: 
' @return: nothing
'**********************************************************
Function CreateTemplateRevision()
	debug2File "start CreateTemplateRevision"
	
	Dim bOnlyDocumentInRevision
	Dim bNewestDocumentForRevision
	
	initFromArchive wfvariables.recStructure.iDocumentID.Value 'initialize variables from archive fields (e.g. version information)

	'check if the document status is valid	
	If wfvariables.sStatus.Value <> "1" Then
		wfvariables.sError.Value = "StandardWF;;;TemplateHasToBeValid;;;Die Vorlage muss den Status 'gltig' aufweisen."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If	
	
	'check if there is a further document in revision - if this is the case we can't create a new revision
	bOnlyDocumentInRevision = isOnlyDocumentInRevision(wfvariables.sDocumentNumber.Value)
	If bOnlyDocumentInRevision = False Then
		wfvariables.sError.Value = "StandardWF;;;AlreadyRevisioningTemplate;;;Es befindet sich bereits eine Vorlage in der Revisionierung."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revisions
	End If
	
	'check if there is a document with a higher version number - if this is the case, we can't revise an old document
	bNewestDocumentForRevision = isNewestDocumentForRevision(wfvariables.sDocumentNumber.Value, wfvariables.sVersion.Value)
	If bNewestDocumentForRevision = False Then
		wfvariables.sError.Value = "StandardWF;;;HigherVersionTemplateExists;;;Es existiert eine Vorlage mit einer hheren Version. Sie knnen keine veraltete Vorlage revisionieren."
		wfvariables.bCorrect.Value = 1
		Exit Function 'no revision		
	End If
	
	'get the guid for the next author and assign it to the variable sActivityUserGuids (this variable will be checked first in the start activity, if this variable is set, the activity will be assigned to this user)
	'we deleted the field "next author" already on the archive object a few line above. but we still have the value in the internal variable
	If wfvariables.sNextAuthor.value <> "" Then
		wfvariables.sActivityUserGuids.value = wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).Id
		'now overwrite the performers-table for first activity (e.g. Revise)
		'1. get the full username
		sUserName = wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).GetAttributeValueByName("Vorname") & " " & wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).GetAttributeValueByName("Nachname")
		If Len(Trim(sUserName)) = 0 Then
			sUserName = wfvariables.sNextAuthor.value 'use the login name, if no user name is defined
		End If
		wfvariables.recUsers.Item(0).Item("sUserName").Value = sUserName
		wfvariables.recUsers.Item(0).Item("sUserGuid").Value = wforganisation.GetOrgObjectsByName(wfvariables.sNextAuthor.value).Item(0).Id
		
'		For a = 0 To wfvariables.recUsers.Count - 1
'			If wfvariables.recUsers.Item(a).Item("sActivity").Value = sActivity Then 'user are assigned in the table
'				sUsers = sUsers & wfvariables.recUsers.Item(a).Item("sUserGuid").Value & ","
'			End If			
'		Next
		
	End If	
	
	wfvariables.sTitle2.Value = wfvariables.sTitle.Value 'we got two title fields, we use the title also for the header of the mask
	folderID = getDocumentFolderID (wfvariables.recStructure.iDocumentID.Value) 'get the folderID of the current document
	wfvariables.recStructure.iFolderID.Value = folderID
	registerID = getDocumentRegisterID (wfvariables.recStructure.iDocumentID.Value) 'get the registerID of the current document
	wfvariables.recStructure.iRegisterID.Value = registerID
	
	newRegisterID = copyRegister (folderID, registerID) 'copy the register
	setRegisterStatus 0, newRegisterID 'set the new status for the new register
	setRegisterVersion CLng(wfvariables.sVersion.Value) + 1, newRegisterID 'increase the version for the new register
	originalDocumentID = getDocumentOriginalVariant (wfvariables.recStructure.iDocumentID.Value) 'get the object id of the original word document
	Dim bVariants
	If originalDocumentID = wfvariables.recStructure.iDocumentID.Value Then 'we got no variants for this document
		bVariants = False
	Else
		bVariants = True
	End If
	
	sProtocolRegister = CreateProtocolRegister (folderID, newRegisterID) 'create a protocol register
	sProtocolRegister = Split(sProtocolRegister,",") 'the result is the objectId and the objectType in a comma separated string
	wfvariables.recStructure.iProtocolRegisterID.Value = sProtocolRegister(0)
	wfvariables.recStructure.iProtocolRegisterType.Value = sProtocolRegister(1)	
	
	
	'cause it is an inactive variant, we can't copy the document file
	'so at first we need to temporaly activate the inactive variant	'TODO: better way ? storeObjectInCacheByID (sFile = storeObjectInCacheByID (documentID, 0))does not work correctly
	If bVariants = True Then
		iRet = setActiveVariant (wfvariables.recStructure.iDocumentID.Value, originalDocumentID, wfvariables.recStructure.iDocumentType.Value)
	End If
	
	newDocumentID = copyDocument (folderID, newRegisterID, originalDocumentID, wfvariables.recStructure.sDocumentInternalName.value)
	wfvariables.sStatus.Value = "0"

	'get the statusinformation of the document (the descriptive text, e.g. the status "0" means "in Arbeit / in progress"
	'the function is implemented in the customer functions, cause the descriptive text could differ for each customer
	sDescriptiveStatus = getStatusInformation (wfvariables.sStatus.Value)	
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value,newDocumentID,getInternalName_Document_DocumentStatusInfo, sDescriptiveStatus	
	'set write access of new variant to defined variable
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value,newDocumentID,getInternalName_Document_WriteRights(), wfvariables.sWriteRights.Value
	'set read access of new variant to defined variable
	updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sDocumentInternalName.Value,newDocumentID,getInternalName_Document_ReadRights(), wfvariables.sReadRights.Value

	'now activate the temporaly inactive variant again
	If bVariants = True Then
		iRet = setActiveVariant (originalDocumentID, wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value)
	End If
	
	'copy all attachments of the old document to the new version register
	copyAttachmentsAndIncreaseVersion wfvariables.recStructure.iDocumentID.Value, newRegisterID
	

	'now we created all objects in the next version, so increase the version variable
	wfvariables.sVersion.Value = wfvariables.sVersion.Value + 1
	
	'move the base version to the 'Info Bereich' in the wffile
	'first delete the base version from wffile
	thisprocess.WFFile.DeleteFileObject wfvariables.recStructure.iDocumentID.Value
	'now add the base version to info
	thisprocess.WFFile.AddFileObject wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, False, 1
	
	'add the new document to the workflow file			
	thisprocess.WFFile.AddFileObject newDocumentID, wfvariables.recStructure.iDocumentType.Value, True, 1
	For i=0 To thisprocess.WFFile.FileObjects.Count - 1
		If thisprocess.WFFile.FileObjects.Item(i).ID = objectId Then
			thisprocess.WFFile.FileObjects.Item(i).Moveable = False
			thisprocess.WFFile.FileObjects.Item(i).Deleteable = False
			Exit For
		End If
	Next
	'now assign the new document id to the internal variable and store the previous version
	wfvariables.recStructure.iPreviousDocumentID.Value = wfvariables.recStructure.iDocumentID.Value
	wfvariables.recStructure.iDocumentID.Value = newDocumentID
	'now assign the new register id to the internal variable and store the previous version
	wfvariables.recStructure.iPreviousRegisterID.Value = wfvariables.recStructure.iRegisterID.Value
	wfvariables.recStructure.iRegisterID.Value = newRegisterID
	
	wfvariables.dCreatorDate.Value = Date	'set the creation date
	
	'set the author
	Dim sCurrentUserGuid : sCurrentUserGuid = getCurrentActivityPerformerId
	sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).Name
	wfvariables.sCreatorName.Value = sCurrentUserName
	
	
	'write back all data to the new document
	'nice effect:
		'cause of this mapToArchive the participants table will be empty on the datasheet of the document.
		'in mapToArchive we write back the recUsersSorted record, which is empty at this time	
	mapToArchive wfvariables.recStructure.iDocumentID.Value
	
	
	debug2File "end CreateTemplateRevision"
End Function

'**********************************************************
' CreateRegister
' @description: creates a new protocol register
' @param: folderID - the folder under which the register should be created, 
'		  registerID - the register under which the register should be created
' @return: the objectID and the objectType of the created object separated by comma
'			e.g. 150,262151
'**********************************************************
Function CreateProtocolRegister (folderID, registerID)
	debug2File "start CreateProtocolRegister (" & folderID & "," & registerID & ")"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	sXML = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sProtocolRegisterInternalName.Value & "' type='REGISTER'>" &_
	"<Object folder_id='" & CLng(folderID) & "' register_id='" & registerID & "'>" &_
	"<Fields>" &_
	"<Field internal_name='" & getInternalName_ProtocolRegister_DocumentNumber & "'>" & convertToValidXML(wfvariables.sDocumentNumber.Value) & "</Field>" &_
	"</Fields>" &_
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("XML")=dom 
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	
	iRet = RC.Jobs.DMS.XMLInsert(PrmIn, PrmOut)
	
	CreateProtocolRegister = PrmOut.Value("ObjectID") & "," &  PrmOut.Value("ObjectType")
	
	debug2File "end CreateProtocolRegister (" & folderID & "," & registerID & ")"
End Function


'**********************************************************
' getDocumentOriginalVariant
' @description: get the object id of the original variant of the document (documentObjectID)
' @param: documentObjectID (Integer) - the document of which the orginal variant id should be returned
' @return: documentID (Integer)
'**********************************************************
Function getDocumentOriginalVariant (documentObjectID)
	debug2File "start getDocumentOriginalVariant (" & documentObjectID & ")"
	
	getDocumentOriginalVariant = -1 
	
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
				"<Fields field_schema='DEF'/>" &_
				"<Conditions>" &_
					"<ObjectID>" & documentObjectID & "</ObjectID>" &_
				"</Conditions>" &_
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"	
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("Variants") = 1
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		Dim oNode
		Dim oxmlDoc : Set oxmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oxmlDoc.load(sfile) = True Then 
			Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/DocumentVariants/DocumentVariant[@doc_ver='Original']"
			Set oNode = oxmlDoc.selectSingleNode(xpath)
			If Not oNode Is Nothing Then
				getDocumentOriginalVariant = oNode.attributes.getNamedItem("doc_id").text
			Else
				'can't find a variant, so we assume that there is no variant. use the documentID as original document
				getDocumentOriginalVariant = documentObjectID
			End If							
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oxmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"getDocumentOriginalVariant failed"
	End If
	
	'clean up	
	Set dom = Nothing
	
	debug2File "end getDocumentOriginalVariant (" & documentObjectID & ")"
End Function

'**********************************************************
' copyDocument
' @description: copy the document with the 'documentID' to the register with 'registerID'
' @param: folderID (Integer) - the targetfolder of the new document, registerID (Integer) - the targetregister of the new document
'			documentID (Integer) - the source document
'			documentInternalName - the internal name of the document
' @return: documentID (Integer) - objectID of the new document
'**********************************************************
Function copyDocument (folderID, registerID, documentID, documentInternalName)
	debug2File "start copyDocument (folderID=" & folderID & ")" & "," & "registerID=(" & registerID & ")" & "," & "documentID=(" & documentID & ")"
	
	copyDocument = -1	
	
	If (folderID > 0) And (registerID > 0) And (documentID > 0) Then
		copyDocument = -1
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Dim sXML		
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & documentInternalName & "' type='DOCUMENT'>" &_
				"<Object object_id='" & documentID & "' folder_id='" & folderID & "' register_id='" & registerID & "'/>" &_
			"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		debug2file "copyDocument => copy XML = " & sXML
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 16
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		PrmIn.Value("Options")="ARCHIVABLE=0"
		
		
		iRet = RC.Jobs.DMS.XMLCopy(PrmIn, PrmOut)
		If iRet = 0 Then
			Dim newDocumentID
			newDocumentID = PrmOut.value("ObjectID")
			copyDocument = newDocumentID
		Else
			debug2File "copyDocument failed"
		End If
		
	Else
		debug2File "copyDocument failed - folderID or registerID or documentID are not valid"
	End If
	
	debug2File "end copyDocument (" & folderID & ")" & "," & "(" & registerID & ")" & "," & "(" & documentID & ") => " & copyDocument
End Function

'**********************************************************
' copyAttachmentsAndIncreaseVersion
' @description: copy all attachments of the documentID to a new register and increases the version and set the inital read and write rights
' @param: documentID (Integer) - the documentID of the main document for which all attachments should copied
' @param: newRegisterID (Integer) - the id of the new target register
' @return: nothing
'**********************************************************
Function copyAttachmentsAndIncreaseVersion (documentID, newRegisterID)
debug2File "Start copyAttachments"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	'at first get the version register
	folderID = getDocumentFolderID (documentID)
	registerID = getDocumentRegisterID (documentID)
		
	'at first get all attachments of the main document (documentID)
	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
				"<Fields field_schema='MIN'/>" &_
				"<ChildObjects>" &_
					"<ChildObjectType internal_name='" & wfvariables.recStructure.sAttachmentInternalName.Value & "' type='DOCUMENT'>" &_
						"<Fields field_schema='DEF'>" &_
							"<Field internal_name='" & getInternalName_Attachment_Status & "'/>"	&_
						"</Fields>" &_
					"</ChildObjectType>" &_			
				"</ChildObjects>" &_								
				"<Conditions>" &_
					"<ObjectID>" & registerID & "</ObjectID>" &_
				"</Conditions>" &_
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		Dim oNodes
		Dim oXmlDoc : Set oxmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oXmlDoc.load(sfile) = True Then 
			
			Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/ChildObjects/ObjectType/ObjectList/Object"
			Set oNodes = oxmlDoc.selectNodes (xpath)
			If Not oNodes Is Nothing Then
				Dim i
				For i = 0 To oNodes.length - 1
					attachmentID = oNodes.item(i).attributes.getNamedItem("id").text
					debug2File "Copy attachment with id: " & attachmentID
					newAttachmentID = copyDocument (folderID, newRegisterID, attachmentID, wfvariables.recStructure.sAttachmentInternalName.Value)
					setAttachmentVersion CLng(wfvariables.sVersion.Value) + 1, newAttachmentID
					'set attachment status to 0 (in progress)
					updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sAttachmentInternalName.Value,newAttachmentID,getInternalName_Attachment_Status(), "0"
					'set initial read and write access
					updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sAttachmentInternalName.Value,newAttachmentID,getInternalName_Attachment_WriteRights(), wfvariables.sWriteRights.Value
					updateField wfvariables.recStructure.sFolderInternalName.Value, "DOCUMENT", wfvariables.recStructure.sAttachmentInternalName.Value,newAttachmentID,getInternalName_Attachment_ReadRights(), wfvariables.sReadRights.Value
				Next
			End If		
		
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oXmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"Error: copyAttachments GetResultList failed..."
	End If
	
	'clean up	
	Set oXmlDoc = Nothing
debug2File "End copyAttachments"
End Function

'**********************************************************
' copyRegister
' @description: copy the register with the 'registerID' to the folder with 'folderID'
' @param: folderID (Integer) - the targetfolder of the new register, registerID (Integer) - the source
' @return: registerID (Integer) - objectID of the new register
'**********************************************************
Function copyRegister (folderID, registerID)
	debug2File "start copyRegister (" & folderID & ")" & "," & "(" & registerID & ")"
	
	If (folderID > 0) And (registerID > 0) Then
		copyRegister = -1
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Dim sXML		
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType type='REGISTER' internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "'>" &_
		"<Object folder_id='" & folderID & "' object_id='" & registerID & "'/>" &_
		"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 16
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		PrmIn.Value("Options")="ARCHIVABLE=0"
		
		iRet = RC.Jobs.DMS.XMLCopy(PrmIn, PrmOut)
		If iRet = 0 Then
			Dim newRegisterID
			newRegisterID = PrmOut.value("ObjectID")
			copyRegister = newRegisterID
		Else
			copyRegister = -1
			debug2File "copyRegister failed"
		End If
		
	Else
		debug2File "copyRegister failed - folderID or registerID are not valid"
	End If
	
	debug2File "end copyRegister (" & folderID & ")" & "," & "(" & registerID & ")"
End Function

'**********************************************************
' getDocumentFolderID
' @description: get the object id of a superior folder of the document (documentObjectID)
' @param: documentObjectID (Integer) - the document of which the superior folder id should be returned
' @return: folderID (Integer)
'**********************************************************
Function getDocumentFolderID (documentObjectID)
	debug2File "start getDocumentFolderID (" & documentObjectID & ")"
	
	If wfvariables.recStructure.iFolderID.Value > 0 Then
		getDocumentFolderID = wfvariables.recStructure.iFolderID.Value
		debug2File "getDocumentFolderID: " & wfvariables.recStructure.iFolderID.Value
		Exit Function
	End If
	
	getDocumentFolderID = -1 
	
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
				"<Fields field_schema='MIN'/>" &_
				"<ParentObjects>" &_
					"<ParentObjectType internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "' type='FOLDER'>" &_
						"<Fields field_schema='MIN'/>" &_				
					"</ParentObjectType>" &_			
				"</ParentObjects>" &_								
				"<Conditions>" &_
					"<ObjectID>" & documentObjectID & "</ObjectID>" &_
				"</Conditions>" &_					
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		Dim oNode
		Dim oxmlDoc : Set oxmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oxmlDoc.load(sfile) = True Then 
			Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/@id"
			Set oNode = oxmlDoc.selectSingleNode(xpath)
			getDocumentFolderID = CLng(oNode.text)
			debug2File vbTab & "FolderID: " & oNode.text
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oxmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"getDocumentFolderID failed"
	End If
	
	'clean up	
	Set dom = Nothing
	
	debug2File "end getDocumentFolderID (" & documentObjectID & ")"
End Function


'**********************************************************
' getProtocolRegisterID
' @description: get the protocolRegisterID
' @param: versionRegisterID (Integer) - the versionRegisterID of the superior register
' @return: registerID (Integer)
'**********************************************************
Function getProtocolRegisterID (versionRegisterID)
debug2File "start getProtocolRegisterID (" & documentObjectID & ")"
	
	If wfvariables.recStructure.iProtocolRegisterID.Value > 0 Then
		getProtocolRegisterID = wfvariables.recStructure.iProtocolRegisterID.Value
		Exit Function
	End If
	
	getProtocolRegisterID = -1 
	
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
			"<Fields field_schema='MIN'/>" &_
			"<ChildObjects>" &_
				"<ChildObjectType internal_name='" & wfvariables.recStructure.sProtocolRegisterInternalName.Value & "' type='REGISTER'>" &_
					"<Fields field_schema='MIN'/>" &_				
				"</ChildObjectType>" &_			
			"</ChildObjects>" &_								
			"<Conditions>" &_
				"<ObjectID>" & versionRegisterID & "</ObjectID>" &_
			"</Conditions>" &_					
		"</ObjectType>" &_
	"</Archive>" &_
	"</DMSQuery>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		Dim oNode
		Dim oxmlDoc : Set oxmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oxmlDoc.load(sfile) = True Then 
			Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/ChildObjects/ObjectType/ObjectList/Object/@id"
			Set oNode = oxmlDoc.selectSingleNode(xpath)
			If Not oNode Is Nothing Then
				getProtocolRegisterID = CLng(oNode.text)
				debug2File vbTab & "ProtocolRegisterID: " & oNode.text
			Else
			'we found no protocol register, so create the register
				debug2File vbTab & "WARNING: Found no protocol register..."
			End If
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oxmlDoc = Nothing
		Set oFSO = Nothing
	Else
		debug2file	"getProtocolRegisterID failed"
	End If
	
	'clean up	
	Set dom = Nothing
	
debug2File "end getProtocolRegisterID (" & documentObjectID & ")"
End Function

'**********************************************************
' getDocumentRegisterID
' @description: get the object id of a superior register of the document (documentObjectID)
' @param: documentObjectID (Integer) - the document of which the superior register id should be returned
' @return: registerID (Integer)
'**********************************************************
Function getDocumentRegisterID (documentObjectID)
	debug2File "start getDocumentRegisterID (" & documentObjectID & ")"
	
'	If wfvariables.recStructure.iRegisterID.Value > 0 Then
'		getDocumentRegisterID = wfvariables.recStructure.iRegisterID.Value
'		debug2File "RegisterID: " & wfvariables.recStructure.iRegisterID.Value
'		Exit Function
'	End If
	
	getDocumentRegisterID = -1 
	
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sXML
	sXML = "" &_
	"<DMSQuery request_type='HOL'>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
	"<Fields field_schema='MIN'/>" &_
	"<ParentObjects>" &_
	"<ParentObjectType internal_name='" & wfvariables.recStructure.sRegisterInternalName.Value & "' type='REGISTER'>" &_
	"<Fields field_schema='MIN'/>" &_				
	"</ParentObjectType>" &_			
	"</ParentObjects>" &_								
	"<Conditions>" &_
	"<ObjectID>" & documentObjectID & "</ObjectID>" &_
	"</Conditions>" &_					
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSQuery>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		Dim oNode
		Dim oxmlDoc : Set oxmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oxmlDoc.load(sfile) = True Then 
			Dim xpath : xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object/ChildObjects/ObjectType/ObjectList/Object/@id"
			Set oNode = oxmlDoc.selectSingleNode(xpath)
			getDocumentRegisterID = CLng(oNode.text)
			debug2File vbTab & "RegisterID: " & oNode.text
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oFSO = Nothing
	Else
		debug2file	"getDocumentRegisterID failed"
	End If
	
	'clean up	
	Set dom = Nothing
	
	debug2File "end getDocumentRegisterID (" & documentObjectID & ")"
End Function

'**********************************************************
' storeObjectInCacheByID
' @description: transfers a document from osecm to the user cache
' @param: ObjectID (Integer) - objectID of the object which should be stored in the user cache
'		 for example used to store a document template temporary in the cache
'		  Convert (Integer): 0 no conversion, 1 convert to PDF
' @return: filepath of the stored object
'**********************************************************
Function storeObjectInCacheByID (ObjectID, Convert)
	debug2File "start storeObjectInCacheByID (" & ObjectID & "," & Convert & ")"	
	If CLng(ObjectID) > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 1
		PrmIn.Value("dwObjectID") = CLng(ObjectID)
		PrmIn.Value("Convert") = CLng(Convert)
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		
		iRet = RC.Jobs.STD.StoreInCacheByID(PrmIn, PrmOut)
		
		If iRet = 0 Then 'check the results
			debug2File vbTab & "storeObjectInCacheByID successful"
			sfile = PrmOut.Value("$Job$Files$")
			debug2File vbTab & "Filepath vor nderung: " & sfile
			Dim bDeleteFile : bDeleteFile = False
			If (Left(sfile,1) = "?") Then
				sfile = Mid(sfile,2,Len(sfile)-2) 'the filepath could be like this: ?c:\os\osecm\server\ostemp\cnv_8344DC14615E446393CAB88B2096AC27.pdf;
				bDeleteFile = True
			Else
				sfile = Mid(sfile,1,Len(sfile)-1) 'the filepath could be like this: C:\OS\OSECM\server\WORK\07\02\22\00000322.xml;
			End If
			debug2File vbTab & "Filepath: " & sfile
			
			Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
			Dim sNewFile 'copy the file, cause the file will be deleted if the job ends
			
			
			'sNewFile = sfile & ".tmp." & oFSO.GetExtensionName(sfile) 'the file should be deleted by the calling function
			sNewFile = RC.ServerData.TempDir & oFSO.GetFileName(sfile) & ".tmp." & oFSO.GetExtensionName(sfile)
			debug2File vbTab & "CopyFile: " & sfile & " -> " & sNewFile 
			oFSO.CopyFile sfile, sNewFile
			debug2File vbTab & "Stored document path: " & sNewFile
			storeObjectInCacheByID  = sNewFile
			
			If (oFSO.FileExists (sfile) = True) And (bDeleteFile = True) Then 'delete the file
				debug2File "Delete " & sfile
				oFSO.DeleteFile sfile
			End If
			
			'clean up
			Set oFSO = Nothing
		Else
			debug2File "storeObjectInCacheByID failed"
		End If
		
	Else
		debug2File "No document available"	
	End If
	debug2File "end storeObjectInCacheByID (" & ObjectID & "," & Convert & ")"	
End Function

'**********************************************************
' isNewestDocumentForRevision
' @description: checks if the document is the newest (got the highest version)
' @param: 		documentNumber (String) - the number of the document which should be checked
'				documentVersion (String) - the version of the document which should be checked
'
' @return: True, if the document got the highest version number - otherwise False
'**********************************************************
Function isNewestDocumentForRevision (documentNumber, documentVersion)
	debug2File "start isNewestDocumentForRevision (" & documentNumber & "," & documentVersion & ")"
	
	'create running context object
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	'check if there is a document with the same document number and a higher version and a status lower than 4 - if this is the case we can't revise an old document
	Dim sXML : sXML = "" &_
	"<DMSQuery request_type='HOL' status='1'>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_		
				"<Fields>"  &_
					"<Field internal_name='" & getInternalName_Document_DocumentVersion & "' sortpos='1' sortorder='DESC'/>" &_
				"</Fields>"	&_
				"<Conditions>" &_
					"<ConditionObject internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
						"<FieldCondition internal_name='" & getInternalName_Document_DocumentNumber & "' operator='='>" &_
							"<Value>" & documentNumber & "</Value>" &_
						"</FieldCondition>" &_
						"<FieldCondition internal_name='" &  getInternalName_Document_DocumentVersion & "' operator='&gt;'>" &_
							"<Value>" & documentVersion & "</Value>" &_
						"</FieldCondition>" &_	
						"<FieldCondition internal_name='" &  getInternalName_Document_DocumentStatus & "' operator='&lt;'>" &_
							"<Value>4</Value>" &_
						"</FieldCondition>" &_							
					"</ConditionObject>" &_
				"</Conditions>" &_
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSQuery>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oXmlDoc.load(sfile) = True Then 
			Dim oNodes
			
			debug2File sfile
			debug2File oXmlDoc.xml
			
			Set oNodes = oXmlDoc.DocumentElement.selectNodes("//DMSContent/Archive/ObjectType/ObjectList/Object/Fields/Field[@internal_name='" & getInternalName_Document_DocumentVersion & "']")
			If oNodes.length = 0 Then
				isNewestDocumentForRevision = True 
			Else
				isNewestDocumentForRevision = False 'we got a document with a higher version
			End If						
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oFSO = Nothing
		
		
	Else
		isNewestDocumentForRevision = False 'for safety reasons
	End If
	
	'clean up
	Set dom = Nothing
	Set oXmlDoc = Nothing
	
	debug2File "end isNewestDocumentForRevision (" & documentNumber & "," & documentVersion & ")"
End Function


'**********************************************************
' isOnlyDocumentInRevision
' @description: checks if another document is already in revision
' @param: 		documentNumber (String) - the number of the document which should be checked
'
' @return: True, if there is no further document with status 0 - otherwise False
'**********************************************************
Function isOnlyDocumentInRevision (documentNumber)
	debug2File "start isOnlyDocumentInRevision (" & documentNumber & ")"
	
	'create running context object
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	'check if there is another document with the same document number and status 0  - if this is the case, we got a further document in Revision
	Dim sXML : sXML = "" &_
	"<DMSQuery request_type='HOL' status='1'>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_		
	"<Fields>"  &_
	"<Field internal_name='" & getInternalName_Document_DocumentVersion & "' sortpos='1' sortorder='DESC'/>" &_
	"</Fields>"	&_
	"<Conditions>" &_
	"<ConditionObject internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
	"<FieldCondition internal_name='" & getInternalName_Document_DocumentNumber & "' operator='='>" &_
	"<Value>" & documentNumber & "</Value>" &_
	"</FieldCondition>" &_
	"<FieldCondition internal_name='" &  getInternalName_Document_DocumentStatus & "' operator='='>" &_
	"<Value>0</Value>" &_
	"</FieldCondition>" &_				
	"</ConditionObject>" &_
	"</Conditions>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSQuery>"
	
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oXmlDoc.load(sfile) = True Then 
			Dim oNodes
			
			Set oNodes = oXmlDoc.DocumentElement.selectNodes("//DMSContent/Archive/ObjectType/ObjectList/Object/Fields/Field[@internal_name='" & getInternalName_Document_DocumentVersion & "']")
			If oNodes.length = 0 Then
				isOnlyDocumentInRevision = True 
			Else
				isOnlyDocumentInRevision = False 'we got a further document in revision
			End If						
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oFSO = Nothing		
		
	Else
		debug2File "isOnlyDocumentInRevision failed"
		isOnlyDocumentInRevision = False 'for safety reasons
	End If
	
	'clean up
	Set dom = Nothing
	Set oXmlDoc = Nothing
	
	debug2File "end isOnlyDocumentInRevision (" & documentNumber & ")"
End Function

'**********************************************************
' getObjectDetails
' @description: Runs the DMS.GetObjectDetails job (running context)
' @param: ObjectID, ObjectType (empty string alternative), Systemfields (see API documentation, empty string alternative)
' @return: xml file, -1 if the job was not successfull (the file must be deleted by the calling function)
'**********************************************************
Function getObjectDetails (ObjectID, ObjectType, SystemFields)
	debug2File "start getObjectDetails (" & ObjectID & ")" & "," & "(" & ObjectType & ")" & "," & "(" & SystemFields & ")" 
	'create running context object
	Dim RC
	Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	If ObjectType = "" Then	'check the object type, an empty string is not allowed
		ObjectType = -1
	End If
	
	PrmIn.Clear()
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")
	PrmIn.Value("ObjectID") = CLng(ObjectID)
	PrmIn.Value("ObjectType") = CLng(ObjectType)
	If SystemFields <> "" Then
		PrmIn.Value("SystemFields") = SystemFields
	End If
	
	' run Job
	iRet = RC.Jobs.DMS.GetObjectDetails(PrmIn, PrmOut)  
	'check return values
	If iRet=0 Then
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		getObjectDetails = sfile
	Else
		debug2File "Failed: getObjectDetails (" & ObjectID & ")" & "," & "(" & ObjectType & ")" & "," & "(" & SystemFields & ")" 
		getObjectDetails = -1
	End If
	debug2File "end getObjectDetails (" & ObjectID & ")" & "," & "(" & ObjectType & ")" & "," & "(" & SystemFields & ")" 
End Function


'**********************************************************
' deleteDocument
' @description: deletes a document
' @param: objectID (Integer) - the object id of the document which should be deleted
' @param: internalName (String) - the internal name of the document which should be deleted
' @return: returnvalue of the XMS.XMLDelete job
'**********************************************************
Function deleteDocument (objectID, internalName)
	debug2File "start - DeleteDocument (" & objectID & ", " & internalName & ")" 
	If CLng(objectID) > 0 Then
		
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		sXML = "" &_
		"<DMSData>" &_
		"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
		"<ObjectType internal_name='" & internalName & "' type='DOCUMENT'>" &_
		"<Object object_id='" & objectID & "'>" &_
		"</Object>" &_
		"</ObjectType>" &_
		"</Archive>" &_
		"</DMSData>"
		
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 16
		PrmIn.Value("XML")=dom 
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		'PrmIn.Value("Options")="HARDDELETE=1;CHECKACCESS=1"
		PrmIn.Value("Options")="CHECKACCESS=1"
		
		
		iRet = RC.Jobs.DMS.XMLDelete(PrmIn, PrmOut)
		If iRet <> 0 Then
			debug2File vbTab & "ERROR: deleteDocument not sucessful... (ErrorCode: " & iRet & ")"
		End If
		deleteDocument = iRet
	Else
		debug2File vbTab & "Error: No document available."
	End If
	debug2File "end - DeleteDocument" 
End Function

Function STDdeleteDocumentVariant (objectID, objectType, parentID)
	debug2File "start - STDdeleteDocumentVariant (" & objectID & ", " & objectType & ")" 
	If CLng(objectID) > 0 Then
		
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("sDeleteMethod") = "Delete"
		PrmIn.Value("dwObjectID") = objectID
		PrmIn.Value("dwObjectType") = objectType
		PrmIn.Value("dwParentID") = 0'parentID
		PrmIn.Value("dwParentType") = objectType
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
				
		iRet = RC.Jobs.STD.DeleteObject(PrmIn, PrmOut)
		If iRet <> 0 Then
			debug2File vbTab & "ERROR: STDdeleteDocumentVariant not sucessful... (ErrorCode: " & iRet & ")"
		End If
		STDdeleteDocumentVariant = iRet
	Else
		debug2File vbTab & "Error: No document available."
	End If
	debug2File "end - STDdeleteDocumentVariant" 
End Function


Function MoveDocumentToRegister (objectID, internalName, RegisterDestinationID)
debug2File "start - MoveDocumentToRegister (" & objectID & ", " & RegisterDestinationID & ")" 
	If CLng(objectID) > 0 Then
		
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		sXML = "" &_
		"<DMSData>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
				"<ObjectType internal_name='" & internalName & "' type='DOCUMENT'>" &_
					"<Object object_id='" & objectID & "' register_id='" & RegisterDestinationID & "'>" &_
					"</Object>" &_
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSData>"
		debug2file sXML
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 16
		PrmIn.Value("XML")=dom 
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		'wforganisation.GetOrgObjectsByName("osservice").Item(0).Id
		
		iRet = RC.Jobs.DMS.XMLMove(PrmIn, PrmOut)
		If iRet <> 0 Then
			debug2File vbTab & "ERROR: MoveDocumentToRegister not sucessful... (ErrorCode: " & iRet & ")"
		End If
		MoveDocumentToRegister = iRet
	Else
		debug2File vbTab & "Error: No document available."
	End If
	debug2File "end - MoveDocumentToRegister" 

End Function


'*************************************************************
'deleteObjectInWFFile
'description: deletes a file which is in the wffile. therefore
'				temporarly a database table entry has to be changed
'*************************************************************
Function deleteObjectInWFFile (objectID, internalName)
	processID = thisprocess.ProcessId
	debug2File "start deleteObjectInWFFile( " & objectID & ", " & processID & ")"
	
    
    
    ExecuteSQL "update oswfdrel set object_id = 0 where object_id = " & objectID & " and processid = '" & processID & "'"

	deleteDocument objectID, internalName
	
 	ExecuteSQL "update oswfdrel set object_id = " & objectID & " where object_id = 0 and processid = '" & processID & "'"


debug2file "end deleteObjectInWFFile( " & objectID & ", " & processID & ")"
End Function

'**********************************************************
' ExecuteSQL
' @description: executes a sql statement with the os server api
' @param: valSQL (String)  - the sql statement which should be executed
' @return: the result of the sql statement
'**********************************************************
Public Function ExecuteSQL(valSQL)

	Dim RC 
	Set RC = RunningContext 		
	'create running context object
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams

	PrmIn.Clear() 
	PrmIn.Value("Flags") = 0
	PrmIn.Value("Command") = valSQL
	'PrmIn.Value("User") = strTechnicalUser
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 

    Result = CLng(0)
  	ExecuteSQL = Result
  	
	iRet = RC.Jobs.ADO.ExecuteSQL(PrmIn, PrmOut)
	
	If iRet = 0 Then
		'sfile = PrmOut.Value("$Job$Files$")
		'sfile = Mid(sfile,2,Len(sfile)-2)
		'Result = sfile
		'debug2file sfile
		debug2File vbTab & "ExecuteSQL succesful..."			
	Else
		debug2File vbTab & "ERROR: ExecuteSQL failed..."			
	End If
	
	ExecuteSQL = Result

End Function

'**********************************************************
' addActiveVariant
' @description: adds an active variant to an object, the file 'sDocumentFilePath' will be deleted in the end
' @param: 		objectID (Integer) - objectID of the object which should get the new variant
'				objectType (Integer) - objectType of the object which should get the new variant
'				sDocumentFilePath (String) - document file path of the new variant
' @return: nothing
'**********************************************************
Function addActiveVariant (objectID, objectType, sDocumentFilePath)
	debug2File "start addActiveVariant (" & ObjectID & "," & objectType & "," & sDocumentFilePath & ")"	
	If CLng(ObjectID) > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		PrmIn.Clear() 
		PrmIn.Value("sDocVer") = "1.0.0"
		PrmIn.Value("dwParentID") = CLng(ObjectID)
		PrmIn.Value("dwObjectType") = CLng(objectType)
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		
		'create a new variant first
		iRet = RC.Jobs.STD.GetDocVariant(PrmIn, PrmOut)
		If iRet = 0 Then
			'now add the document file to the new variant
			debug2File "New variant: " & PrmOut.value("dwVariantID")
			Dim iVariantID
			iVariantID = PrmOut.Value("dwVariantID")
			PrmIn.Clear()
			PrmOut.Clear()
			
			PrmIn.Value("Flags") = 0
			PrmIn.Value("dwObjectID") = CLng(iVariantID)
			PrmIn.Value("dwObjectType") = CLng(objectType)
			PrmIn.Value("FileCount") = 1
			PrmIn.Value("$Job$Files$" ) = sDocumentFilePath
			
			iRet = RC.Jobs.STD.StoreInWork(PrmIn, PrmOut)
			If iRet = 0 Then
				
				Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
				If oFSO.FileExists (sDocumentFilePath) = True Then 'delete the file
					oFSO.DeleteFile sDocumentFilePath
				End If
				'clean up
				Set oFSO = Nothing
				
				'now activate the new variant
				PrmIn.Clear()
				PrmOut.Clear()
				
				PrmIn.Value("Flags") = 0
				PrmIn.Value("dwNextActVarID") = CLng(iVariantID)
				PrmIn.Value("dwPrevActVarID") = CLng(objectID)
				PrmIn.Value("dwObjectType") = CLng(objectType)
				
				iRet = RC.Jobs.STD.SetActiveVariant(PrmIn, PrmOut)
				If iRet = 0 Then
					
					'remember old variant (Word Document)
					wfvariables.recStructure.iOldDocumentID.Value = wfvariables.recStructure.iDocumentID.Value
					
					'remember pdf variant
					wfvariables.recStructure.iPDFID.Value = iVariantID		
					
					'now we had to update the internal document object ID
					wfvariables.recStructure.iDocumentID.Value = iVariantID
				Else
					debug2File "SetActiveVariant failed"
				End If
			Else
				debug2File "StoreInWork failed"	
			End If
		Else
			debug2File "GetDocVariant failed"		
		End If
	Else
		debug2File "No document available"	
	End If
	debug2File "end addActiveVariant (" & ObjectID & "," & objectType & "," & sDocumentFilePath & ")"	
End Function

'**********************************************************
' setActiveVariant
' @description: sets the active variant
' @param: currentActiveVariant
' @param: futureActiveVariant
' @param: objectType
' @return: nothing
'**********************************************************
Function setActiveVariant (currentActiveVariant, futureActiveVariant, objectType)
	debug2File 	"start - setActiveVariant (currentActiveVariant=" & currentActiveVariant & ",futureActiveVariant=" & futureActiveVariant & ",objectType=" & objectType & ")"
	'create running context object
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	
	PrmIn.Value("Flags") = 0
	PrmIn.Value("dwNextActVarID") = CLng(futureActiveVariant)
	PrmIn.Value("dwPrevActVarID") = CLng(currentActiveVariant)
	PrmIn.Value("dwObjectType") = CLng(objectType)
	
	iRet = RC.Jobs.STD.SetActiveVariant(PrmIn, PrmOut)
	If iRet <> 0 Then
		debug2File vbTab & "setActiveVariant failed... Errorcode: " & CStr(iRet)
	Else
		debug2File vbTab & "setActiveVariant successfull..."
	End If
	setActiveVariant = iRet
	debug2File "end - setActiveVariant"
End Function

'**********************************************************
' setInvalidation
' @description: sets the invalidation date and the name of the invalidator
' @param: nothing
' @return: nothing
'**********************************************************
Function setInvalidation
	debug2File "start - setInvalidation"
	wfvariables.dInvalidatorDate.Value = Now
	
	Dim sCurrentUserGuid : sCurrentUserGuid = getCurrentActivityPerformerId
	If sCurrentUserGuid = "" Then
		debug2File "setInvalidation => No User Guid"	
		Exit Function
	End If
	'get the complete (firstname + lastname) username
	Dim sCurrentUserName : sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).GetAttributeValueByName("Vorname") & " " & wforganisation.GetOrgObjectById(sCurrentUserGuid).GetAttributeValueByName("Nachname")
	If sCurrentUserName = "" Then 'use the LogIn Name if no complete name is defined
		sCurrentUserName = wforganisation.GetOrgObjectById( sCurrentUserGuid ).Name
	End If
	
	'set the invalidator and the invalidationDate. The values will me mapped by the mapToArchive feature
	wfvariables.sInvalidator.Value = sCurrentUserName
	wfvariables.dInvalidatorDate.Value = Date
	
	'sets the document and register status
	setDocumentStatus_3
	
	debug2File "end - setInvalidation"	
End Function

'**********************************************************
' getTemplates
' @description
' @param
' @return
'**********************************************************
Function getTemplates()
	debug2File "start - getTemplates"
	'create running context object
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	'create XML request - in this case we already stored the request in a variable (read from the configuration file)
	Dim sXML : sXML = wfvariables.sTemplateRequest.Value
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	
	If iRet=0 Then
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		Dim oxmlDoc : Set oxmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oxmlDoc.load(sfile) = True Then 
			Dim oNodesObjects, oNodesFields
			Dim xpathObjects, xpathFields
			
			
			xpathObjects = "/DMSContent/Archive/ObjectType/ObjectList/Object"
			Set oNodesObjects = oxmlDoc.selectNodes(xpathObjects)
			If Not oNodesObjects Is Nothing Then
				wfvariables.recTemplates.ClearList
				For i=0 To oNodesObjects.length - 1
					Dim objectID			
					objectID = oNodesObjects.item(i).attributes.getNamedItem("id").text
					xpathFields = "/DMSContent/Archive/ObjectType/ObjectList/Object[@id='" & objectID & "']/Fields/Field"
					Set oNodesFields = oxmlDoc.selectNodes (xpathFields)
					If Not oNodesFields Is Nothing Then					
						
						Set oEntry = wfvariables.recTemplates.CreateListItem
						oEntry.Item("sTemplateNumber").Value = oNodesFields.item(0).text 'template document number
						'template document number + template name + template language
						'(e.g. TEM-00001|Template SOP - deutsch;TEM-00002|Template Inspection Plan - english)
						oEntry.Item("sTemplateDescription").Value = oNodesFields.item(0).text & "|" & oNodesFields.item(1).text & " - " & oNodesFields.item(2).text
						oEntry.Item("iTemplateObjectID").Value = objectID 'template objectID					
						wfvariables.recTemplates.AddListItem oEntry											
					End If				
				Next
			End If               
		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		'Clean up
		Set oFSO = Nothing			
	Else
		debug2File "getTemplates failed"
	End If
	
	
	Set oxmlDoc = Nothing
	debug2File "end - getTemplates"	
End Function

Function getSystemTemplates
	debug2File "start - getSystemTemplates"
	'create running context object
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	PrmIn.Clear()
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("dwObjectType") = CLng(wfvariables.recStructure.iDocumentType.Value)
	iRet = RC.Jobs.Std.GetTemplates(PrmIn, PrmOut)
	
	Dim nCount : nCount = CLng( PrmOut.Value("nCount") )
	debug2File "Anzahl GetTemplates: " & nCount
	wfvariables.recTemplates.ClearList
	For i=0 To nCount - 1
		
		Dim sNum : sNum = "" & i
		If i < 10 Then
			sNum = "0" & sNum
		End If
		If i < 100 Then
			sNum = "0" & sNum
		End If
		
		Set oEntry = wfvariables.recTemplates.CreateListItem
		oEntry.Item("sTemplateNumber").Value = PrmOut("TemplateId" & sNum).Value 'alias of the template
		'template document number + template name + template language
		'(e.g. TEM-00001|Template SOP - deutsch;TEM-00002|Template Inspection Plan - english)
		oEntry.Item("sTemplateDescription").Value = PrmOut("TemplateId" & sNum).Value & "|" & PrmOut("Aliase" & sNum).Value
		oEntry.Item("iTemplateObjectID").Value = PrmOut("FileName" & sNum).Value 'template filename
		wfvariables.recTemplates.AddListItem oEntry	
		
		debug2File PrmOut("TemplateId" & sNum).Value & "|" & PrmOut("Aliase" & sNum).Value	
	Next
	
	debug2File "end - getSystemTemplates"	
End Function

'**********************************************************
' createXMLProtocol
' @description: creates a XML Protocol, which describes an instance of the controlled document process
' @param: FolderID - the id of the folder where the protocol should be archived
'		  RegisterID - the id of the register where the protocol should be archived
' @return: 
'**********************************************************
Function createXMLProtocol (FolderID, RegisterID)
	debug2File "Start createXMLProtocol"
	
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	wfvariables.sProtocolCreation.Value = Now
	
	'get all protocol document fields to write them back to the archive object
	Dim sFields
	For i = 0 To wfvariables.recConfigStructureFields.Count - 1 	
		If wfvariables.recConfigStructureFields.Item(i).Item("sArchiveObject").Value = "ProtocolDocument" Then
			internalName = wfvariables.recConfigStructureFields.Item(i).Item("sInternalName").Value
			variable = wfvariables.recConfigStructureFields.Item(i).Item("sVariableName").Value
			sFields = sFields & vbCrLf &_
			"<Field internal_name='" & internalName & "'>" & convertToValidXML(CStr(wfvariables.Item(variable).Value)) & "</Field>"
		End If
	Next
	
	
	sXML = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sProtocolDocumentInternalName.Value & "' type='DOCUMENT'>" &_
	"<Object folder_id='" & CLng(FolderID) & "' register_id='" & CLng(RegisterID) & "'>" &_
	"<Fields>" &_
	sFields &_
	"</Fields>" &_
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("XML")=dom 
	'PrmIn.Value("$Job$Files$" ) = sTmpProtocolPath
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	
	iRet = RC.Jobs.DMS.XMLInsert(PrmIn, PrmOut)	
	If iRet = 0 Then
		wfvariables.recStructure.iProtocolDocumentID.Value = PrmOut.Value("ObjectID")
		wfvariables.recStructure.iProtocolDocumentType.Value = PrmOut.Value("ObjectType")
		debug2File vbTab & "createXMLProtocol successfull..."
	Else
		debug2File vbTab & "Error: createXMLProtocol failed..."
	End If
	
	Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists (sTmpProtocolPath) = True Then 'delete the sTmpProtocolPath
		oFSO.DeleteFile sTmpProtocolPath
	End If
	Set oFSO = Nothing
	debug2File "End createXMLProtocol"	
End Function

'**********************************************************
' updateXMLProtocol
' @description: updates the xml protocol
' @param: 	FolderID - id of the folder where the protocol should be archived
'			RegisterID - id of the register where the protocol should be archived
'
' @return: 
'**********************************************************
Function updateXMLProtocol (FolderID, RegisterID)
	debug2File "Start updateXMLProtocol"
	'check if a protocol is created -> optionally create the protocol now?
	
	If wfvariables.recStructure.iProtocolDocumentID.Value < 1 Then 
		'create a protocol document
		createXMLProtocol FolderID, RegisterID
	End If
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim sTmpProtocolPath
	sTmpProtocolPath = RC.ServerData.TempDir & Replace( thisprocess.ProcessName, "/", "") & "_protocol.xml"
	
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	Dim oXmlFields : Set oXmlFields = CreateObject("Msxml2.DOMDocument")
	Set procInfo = oXmlDoc.createProcessingInstruction("xml", "version=""1.0"" encoding=""ISO-8859-1""")
	oXmlDoc.appendChild procInfo
	
	Set oProtocol = oXmlDoc.createElement ("Protocol")
	oXmlDoc.appendChild oProtocol	
	
	'Protocol Header
	'*******************
	Set oDocumentNumber = oXmlDoc.createElement ("DocumentNumber")
	oDocumentNumber.appendChild oXmlDoc.createTextNode ( wfvariables.sDocumentNumber.Value )
	oProtocol.appendChild oDocumentNumber	
	
	Set oDocumentTitle = oXmlDoc.createElement ("DocumentTitle")
	oDocumentTitle.appendChild oXmlDoc.createTextNode ( wfvariables.sTitle.Value )
	oProtocol.appendChild oDocumentTitle
	
	Set oDocumentVersion = oXmlDoc.createElement ("DocumentVersion")
	oDocumentVersion.appendChild oXmlDoc.createTextNode ( wfvariables.sVersion.Value )
	oProtocol.appendChild oDocumentVersion
	
	Set oProcessNumber = oXmlDoc.createElement ("ProcessNumber")
	oProcessNumber.appendChild oXmlDoc.createTextNode ( thisprocess.ProcessId ) 
	oProtocol.appendChild oProcessNumber
	
	Set oWorkflow = oXmlDoc.createElement ("Workflow")
	oWorkflow.appendChild oXmlDoc.createTextNode ( thisprocess.ProcessName ) 
	oProtocol.appendChild oWorkflow	
	
	'Protocol Entries
	'****************
	Dim protocolDate, protocolTime, protocolUser, protocolActivity, protocolType, protocolEntry, protocolFields
	For i = 0 To wfvariables.wfProtocol.Count - 1
		
		
		protocolDate = wfvariables.wfProtocol.Item(i).Item("Date").Value
		protocolTime = wfvariables.wfProtocol.Item(i).Item("Time").Value
		protocolUser = wfvariables.wfProtocol.Item(i).Item("User").Value
		protocolActivity = wfvariables.wfProtocol.Item(i).Item("Activity").Value
		protocolType = wfvariables.wfProtocol.Item(i).Item("Type").Value
		protocolEntry = wfvariables.wfProtocol.Item(i).Item("Protocol").Value
		protocolFields = wfvariables.wfProtocol.Item(i).Item("Fields").Value
		
		protocolDate = protocolDate & " " & protocolTime
		
		Set oDocumentEntries = oXmlDoc.createElement ("Entries")
		oProtocol.appendChild oDocumentEntries
		
		Dim oEntry
		Set oEntry = oXmlDoc.createElement ("Entry")
		
		Dim oActivityName
		Set oActivityName = oXmlDoc.createElement ("ActivityName")
		oActivityName.appendChild oXmlDoc.createTextNode (protocolActivity)
		oEntry.appendChild oActivityName
		
		Dim oType
		Set oType = oXmlDoc.createElement ("Type")
		oType.appendChild oXmlDoc.createTextNode (protocolType)
		oEntry.appendChild oType
		
		Dim oUserName
		Set oUserName = oXmlDoc.createElement ("Username")
		oUserName.appendChild oXmlDoc.createTextNode (protocolUser)
		oEntry.appendChild oUserName
		
		Dim oMessage
		Set oMessage = oXmlDoc.createElement ("Message")
		oMessage.appendChild oXmlDoc.createTextNode (protocolEntry)
		oEntry.appendChild oMessage
		
		Dim oTime
		Set oTime = oXmlDoc.createElement ("Time")
		oTime.appendChild oXmlDoc.createTextNode (protocolDate)
		oEntry.appendChild oTime
		
		Dim oFieldValues
		Set oFieldValues = oXmlDoc.createElement ("Details")
		
		
		If True = oXmlFields.loadXML(protocolFields) Then
			Dim oObjectNode
			Set oObjectNode = oXmlFields.selectSingleNode("Object")
			If Not oObjectNode Is Nothing Then
				oFieldValues.appendChild oObjectNode
				'oEntry.appendChild oObjectNode
			End If
		End If
		
		
		'		Dim oField
		'		For b = 0 To oFieldNodes.length - 1
		'			Set oField = oXmlDoc.createElement ("Field")
		'			oField.appendChild oXmlDoc.createTextNode (oFieldNodes.item(b).text)
		'			debug2File oFieldNodes.item(b).text
		'			oFieldValues.appendChild oField
		'		Next
		
		'		Dim oTableRowNodes
		'		Set oTableRowNodes = oXmlFields.selectNodes("/TableRow")
		'		Dim oTableRow
		'		For c = 0 To oTableRowNodes.length - 1
		'			Set oTableRow = oXmlDoc.createElement ("TableRow")
		'			oTableRow.appendChild oXmlDoc.createTextNode (oTableRowNodes.item(c).text)
		'			oFieldValues.appendChild oTableRow
		'		Next		
		
		'protocolFields = Split (protocolFields,"###")
		
		'		For x = 0 To UBound(protocolFields)
		'			Dim oField
		'			Set oField = oXmlDoc.createElement ("Field")
		'			oField.appendChild oXmlDoc.createTextNode (protocolFields(x))
		'			oFieldValues.appendChild oField
		'		Next
		
		oEntry.appendChild oFieldValues		
		oDocumentEntries.appendChild oEntry
	Next
	'save the xml protocol
	oXmlDoc.save sTmpProtocolPath
	
	'update the protocol
	sXML = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sProtocolDocumentInternalName.Value & "' type='DOCUMENT'>" &_
	"<Object object_id='" & CLng(wfvariables.recStructure.iProtocolDocumentID.Value) & "'>" &_
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
	
	
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	
	PrmIn.Value("Flags") = 16
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	PrmIn.Value("Options") = "REPLACEFILES=1"
	PrmIn.Value("$Job$Files$") = sTmpProtocolPath
	
	Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists (sTmpProtocolPath) = False Then 
		debug2File vbTab & "updateXMLProtocol->Protocol file is missing..."
	End If
	
	iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
	If iRet <> 0 Then
		debug2File vbTab & "updateXMLProtocol->XMLUpdate failed"
	Else
		debug2File vbTab & "updateXMLProtocol->XMLUpdate successful..."
	End If
	
	
	If oFSO.FileExists (sTmpProtocolPath) = True Then 'delete the sTmpProtocolPath
		debug2File "DeleteFile " & sTmpProtocolPath
		oFSO.DeleteFile sTmpProtocolPath
	End If
	
	
	'clean up
	Set oFSO = Nothing
	Set dom = Nothing 
	Set oXmlDoc = Nothing
	Set oXmlFields = Nothing
	
	debug2File "end updateXMLProtocol"
End Function

'**********************************************************
' addProtocolEntry
' @description: adds a protocol entry to the wfprotocol variable
' @param: 	sEntry - the message of the protocol entry
'			sType - the type of the protocol entry
'			sPerformer - the current performer
'			bLogDocumentFields - true, if all fields of the controlled document should be logged
'
' @return: 
'**********************************************************
Private Sub addProtocolEntry( sEntry, sType, sPerformer, bLogDocumentFields )
	debug2File "Start addProtocollEntry"
	
	Dim protocolValue : protocolValue = ""
	If bLogDocumentFields = True Then
		'read all fields from the controlled document for protocol purposes	
		Dim xmlFile
		xmlFile = getObjectDetails (wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, "")
		
		Dim oNode
		
		Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
		If True = oXmlDoc.load(xmlFile) Then
			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object"
			Set oNode = oXmlDoc.selectSingleNode(xpath)
			If Not oNode Is Nothing Then
				protocolValue = oNode.xml
			End If
		End If
		
		'		If True = oXmlDoc.load(xmlFile) Then
		'			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/Fields/Field"
		'			Set oNodes = oXmlDoc.selectNodes(xpath)
		'			If Not oNodes Is Nothing Then
		'				For i = 0 To oNodes.length - 1	
		'					fieldName = oNodes.item(i).attributes.getNamedItem("name").text
		'					fieldValue = oNodes.item(i).text
		'					protocolValue = protocolValue & "<Field>" & fieldName & " " & fieldValue & "</Field>"
		'				Next
		'			End If
		
		'			xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sLinkedDocumentsInternalName.Value & "']/Row" 
		'			Set oNodesRows = oXmlDoc.selectNodes(xpath)
		'			If Not oNodesRows Is Nothing Then
		'				For b = 0 To oNodesRows.length - 1
		'					rowID = oNodesRows.item(b).attributes.getNamedItem("id").text
		'	ToDo: Read first the columns to determine the correct order of the row values
		'					xpath = "DMSContent/Archive/ObjectType/ObjectList/Object/TableFields/TableField/Row[@id='" & rowID & "']/Value"
		'					Set oNodesValues = oXmlDoc.selectNodes(xpath)
		'					If Not oNodesValues Is Nothing Then
		'						protocolValue = protocolValue & "<TableRow>" & "Linked document:" & " " & oNodesValues.item(0).text & "," & oNodesValues.item(1).text & "," &oNodesValues.item(2).text & "," &oNodesValues.item(3).text & "," &oNodesValues.item(4).text & "," &oNodesValues.item(5).text & "," & "</TableRow>"			
		'					End If
		'				Next
		'			End If
		'		End If
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		If oFSO.FileExists (xmlFile) = True Then 'delete the xmlFile
			oFSO.DeleteFile xmlFile
		End If
		'clean up
		Set oFSO = Nothing
	End If
	
	'now add the protocol entry
	Dim li : Set li = wfProtocol.CreateListItem
	li.Item("Date").Value = Date
	li.Item("Time").Value = Time
	li.Item("User").Value = sPerformer
	li.Item("Activity").Value = thisprocess.CurrentActivity.Name
	li.Item("Type").Value = sType
	li.Item("Protocol").Value = sEntry
	li.Item("Fields").Value = protocolValue
	wfProtocol.AddListItem li
	
	debug2File "end addProtocollEntry"
End Sub


'**********************************************************
' createSession
' @description: create a session with the OS app server
' @param: 
'
' @return: the session object
'**********************************************************
Public Function createSession()
	Dim RC 
	Set RC = RunningContext 
	Dim aSes : aSes = Split(RC.ServerData.Connect, "#")
	osCOM = aSes(0)
	osPort = aSes(1)
	
	Set oServer = CreateObject("OxSvrSpt.Server") 
	Set createSession = oServer.Login(wfvariables.recSession.sTechUser.Value, wfvariables.recSession.sTechPwd.Value, osCOM, osPort, 1)
End Function

'**********************************************************
' getObjectTypeByID
' @description: returns the objectType of an object
' @param: objectID - the id of the object of which the type should be determined
' @return: objectType
'**********************************************************
Function getObjectTypeByID (objectID)
debug2File "start - getObjectTypeByID (" & objectID & ")"
	Dim RC : Set RC = RunningContext

	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	PrmIn.Value("Flags") = 0
	PrmIn.Value("ObjectID") = objectID

	iRet = RC.Jobs.DMS.GetObjectTypeByID(PrmIn, PrmOut)
	
	If iRet = 0 Then
		getObjectTypeByID = PrmOut.Value("ObjectType")
		debug2File vbTab & "Result: " & PrmOut.Value("ObjectType")
	Else
		getObjectTypeByID = iRet
		debug2File vbTab & "Error: " & iRet
	End If
debug2File "end - getObjectTypeByID (" & objectID & ")"
End Function

'**********************************************************
'getObjectTypeInternalName
'@description: determine the internal name of the given object
'@param: iObjectId the id of the object
'@param: iObjectTypeId the id of the objectType
'@return: the internal name or an empty string if the type cannot be determined
'**********************************************************
Public function getObjectTypeInternalName( iObjectId, iObjectTypeId )
	debug2file "getObjectTypeInternalName(" & iObjectId & ", " & iObjectTypeId & ")"
	getObjectTypeInternalName = ""
	Dim RC : Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	PrmIn.Value("Flags") = 16
	PrmIn.Value("ObjectID") = CLng(iObjectId)
	PrmIn.Value("ObjectType") = CLng(iObjectTypeId)
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId")
	
	iRet = RC.Jobs.DMS.GetObjectDetails(PrmIn, PrmOut)	
	
	Dim sDocumentFilePath : sDocumentFilePath = PrmOut.Value("$Job$Files$")
	sDocumentFilePath = Mid(sDocumentFilePath,2,Len(sDocumentFilePath)-2)
	
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	If True = oXmlDoc.load(sDocumentFilePath) Then	

		Dim xpath : xpath = "//DMSContent/Archive/ObjectType/@internal_name"
		Dim oNode : Set oNode = oXmlDoc.selectSingleNode( xpath )
		If oNode is Nothing Then
			'Nothing
		Else
			getObjectTypeInternalName = oNode.text
		End If
	End If
	
	'clean up
	Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists (sDocumentFilePath) = True Then 'delete the file
		oFSO.DeleteFile sDocumentFilePath
	End If
	
	Set oFSO = nothing
	
	debug2file "getObjectTypeInternalName(" & iObjectId & ", " & iObjectTypeId & ") => " & getObjectTypeInternalName	
end function

'**********************************************************
' getObjectDefListValues
' @description: return all values of a list entry in the object def
' @param: xPath the xpath where the list is stored
'
' @return: the entries as string separated by | or an empty string if not found
'**********************************************************
Private Function getObjectDefListValues( xPath )
	debug2file "start getObjectDefListValues(" & xPath & ")"
	Dim sFilePath : sFilePath = getObjectDef()
	Dim oXmlDoc : Set oXmlDoc = CreateObject("Msxml2.DOMDocument")
	getObjectDefListValues = ""
	
	If True = oXmlDoc.load(sFilePath) Then				
		Dim oNode : Set oNode = oXmlDoc.selectSingleNode( xPath )
		If oNode Is Nothing Then
			'
		Else
			Dim oNodes : Set oNodes = oNode.selectNodes("row")
			Dim str : str = ""
			Dim i
			For i=0 To oNodes.Length - 1
				If i > 0 Then
					str = str & ";"
				End If
				'check if the node got an value attribute, a value attribute exists if the entry is splitted (by "|") in description and value (e.g. "Freigabe / Release|1")
				value = ""
				For a = 0 To oNodes.item(i).attributes.length -1
					If oNodes.item(i).attributes.item(a).baseName = "value" Then
						value = oNodes.item(i).attributes.item(a).text
					End If
				Next
				If value = "" Then 
					str = str & oNodes.Item(i).text
				Else
					str = str & value & "|" & oNodes.Item(i).text
				End If 
			Next
			Set oNodes = Nothing
			
			' CC-000934
			debug2File "getObjectDefListValues: result: " & str
			sortedString = SortString(str)
			filteredString = FilterElements(sortedString)
			debug2File "getObjectDefListValues: filteredString: " & filteredString
			getObjectDefListValues = filteredString
			' CC-000934
		End If	
		Set oNode = Nothing
	Else
		debug2file "Error Loading Xml: " & oXmlDoc.parseError.errorCode & " " & oXmlDoc.parseError.reason 
	End If
	Set oXmlDoc = Nothing
	debug2file "end getObjectDefListValues(" & xPath & ") => " & getObjectDefListValues
End Function


'**********************************************************
' SortString
' @description: Sorts the elements of a semicolon-separated string in alphabetical order
' @param: inputString - A string containing elements separated by semicolons
'
' @return: An alphabetically sorted string with elements separated by semicolons
' added in CC-000934
'**********************************************************
function SortString(inputString)
    ' Den Eingabestring in ein Array aufteilen

    items = Split(inputString, ";")

	Dim i, j, temp
    For i = UBound(items) To 1 Step -1
        For j = 0 To i - 1
            If StrComp(items(j), items(j + 1)) > 0 Then
                ' Elemente tauschen
                temp = items(j)
                items(j) = items(j + 1)
                items(j + 1) = temp
            End If
        Next
    Next    
    ' Das Array wieder zu einem String zusammenfgen

    SortString = Join(items, ";")
End function

'**********************************************************
' FilterElements
' @description: Filters elements from a semicolon-separated string, removing those ending with an asterisk (*)
' @param: inputString - A string containing elements separated by semicolons
'
' @return: A string with elements that do not end with an asterisk, separated by semicolons
' added in CC-000934
'**********************************************************
Function FilterElements(inputString)
    ' Den Eingabestring in ein Array aufteilen
    Dim items, filteredItems, i, element
    items = Split(inputString, ";")
    
    ' Neues Array fr gefilterte Elemente
    Dim result()
    ReDim result(-1) ' Start mit leerem Array
    
    ' Jedes Element berprfen
    For i = 0 To UBound(items)
        element = Trim(items(i)) ' Leerzeichen entfernen
        ' Prfen, ob das letzte Zeichen kein Sternchen ist
        If Right(element, 1) <> "*" Then
            ' Element zum neuen Array hinzufgen
            ReDim Preserve result(UBound(result) + 1)
            result(UBound(result)) = element
        End If
    Next
    
    ' Das gefilterte Array wieder zu einem String zusammenfgen
    FilterElements = Join(result, ";")
    
End Function




'**********************************************************
' updateAttachmentTable
' @description: updates the attachment record with document variables
' @param: nothing
' @return: nothing
'**********************************************************
Function updateAttachmentTable
	debug2File "start updateAttachmentTable()"
	For i = 0 To wfvariables.recAttachments.Count - 1 
		wfvariables.recAttachments.Item(i).Item("sDocumentNumber").Value = wfvariables.sDocumentNumber.Value
		wfvariables.recAttachments.Item(i).Item("sStatus").Value = wfvariables.sStatus.Value
		wfvariables.recAttachments.Item(i).Item("sVersion").Value = wfvariables.sVersion.Value
		wfvariables.recAttachments.Item(i).Item("dValidDate").Value = wfvariables.dValidDate.Value
		wfvariables.recAttachments.Item(i).Item("sReadRights").Value = wfvariables.sReadRights.Value
		wfvariables.recAttachments.Item(i).Item("sWriteRights").Value = wfvariables.sWriteRights.Value
		If wfvariables.recAttachments.Item(i).Item("sObjectId").Value <> "" And CLng( wfvariables.recAttachments.Item(i).Item("sObjectId").Value ) > 0 Then
			Dim RC : Set RC = RunningContext
			Set PrmIn = RC.NewJobsParams 
			Set PrmOut = RC.NewJobsParams
			
			Dim sXML : sXML = "" &_
			"<DMSData>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
			"<ObjectType internal_name='" & wfvariables.recStructure.sAttachmentInternalName.Value & "' type='DOCUMENT'>" &_
			"<Object object_id='" & wfvariables.recAttachments.Item(i).Item("sObjectId").Value & "'>" &_
			"<Fields>" &_ 
			"<Field internal_name='" & getInternalName_Attachment_DocumentNumber & "'>" & convertToValidXML( wfvariables.sDocumentNumber.Value ) & "</Field>" &_					
			"<Field internal_name='" & getInternalName_Attachment_Version & "'>" & convertToValidXML( wfvariables.sVersion.Value ) & "</Field>" &_					
			"<Field internal_name='" & getInternalName_Attachment_ValidDate & "'>" & convertToValidXML( wfvariables.dValidDate.Value ) & "</Field>" &_					
			"<Field internal_name='" & getInternalName_Attachment_AttachmentNo & "'>" & convertToValidXML( wfvariables.recAttachments.Item(i).Item("sAttNr").Value ) & "</Field>" &_
			"<Field internal_name='" & getInternalName_Attachment_Status & "'>" & convertToValidXML( wfvariables.sStatus.Value ) & "</Field>" &_
			"<Field internal_name='" & getInternalName_Attachment_Persisted & "'>1</Field>" &_
			"<Field internal_name='" & getInternalName_Attachment_Title &"'>" & convertToValidXML( wfvariables.recAttachments.Item(i).Item("sTitle").Value ) & "</Field>" &_
			"<Field internal_name='" & getInternalName_Attachment_CreatedOn & "'>" & convertToValidXML( wfvariables.recAttachments.Item(i).Item("dCreatedOn").Value) & "</Field>" &_		
			"<Field internal_name='" & getInternalName_Attachment_CreatorId & "'>" & convertToValidXML( wfvariables.recAttachments.Item(i).Item("sCreatorId").Value) & "</Field>" &_		
			"<Field internal_name='" & getInternalName_Attachment_Creator & "'>" & convertToValidXML( wfvariables.recAttachments.Item(i).Item("sCreator").Value ) & "</Field>" &_
			"<Field internal_name='" & getInternalName_Attachment_ReadRights & "'>" & convertToValidXML( wfvariables.sReadRights.Value ) & "</Field>" &_					
			"<Field internal_name='" & getInternalName_Attachment_WriteRights & "'>" & convertToValidXML( wfvariables.sWriteRights.Value ) & "</Field>" &_
			"</Fields>" &_		
			"</Object>" &_
			"</ObjectType>" &_
			"</Archive>" &_
			"</DMSData>"
			debug2File "updateAttachmentTable() Update Attachment " & wfvariables.recAttachments.Item(i).Item("sObjectId").Value & " - " & wfvariables.recAttachments.Item(i).Item("sAttNr").Value
			debug2File "updateAttachmentTable() Update Attachment xml = " & sXML
			Set dom = CreateObject("MSXML.DOMDocument") 
			
			dom.loadXML(sXML) 
			PrmIn.Value("Flags") = 0
			PrmIn.Value("Options") ="CHECKREADONLY=0"
			PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
			PrmIn.Value("XML")=dom 
			
			iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
			debug2File "updateAttachmentTable() Update Attachment " & wfvariables.recAttachments.Item(i).Item("sObjectId").Value & " - " & wfvariables.recAttachments.Item(i).Item("sAttNr").Value & " - return value = " & iRet
		End If
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		debug2File "updateAttachmentTable() Update Attachment " & wfvariables.recAttachments.Item(i).Item("sObjectId").Value & " - " & wfvariables.recAttachments.Item(i).Item("sAttNr").Value & " - return value = " & iRet
	Next
	debug2file "end updateAttachmentTable()"
End Function

'**********************************************************
' getObjectDef
' @description: get the current object definition as path to an xml file
' @param: 
'
' @return: the path to the xml file
'**********************************************************
Public Function getObjectDef()
	debug2file "start getObjectDef()"
	Dim RC : Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
	If oFso.FileExists( RC.ServerData.TempDir & QM_CONFIG_PREFIXES & thisprocess.ProcessId & "_ObjectDef.xml" ) = True Then
		getObjectDef = RC.ServerData.TempDir & QM_CONFIG_PREFIXES & thisprocess.ProcessId & "_ObjectDef.xml"
	Else
		Set oSession = createSession()	
		Set oJob = oSession.NewJob("dms.GetObjDef")
		oJob.InputParameters.AddNewIntegerParameter "Flags", 4096		
		iRet = oJob.Execute		
		If iRet <> 0 Then
			debug2File vbTab & "getObjectDef->GetObjDef failed"
		Else
			debug2File vbTab & "getObjectDef->GetObjDef successful..."
			Dim sFile : sFile = oJob.OutputFileParameters.Item(1).FileName
			oFso.CopyFile sFile, RC.ServerData.TempDir & QM_CONFIG_PREFIXES & thisprocess.ProcessId & "_ObjectDef.xml", True
		End If
		
		Set oJob = Nothing
		Set oSession = Nothing
		getObjectDef = RC.ServerData.TempDir & QM_CONFIG_PREFIXES & thisprocess.ProcessId & "_ObjectDef.xml"
	End If
	Set oFso = Nothing
	debug2file "end getObjectDef() => " & getObjectDef
End Function

'**********************************************************
' deleteObjectDef
' @description: deletes the objectdef file from the OSTEMP directory
' @param: nothing
'
' @return: 0 if the file could be deleted, otherwise -1
'**********************************************************
Public Function deleteObjectDef()
	debug2file "start deleteObjectDef()"
	
	Dim RC : Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
	If oFso.FileExists( RC.ServerData.TempDir & QM_CONFIG_PREFIXES & thisprocess.ProcessId & "_ObjectDef.xml" ) = True Then
		oFso.DeleteFile(RC.ServerData.TempDir & QM_CONFIG_PREFIXES & thisprocess.ProcessId & "_ObjectDef.xml")
		deleteObjectDef = 0
	Else
		deleteObjectDef = -1
	End If
	
	debug2file "end deleteObjectDef() => " & deleteObjectDef
End Function



'**********************************************************
' convertWithDocuConverter
' @description: converts the given File with the Neevia converter to PDF
' @param: path(String) - path of the file which should be converted
'			sTypeName(String) - type of the PDF (e.g. PDFA)
' @return: the path of the converted file
'**********************************************************
Private Function convertWithDocuConverter( path, sTypeName )
	
	debug2file "convertWithDocuConverter( " & path & ")"
	
	convertWithDocuConverter = ""
	
	Dim xoFso : Set xoFso = CreateObject("Scripting.FileSystemObject")	
	
	Dim fileToConvert : fileToConvert = path
	
	Dim aFileName : aFileName = Split(xoFso.GetFileName( path ), ".")
	
	Dim fileNameToConvert : fileNameToConvert = ""
	For iax = 0 To UBound(aFileName) - 1
		fileNameToConvert = fileNameToConvert & aFileName(iax) & "."
	Next
	Dim orgFileName : orgFileName = xoFso.GetFileName( path ) 
	fileNameToConvert = fileNameToConvert & "pdf"
	
	
	Dim NVDC : Set NVDC = CreateObject("Neevia.docConverter")
	
	If NVDC.isConverterActive() = False Then
		Set NVDC = Nothing
		Set xoFso = Nothing
		debug2file " Error converting: Converter not active!"
		Exit Function		
	End If
	
	'NVDC.setParameter "DocumentOutputFormat", "PDFA"
	NVDC.setParameter "DocumentOutputFormat", sTypeName
	'NVDC.setParameter "OutputIntent", "srgb"
	NVDC.setParameter "PDFAutoRotatePage", "All"
	'NVDC.setParameter "UsePrinter", "docuPrinter"
	
	NVDC.setParserParameter "WORD", "ConvertHeadings", "true"
	NVDC.setParserParameter "WORD", "CreateLinksFromTOC", "true"
	NVDC.setParserParameter "WORD", "ConvertCrossReferenceLinks", "true"
	NVDC.setParserParameter "WORD", "ConvertCrossDocLinks", "true"
	NVDC.setParserParameter "WORD", "ConvertBookmarksToNamedDest", "true"
	NVDC.setParserParameter "WORD", "ConvertBookmarksToNamedDest", "true"
	NVDC.setParserParameter "WORD", "ConvertCommentsToPDFNotes", "true"
	NVDC.setParserParameter "WORD", "DisableMacros", "true"
	Dim inFolder : inFolder = NVDC.getDefaultInputFolder
	Dim outFolder : outFolder = NVDC.getOutputFolder( inFolder )
	Dim errorFolder : errorFolder = NVDC.getErrorFolder( inFolder )
	Dim origFolder : origFolder = NVDC.getOrigFolder( inFolder )
	'Dim rv : rv = NVDC.submitFile(fileToConvert, inFolder)
	
	Dim rv : rv = NVDC.submitFileEx(fileToConvert,outFolder,errorFolder,origFolder)
	
	If (rv <> 0) Then
		debug2file "submitFileEx error: " & NVDC.errorCodeToString( rv )
	Else
		rv = 2
		While (rv = 2)
			rv = NVDC.checkStatusEx(fileToConvert,outFolder,errorFolder)
			NVDC.doSleep 1000
		Wend
		If (rv = 0) Then
			convertWithDocuConverter = xoFso.BuildPath( outFolder, fileNameToConvert )	  
			Dim curPath : curPath = xoFso.BuildPath(origFolder, orgFileName )
			If xoFso.FileExists( curPath ) = True Then
				debug2file "Delete : " & curPath
				xoFso.DeleteFile curpath
			End If
			curPath = xoFso.BuildPath(inFolder, orgFileName )
			If xoFso.FileExists( curPath ) = True Then
				debug2file "Delete : " & curPath
				xoFso.DeleteFile curpath
			End If	    
			Set NVDC = Nothing
			Set xoFso = Nothing
			debug2file " convertWithDocuConverter: Converted successfully: " & convertWithDocuConverter
		Else
			debug2file " Error converting: " & NVDC.errorCodeToString( rv )
		End If
	End If	
	
End Function

'**********************************************************
' DisablePrinting
' @description: disables the printing function for PDF documents
' @param: path(String) - path of the file for which printing should be disabled
'			sTypeName(String) - type of the PDF (e.g. PDFA)
' @return: the path of the converted file
'**********************************************************
Function DisablePrinting( path , pathout )           
	debug2file "DisablePrinting" & path & " " & pathout
	Dim NVDC : Set NVDC = CreateObject("Neevia.docConverter")
	
	If NVDC.isConverterActive() = False Then
		Set NVDC = Nothing
		Set xoFso = Nothing
		debug2file " Error converting: Converter not active!"
		Exit Function                 
	End If
	
	NVDC.setParameter "PDFEncryption", "true"
	NVDC.setParameter "PDFEncryptionType", "40"
	NVDC.setParameter "PDFOwnerPassword", "owner"
	'               NVDC.setParameter "PDFUserPassword", "open"
	NVDC.setParameter "PDFNoCopyPermission", "true"
	NVDC.setParameter "PDFNoPrintPermission", "true"
	NVDC.setParameter "PDFNoChangePermission", "true"
	NVDC.setParameter "PDFNoAddPermission", "true"
	Dim rv : rv = NVDC.encryptPDF(path, pathout)
	
	If (rv = 0) Then
		Dim xoFso : Set xoFso = CreateObject("Scripting.FileSystemObject")   
		If xoFso.FileExists( path ) = True Then
			debug2file "Delete : " & path
			xoFso.DeleteFile path
		End If   
		Set NVDC = Nothing
		Set xoFso = Nothing
		debug2file " DisablePrinting"
	Else
		debug2file " Error DisablePrinting: " & NVDC.errorCodeToString( rv )
	End If
End Function

'**********************************************************
' updateDistributionRecipients
' @description: updates the distribution objects with recipients
' @param: objectID of the distribution object
' @return: nothing
'**********************************************************
Function updateDistributionRecipients (objectID)
debug2File "start updateDistributionRecipients (" & objectID & ")"

	Dim RC : Set RC = RunningContext
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams

	Dim sRowsRecipients : sRowsRecipients = ""	
	'iterate over all rows
	For v = 0 To wfvariables.TrainingRecipients.Count - 1  
		sRowsRecipients = sRowsRecipients & "<Row>" &_
		"<Field internal_name='" & "Guid" & "'>" & convertToValidXML(wfvariables.TrainingRecipients.Item(v).Item("Guid").Value) & "</Field>" &_
		"<Field internal_name='" & "Name" & "'>" & convertToValidXML(wfvariables.TrainingRecipients.Item(v).Item("Name").Value) & "</Field>" &_
		"</Row>"
	Next

	Dim sXML
	sXML = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" &_
	"<Object object_id='" & objectID & "'>"
	
	If wfvariables.sTrainingTrainer.count > 0 Then
		sXML = sXML &_
		"<Fields>" &_
			"<Field internal_name='" & getInternalName_DistributionObject_Trainer & "'>" & convertToValidXML(CStr(wfvariables.sTrainingTrainer.Item(0).Item("Name").Value)) & "</Field>" &_
		"</Fields>"
	End If

	sXML = sXML &_	
	"<TableFields>" &_
		"<TableField internal_name='" & wfvariables.recStructure.sDistributionObjectRecipientsTableInternalName.Value & "'>" &_
			sRowsRecipients &_
		"</TableField>" &_
	"</TableFields>" &_			
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
debug2File "3"	
	Set dom = CreateObject("MSXML.DOMDocument") 
	debug2file sXML
	dom.loadXML(sXML) 
	PrmIn.Value("Flags") = 0
	PrmIn.Value("Options") ="CHECKREADONLY=0;REPLACETABLEFIELDS=1"
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
	If iRet = 0 Then
		debug2File vbTab & "updateDistributionRecipients successful..."
	Else
		debug2File vbTab & "Error: updateDistributionRecipients failed..."
	End If
debug2File "end updateDistributionRecipients (" & objectID & ")"
End Function

'**********************************************************
' getUpdatedDistributionRegisters
' @description: Erzeugt nicht vorhandene Verteiler oder lscht berflssige auf Grundlage der Verantwortlichen
' @param: nothing
' @return: nothing
'**********************************************************
Function getUpdatedDistributionRegisters
	debug2File "start getUpdatedDistributionRegisters"
	Dim i 
	Dim sreturn : sreturn= ""
	Dim oxmlDoc : Set oxmlDoc = CreateObject("MSXML.DOMDocument")
	If oxmlDoc.loadXML(getDistributionRegistersAsXml) Then
		
		'Step 1) Falls Verantwortliche entfernt wurden, so soll das Verteilerregister ein "deleted" flag erhalten
		Dim oDistRegisters
		Set oDistRegisters = oxmlDoc.selectNodes("//DMSContent/Archive/ObjectType/ObjectList/Object")
	
		debug2File "berprfe ob Register entfernt werden mssen..."
		For v = 0 To oDistRegisters.length -1
	
			registerObjectID = Trim(oDistRegisters.item(v).attributes.getNamedItem("id").text)
			xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object[@id='" & registerObjectID & "']/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sDistributionObjectResponsibleTableInternalName.Value & "']/Row[@id=1]/Value"
			Dim oNode : Set oNode = oxmlDoc.selectSingleNode(xpath)
			sResponsibleGUID = oNode.Text
			debug2File "1. GUID des Schulungsverantwortlichen: " & sResponsibleGUID
			Dim bResponsibleDefinedInWF : bResponsibleDefinedInWF = 0
			For x = 0 To wfvariables.TrainingResponsible.count - 1	
				If wfvariables.TrainingResponsible.Item(x).Item("Guid").Value = sResponsibleGUID Then
					bResponsibleDefinedInWF = 1
				End If
			Next
			
			If bResponsibleDefinedInWF = 0 Then 'fr ein existierendes VerteilerRegister wurde im aktuellen Durchlauf kein Verantwortlicher mehr definiert. Daher muss ein Gelscht-Flag gesetzt werden.
				setDistributionRegisterDeletedFlag(registerObjectID)
			End If
			
		Next
		
		'Step 2) Falls noch kein Verteilerregister existiert, so muss eines angelegt werden.
		debug2File "berprfe ob Register hinzugefgt werden mssen..."
		debug2File "Anzahl der im WF definierten Verantwortlichen : " & wfvariables.TrainingResponsible.count
		For  i = 0 To wfvariables.TrainingResponsible.count - 1
			Dim oNodes : Set oNodes = oxmlDoc.selectNodes("//DMSContent/Archive/ObjectType/ObjectList/Object")
			Dim bResponsibleDefinedInArchive : bResponsibleDefinedInArchive = 0
			debug2File "Durchgang: " & i & " - Betrachte Verantw. mit GUID : " & wfvariables.TrainingResponsible.Item(i).Item("Guid").Value
			
			For n = 0 To oNodes.length -1
		
				registerObjectID = Trim(oDistRegisters.item(n).attributes.getNamedItem("id").text)
				xpath = "//DMSContent/Archive/ObjectType/ObjectList/Object[@id='" & registerObjectID & "']/TableFields/TableField[@internal_name='" & wfvariables.recStructure.sDistributionObjectResponsibleTableInternalName.Value & "']/Row[@id=1]/Value"
				Dim oNode2 : Set oNode2 = oxmlDoc.selectSingleNode(xpath)
				sResponsibleGUID = oNode2.Text
				debug2File "2. GUID des Schulungsverantwortlichen: " & sResponsibleGUID
				If sResponsibleGUID = wfvariables.TrainingResponsible.Item(i).Item("Guid").Value Then
					bResponsibleDefinedInArchive = 1
				End If
			Next
			
			If bResponsibleDefinedInArchive = 0 Then 'es existiert noch kein Verteiler, also anlegen
				CreateDistributionRegister wfvariables.recStructure.iFolderID.Value, wfvariables.recStructure.iRegisterID.Value, wfvariables.TrainingResponsible.Item(i)
			End If
			
		Next
				
		
	End If
	getUpdatedDistributionRegisters = sreturn
	debug2File "end getUpdatedDistributionRegisters"
End Function


'**********************************************************
' getDistributionRegistersAsXml
' @description: Holt alle Distributionregister als xml
' @param: nothing
' @return: nothing
'**********************************************************

Function getDistributionRegistersAsXml
debug2File "start getDistributionRegistersAsXml "
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
    Dim sXML : sXML = ""
    sXML = sXML & "<DMSQuery request_type='HOL'>" 
	    sXML = sXML & "<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value  & "'>" 
		    sXML = sXML & "<ObjectType internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" 	
		    	sxml = sxml & "<Fields field_schema=""ALL""/>"
			    sXML = sXML & "<Conditions>"
					sXML = sXML & "<ConditionObject internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" 
						sXML = sXML & "<FieldCondition internal_name='" & getInternalName_DistributionObject_DocumentNumber & "' operator='='>"
							sXML = sXML & "<Value>" & wfvariables.sDocumentNumber.Value & "</Value>"
						sXML = sXML & "</FieldCondition>"
						sXML = sXML & "<FieldCondition internal_name='" &  getInternalName_DistributionObject_Version & "' operator='='>"
							sXML = sXML & "<Value>" & wfvariables.sVersion.Value & "</Value>"
						sXML = sXML & "</FieldCondition>"	
						sXML = sXML & "<FieldCondition internal_name='" &  getInternalName_DistributionObject_Deleted & "' operator='!='>"
							sXML = sXML & "<Value>1</Value>"
						sXML = sXML & "</FieldCondition>"							
					sXML = sXML & "</ConditionObject>"
				sXML = sXML & "</Conditions>"
			sXML = sXML & "</ObjectType>"
		sXML = sXML & "</Archive>"
	sXML = sXML & "</DMSQuery>"	
	debug2File sXML
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("Variants") = 1
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	PrmIn.Value("XML")=dom 
	
	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	If iRet = 0 Then
		
		sfile = PrmOut.Value("$Job$Files$")
		sfile = Mid(sfile,2,Len(sfile)-2)
		
		Dim oNode
		Dim oxmlDoc : Set oxmlDoc = CreateObject("Msxml2.DOMDocument")
		
		If oxmlDoc.load(sfile) = True Then 	
			getDistributionRegistersAsXml = oXmlDoc.xml
			debug2File vbTab & "Ergebnis"
			debug2File oXmlDoc.xml
		End If	
		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
		
		If oFSO.FileExists (sfile) = True Then 'delete the file
			oFSO.DeleteFile sfile
		End If
		
		'clean up
		Set oFSO = Nothing
	
	End If
debug2File "ende getDistributionRegistersAsXml "	
End Function


'**********************************************************
' CreateDistributionRegister
' @description: Erzeugt neues Register
' @param: nothing
' @return: nothing
'**********************************************************
Function createDistributionRegister (folderID, registerID, oResponsible)
	debug2File "start CreateDistributionRegister (" & folderID & "," & registerID & ")"
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	sTablename = wfvariables.recStructure.sDistributionObjectResponsibleTableInternalName.Value	
	sXML = "" &_
	"<DMSData>" &_
	"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
	"<ObjectType internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" &_
	"<Object folder_id='" & CLng(folderID) & "' register_id='" & registerID & "'>" &_
	"<Fields>" &_
	"<Field internal_name='" & getInternalName_DistributionObject_DocumentNumber & "'>" & convertToValidXML(wfvariables.sDocumentNumber.Value) & "</Field>" &_
	"<Field internal_name='" & getInternalName_DistributionObject_Version & "'>" & convertToValidXML(wfvariables.sVersion.Value) & "</Field>" &_
	"<Field internal_name='" & getInternalName_DistributionObject_Title & "'>" & convertToValidXML(wfvariables.sTitle.Value) & "</Field>" &_
	"<Field internal_name='" & getInternalName_DistributionObject_Deleted & "'>" & "0" & "</Field>" &_	
	"</Fields>" &_
	"<TableFields>" &_
	"<TableField internal_name='" & wfvariables.recStructure.sDistributionObjectResponsibleTableInternalName.Value & "'>" &_	
	"<Row>" &_
	"<Field internal_name='" &  getInternalName_DistributionResponsible_Guid & "'>" & convertToValidXML(oResponsible.Item("Guid").Value) & "</Field>" &_	
	"<Field internal_name='" & getInternalName_DistributionResponsible_Name  & "'>" & convertToValidXML(oResponsible.Item("Name").Value) & "</Field>" &_	
	"</Row>" &_
	"</TableField>" &_		
	"</TableFields>" &_		
	"</Object>" &_
	"</ObjectType>" &_
	"</Archive>" &_
	"</DMSData>"
	debug2File sXML
	Set dom = CreateObject("MSXML.DOMDocument") 
	dom.loadXML(sXML) 
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	PrmIn.Value("XML")=dom 
	PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
	
	iRet = RC.Jobs.DMS.XMLInsert(PrmIn, PrmOut)
	If iRet = 0 Then
		createDistributionRegister = PrmOut.Value("ObjectID") & "," &  PrmOut.Value("ObjectType")	
		debug2File vbTab & "CreateDistributionRegister successful..."
	Else
		debug2File vbTab & "ERROR: CreateDistributionRegister failed..."
	End If
	
	
	debug2File "end CreateDistributionRegister (" & folderID & "," & registerID & ")"
End Function


'**********************************************************
' setDistributionRegisterDeletedFlag
' @description: sets the deleted flag for a distribution register
' @param: registerObjectID (Integer) - the object id of the distribution register which should be updated
' @return: nothing
'**********************************************************
Function setDistributionRegisterDeletedFlag (registerObjectID)
    debug2File "start setDistributionRegisterDeletedFlag (" & registerObjectID & ")"
    If registerObjectID > 0 Then
        'create running context object
        Dim RC 
        Set RC = RunningContext 
        Set PrmIn = RC.NewJobsParams 
        Set PrmOut = RC.NewJobsParams
        
        Set dom = CreateObject("MSXML.DOMDocument") 
        sXML = "" &_
        "<DMSData>" &_
        "<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
        "<ObjectType internal_name='" & wfvariables.recStructure.sDistributionRegisterInternalName.Value & "' type='REGISTER'>" &_
        "<Object object_id='" & CLng(registerObjectID) & "'>" &_
        "<Fields>" &_
        "<Field internal_name='" & getInternalName_DistributionObject_Deleted & "'>" & "1" & "</Field>" &_
        "</Fields>" &_
        "</Object>" &_
        "</ObjectType>" &_
        "</Archive>" &_
        "</DMSData>"
        
        dom.loadXML(sXML) 
        PrmIn.Clear() 
        PrmIn.Value("Flags") = 0
        PrmIn.Value("Options") ="CHECKREADONLY=0"
        PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
        PrmIn.Value("XML")=dom 
        
        iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
        
        Set oxmlDoc = Nothing
    Else
        debug2File "No distribution register available"    
    End If
    debug2File "end setDistributionRegisterDeletedFlag (" & registerObjectID & ")"
End Function


'**********************************************************
' convertToValidXML
' @description: converts a string value to a valid xml value
' @param: sInput - string
'
' @return: the valid xml string
'**********************************************************
Const C_XMLOK="yxcvbnmasdfghjklqwertzuiopYXCVBNMASDFGHJKLQWERTZUIOP1234567890() ."
Function convertToValidXML(sInput)
	sDest=""
	sSource=sInput
	sChar=""
	For jj = 0 To Len(sInput)-1
		sChar = Left(sSource,1)
		sSource = Right(sSource, Len(sSource)-1)
		If InStr(1, C_XMLOK, sChar) = 0 Then sChar="&#"&Asc(sChar)&";"
		sDest = sDest & sChar	
	Next
	convertToValidXML=sDest
End Function

'**********************************************************
' createTrainingSurvey
' @description: create a trainingsurvey object for the current cd
'**********************************************************
Sub createTrainingSurvey
	debug2File "createTrainingSurvey.START"
	If checkTrainingSurvey (QM_TM_CABINET_INTERNAL_NAME, QM_TM_TRAINING_TITLE_PREFIX & wfvariables.sDocumentNumber.Value & " v" & wfvariables.sVersion.Value & " - " & wfvariables.sTitle.Value) <> 0 Then
		Dim aFields : aFields = Array (	"sTopic", _
										"sStatus", _
										"sTypeOfTraining", _
										"sCreator", _
										"sCompulsory", _
										"sCreatedByModule", _
										"sIDOfReferencedObject",_
										"sIDOfReferencedDocument",_
										"m_doc_title",_
										"m_doc_number",_
										"m_doc_version",_
										"sRecapitulationEvery",_
										"lIntervalType")
		Dim aValues : aValues = Array (	QM_TM_TRAINING_TITLE_PREFIX & wfvariables.sDocumentNumber.Value & " v" & wfvariables.sVersion.Value & " - " & wfvariables.sTitle.Value, _
										1, _
										"SOP", _
										wfvariables.sCreatorName.Value, _
										1,_
										QM_TM_MODULE_NAME,_
										wfvariables.recStructure.iRegisterID.Value,_
										wfvariables.recStructure.iDocumentID.Value,_
										wfvariables.sTitle.Value,_
										wfvariables.sDocumentNumber.Value,_
										wfvariables.sVersion.Value,_
										wfvariables.sTrainingInterval.value,_
										wfvariables.sTrainingUnit.value)
		sRet = createFolder (QM_TM_CABINET_INTERNAL_NAME, aFields, aValues)

	Else
		debug2File vbtab & "createTrainingSurvey: Folder exists already"
	End If
	debug2File "createTrainingSurvey.END"
End Sub

'**********************************************************
'Creates a Folder
'sCabinetInternalName
'aFields - array of fields to be filled
'aValues - array of values to fill the fields with. Needs identical indexes
'**********************************************************
Function createFolder ( sCabinetInternalName, aFields, aValues )
	debug2File "createFolder: START."

	Dim sXml : sXml = "" &_
	"<DMSData>" &_
		"<Archive internal_name='" & sCabinetInternalName & "'>" &_
			"<ObjectType internal_name='" & sCabinetInternalName & "' type='FOLDER'>" &_
				"<Object>" &_
					"<Fields>" & vbCrLf
					Dim i : i = 0
					For Each sField In aFields
						sXml = sXml & "<Field internal_name=""" & sField & """>" & convertToValidXML( CStr (aValues(i) ) ) & "</Field>" & vbCrLf									
						i = i + 1
					Next
					sXml = sXml & "</Fields>" &_						
				"</Object>" &_
			"</ObjectType>" &_
		"</Archive>" &_
	"</DMSData>"
	debug2File vbTab & "createFolder.request.xml " & vbCrLf & sXML
	Dim RC 
	Set RC = RunningContext 
    Dim PrmIn : Set PrmIn = RC.NewJobsParams
    Dim PrmOut : Set PrmOut = RC.NewJobsParams
    Dim ix
    PrmIn.Value("XML") = sXML
    PrmIn.Value("Flags") = 16
    PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("OSSERVICE").Item(0).GetAttributeValueByName("UserId") 
'    PrmIn.Value("Options") = "CHECKACCESS=0;"
	lRet = RC.Jobs.DMS.XMLInsert(PrmIn, PrmOut)

	debug2File "createFolder.lRet: " & lRet	
	if lRet = 0 Then
		debug2File "createFolder: SUCCESS"
		createFolder = PrmOut.Value("ObjectID") & "," &  PrmOut.Value("ObjectType")
	Else
		debug2File "createFolder: Creation of Folder failed."
		createFolder = ""
		'MsgBox "ProvokeError"
	End If
	debug2File "createFolder: END."
End Function

'**********************************************************
'Checks if there is already a training survey for the given topic
'sCabinetInternalName
'sTopic - QM_TM_TRAINING_TITLE_PREFIX & wfvariables.sDocumentNumber.Value & " v" & wfvariables.sVersion.Value & " - " & wfvariables.sTitle.Value
'**********************************************************
Function checkTrainingSurvey (sCabinetInternalName, sTopic)
	debug2file "checkTrainingSurvey.START"
'Query erstellen
	Dim RC 
	Set RC = RunningContext     
	Dim PrmIn : Set PrmIn = RC.NewJobsParams
    Dim PrmOut : Set PrmOut = RC.NewJobsParams
    Dim xmlStr : xmlStr = "" &_
    "<DMSQuery request_type='HOL'>" &_
    "<Archive internal_name='" & sCabinetInternalName & "'>" &_
       	"<ObjectType internal_name='" & sCabinetInternalName & "' type='FOLDER'>" &_
			"<Conditions>" &_
                "<ConditionObject internal_name='" & sCabinetInternalName & "' type='FOLDER'>" &_ 
                	"<FieldCondition internal_name='sTopic'>" &_
                		"<Value>" & convertToValidXML( sTopic ) & "</Value>" &_
                	"</FieldCondition>" &_
                "</ConditionObject>" &_
           	"</Conditions>" &_
       	"</ObjectType>" &_
   	"</Archive>" &_
   	"</DMSQuery>"
    PrmIn.Value("XML") = xmlStr
    PrmIn.Value("Flags") = 16
    PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("OSSERVICE").Item(0).GetAttributeValueByName("UserId") 
	debug2file vbtab & "checkTrainingSurvey.request: " & xmlStr
	lRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	if lRet = 0 Then
		sReturnFile = PrmOut.Value("$Job$Files$")
		if (left(sReturnFile,1) = "?") then sReturnFile = mid(sReturnFile,2)
		if (Right(sReturnFile,1) = ";") then sReturnFile = left(sReturnFile,len(sReturnFile)-1)
		Dim oDOMDocument : Set oDOMDocument = CreateObject("MSXML.DOMDocument")
		'https://jira.os-bielefeld.de/browse/SOPMC-181 START
		If (oDOMDocument.load(sReturnFile)) Then
           debug2File "checkTrainingSurvey.result" & oDOMDocument.xml
           Dim oNode : Set oNode = oDOMDocument.selectSingleNode("//DMSContent/Archive/ObjectType/Statistics")
           lTotalHits = cLng(oNode.GetAttribute("total_hits"))
           debug2File "oNode.total_hits: " & cStr(lTotalHits)
           If lTotalHits = 0 Then lRet = 1
        End If
        'https://jira.os-bielefeld.de/browse/SOPMC-181 END

		
		Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")		
		If oFSO.FileExists (sReturnFile) = True Then 'delete the file
			oFSO.DeleteFile sReturnFile
		End If		
		'clean up
		Set oFSO = Nothing
		
	End if
	checkTrainingSurvey = lRet '0 im Erfolgsfall
	debug2file "checkTrainingSurvey.END with lRet = " & lRet
End Function

'**********************************************************
' RemoveControlledPrintingInformations
' @description: removes controlled printing informations in case of a document revision
'				ServerEvent, need running context
' @param: documentID (Integer)
' @return: nothing
'**********************************************************
Function RemoveControlledPrintingInformations ()

	debug2File "start RemoveControlledPrintingInformations()"
	
	If wfvariables.recStructure.iDocumentID.Value > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		Set dom = CreateObject("MSXML.DOMDocument") 
		sXML = "" &_
		"<DMSData>" &_
			"<Archive internal_name='" & wfvariables.recStructure.sFolderInternalName.Value & "'>" &_
				"<ObjectType internal_name='" & wfvariables.recStructure.sDocumentInternalName.Value & "' type='DOCUMENT'>" &_
					"<Object object_id='" & CLng(wfvariables.recStructure.iDocumentID.Value) & "'>" &_
						"<Fields>" &_
						"</Fields>" &_
						"<TableFields>" &_
							"<TableField internal_name='" & "rManagedCopies" & "'>" &_
							"</TableField>" &_
						"</TableFields>" &_
					"</Object>" &_
				"</ObjectType>" &_
			"</Archive>" &_
		"</DMSData>"
		
		dom.loadXML(sXML) 
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 0
		PrmIn.Value("Options") ="REPLACETABLEFIELDS=1"
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		PrmIn.Value("XML")=dom 
		
		iRet = RC.Jobs.DMS.XMLUpdate(PrmIn, PrmOut)
		If iRet = 0 Then
			debug2File vbTab & "RemoveControlledPrintingInformations successful..."
		Else
			debug2File vbTab & "ERROR: RemoveControlledPrintingInformations failed..."
		End If		
		
		Set oxmlDoc = Nothing
	Else
		debug2File "No document available"	
	End If
	debug2File "end RemoveControlledPrintingInformations()"
End Function


Function getParentRegister(sObjectId,sObjectType,sFoldername)
	debug2File "getParentRegister<="
'NICHT FERTIG
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams

	sxml = "<DMSQuery request_type='HOL'>"
	sxml = sxml & "<Archive internal_name='" & sFoldername & "'>"
	sxml = sxml & "<ParentObjects></ParentObjects>"	    
	sxml = sxml & "<ObjectType id=""" & sObjectType & """ type=""DOCUMENT"">"	    
	sxml = sxml & "<Fields field_schema=""MIN"">" & vbcrlf
	sxml = sxml & "</Fields>" & vbcrlf
	sxml = sxml & "<Conditions>" & vbcrlf
	sxml = sxml & "<ConditionObject id=""" & sObjectType & """ type=""DOCUMENT"">"
	sxml = sxml & "<FieldCondition dbname=""" & "id" & """ operator=""="">" & vbcrlf
	sxml = sxml & "<Value>" & sObjectId & "</Value>" & vbcrlf
	sxml = sxml & "</FieldCondition>"	& vbcrlf
	sxml = sxml & "</ConditionObject>" & vbcrlf
	sxml = sxml & "</Conditions>" & vbcrlf
	sxml = sxml & "</ObjectType>" & vbcrlf
	sxml = sxml & "</Archive>" & vbcrlf
	sxml = sxml & "</DMSQuery>" & vbcrlf
	debug2File "getVariantInfo " & sxml
	Set xmldoc = CreateObject("MSXML.DOMDocument") 
	xmldoc.loadXML(sxml)
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	'PrmIn.Value("Options")="checkaccess=0"
	PrmIn.Value("Encoding")="UTF-8"
	PrmIn.Value("Variants")=1
	PrmIn.Value("XML")=xmldoc

	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	If iRet=0 Then
    	sfile = PrmOut.Value("$Job$Files$")
    	sfile = Mid(sfile,2,len(sfile)-2)
    	xmldoc.load(sfile)
		Set fso = CreateObject("Scripting.FileSystemObject")
		fso.deletefile(sfile)
	end if	
	debug2File xmlDoc.xml
	Set Nodes=xmlDoc.SelectSingleNode("\\Object")
	'Todo id richtig auslesen
	debug2File "getParentRegister=>"
End Function

Function getObjectId(sObjectName,sFolderName,sFieldNames,sFieldValues)
	debug2File "getObjectId<="
'NICHT FERTIG
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	aFieldNames=Split(sFieldNames,"|")
	aFieldValues=Split(sFieldValues,"|")

	sxml = "<DMSQuery request_type='HOL'>"
	sxml = sxml & "<Archive internal_name='" & sFoldername & "'>"  
	sxml = sxml & "<ObjectType internal_name=""" & sObjectName & """ type=""DOCUMENT"">"	    
	sxml = sxml & "<Fields field_schema=""MIN"">" & vbcrlf
	sxml = sxml & "</Fields>" & vbcrlf
	sxml = sxml & "<Conditions>" & vbcrlf
	sxml = sxml & "<ConditionObject internal_name=""" & sObjectName & """ type=""DOCUMENT"">"
	For i=0 To UBound(aFieldNames)
		sxml = sxml & "<FieldCondition internal_name=""" & aFieldNames(i) & """ operator=""="">" & vbcrlf
		sxml = sxml & "<Value>" & aFieldValues(i) & "</Value>" & vbcrlf
		sxml = sxml & "</FieldCondition>"	& vbCrLf
	next
	sxml = sxml & "</ConditionObject>" & vbcrlf
	sxml = sxml & "</Conditions>" & vbcrlf
	sxml = sxml & "</ObjectType>" & vbcrlf
	sxml = sxml & "</Archive>" & vbcrlf
	sxml = sxml & "</DMSQuery>" & vbcrlf
	debug2File "getVariantInfo " & sxml
	Set xmldoc = CreateObject("MSXML.DOMDocument") 
	xmldoc.loadXML(sxml)
	PrmIn.Clear() 
	PrmIn.Value("Flags") = 16
	'PrmIn.Value("Options")="checkaccess=0"
	PrmIn.Value("Encoding")="UTF-8"
	PrmIn.Value("Variants")=1
	PrmIn.Value("XML")=xmldoc

	iRet = RC.Jobs.DMS.GetResultList(PrmIn, PrmOut)
	If iRet=0 Then
    	sfile = PrmOut.Value("$Job$Files$")
    	sfile = Mid(sfile,2,len(sfile)-2)
    	xmldoc.load(sfile)
		Set fso = CreateObject("Scripting.FileSystemObject")
		fso.deletefile(sfile)
	end if	
	debug2File xmlDoc.xml
	Set Nodes=xmlDoc.SelectSingleNode("\\Object")
	'Todo id richtig auslesen
	debug2File "getObjectId=>"
End Function

'**********************************************************
'sets the training status at the person register of the training surview
'**********************************************************
Sub setPersonRegister
	debug2File vbTab & "setPersonRegister: START"
	updateField "fTrainingSurvey", "REGISTER", "rPerson", wfvariables.sPersonRegisterID.Value, "sTrainingStatus", wfvariables.sOptions.Value
	updateField "fTrainingSurvey", "REGISTER", "rPerson", wfvariables.sPersonRegisterID.Value, "sComment", wfvariables.sComment.Value
	updateField "fTrainingSurvey", "REGISTER", "rPerson", wfvariables.sPersonRegisterID.Value, "sProcessID", "0"
	
	debug2File vbTab & "setPersonRegister: END"
End Sub 

'**********************************************************
' setTrainingStatus
' @description: updates the field sTrainingStatus of a person register to the selected value
' @param: 
' @return: nothing
'**********************************************************
Sub setTrainingStatus
	debug2File vbTab & "setTrainingStatus: START" & wfvariables.sOptions.Value & " - " & CStr ( wfvariables.iOptionsResultLocal.Value)
	wfvariables.sDocumentNumber.Value = "unnecessary"
	sFieldValues = "<Field internal_name='sTrainingStatus'>" & convertToValidXML(CStr(wfvariables.iOptionsResultLocal.Value)) & "</Field>" & vbCrLf & "<Field internal_name='sComment'>" & convertToValidXML(wfvariables.sComment.Value) & "</Field>"
	setFieldValues "fTrainingSurvey", "rPerson", "REGISTER", sFieldValues, wfvariables.sPersonRegisterID.Value
	
	sTrainingStatus = wfvariables.iOptionsResultLocal.Value
	If sTrainingStatus = 0 Then
		sDescriptiveStatus = "Aufgefordert / invited"
	End If			
	If sTrainingStatus = 1 Then
		sDescriptiveStatus = "Nicht gelesen / Not read"
	End If
	If sTrainingStatus = 2 Then
		sDescriptiveStatus = "Gelesen / Read"
	End If
	If sTrainingStatus = 3 Then
		sDescriptiveStatus = "Geschult / Trained"
	End If	
	updateField "fTrainingSurvey", "REGISTER", "rPerson", wfvariables.sPersonRegisterID.Value, "sStatusInformation", sDescriptiveStatus	
	
	debug2File vbTab & "setTrainingStatus: END"
End Sub

'**********************************************************
' storeObjectInCacheDirect
' @description: returns a document from the work directory
' @param: ObjectID (Integer) - objectID of the object which should be stored in the user cache
'		 for example used to store a document template temporary in the cache
' @return: filepath of the stored object
'**********************************************************
Function storeObjectInCacheDirect (ObjectID)
	debug2File "start storeObjectInCacheDirect (" & ObjectID & ")"	
	If CLng(ObjectID) > 0 Then
		'create running context object
		Dim RC 
		Set RC = RunningContext 
		Set PrmIn = RC.NewJobsParams 
		Set PrmOut = RC.NewJobsParams
		
		PrmIn.Clear() 
		PrmIn.Value("Flags") = 1
		PrmIn.Value("dwObjectID") = CLng(ObjectID)
		PrmIn.Value("Path") = RC.ServerData.TempDir
		PrmIn.Value("JobUserGUID") = wforganisation.GetOrgObjectsByName("osservice").Item(0).GetAttributeValueByName("UserId") 
		
		iRet = RC.Jobs.STD.StoreInCacheDirect(PrmIn, PrmOut)
		
		If iRet = 0 Then 'check the results
			debug2File vbTab & "storeObjectInCacheDirect successful"
			sfile = PrmOut.Value("File_0")
			debug2File vbTab & "Filepath: " & sfile
				
			storeObjectInCacheDirect = sfile	

		Else
			debug2File "storeObjectInCacheDirect failed"
		End If
		
	Else
		debug2File "No document available"	
	End If
	debug2File "end storeObjectInCacheDirect (" & ObjectID & ")"	
End Function

'**********************************************************
' storeInWork
' @description: stores a document in the work directory
' @param: iObjectID (Integer) - objectID of the object which should be stored in the work directory
' @param: iObjectType (Integer) - objectID of the object which should be stored in the work directory
' @param: sDocumentFilePath (String) - the path of the document which should be stored in the work directory
' @return: 0 if the job is successful, otherwise -1
'**********************************************************
Function storeInWork (iObjectID, iObjectType, sDocumentFilePath)
debug2File "start storeInWork (" & iObjectID & ", " & iObjectType & ", " & sDocumentFilePath & ")"

	Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists (sDocumentFilePath) = False Then 
		debug2File vbTab & "Document does not exist..."
		storeInWork = -1
		Exit Function
	End If

	'create running context object
	Dim RC 
	Set RC = RunningContext 
	Set PrmIn = RC.NewJobsParams 
	Set PrmOut = RC.NewJobsParams
	
	PrmIn.Clear()
	PrmOut.Clear()
	
	PrmIn.Value("Flags") = 0
	PrmIn.Value("dwObjectID") = CLng(iObjectID)
	PrmIn.Value("dwObjectType") = CLng(iObjectType)
	PrmIn.Value("FileCount") = 1
	PrmIn.Value("$Job$Files$" ) = sDocumentFilePath
	
	iRet = RC.Jobs.STD.StoreInWork(PrmIn, PrmOut)
	If iRet = 0 Then 'check the results
		debug2File vbTab & "StoreInWork successful"
		storeInWork = 0
	Else
		debug2File "StoreInWork failed. Error Code: " & iRet
		storeInWork = -1
	End If	
debug2File "end storeInWork"
End Function 

'**********************************************************
'Office Utilities
'This class should offer utilites to handle with  microsoft documents
'**********************************************************
Class OfficeUtilities
	Private sProtectionPassword
	
	
	Private Sub Class_Initialize(  )
		sProtectionPassword = "optimal#2015" 	'ToDo: hardcoded password :-(
	End Sub

	'**********************************************************
	' setWordDocumentProtection
	' @description: protects a MS WORD document with a password; only the track changes mode is allowed
	' @param: path to the word document
	' @return: true
	'**********************************************************
	Private Function setWordDocumentProtection (sDocumentFilePath)
	debug2File "start setWordDocumentProtection"

		
'		Set oWord = Nothing
		'On Error Resume Next
'		Dim bFoundWord : bFoundWord = 0
		Dim iWordProtected : iWordProtected = 0
		
		'initialize the word object
'		Set oWord = getWordInstance (bFoundWord)
		
'		If oWord Is Nothing Then
	        'nothing
'			debug2file vbTab & "setWordDocumentProtection: " & "Can't initialize word com object"
'	    Else	'we got a word object
'	    	debug2File vbTab & "Open the word document..."
'			Set objDoc = oWord.Documents.Open(sDocumentFilePath)
			
'			debug2file vbTab & "Set ReadingLayout to False..."
'			objDoc.ActiveWindow.View.ReadingLayout = False

'			debug2file vbTab & "Check protection type..."
'			if objDoc.ProtectionType = -1 Then
'				debug2file vbTab & "setWordDocumentProtection: Protect document"
'				objDoc.Protect 0, False, sProtectionPassword,False,False  
'				iWordProtected = 1
'			Else
'				debug2file vbTab & "setWordDocumentProtection: " & "Redundant Document Protection: Document Protection could not be activated when opening workflow step.", "INFO"
'			End If
			
			'SaveAs, da Save die OS-OfficeUtilites mit der AutoCheckIn Funktion aufrufen knnte. In diesem Fall wrde aufgrund von parallelen Dateizugriffen ein Fehler erzeugt.
			'Das SavedAs (also umbenannte) Dokument wird anschlieend wieder in den Originalnamen zurckgefhrt (siehe MoveFile).			
			
			'objDoc.Save
'			debug2File vbTab & "SaveAs: " & sDocumentFilePath & ".bak"
'			objDoc.SaveAs sDocumentFilePath & ".bak"
			
'			debug2File vbTab & "Close word..."	
'			objDoc.Close
			
			
			'delete the original file
'			debug2File vbTab & "Delete the original file... (" & sDocumentFilePath & ")"
'			Set oFSO = CreateObject("Scripting.FileSystemObject")
'			If oFSO.FileExists (sDocumentFilePath) = True Then 'delete the file
'				oFSO.DeleteFile sDocumentFilePath
'			End If
			
			'overwrite the orginal file with the bak file
'			debug2File vbTab & "overwrite the orginal file with the bak file..."
'			oFSO.MoveFile sDocumentFilePath & ".bak", sDocumentFilePath
			
'			if bFoundWord = 0 Then 'WORD nicht beenden, falls es schon vorher geffnet war
'		 		oWord.Quit
'		 	End If		       
'		End If
'		Set oWord = Nothing
'		Set objDoc = Nothing

		Dim myObj
		Dim myClass
		Set myObj = CreateObject("osvsbUtils.Utils")
		myObj.protectDocument(sDocumentFilePath)
		Set myObj = nothing
		iWordProtected = 1
		
		'stores the modified document in the work directory
		iRet = storeInWork (wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, sDocumentFilePath)
	    If iRet = 0 Then
			If iWordProtected = 1 Then
				debug2File vbTab & "setWordDocumentProtection: sets iDocumentProtection to 1"
				wfvariables.iDocumentProtected.Value = 1 'sets the protectionflag to true (1)
			End If
		Else
			debug2File vbTab & "ERROR: setWordDocumentProtection failed, because storeInWork failed..."
		End If
		Set oFSO = nothing
	debug2File "end setWordDocumentProtection"	
	End Function

	'**********************************************************
	' setDocumentProtection
	' @description: protects the document with a password; only the track changes mode is allowed
	' @return: true
	'**********************************************************
	Public Function setDocumentProtection ()
		'at first get the document from the work directory
		sDocumentFilePath = storeObjectInCacheDirect (wfvariables.recStructure.iDocumentID.Value)
		debug2file "setDocumentProtection: " & sDocumentFilePath
		
		'at first check, if we deal with a word document (extension starts with 'doc')
		Set oFSO = CreateObject("Scripting.FileSystemObject")
		extension = oFSO.GetExtensionName(sDocumentFilePath)
		If LCase(Left(extension,4)) = "docx" Then
			setWordDocumentProtection (sDocumentFilePath)
		Else
			debug2File vbTab & "setDocumentProtection: exit function, cause we don't deal with a word document..."
			If oFSO.FileExists (sDocumentFilePath) = True Then 'delete the file
				oFSO.DeleteFile sDocumentFilePath
			End If
			debug2File "end setDocumentProtection"
			Exit Function		
		End If
	
	End Function
	
	'**********************************************************
	' removeWordDocumentProtection
	' @description: removes the protection from a MS WORD document
	' @return: true
	'**********************************************************
	Private Function removeWordDocumentProtection (sDocumentFilePath)
	debug2File "start removeWordDocumentProtection"	

'		Set oWord = Nothing
		'On Error Resume Next
'		Dim bFoundWord : bFoundWord = 0
		Dim iWordUnProtected : iWordUnProtected = 0
		
		'initialize the word object
'		Set oWord = getWordInstance (bFoundWord)
		
'		If oWord Is Nothing Then
	        'nothing
'			debug2file "removeWordDocumentProtection: " & "Can't initialize word com object"
'		    Else	'we got a word object
'		    	debug2File vbTab & "Open the word document..."
'				Set objDoc = oWord.Documents.Open(sDocumentFilePath)
				
'				objDoc.ActiveWindow.View.ReadingLayout = False
	
'				if objDoc.ProtectionType = 0 Then
'					debug2file "removeWordDocumentProtection: Unprotect document"
'					objDoc.Unprotect sProtectionPassword			
'					iWordUnProtected = 1
'				Else
'					debug2file "removeWordDocumentProtection: "
'				End If			
				
				'SaveAs, da Save die OS-OfficeUtilites mit der AutoCheckIn Funktion aufrufen knnte. In diesem Fall wrde aufgrund von parallelen Dateizugriffen ein Fehler erzeugt.
				'Das SavedAs (also umbenannte) Dokument wird anschlieend wieder in den Originalnamen zurckgefhrt (siehe MoveFile).			
				
				'objDoc.Save
				
'				objDoc.SaveAs sDocumentFilePath & ".bak"
					
'				objDoc.Close
				
				'overwrite the orginal file with the bak file
'				Set oFSO = CreateObject("Scripting.FileSystemObject")
'				If oFSO.FileExists (sDocumentFilePath) = True Then 'delete the file
'					oFSO.DeleteFile sDocumentFilePath
'				End If
				
'				oFSO.MoveFile sDocumentFilePath & ".bak", sDocumentFilePath
				
'				if bFoundWord = 0 Then 'WORD nicht beenden, falls es schon vorher geffnet war
'			 		oWord.Quit
'			 	End If
		       
'		End If
'		Set oWord = Nothing
'		Set objDoc = Nothing

		Dim myObj
		Dim myClass
		Set myObj = CreateObject("osvsbUtils.Utils")
		myObj.unprotectDocument(sDocumentFilePath)
		Set myObj = nothing
		iWordUnProtected = 1
		'stores the modified document in the work directory
		 iRet = storeInWork (wfvariables.recStructure.iDocumentID.Value, wfvariables.recStructure.iDocumentType.Value, sDocumentFilePath)
		 If iRet = 0 Then
		  If iWordUnProtected = 1 Then
		  	debug2File vbTab & "setWordDocumentProtection: sets iDocumentProtection to 0"
		  	wfvariables.iDocumentProtected.Value = 0	'sets the protectionflag to false (0)
		  End If
		 End If
		 
	debug2File "end removeWordDocumentProtection"		
	End Function
	
	'**********************************************************
	' removeDocumentProtection
	' @description: removes the document protection
	' @return: true
	'**********************************************************
	Public Function removeDocumentProtection ()
		'at first get the document from the work directory
		sDocumentFilePath = storeObjectInCacheDirect (wfvariables.recStructure.iDocumentID.Value)
		debug2file "removeDocumentProtection: " & sDocumentFilePath
		
		'at first check, if we deal with a word document (extension starts with 'doc')
		Set oFSO = CreateObject("Scripting.FileSystemObject")
		extension = oFSO.GetExtensionName(sDocumentFilePath)
		If LCase(Left(extension,4)) = "docx" Then
			removeWordDocumentProtection (sDocumentFilePath)
		Else
			debug2File vbTab & "removeDocumentProtection: exit function, cause we don't deal with a word document..."
			If oFSO.FileExists (sDocumentFilePath) = True Then 'delete the file
				oFSO.DeleteFile sDocumentFilePath
			End If
			debug2File "end removeDocumentProtection"
			Exit Function		
		End If
	End Function
	
	'**********************************************************
	' getWordInstance
	' @description: gets an exisiting word object or creates a new one
	' @return: true
	'**********************************************************
	Function getWordInstance (bFoundWord)
		On Error Resume Next
		'check if word is already open - this could raise an error
		Set oWord = Nothing
		Set oWord = GetObject(, "Word.Application")
		
		If Err <> 0 Then
			debug2file vbTab & "Fehler beim Initialisieren von MSWORD aufgetreten: " & Err.Description
			Set oWord = CreateObject("Word.Application")
			bFoundWord = 0
		Else
			bFoundWord = 1
		End If
		Set getWordInstance = oWord	
	End Function
	
	'**********************************************************
	' CheckForWordDocumentRevisions
	' @description: checks if revisions or comments are implemented in the MS WORD document; if this is the case, it's not allowed to forward the document
	' @param nothing
	' @return nothing
	'**********************************************************
	Private Function CheckForWordDocumentRevisions (sDocumentFilePath)
	debug2File "start CheckForWordDocumentRevisions"	
		If wfvariables.recStructure.iDocumentID.Value > 0 Then
			
			'at first get the document from the work directory
			sDocumentFilePath = storeObjectInCacheDirect (wfvariables.recStructure.iDocumentID.Value)
'			debug2file vbTab & "Document which should be checked: " & sDocumentFilePath
'			Set oWord = Nothing
			'On Error Resume Next
'			Dim bFoundWord : bFoundWord = 0
			
			'initialize the word object
'			Set oWord = getWordInstance (bFoundWord)
			
'			If oWord Is Nothing Then
		        'nothing
'				debug2file "CheckForWordDocumentRevisions: " & "Can't initialize word com object"
'		    Else	'we got a word object
'		    	debug2File vbTab & "Open the document..."
'				Set objDoc = oWord.Documents.Open(sDocumentFilePath)
				
'				debug2File vbTab & "Set the ReadingLayout to False..."
'				objDoc.ActiveWindow.View.ReadingLayout = False
	
'				debug2File vbTab & "Check for Revisions or Comments..."
		Dim myObj
		Dim myClass
		Set myObj = CreateObject("osvsbUtils.Utils")
		bHasComments = myObj.hasComments(sDocumentFilePath)
		bHasTrackedRevision = myObj.hasTrackedRevisions(sDocumentFilePath)
		Set myObj = Nothing
		
				'If ((objDoc.Revisions.Count > 0) Or (objDoc.Comments.Count > 0)) Then				
				If ((bHasComments = True) Or (bHasTrackedRevision = True)) Then				
					debug2File vbTab & "Revsions / Comments found..."
					'add a protocol entry
					'The document includes revisions or comments. It is not allowed to forward this document.
					addProtocolEntry "The document includes revisions or comments. It is not allowed to forward this document.", "INFO", "SYSTEM", False
					
					'remove all entries in the columns "PerformedBy" and "PerformedAt" cause this steps must be perfomed again
					'in this case the review / approval steps must be performed again
					ClearPerformedValuesFromUserTable
					wfvariables.iOptionsResult.Value = 0 
					
					'check the configuration file for next activity (normally this is done in the end activity - but the features are executed after the next activity check, so we need to do this again manually)
					'**************************************************************
					debug2file vbTab & "Checking configuration for next activity..."
					For v = 0 To wfvariables.recConfigNextActivityConditions.Count - 1
						Dim ActivityName : ActivityName = wfvariables.recConfigNextActivityConditions.Item(v).Item("sNextActivity").Value
						debug2file "checking for activity "  & ActivityName
						Execute wfvariables.recConfigNextActivityConditions.Item(v).Item("sCondition").Value							
					Next
					debug2file vbTab & "Next Activity: " & wfvariables.sNextActivity.Value
					wfvariables.sHint.Value = "V1-6;;;WordRevisions;;;Im Dokument exisitieren nderungen. Bitte berprfen Sie die nderungen."
				End If		
				debug2File vbTab & "Close the document"				
				'objDoc.Close
				
				Set oFSO = CreateObject("Scripting.FileSystemObject")
				Set oFile = oFSO.GetFile(sDocumentFilePath)
				debug2File vbTab & "Delete the document..."
				oFile.Delete
				
				'if bFoundWord = 0 Then 'WORD nicht beenden, falls es schon vorher geffnet war
			 	'	oWord.Quit
			 	'End If
			       
'			End If
'			Set oWord = Nothing
'			Set objDoc = Nothing
		End If
	debug2File "end CheckForWordDocumentRevisions"		
	End Function
	
	'**********************************************************
	' CheckForDocumentRevisions
	' @description: checks if revisions or comments are implemented in the document; if this is the case, it's not allowed to forward the document
	' @param nothing
	' @return nothing
	'**********************************************************
	Public Function CheckForDocumentRevisions
		'at first get the document from the work directory
		sDocumentFilePath = storeObjectInCacheDirect (wfvariables.recStructure.iDocumentID.Value)
		debug2file "CheckForDocumentRevisions Filepath: " & sDocumentFilePath
		
		'at first check, if we deal with a word document (extension starts with 'doc')
		Set oFSO = CreateObject("Scripting.FileSystemObject")
		extension = oFSO.GetExtensionName(sDocumentFilePath)
		If LCase(Left(extension,4)) = "docx" Then
			CheckForWordDocumentRevisions (sDocumentFilePath)
		Else
			debug2File vbTab & "CheckForDocumentRevisions: exit function, cause we don't deal with a word document..."
			debug2File "end CheckForDocumentRevisions"
			Exit Function		
		End If
	End Function

End Class

'**********************************************************
' getMessageText
' @description: returns a text message depending on the language chosen in the client settings
' @param  sParagraph (of the ini file), sKey (under the paragraph), sDefault (will be returned if no messages matches)
' @return String
'**********************************************************
Function getMessageText ( sParagraph, sKey, sDefault, sLang )
	Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFso.FileExists( wfvariables.recCommon.sScriptPath.Value & "lang\" & sLang & "-messages.ini" ) = True Then
		sRet = GetINIString (sParagraph, sKey, sDefault, wfvariables.recCommon.sScriptPath.Value & "lang\" & sLang & "-messages.ini")
		if sRet <> "" then
			getMessageText = sRet
		else
			getMessageText = "Error: Could not get message: " & sParagraph & " " & sKey
		end if
	Else
		getMessageText = "Default: " & sDefault
	End if
	Set oFSO = Nothing
End Function

'**********************************************************
' getMessageTextWithValue
' @description: returns a text message depending on the language chosen in the client settings with an additional value from a parameter
' @param  sParagraph (of the ini file), sKey (under the paragraph), sDefault (will be returned if no messages matches), sValue (value to be concatenated)
' @return String
'**********************************************************
Function getMessageTextWithValue ( sParagraph, sKey, sDefault, sValue, sLang )
	Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFso.FileExists( wfvariables.recCommon.sScriptPath.Value & "lang\" & sLang & "-messages.ini" ) = True Then
		sRet = GetINIString (sParagraph, sKey, sDefault, wfvariables.recCommon.sScriptPath.Value & "lang\" & sLang & "-messages.ini")
		if sRet <> "" then
			getMessageTextWithValue = sRet & " " & sValue
		else
			getMessageTextWithValue = "Error: Could not get message: " & sParagraph & " " & sKey
		end if
	Else
		getMessageTextWithValue = "Default: " & sDefault & " " & sValue
	End if
	Set oFSO = Nothing
End Function

Function GetINIString(Section, KeyName, Default, FileName)
  Dim INIContents, PosSection, PosEndSection, sContents, Value, Found
  
  'Get contents of the INI file As a string
  INIContents = GetFile(FileName)

  'Find section
  PosSection = InStr(1, INIContents, "[" & Section & "]", vbTextCompare)
  If PosSection>0 Then
    'Section exists. Find end of section
    PosEndSection = InStr(PosSection, INIContents, vbCrLf & "[")
    '?Is this last section?
    If PosEndSection = 0 Then PosEndSection = Len(INIContents)+1
    
    'Separate section contents
    sContents = Mid(INIContents, PosSection, PosEndSection - PosSection)

    If InStr(1, sContents, vbCrLf & KeyName & "=", vbTextCompare)>0 Then
      Found = True
      'Separate value of a key.
      Value = SeparateField(sContents, vbCrLf & KeyName & "=", vbCrLf)
    End If
  End If
  If isempty(Found) Then Value = Default
  GetINIString = Value
End Function

'Separates one field between sStart And sEnd
Function SeparateField(ByVal sFrom, ByVal sStart, ByVal sEnd)
  Dim PosB: PosB = InStr(1, sFrom, sStart, 1)
  If PosB > 0 Then
    PosB = PosB + Len(sStart)
    Dim PosE: PosE = InStr(PosB, sFrom, sEnd, 1)
    If PosE = 0 Then PosE = InStr(PosB, sFrom, vbCrLf, 1)
    If PosE = 0 Then PosE = Len(sFrom) + 1
    SeparateField = Mid(sFrom, PosB, PosE - PosB)
  End If
End Function


'File functions
Function GetFile(ByVal FileName)
  Dim FS: Set FS = CreateObject("Scripting.FileSystemObject")
  'Go To windows folder If full path Not specified.
  If InStr(FileName, ":\") = 0 And Left (FileName,2)<>"\\" Then 
    FileName = FS.GetSpecialFolder(0) & "\" & FileName
  End If
  On Error Resume Next

  GetFile = FS.OpenTextFile(FileName).ReadAll
End Function

Function WriteFile(ByVal FileName, ByVal Contents)
  
  Dim FS: Set FS = CreateObject("Scripting.FileSystemObject")
  'On Error Resume Next

  'Go To windows folder If full path Not specified.
  If InStr(FileName, ":\") = 0 And Left (FileName,2)<>"\\" Then 
    FileName = FS.GetSpecialFolder(0) & "\" & FileName
  End If

  Dim OutStream: Set OutStream = FS.OpenTextFile(FileName, 2, True)
  OutStream.Write Contents
End Function