
'<Script Language="VBScript">
Option Explicit
'******************************************************************************************
'* cDocumentHandler
'* This script class handles transfers, locking and unlocking of documents
'******************************************************************************************
'******************************************************************************************
'* WHO     WHEN               WHAT
'*========================================================================================
'* MSD      07/26/2002        Original - Matt Daivs, Jimmy Moore
'* JRM      05/12/2003        Updating to include Fragment enhancments 
'* JRM      05/13/2003        Updating to make the whole thing async.
'******************************************************************************************

'
' NOTE: Field was not removed when removing all the global callbacks. It's used by some infrastructure pages to get "LocalFileName"
'       The places the set it before, are still setting it. It's advised for new development to keep reference to the object themselves.
'
Dim g_CurrentDocumentHandlerInstance

' Sub AddDocumentFragmentsToServer( Transaction )
'   Call g_CurrentDocumentHandlerInstance.AddDocumentFragmentsToServer( Transaction )
' End Sub

' Sub GetServerPathsOnTaskComplete( Task )
'   Call g_CurrentDocumentHandlerInstance.GetServerPathsOnTaskComplete( Task )
' End Sub

' Sub GetServerPathsOnError( Task )
'   Call g_CurrentDocumentHandlerInstance.GetServerPathsOnError( Task )
' End Sub

' Sub GetDocumentOnTaskComplete( Transaction )
'   Call g_CurrentDocumentHandlerInstance.GetDocumentOnTaskComplete( Transaction ) 
' End Sub 

' Sub SaveDocumentXMLAsyncOnTaskComplete( Transaction )
'   Call g_CurrentDocumentHandlerInstance.SaveDocumentXMLAsyncOnTaskComplete( Transaction )
' End Sub

' Sub GetServerConfigReferenceAsyncOnTaskComplete( Transaction )
'   Call g_CurrentDocumentHandlerInstance.GetServerConfigReferenceAsyncOnTaskComplete( Transaction )
' End Sub

' Sub AsyncProcessingComplete( Transaction )
'   Call g_CurrentDocumentHandlerInstance.AsyncProcessingComplete( Transaction )
' End Sub

' Sub UpdateDocumentOnServerOnComplete( Transaction )
'   Call g_CurrentDocumentHandlerInstance.UpdateDocumentOnServerOnComplete( Transaction )
' End Sub

' Sub DownloadMultiDocumentFilesError( Task )
'   Call g_CurrentDocumentHandlerInstance.DownloadMultiDocumentFilesError( Task )
' End Sub

' Sub DownloadMultiDocumentFilesComplete( Task )
'   Call g_CurrentDocumentHandlerInstance.DownloadMultiDocumentFilesComplete( Task )
' End Sub

' Sub LockMultiDocumentAsyncError( Task )
'   Call g_CurrentDocumentHandlerInstance.LockMultiDocumentAsyncError( Task )
' End Sub

' Sub LockMultiDocumentAsyncComplete( Task )
'   Call g_CurrentDocumentHandlerInstance.LockMultiDocumentAsyncComplete( Task )
' End Sub 

' Sub UploadProgressAsyncProgressCallBack( Transaction )
'   Call g_CurrentDocumentHandlerInstance.UploadProgress( Transaction )
' End Sub

Class cDocumentHandler

  Private mvarServerConfigDOM
  Private mvarExternalViewer
  Private mvarCallBackFunction
  Private mvarInternalTransaction
  Private mvaroAddDocumentCollection
  Private mvaroDocumentDOM
  Private mvarCurrentDocumentFragment
  Private mvarLocationID
  Private mvarIsCentral
  Private mvarCategoryID
  Private mvarErrorOccured
  Private mvarErrorDescription
  Private mvarTotalDownloadSize
  Private mvarCurrentDownloadCount
  Private mvarErrorCallBackFunction
  Private mvarResult
  Private mvarGetServerConfigCallBack
  Private mvarDocumentHandlerFragment
  Private mvarLockRequired
  Private mvarAsyncProcessingScript
  Private mvarUploadProgress
  Private mvarDownloadProgress
  Private mvarGotLocksArray()
  Private mvarFilePathArray()
  Private mvarDocumentHandlerFragments()
  
  Private Sub Class_Initialize
    Call ClassClear()
    Set g_CurrentDocumentHandlerInstance = Me
  End Sub
  
  
  '
  ' Clear out the variables in the class.
  Public Sub ClassClear()
    Set mvarServerConfigDOM         = Nothing
    Set mvaroAddDocumentCollection  = Nothing
    Set mvaroDocumentDOM            = Nothing
    Set mvarDocumentHandlerFragment = Nothing
    Set mvarInternalTransaction     = Nothing
    mvarIsCentral                   = False
    mvarErrorOccured                = False
    mvarLockRequired                = False
    mvarExternalViewer              = False
    mvarCategoryID                  = vbNullString
    mvarErrorDescription            = vbNullString
    mvarErrorCallBackFunction       = vbNullString
    mvarResult                      = vbNullString
    mvarAsyncProcessingScript       = vbNullString
    mvarUploadProgress              = vbNullString
    mvarCurrentDocumentFragment     = 0
    mvarLocationID                  = 0
    mvarTotalDownloadSize           = 0
    mvarCurrentDownloadCount        = 0
  End Sub
  
  
  '
  ' This function tells the consumer that an error occured
  Public Property Get ErrorOccured()
    ErrorOccured = mvarErrorOccured
  End Property
  
  
  '
  ' This function tells the consumer that an error occured
  Public Property Get ErrorDescription()
    ErrorDescription = mvarErrorDescription
  End Property
  
  
  '
  ' This function is used by the consumer to recieve a message if an error occurs
  Public Property Let ErrorCallBackFunction(vntData)
    if IsObject( vntData ) Then
      Set mvarErrorCallBackFunction = vntData
    Else
      mvarErrorCallBackFunction = vntData
    End If
  End Property 
  
  
  '
  ' This function will be used to access the results of any handler functions
  Public Property Get Result()
    Result = mvarResult
  End Property
  
  
  '
  ' This function will be used to access the the local file name after a get operation
  Public Property Get LocalFileName()
    If Not mvarDocumentHandlerFragment is Nothing Then
      LocalFileName = mvarDocumentHandlerFragment.LocalFileName
    End If
  End Property
  
  '
  ' This function will be used to access the the local file name after a get operation
  Public Property Get GotLock()
    If Not mvarDocumentHandlerFragment is Nothing Then
      GotLock = mvarDocumentHandlerFragment.GotLock
    End If
  End Property
  
  
  '
  ' This allows user access to the transaction object on an upload
  Public Property Get UploadStatusTransaction()
    Set UploadStatusTransaction = mvarInternalTransaction
  End Property
  
  
  '
  ' This allows the user of the document handler to set a call back when all the
  ' processing is complete.  It can either pass in a function name or an object 
  ' instance which has to have the function "DocumentHandlerCallBack"
  Public Property Let CallBackFunction(vntData)
    if IsObject( vntData ) Then
      Set mvarCallBackFunction = vntData
    Else
      mvarCallBackFunction = vntData
    End If
  End Property
  
  '
  ' This function allows you to have a callback when the file has an download progress.
  Public Property Let DownloadProgressCallBack(vntData)
    If IsObject( vntData ) Then
      Set mvarDownloadProgress = vntData
    Else
      mvarDownloadProgress = vntData
    End If
  End Property
  
  '
  ' This function allows you to have a callback when the file has an upload progress.
  Public Property Let UploadProgressCallBack(vntData)
    if IsObject( vntData ) Then
      Set mvarUploadProgress = vntData
    Else
      mvarUploadProgress = vntData
    End If
  End Property
  
  
  '
  ' This function sets wether the download file is going to be used for external viewing.
  Public Property Let ExternalViewer(vntData)
    mvarExternalViewer = vntData
  End Property
  
  
  
  '
  ' This function indicated if the Upload Progress callback is valid.
  Private Function IsValidUploadProgress()
    Dim Result : Result = True
    If Not IsObject( mvarUploadProgress ) Then
      If Len( mvarUploadProgress ) = 0 Then
        Result = False
      End If
    End If
    
    IsValidUploadProgress = Result
  End Function
  
  
  '
  ' This function will call back into the call script to update the transfer amount
  Public Function UploadProgress( Transaction )
  
    Set mvarInternalTransaction = Transaction
    
    If IsObject( mvarUploadProgress ) Then
      Call mvarUploadProgress.UploadProgress()
    Else
      If Len( mvarUploadProgress ) > 0 Then
        Call Execute( mvarUploadProgress )
      End If
    End If
  End Function
  
  
  '
  ' This function will return the directory path for a fragment.
  ' This function should only be used if you are using it for 
  ' GetDocumentVersionFragments
  Public Function GetPath( Index )
    GetPath = mvarFilePathArray( Index )
  End Function

  
  '
  'So that upon return, you can get the count of files from the object without having
  'to keep a global on your page.
  Public Property Get DownloadCount()
    DownloadCount = UBound(mvarFilePathArray)
  End Property
  
  '
  ' This function will return the Got lock value for the fragment.
  ' This function should only be used if you are using it for 
  ' GetDocumentVersionFragments
  Public Function GetGotLocks( Index )
    GetGotLocks = mvarGotLocksArray( Index ) 
  End Function
  
  
  '
  ' This function will download all of the fragments of a given version.
  ' Use the Get Path and Get GotLocks functions to retrieve the
  ' values for the array.  DocumentFragmentIDs , DocumentPaths , FileNames
  ' DocumentLocationIDs , CategoryIDs are all arrays holding the values
  ' of the files that need to be downloaded.
  Public Sub GetDocumentFragments( LockFile, DocumentFragmentIDs , LockRequired, DocumentPaths , FileNames , DocumentLocationIDs , CategoryIDs )
    Redim mvarGotLocksArray( UBound( DocumentFragmentIDs ) )
    Redim mvarFilePathArray( UBound( DocumentFragmentIDs ) )
    Redim mvarDocumentHandlerFragments( UBound( DocumentFragmentIDs ) )
    
    Dim i 
    For i = 0 to UBound( DocumentFragmentIDs )
      Set mvarDocumentHandlerFragments( i ) = New cDocumentHandlerFragment
          
      mvarDocumentHandlerFragments( i ).DocumentFragmentID      = DocumentFragmentIDs( i )
      mvarDocumentHandlerFragments( i ).ServerSideDocumentPath  = DocumentPaths( i )
      mvarDocumentHandlerFragments( i ).ServerSideFileName      = FileNames( i )
      mvarDocumentHandlerFragments( i ).LocationID              = DocumentLocationIDs( i )
      mvarDocumentHandlerFragments( i ).CategoryID              = CategoryIDs( i )
    
      mvarLockRequired = LockRequired
      
    Next
    
    ' Download the server configuration from ther server.
    Set g_CurrentDocumentHandlerInstance = Me
    If LockFile Then
      mvarAsyncProcessingScript = "Call LockMultiDocumentAsyncComplete()"
      Call LockMultiDocumentAsync()
    Else
      Call LockMultiDocumentAsyncComplete( Nothing )
    End If
      
  End Sub
  
  
  '
  ' This will lock multi document fragments at once.
  Private Sub LockMultiDocumentAsync()
    Dim Transaction
    Dim i
    Dim Task        : Set Task = external.ShellTasks.Add
    Dim TaskID      : TaskID   = vbNullString
    
    'Task.onComplete = GetRef("LockMultiDocumentAsyncComplete")
    'Task.onError    = GetRef("LockMultiDocumentAsyncError")
    Call Task.CompleteCallback.SetCallback(Me, "LockMultiDocumentAsyncComplete")
    Call Task.ErrorCallback.SetCallback(Me, "LockMultiDocumentAsyncError")

    For i = 0 to UBound(mvarDocumentHandlerFragments )
      TaskID             = "DocumentLock-" & Task.TaskID & "-" & i
      Set Transaction    = Task.AddHTTPTransaction( TaskID , "/Infrastructure/DocumentManagement/DocumentServer.asp" )
      With Transaction
        .setRequestHeader "Op"                 , "LockDocument"
        .setRequestHeader "DocumentFragmentID" , mvarDocumentHandlerFragments( i ).DocumentFragmentID
      End With
    Next
    
    Set g_CurrentDocumentHandlerInstance = Me
    Call Task.Execute()
  
  End Sub
  
  
  '
  ' This function gets called when it is done downloading all of the fragments.
  Public Sub LockMultiDocumentAsyncComplete( Task )
    Dim Transaction
    Dim i
    Dim TaskID
    
    For i = 0 to UBound(mvarDocumentHandlerFragments )
      If Task is Nothing Then
        mvarGotLocksArray( i ) = False
      Else
        TaskID                 = "DocumentLock-" & Task.TaskID & "-" & i
        Set Transaction        = Task.GetTransaction( TaskID )
        If Transaction.ResponseText = "0" And mvarLockRequired Then
          mvarGotLocksArray( i ) = False
          Call LockMultiDocumentAsyncError( Nothing )
        Else
          If Transaction.ResponseText = "1" Then
            mvarGotLocksArray( i ) =  True
          Else
            mvarGotLocksArray( i ) =  False
          End If
        End If
      End If
    Next
    
    Call GetServerConfigReferenceAsync( "Call DownloadMultiDocumentFiles()" )
  
  End Sub
  
  
  '
  ' This Function will download all of the documents to a local file.
  Private Sub DownloadMultiDocumentFiles()
    Dim LocationID         : LocationID          = external.MOM.sessionStash.Item("ServerConfig/LocationID").Value
    Dim ServerConfigDOM    : Set ServerConfigDOM = GetServerConfigReference()
    Dim DocumentLocationID  
    Dim DocumentFragmentID  
    Dim IsLocal
    Dim ServerURI
    Dim ServerPath
    Dim DocumentPath
    Dim FileName
    Dim FullPath
    Dim CategoryID
    Dim Task               : Set Task = external.ShellTasks.Add
    Dim TaskID
    Dim i
    Dim Transaction 
    Dim FileExt 
    
    ' Task.onComplete = GetRef("DownloadMultiDocumentFilesComplete")
    ' Task.onError    = GetRef("DownloadMultiDocumentFilesError")
    Call Task.CompleteCallback.SetCallback(Me, "DownloadMultiDocumentFilesComplete")
    Call Task.ErrorCallback.SetCallback(Me, "DownloadMultiDocumentFilesError")

    For i = 0 to UBound(mvarDocumentHandlerFragments )
      FileName               = mvarDocumentHandlerFragments( i ).ServerSideFileName
      
      FileExt = Right( FileName , Len( FileName ) - InstrRev( FileName , "." ) )
    
      mvarFilePathArray( i ) = GenerateFileName( FileExt )
      CategoryID             = mvarDocumentHandlerFragments( i ).CategoryID
      DocumentLocationID     = mvarDocumentHandlerFragments( i ).LocationID
      DocumentFragmentID     = mvarDocumentHandlerFragments( i ).DocumentFragmentID
      IsLocal                = ( ServerConfigIDFromLocationID( LocationID ) = ServerConfigIDFromLocationID( DocumentLocationID ) )
      ServerURI              = GetServerURI( CategoryID , DocumentLocationID, ServerConfigDOM, IsLocal )

      TaskID                 = "GetDocument-" & Task.TaskID & "-" & i
      Set Transaction        = Task.AddHTTPTransaction( TaskID , ServerURI )
      Transaction.outputFile = mvarFilePathArray( i )
      Transaction.setRequestHeader "mthOperation" , "GET"
      Transaction.setRequestHeader "mthDocumentFragmentID" , DocumentFragmentID
      Transaction.setRequestHeader "mthLocationID" , LocationID
      Transaction.setRequestHeader "mthDocumentLocationID" , DocumentLocationID
      Transaction.setRequestHeader "mthCategoryID" , CategoryID
    Next
    
    Set g_CurrentDocumentHandlerInstance = Me
    Call Task.Execute()
  
  End Sub
  
  
  Private Function GenerateFileName( FileExt )
    On Error Resume Next
    
    Dim TempPath 
    
    If mvarExternalViewer Then
      TempPath = external.MOM.StorageManager.TranslatePath( "Odyssey\External\Dummy.File" , 0 , 3 )
      Call external.MOM.StorageManager.CreateDirectory( TempPath )
      FileName = external.MOM.StorageManager.TranslatePath( "Odyssey\External\" , 0 , 3 )
      
    Else
      TempPath = external.MOM.StorageManager.TranslatePath( "Odyssey\Dummy.File" , 0 , 3 )
      Call external.MOM.StorageManager.CreateDirectory( TempPath )
      FileName = external.MOM.StorageManager.TranslatePath( "Odyssey\" , 0 , 3 )
      
    End If
    Call external.MOM.StorageManager.DeleteFile( FileName )
    
    Dim FileName : FileName = Left( FileName , instrrev( FileName , "." ) ) & FileExt
    
    GenerateFileName = FileName
    
  End Function
  
  
  '
  ' This function gets called when the download of the multi files is complete
  Public Sub DownloadMultiDocumentFilesComplete( Task )
  
    Call callBackInitiatingScript()
  
  End Sub
  
  
  '
  ' This function gets called when an error occurs during the download of multi fragments.
  Public Sub DownloadMultiDocumentFilesError( Task )
    mvarErrorDescription  = "Error occured while trying to download all of the document fragments."
    mvarErrorOccured      = True
    
    Call callBackInitiatingScript()
  End Sub
  
  
  '
  ' This function gets called if the Lock multi files has an error
  Public Sub LockMultiDocumentAsyncError( Task )
    mvarErrorDescription  = "Error occured while trying to lock all of the document fragments."
    mvarErrorOccured      = True
    
    Call callBackInitiatingScript()
  End Sub
    
  
  '
  ' This function will either call a callback function or it will call a
  ' certain methob on a object "DocumentHandlerCallBack"
  Private Sub callBackInitiatingScript()
    If mvarErrorOccured Then 
      If IsObject( mvarErrorCallBackFunction ) Then
        Call mvarErrorCallBackFunction.DocumentHandlerCallBack()
      Else
        If Len( mvarErrorCallBackFunction ) > 0 Then
          Call Execute(mvarErrorCallBackFunction)
        End If
      End If 
    Else
      If IsObject( mvarCallBackFunction ) Then
        Call mvarCallBackFunction.DocumentHandlerCallBack()
      Else
        If Len( mvarCallBackFunction ) > 0 Then
          Call Execute(mvarCallBackFunction)
        End If
      End If
    End IF
  End Sub
  
  Private Sub progressCallBackInitiatingScript(currentProgress, progressMax)
    If IsObject( mvarDownloadProgress ) Then
      Call mvarDownloadProgress.ProgressCallback(currentProgress, progressMax)
    Else
      If Len( mvarDownloadProgress ) > 0 Then
        Call Execute("Call " & mvarDownloadProgress & "(currentProgress, progressMax)") 
      End If
    End If
  End Sub
  
  
  '
  ' This is just a standard call back many functions.  This will remove the
  ' existing transaction and all the user defined call back.
  Public Sub AsyncProcessingComplete( Transaction )
  
    mvarResult = Transaction.ResponseText
  
    Call External.HTTPTransactions.Remove( Transaction.ID )
    Set Transaction = Nothing
    
    If Len( mvarAsyncProcessingScript ) > 0 Then
      Execute( mvarAsyncProcessingScript ) 
    Else
      Call callBackInitiatingScript()
    End If
    
  End Sub
  
  
  '
  ' This function will download a document from the server.  If the consumer wants a lock to 
  ' occur on the file it will do that also.
  ' The steps for downloading a file:
  ' 1. Lock Document ( If Needed )
  ' 2. Get Server Configuration from the server.
  ' 3. Retieve the file from the server.
  Public Function GetDocument( LockFile, DocumentFragmentID , LockRequired, DocumentPath, FileName, DocumentLocationID, CategoryID )
    
    '
    ' Storing away a lot of the passed in values because there will be a few async transaction.
    Set mvarDocumentHandlerFragment      = New cDocumentHandlerFragment
    
    mvarDocumentHandlerFragment.DocumentFragmentID      = DocumentFragmentID
    mvarDocumentHandlerFragment.ServerSideDocumentPath  = DocumentPath
    mvarDocumentHandlerFragment.ServerSideFileName      = FileName
    mvarDocumentHandlerFragment.LocationID              = DocumentLocationID
    
    mvarCategoryID   = CategoryID
    mvarLockRequired = LockRequired
    
    '
    ' Download the server configuration from ther server.
    If LockFile Then
      mvarAsyncProcessingScript = "Call GetDocumentLockFileOnTaskComplete()"
      Call LockDocumentAsync( DocumentFragmentID )
    Else
      mvarResult = "0"
      Call GetDocumentLockFileOnTaskComplete()
    End If
    
  End Function
  
  
  '
  ' At this point the file might be locked depending on the passed in values.  
  ' Now we are going to download the server configuration to the client.
  Private Function GetDocumentLockFileOnTaskComplete()
  
    mvarAsyncProcessingScript = ""
    If mvarResult = "0" And mvarLockRequired Then
      '
      ' If the lock is required and we did not get it then we are finished with the 
      ' transfer.
      mvarDocumentHandlerFragment.GotLock = False
      mvarResult = 0 
      Call callBackInitiatingScript()

    Else
    
      If mvarResult = "1" Then
        mvarDocumentHandlerFragment.GotLock = True
      Else
        mvarDocumentHandlerFragment.GotLock = False
      End If
      
      '
      ' Continue with the download of the server configuration xml
      Call GetServerConfigReferenceAsync( "Call DownloadDocumentFile()" )
      
    End If
  
  End Function
  
  
  Public Sub GenerateDocumentFragmentURL( DocumentFragmentID , DocumentPath , FileName , DocumentLocationID , CategoryID )
    
    Set mvarDocumentHandlerFragment      = New cDocumentHandlerFragment
    
    mvarDocumentHandlerFragment.DocumentFragmentID      = DocumentFragmentID
    mvarDocumentHandlerFragment.ServerSideDocumentPath  = DocumentPath
    mvarDocumentHandlerFragment.ServerSideFileName      = FileName
    mvarDocumentHandlerFragment.LocationID              = DocumentLocationID
    
    mvarCategoryID   = CategoryID
    
    Call GetServerConfigReferenceAsync( "Call GenerateDocumentFragmentURLContinue()" )
  
  End Sub
  
  
  Public Sub GenerateDocumentFragmentURLContinue()
  
    Dim LocationID         : LocationID          = external.MOM.sessionStash.Item("ServerConfig/LocationID").Value
    Dim ServerConfigDOM    : Set ServerConfigDOM = GetServerConfigReference()  
    Dim FileExt
   
   
    Dim FileName           : FileName            = mvarDocumentHandlerFragment.ServerSideFileName 
    FileExt = Right( FileName , Len( FileName ) - InstrRev( FileName , "." ) )
    mvarDocumentHandlerFragment.LocalFileName    = GenerateFileName( FileExt )
  
    Dim DocumentLocationID : DocumentLocationID  = mvarDocumentHandlerFragment.LocationID
   
    Dim IsLocal            : IsLocal             = ( ServerConfigIDFromLocationID( LocationID ) = ServerConfigIDFromLocationID( DocumentLocationID ) )
    Dim ServerURI          : ServerURI           = GetServerURI( mvarCategoryID, DocumentLocationID, ServerConfigDOM, IsLocal )
    Dim ServerPath         : ServerPath          = GetServerSharePath( mvarCategoryID, DocumentLocationID, ServerConfigDOM, IsLocal ) & vbNullString
   
    Dim DocumentPath       : DocumentPath        = mvarDocumentHandlerFragment.ServerSideDocumentPath
    Dim FullPath           : FullPath            = ServerPath & "\" & DocumentPath 
  
    If Len(DocumentPath & vbNullString) > 1 Then
      If Left(DocumentPath, 2) = "\\" Then
        FullPath = DocumentPath
      End If
    End If
  
    FullPath = FullPath & DocumentPath
 
    mvarResult = GenerateDocumentFragmentURLText(FullPath, FileName, ServerURI)
 
    Call callBackInitiatingScript()

  End Sub
  
  Public Function GenerateDocumentFragmentURLText(FilePath, FileName, FileURI)
    GenerateDocumentFragmentURLText = FileURI & "?Operation=Get&FilePath=" & FilePath & "&FileName=" & FileName & "&SiteID=" & external.MOM.ShellSession.SiteID
  End Function

  '
  ' At this point the file has been locked and the server configuration xml has been 
  ' downloaded.  Now we are going to download the file to the local computer.
  Private Function DownloadDocumentFile()

    On Error Resume Next
    
    Dim LocationID         : LocationID          = external.MOM.sessionStash.Item("ServerConfig/LocationID").Value
    Dim ServerConfigDOM    : Set ServerConfigDOM = GetServerConfigReference()
    Dim FileExt
   
    Dim FileName           : FileName            = mvarDocumentHandlerFragment.ServerSideFileName 
    FileExt = Right( FileName , Len( FileName ) - InstrRev( FileName , "." ) )
    mvarDocumentHandlerFragment.LocalFileName    = GenerateFileName( FileExt )
  
    Dim DocumentLocationID : DocumentLocationID  = mvarDocumentHandlerFragment.LocationID
    Dim IsLocal            : IsLocal             = ( ServerConfigIDFromLocationID( LocationID ) = ServerConfigIDFromLocationID( DocumentLocationID ) ) 
    Dim ServerURI          : ServerURI           = GetServerURI( mvarCategoryID, DocumentLocationID, ServerConfigDOM, IsLocal )
    
    Dim Transaction        : Set Transaction     = external.HTTPTransactions.Add("_GetDocument_" & External.CreateID())
    
    Set g_CurrentDocumentHandlerInstance = Me  
    With Transaction 
      .Open "GET" , ServerURI , True
      .outputFile        = mvarDocumentHandlerFragment.LocalFileName
      .setRequestHeader "mthOperation" , "GET"
      .setRequestHeader "mthDocumentFragmentID" , mvarDocumentHandlerFragment.DocumentFragmentID
      .setRequestHeader "mthLocationID" , LocationID
      .setRequestHeader "mthDocumentLocationID" , DocumentLocationID
      .setRequestHeader "mthCategoryID" , mvarCategoryID
      .ProgressCallback.SetCallback Me, "GetDocumentProgress"
      .CompleteCallback.SetCallback Me, "GetDocumentOnTaskComplete"
      .send
    End With
   
  End Function
  
  Public Sub GetDocumentProgress( Transaction )
    Call progressCallBackInitiatingScript( Transaction.progress, Transaction.progressMax )
  End Sub
  
  '
  ' This function get called when the getdocuments has been finished retrieving the
  ' file from the server.  Use the LocalFileName, GotLock property to recieve more
  ' information about the download.
  Public Sub GetDocumentOnTaskComplete( Transaction )
  
    If Transaction.Status <> 200 Or Not Transaction.ResponseErrors is Nothing Then
      mvarResult = 0
      Call DeleteLocalFile( mvarDocumentHandlerFragment.LocalFileName )
      mvarErrorDescription  = "Error occured while trying to download the document from server."
      mvarErrorOccured      = True
    Else
      mvarResult = 1
    End If
  
    Call External.HTTPTransactions.Remove( Transaction.ID )
    Set Transaction = Nothing
    
    Call callBackInitiatingScript()
  
  End Sub
  
  
  '
  ' This is the function that needs to be called to save a new document to the server.
  ' Before calling this function make sure to Set the Callbackfunction for this instance.
  ' Steps to this function :
  ' 1. Download the server configuration xml
  ' 2. Download the Path for each document
  ' 3. Upload the files to the server
  ' 4. Save the document xml to the server
  Public Function AddDocument( sDocumentXML , oAddDocumentsCollection )

    mvarCurrentDownloadCount = 0
    
    If oAddDocumentsCollection.Count = 0 Then
      mvarErrorDescription  = "Error, No documents present to upload."
      mvarErrorOccured      = True
      Call callBackInitiatingScript()
   
    Else 
      
      Set mvaroAddDocumentCollection = oAddDocumentsCollection
    
      Set mvaroDocumentDOM = Nothing
      Set mvaroDocumentDOM = CreateObject("MSXML2.DOMDocument.3.0")
      Call mvaroDocumentDOM.LoadXML(sDocumentXML)

      Call GetServerConfigReferenceAsync( "Call GetServerPaths()" )
      
    End If
    
  End Function
  
  
  '
  ' This function will download the Async download the Server configuration xml from the
  ' the server.
  Public Function GetServerConfigReferenceAsync( CallBackFunction )
 
    if mvarServerConfigDOM is Nothing Then
      mvarGetServerConfigCallBack = CallBackFunction
    
      Set g_CurrentDocumentHandlerInstance = Me
      
      Dim Transaction : Set Transaction = external.HTTPTransactions.Add("_GetServerConfig_" & External.CreateID())
      With Transaction  
        .Open "POST" , "/Infrastructure/DocumentManagement/DocumentServer.asp", True
        '.onrequestcomplete = GetRef( "GetServerConfigReferenceAsyncOnTaskComplete" )
        Call .CompleteCallback.SetCallback(Me, "GetServerConfigReferenceAsyncOnTaskComplete")
        .setRequestHeader "Op" , "LoadServerConfigXML"
        .send vbNullString
      End With
    
      Set Transaction = Nothing 
    Else
      If Len( CallBackFunction ) > 0 Then
        Execute( CallBackFunction )
      End If
    End If
    
  End Function
      
      
  '
  ' Call back when the Server configuration has completed the download.	  
  Public Sub GetServerConfigReferenceAsyncOnTaskComplete( Transaction )
    
    Set mvarServerConfigDOM = External.CreateObject("MSXML2.DOMDocument.3.0")
    Call mvarServerConfigDOM.LoadXML( Transaction.ResponseText )
    
    Call External.HTTPTransactions.Remove( Transaction.ID )
    Set Transaction = Nothing
    
    mvarResult = mvarServerConfigDOM.xml
    
    If Len( mvarGetServerConfigCallBack ) > 0 Then
      Execute( mvarGetServerConfigCallBack )
    End If
    
  End Sub

  
  '
  ' This function will create a task so that all of the all of the document fragments
  ' get the server path that they need to be uploaded too.
  Private Function GetServerPaths()
  
    Dim ByteCount
    Dim Task           : Set Task = external.ShellTasks.Add
    Dim TaskID         : TaskID   = ""
    Dim Transaction
    Dim CurrentDocFrag
    Dim CurrentSeqNumber
    Dim sDocTypeID
    
    mvarGetServerConfigCallBack = ""
    
    '
    ' The next couple of statements determine the Doc Type, Cat , Location , Central
    sDocTypeID      = mvaroDocumentDOM.documentElement.getAttribute("DocumentTypeID")
    mvarCategoryID  = External.CodeQuery.GetCodeField("Operations", "uDocType", "", sDocTypeID, "DOCCATID")
    mvarLocationID  = GetLocationIDForSaving(mvarCategoryID)
    mvarIsCentral   = IsThisLocationCentral(mvarLocationID)
    Call External.CodeQuery.CloseTable("Operations", "uDocType")
        
    'Task.onComplete = GetRef("GetServerPathsOnTaskComplete")
    'Task.onError    = GetRef("GetServerPathsOnError")
    Call Task.CompleteCallback.SetCallback(Me, "GetServerPathsOnTaskComplete")
    Call Task.ErrorCallback.SetCallback(Me, "GetServerPathsOnError")

    For CurrentSeqNumber = 0 to mvaroAddDocumentCollection.Count - 1
      Set CurrentDocFrag    = mvaroAddDocumentCollection.GetDocument( CurrentSeqNumber )
      TaskID                = "DocumentPath-" & Task.TaskID & "-" & CurrentSeqNumber
      ByteCount             = GetFileByteCount( CurrentDocFrag.LocalPath )
      mvarTotalDownloadSize = mvarTotalDownloadSize + ByteCount
      
      Set g_CurrentDocumentHandlerInstance = Me
      
      Set Transaction    = Task.AddHTTPTransaction( TaskID , "/Infrastructure/DocumentManagement/DocumentServer.asp" )
      With Transaction
        .setRequestHeader "Op"        , "GetStoragePath"
        .setRequestHeader "ByteCount" , ByteCount
        .setRequestHeader "CategoryID", mvarCategoryID
      End With
    Next
        
    Task.Execute
    
  End Function
  
  
  '
  ' This function gets called if the task has a problem downloading the server paths.
  Public Function GetServerPathsOnError( Task )
    mvarErrorDescription  = "Error occured during the task of determining the server path."
    mvarErrorOccured      = True
    
    Call callBackInitiatingScript()
    
  End Function
  
  
  '
  ' This function will update the collection of add documents with the 
  ' result of the tasks transaction.
  Public Function GetServerPathsOnTaskComplete( Task )
  
    Dim TaskID
    Dim CurrentSeqNumber
    Dim Transaction
    Dim CurrentDocFrag
    Dim localErrorOccured     : localErrorOccured = False
    
    For CurrentSeqNumber = 0 to mvaroAddDocumentCollection.Count - 1
    
      Set CurrentDocFrag  = mvaroAddDocumentCollection.GetDocument( CurrentSeqNumber )
      TaskID              = "DocumentPath-" & Task.TaskID & "-" & CurrentSeqNumber
      Set Transaction     = Task.GetTransaction( TaskID )
      
      '
      ' Updating the collection with the value returned from the server.
      CurrentDocFrag.ServerSideDocumentPath = Transaction.responseText
      If Len( CurrentDocFrag.ServerSideDocumentPath ) = 0 Then localErrorOccured = True
      
      Set Transaction = Nothing
      
    Next
    Set Task = Nothing
    
    If localErrorOccured Then
      mvarErrorDescription  = "Error occured while trying to determine the server upload path."
      mvarErrorOccured      = True
      Call callBackInitiatingScript()
    Else
      Call AddDocumentFragmentsToServer( Nothing )
    End If
    
  End Function
  
  
  '
  ' This method is going to loop through the document add collection and
  ' Upload a file to the server one at a time ( No support in shell for 
  ' multiple uploads).  Once it uploads a document it calls itself back to 
  ' update the DocumentAdd collection.  Once all files have been upload to the
  ' server and no error occur it will call the function to update the xml and save it.
  Public Function AddDocumentFragmentsToServer( Transaction )
  
    Dim CurrentDocFrag
    
    '
    ' If this is the first time in the function it will not enter the next if, but
    ' if this function was called from a callback it will enter the if and store off
    ' the file name from the headers.
    If Not Transaction is Nothing Then
      If ( Transaction.Status <> 200 ) then
        mvarErrorOccured     = True
        mvarErrorDescription = "Error occured while uploading a document to the server."
      Else
        '
        ' Updating the Add Document collection with the Server File Name.
        Set CurrentDocFrag = mvaroAddDocumentCollection.GetDocument( mvarCurrentDownloadCount - 1 )
        CurrentDocFrag.ServerSideFileName =  Transaction.getResponseHeader("DOCUMENT_FILENAME")
        If Len( CurrentDocFrag.ServerSideFileName ) = 0 Then
          mvarErrorDescription = "Error occured while uploading a document to the server."
          mvarErrorOccured     = True
        End If
        
      End If
      
      Call External.HTTPTransactions.Remove( Transaction.ID )
      Set Transaction = Nothing
      
    End If

    '
    ' This will either end the download operation or add another transaction to 
    ' download another file.
    If Not ErrorOccured Then    
      If mvarCurrentDownloadCount = mvaroAddDocumentCollection.Count Then
        Call UpdateAndSaveAddDocumentXML()
      Else
      
        Set CurrentDocFrag       = mvaroAddDocumentCollection.GetDocument( mvarCurrentDownloadCount )
        mvarCurrentDownloadCount = mvarCurrentDownloadCount + 1
        
        Dim oServerXMLDOM  : Set oServerXMLDOM = GetServerConfigReference()
        Dim ServerURI      : ServerURI         = GetServerURI( mvarCategoryID, mvarLocationID, oServerXMLDOM, True)
      
        Set g_CurrentDocumentHandlerInstance = Me
        Dim NewTransaction : Set NewTransaction = External.HTTPTransactions.Add( "_FileUpload_" & External.CreateID() )
        
        With NewTransaction
          .Open "POST", ServerURI, True
          '.onrequestcomplete = GetRef("AddDocumentFragmentsToServer")
          Call .CompleteCallback.SetCallback(Me, "AddDocumentFragmentsToServer")
          .setRequestHeader "mthOperation" , "Add"
          .setRequestHeader "mthLocationID" , mvarLocationID
          .setRequestHeader "mthCategoryID" , mvarCategoryID
          .setRequestHeader "mthFileExt" , CurrentDocFrag.FileExt
          If Len(CurrentDocFrag.ServerSideDocumentPath) > 0 Then
            .setRequestHeader "mthSubFolderPath", CurrentDocFrag.ServerSideDocumentPath
          End If
          If IsValidUploadProgress() Then
            '.onUploadProgress = GetRef("UploadProgressAsyncProgressCallBack")
            Call .UploadProgressCallback.SetCallback(Me, "UploadProgress")
          End If
          .sendFile CurrentDocFrag.LocalPath 
        End With
        
        Set CurrentDocFrag = Nothing
        Set NewTransaction = Nothing
        
      End If
      
    Else
      Call callBackInitiatingScript()
    End If
    
  End Function
    
  
  '
  ' When the upload of the files is complete this method will call the save document xml method
  ' to save the result to the server.
  Private Function UpdateAndSaveAddDocumentXML()
  
    Dim CurrentSeqNumber
    Dim CurrentFragInfo
    Dim oDocFrag
    
    For CurrentSeqNumber = 0 to mvaroAddDocumentCollection.Count - 1
     
      Set CurrentFragInfo = mvaroAddDocumentCollection.GetDocument( CurrentSeqNumber )
      Set oDocFrag        = mvaroDocumentDOM.selectSingleNode("Document/DocumentVersions/DocumentVersion/DocumentFragments/DocumentFragment[@DocumentFragmentID = '" & CurrentFragInfo.DocumentFragmentID & "']")
        
      If Not oDocFrag is Nothing Then
        Call oDocFrag.setAttribute( "FileName"       , CurrentFragInfo.ServerSideFileName     )
        Call oDocFrag.setAttribute( "DocumentPath"   , CurrentFragInfo.ServerSideDocumentPath )
        Call oDocFrag.setAttribute( "SequenceNumber" , CurrentSeqNumber                       )
        Call oDocFrag.setAttribute( "FragmentTypeKey", CurrentFragInfo.FragmentTypeKey        )
        Call oDocFrag.setAttribute( "fPushDocument"  , "0"                                    )
          
        If mvarIsCentral Then
          Call oDocFrag.setAttribute("fArchived", "1")
        Else
          Call oDocFrag.setAttribute("fArchived", "0")
        End If
        Call oDocFrag.ParentNode.ParentNode.SetAttribute( "LocationID" , mvarLocationID )
      End If
      
    Next
    
    Call SaveDocumentXMLAsync( Nothing )
  
  End Function
  
  
  '
  ' This function will save the document data async.  
  Public Function SaveDocumentXMLAsync( DocumentDOM )
  
    '
    ' The consumer can either pass in the DocumentDOM to save or use the existing
    ' mvarDocumentDOM to be saved.
    If Not DocumentDOM is Nothing Then
      Set mvaroDocumentDOM = DocumentDOM
    End If
    
    Set g_CurrentDocumentHandlerInstance = Me
    Dim Transaction : Set Transaction = External.HTTPTransactions.Add( "_DocumentSave_" & External.CreateID() )
    With Transaction
      .Open "POST", "/Infrastructure/DocumentManagement/DocumentServer.asp", True  
      .formElements.add("Op").Value = "SaveDocumentXML"
      .formElements.add("RequestXML").Value = mvaroDocumentDOM.xml
      '.onrequestcomplete = GetRef("SaveDocumentXMLAsyncOnTaskComplete")
      Call .CompleteCallback.SetCallback(Me, "SaveDocumentXMLAsyncOnTaskComplete")
      .send 
    End With
    Set Transaction = Nothing 
     
  End Function
  
  
  '
  ' This function will execute the call back when the save is complete
  Public Function SaveDocumentXMLAsyncOnTaskComplete( Transaction )
  
    mvarResult = Transaction.ResponseText
  
    If ( Transaction.Status <> 200 ) then
      mvarErrorDescription = "Error occured saving the document xml to the server."
      mvarErrorOccured     = True
    End If
    
    Call External.HTTPTransactions.Remove( Transaction.ID )
    Set Transaction = Nothing
  
    Call callBackInitiatingScript()
    
  End Function
 
  
  '
  ' Update document on the server.  This function will update the document xml
  ' taking away the locks.
  ' This will be a Multi step process
  ' 1. Get Server Configuration XML
  ' 2. Send File to the server 
  ' 3. Save the new XML to the server
  Public Function UpdateDocument( DocumentXML, LocalDocumentPath, DocumentFragmentID )
  
    Set mvaroDocumentDOM = Nothing
    Set mvaroDocumentDOM = CreateObject("MSXML2.DOMDocument.3.0")
    
    If mvaroDocumentDOM.LoadXML( DocumentXML ) Then
      If Len( LocalDocumentPath ) > 0 Then
        Set mvarDocumentHandlerFragment = Nothing
        Set mvarDocumentHandlerFragment = new cDocumentHandlerFragment
       
        mvarDocumentHandlerFragment.DocumentFragmentID = DocumentFragmentID
        mvarDocumentHandlerFragment.LocalPath          = LocalDocumentPath
       
        Call GetServerConfigReferenceAsync( "Call UpdateDocumentOnServer()" )
      Else
        mvarErrorDescription = "No local file name was passed into the update document."
        mvarErrorOccured     = True
        Call callBackInitiatingScript()     
      End If
    
    Else
      mvarErrorDescription = "Error occured while trying to load document xml into a DOM."
      mvarErrorOccured     = True
      Call callBackInitiatingScript()
    End If
    
  End Function
    
  
  '
  ' The method will transfer the document to the server and over write the existing document
  Private Function UpdateDocumentOnServer()
  
    Dim oDocFrag : Set oDocFrag = mvaroDocumentDOM.SelectSingleNode( "Document/DocumentVersions/DocumentVersion/DocumentFragments/DocumentFragment[ @DocumentFragmentID = '" & mvarDocumentHandlerFragment.DocumentFragmentID & "' ]" )
    If Not oDocFrag is Nothing Then
    
      Dim ServerConfigDOM : Set ServerConfigDOM = GetServerConfigReference() 
      Dim LocationID      : LocationID          = oDocFrag.ParentNode.ParentNode.getAttribute( "LocationID"   )
      Dim CategoryID      : CategoryID          = mvaroDocumentDOM.documentElement.getAttribute( "DocumentCategoryID" )      
      Dim SaveLocationID  : SaveLocationID      = GetLocationIDForSaving( CategoryID )
      Dim IsLocal         : IsLocal             = ( ServerConfigIDFromLocationID( SaveLocationID ) = ServerConfigIDFromLocationID( LocationID ) )
      Dim ServerURI       : ServerURI           = GetServerURI( CategoryID, LocationID, ServerConfigDOM , IsLocal)
      
      Set g_CurrentDocumentHandlerInstance = Me
      Dim Transaction : Set Transaction = external.HTTPTransactions.Add("UpdateDocument_" & External.CreateID())
      With Transaction
        .Open "POST", ServerURI, True
        .setRequestHeader "mthOperation", "Update"
        .setRequestHeader "mthDocumentFragmentID", mvarDocumentHandlerFragment.DocumentFragmentID
        .setRequestHeader "mthLocationID", LocationID
        .setRequestHeader "mthCategoryID", CategoryID
        .setRequestHeader "mthIsLocal", IsLocal
        '.onrequestcomplete = GetRef("UpdateDocumentOnServerOnComplete")
        Call .CompleteCallback.SetCallback(Me, "UpdateDocumentOnServerOnComplete")
        If IsValidUploadProgress() Then
          '.onUploadProgress = GetRef("UploadProgressAsyncProgressCallBack")
          Call .UploadProgressCallback.SetCallback(Me, "UploadProgress")
        End If
        .sendFile mvarDocumentHandlerFragment.LocalPath 
      End With
    
    Else
      mvarErrorDescription = "Error occured extract Document Fragment from XML."
      mvarErrorOccured     = True
      Call callBackInitiatingScript()
    End If
  
  End Function
  
  
  '
  ' This function is the call back of the upload function.  If there is a status of
  ' 200 on the transaction that means the file got updated correctly.  If the file is
  ' updated correctly then we need to save the xml to the server.
  Public Function UpdateDocumentOnServerOnComplete( Transaction )
    
    If ( Transaction.Status <> 200 ) then
    
      Call External.HTTPTransactions.Remove( Transaction.ID )
      
      mvarErrorDescription = "Error occured while trying to load document xml into a DOM."
      mvarErrorOccured     = True
      mvarResult       = 0
      Call callBackInitiatingScript()
      
    Else    
      mvarResult = 1
      Call UpdateDocumentXMLAndSave()    
      Call External.HTTPTransactions.Remove( Transaction.ID )
    End If
 
  End Function

  
  '
  ' This function updates the document xml and call the async save process.  
  Public Function UpdateDocumentXMLAndSave()
      
    Dim oDocFrag : Set oDocFrag = Nothing
      
    Set  oDocFrag = mvaroDocumentDOM.SelectSingleNode("Document/DocumentVersions/DocumentVersion/DocumentFragments/DocumentFragment[ @DocumentFragmentID = '" & mvarDocumentHandlerFragment.DocumentFragmentID & "' ]" )
        
    If Not oDocFrag is Nothing Then
      Call oDocFrag.setAttribute( "UserIDLock"      , vbNullString                 ) 
      Call oDocFrag.setAttribute( "LockedGUID"      , vbNullString                 )
      Call oDocFrag.setAttribute( "TimestampLocked" , vbNullString                 )
      Call oDocFrag.setAttribute( "Op"              , "E"                          )
      Call oDocFrag.setAttribute( "UserIDChange"    , External.MOM.UserInfo.UserID )
    End If
    
    mvarResult = 1
    
    Set oDocFrag = Nothing
    
    Call SaveDocumentXMLAsync( Nothing )
    
  End Function
      

  '
  ' This is a Sync call to save the document xml to the server.
  Private Function SaveDocumentXML(sDocumentXML)
  
    Dim Transaction : Set Transaction = external.HTTPTransactions.Add("_DocumentServer_" & External.CreateID())
    With Transaction      
      .Open "POST", "/Infrastructure/DocumentManagement/DocumentServer.asp", False
      .formElements.add("Op").Value = "SaveDocumentXML"
      .formElements.add("RequestXML").Value = sDocumentXML
      .send 
      SaveDocumentXML = .ResponseText
    End With

    Call External.HTTPTransactions.Remove( Transaction.ID )
    Set Transaction = Nothing
  End Function
 
 
  '
  ' This function will lock the specified document fragment async.
  ' Be sure to set the call back function.  Check the result property for
  ' the result of the transaction.
  Public Function LockDocumentAsync( DocumentFragmentID )
    Dim Transaction : Set Transaction = external.HTTPTransactions.Add("_LockDocument_" & External.CreateID())
    
    Set g_CurrentDocumentHandlerInstance = Me
    With Transaction
      .setRequestHeader "Op"                 , "LockDocument"
      .setRequestHeader "DocumentFragmentID" , DocumentFragmentID
      '.onrequestcomplete = GetRef("AsyncProcessingComplete")
      Call .CompleteCallback.SetCallback(Me, "AsyncProcessingComplete")
      .Open "POST", "/Infrastructure/DocumentManagement/DocumentServer.asp", True
      .send vbNullString
    End With
   
  End Function
  
  
  '
  ' This function will Lock the specified document fragment.
  Public Function LockDocument(dDocumentFragmentID)
    Dim Transaction : Set Transaction = external.HTTPTransactions.Add("_DocumentServer_" & External.CreateID())
    
    With Transaction
      .setRequestHeader "Op", "LockDocument"
      .setRequestHeader "DocumentFragmentID", dDocumentFragmentID
      .Open "POST", "/Infrastructure/DocumentManagement/DocumentServer.asp", False
      .send vbNullString
    End With
    
    LockDocument =  Transaction.ResponseText
    
    Call External.HTTPTransactions.Remove( Transaction.ID )
    Set Transaction = Nothing
  End Function
  
  
  '
  ' This function will unlock the specified document fragment async.
  ' Be sure to set the call back function.  Check the result property for
  ' the result of the transaction.
  Public Function UnLockDocumentAsync( DocumentFragmentID )
    Dim Transaction : Set Transaction = external.HTTPTransactions.Add("_UnLockDocument_" & External.CreateID())
    
    Set g_CurrentDocumentHandlerInstance = Me
    With Transaction
      .setRequestHeader "Op"                 , "UnLockDocument"
      .setRequestHeader "DocumentFragmentID" , DocumentFragmentID
      '.onrequestcomplete = GetRef("AsyncProcessingComplete")
      Call .CompleteCallback.SetCallback(Me, "AsyncProcessingComplete")
      .Open "POST", "/Infrastructure/DocumentManagement/DocumentServer.asp", True
      .send vbNullString
    End With
   
  End Function
  
  
  '
  ' This Function will unlock a document
  Public Function UnLockDocument(dDocumentFragmentID)
    Dim Transaction : Set Transaction = external.HTTPTransactions.Add("_DocumentServer_" & External.CreateID())

    With Transaction
      .setRequestHeader "Op"                 , "UnLockDocument"
      .setRequestHeader "DocumentFragmentID" , dDocumentFragmentID
      .Open "POST", "/Infrastructure/DocumentManagement/DocumentServer.asp", False
      .send vbNullString
    End With
    
    UnLockDocument = 1
    
    Call External.HTTPTransactions.Remove( Transaction.ID )
    Set Transaction = Nothing
    
  End Function

  
  '
  ' This function will determine the size in bytes of local files.
  Public Function GetFileByteCount(sLocalDocumentPath)
    Dim oFSO
    Dim oFile

    Set oFSO = External.CreateObject("Scripting.FileSystemObject")
    If oFSO.FileExists( sLocalDocumentPath ) Then
      Set oFile = oFSO.GetFile(sLocalDocumentPath)
      GetFileByteCount = oFile.Size
    Else
      GetFileByteCount = 0
    End If

    Set oFSO  = Nothing
    Set oFile = Nothing
  End Function

  
  '
  ' This function will delete a specified local file.
  Public Function DeleteLocalFile(sFilePath)
    Dim oFSO : Set oFSO = External.CreateObject("Scripting.FileSystemObject")
    
    Call oFSO.DeleteFile(sFilePath)

    Set oFSO = Nothing
  End Function
  
  
  '
  ' This function will return the save server URI for saving files.  This Server URI will
  ' be different depending on the passed in Location ID and Category ID.
  Private Function GetServerURI(dCategoryID, dLocationID, oServerXMLDOM, blnLocal)
    Dim oLocationNode
    Dim oCategoryNode
    Dim sAttributeName

    If blnLocal Then
      sAttributeName = "LocalServerURI"
    Else
      sAttributeName = "CentralServerURI"
    End If
 
    Set oLocationNode = oServerXMLDOM.SelectSingleNode("Site/ServerConfigurations/ServerConfiguration/Locations/Location[@LocationID='" & dLocationID & "']")
    Set oCategoryNode = oLocationNode.ParentNode.ParentNode.SelectSingleNode("Categorys/Category[@CategoryID='" & dCategoryID & "']")
  
    GetServerURI = oCategoryNode.getAttribute(sAttributeName) & "/Infrastructure/DocumentManagement/DocumentISAPI.ashx"
  End Function

  '
  ' This function will return the server directory share for saving files.  This share will
  ' be different for different location id and for different category ids.
  Private Function GetServerSharePath(dCategoryID, dLocationID, oServerXMLDOM, blnLocal)
    Dim oLocationNode
    Dim oCategoryNode
    Dim sPath
    Dim sAttributePrefix

    If blnLocal Then
      sAttributePrefix = "Local"
    Else
      sAttributePrefix = "Central"
    End If
 
    Set oLocationNode = oServerXMLDOM.SelectSingleNode("Site/ServerConfigurations/ServerConfiguration/Locations/Location[@LocationID='" & dLocationID & "']")
    Set oCategoryNode = oLocationNode.ParentNode.ParentNode.SelectSingleNode("Categorys/Category[@CategoryID='" & dCategoryID & "']")
  
    sPath = oCategoryNode.getAttribute(sAttributePrefix & "DocumentPath")
    GetServerSharePath = oCategoryNode.getAttribute(sAttributePrefix & "StorageServer") & "\" & sPath
  End Function

  
  '
  ' This function will determine the server config id from the passed in location id.
  Public Function ServerConfigIDFromLocationID(dLocationID)
    Dim oServerXMLDOM
    Dim oLocationNode
    
    Set oServerXMLDOM = GetServerConfigReference()   
  
    Set oLocationNode = oServerXMLDOM.SelectSingleNode("Site/ServerConfigurations/ServerConfiguration/Locations/Location[@LocationID='" & dLocationID & "']")
    ServerConfigIDFromLocationID = oLocationNode.ParentNode.ParentNode.getAttribute("ServerConfigurationID")
  End Function


  '
  ' This method will load the server config dom sync from the server if it has not already been
  ' done.  It will then pass back a reference to the object.
  Function GetServerConfigReference
    Dim Transaction
    Dim sXML
    
    If mvarServerConfigDOM is Nothing Then
      Set Transaction = external.HTTPTransactions.Add("_DocumentServer_" & External.CreateID())
      With Transaction
        .setRequestHeader "Op", "LoadServerConfigXML"
        .Open "POST", "/Infrastructure/DocumentManagement/DocumentServer.asp", False
        .send vbNullString
        sXML = .ResponseText
      End With
      
      Call External.HTTPTransactions.Remove(Transaction.ID)
      Set Transaction = Nothing
    
      If Len(sXML) > 0 Then
        Set mvarServerConfigDOM = External.CreateObject("MSXML2.DOMDocument")
        Call mvarServerConfigDOM.LoadXML(sXML)
      End IF
    End If

    Set GetServerConfigReference = mvarServerConfigDOM
  End Function


  '
  ' This function determines if the passed in location ID is the central server.
  Function IsThisLocationCentral(dLocationID)
    
    Dim oServerDOM         : Set oServerDOM     = GetServerConfigReference
    Dim dCentralLocationID : dCentralLocationID = oServerDom.documentElement.getAttribute("LocationID")
    
    If ServerConfigIDFromLocationID(dLocationID) = ServerConfigIDFromLocationID(dCentralLocationID) Then
      IsThisLocationCentral = True
    Else
      IsThisLocationCentral = False
    End If
    
  End Function  


  '
  ' This function gets the correct location id needed for saving.
  Function GetLocationIDForSaving(dCategoryID)
    
    Dim dLocationID   : dLocationID = external.MOM.sessionStash.Item("ServerConfig/LocationID").Value 
    Dim oServerXMLDOM : Set oServerXMLDOM = GetServerConfigReference()
   
    '
    'Check for a Category Node for the LocationID they have stored in their registry.
    Dim oLocationNode : Set oLocationNode = oServerXMLDOM.SelectSingleNode("Site/ServerConfigurations/ServerConfiguration/Locations/Location[@LocationID='" & dLocationID & "']")
    Dim oCategoryNode : Set oCategoryNode = oLocationNode.ParentNode.ParentNode.SelectSingleNode("Categorys/Category[@CategoryID='" & dCategoryID & "']")

    '
    'If a Category Node doesnst exist for their location, Then we want to save to central, so we
    'go get its LocationID, and return it.
    If oCategoryNode Is Nothing Then
      Dim oSiteNode : Set oSiteNode = oServerXMLDOM.SelectSingleNode("Site")

      If Not oSiteNode Is Nothing Then
        dLocationID = oSiteNode.getAttribute("LocationID")
      End If
    End If

    GetLocationIDForSaving = dLocationID
  End Function


End Class


'
' This class handles the multiple files that need to be added to the server.
Class cDocumentAddList

  Private mDocumentCount 
  Private mDocumentAddArray()

  Private Sub Class_Initialize
    mDocumentCount = 0
  End Sub

  Public Function Count()
    Count = mDocumentCount
  End Function

  Public Function AddDocument( sLocalPath , sFragmentTypeKey , sFileExt , DocumentFragmentID )
  
    Dim oLocalAddFragment : Set oLocalAddFragment = New cDocumentHandlerFragment
    oLocalAddFragment.SequenceNumber     = mDocumentCount
    oLocalAddFragment.FragmentTypeKey    = sFragmentTypeKey
    oLocalAddFragment.LocalPath          = sLocalPath
    oLocalAddFragment.FileExt            = sFileExt
    oLocalAddFragment.DocumentFragmentID = DocumentFragmentID
    
    mDocumentCount = mDocumentCount + 1
    
    ReDim Preserve mDocumentAddArray( mDocumentCount )

    Set mDocumentAddArray( mDocumentCount - 1 ) = oLocalAddFragment
  
    Set AddDocument = mDocumentAddArray( mDocumentCount - 1 )
    
  End Function
  
  Public Function GetDocument( Index )
  
    If Index >= 0 and Index < mDocumentCount Then
      Set GetDocument = mDocumentAddArray( Index )
    Else
      Set GetDocument = Nothing
    End If
  
  End Function 
  
End Class


'
' This class holds the values of the Document that needs to be add to the server.
Class cDocumentHandlerFragment
  Private mLocalPath 
  Private mFragmentTypeKey
  Private mSeqNumber
  Private mFileExt
  Private mDocumentFragmentID
  Private mDocumentPathServerSide
  Private mServerSideFileName
  Private mLocalFileName
  Private mGotLock
  Private mLocationID
  Private mCategoryID
  
  Private Sub Class_Initialize
    mLocalPath              = vbNullString
    mFragmentTypeKey        = vbNullString
    mSeqNumber              = vbNullString
    mFileExt                = vbNullString
    mDocumentFragmentID     = vbNullString
    mDocumentPathServerSide = vbNullString
    mServerSideFileName     = vbNullString
    mLocalFileName          = vbNullString
    mLocationID             = vbNullString
    mCategoryID             = vbNullString
    mGotLock                = False
  End Sub
  
  Public Property Get SequenceNumber()
    SequenceNumber = mSeqNumber
  End Property
  
  Public Property Let SequenceNumber(vntData)
    mSeqNumber = vntData
  End Property
  
  Public Property Get FragmentTypeKey()
    FragmentTypeKey = mFragmentTypeKey
  End Property
  
  Public Property Let FragmentTypeKey(vntData)
    mFragmentTypeKey = vntData
  End Property
  
  Public Property Get LocalPath()
    LocalPath = mLocalPath
  End Property
  
  Public Property Let LocalPath(vntData)
    mLocalPath = vntData
  End Property
  
  Public Property Get FileExt()
    FileExt = mFileExt
  End Property
  
  Public Property Let FileExt(vntData)
    mFileExt = vntData
  End Property
  
  Public Property Get DocumentFragmentID()
    DocumentFragmentID = mDocumentFragmentID
  End Property
  
  Public Property Let DocumentFragmentID(vntData)
    mDocumentFragmentID = vntData
  End Property
  
  Public Property Get ServerSideDocumentPath()
    ServerSideDocumentPath = mDocumentPathServerSide
  End Property
  
  Public Property Let ServerSideDocumentPath(vntData)
    mDocumentPathServerSide = vntData
  End Property
  
  Public Property Get ServerSideFileName()
    ServerSideFileName = mServerSideFileName
  End Property
  
  Public Property Let ServerSideFileName(vntData)
    mServerSideFileName = vntData
  End Property
  
  Public Property Get LocalFileName()
    LocalFileName = mLocalFileName
  End Property
  
  Public Property Let LocalFileName(vntData)
    mLocalFileName = vntData
  End Property
  
  Public Property Get GotLock()
    GotLock = mGotLock
  End Property
  
  Public Property Let GotLock(vntData)
    mGotLock = vntData
  End Property
  
  Public Property Get LocationID()
    LocationID = mLocationID
  End Property
  
  Public Property Let LocationID(vntData)
    mLocationID = vntData
  End Property
  
  Public Property Get CategoryID()
    CategoryID = mCategoryID
  End Property
  
  Public Property Let CategoryID(vntData)
    mCategoryID = vntData
  End Property
  
End Class
