'#Reference {A3B5C45B-F842-44fc-A5E5-50CED69BA86E}#2.0#0#C:\Program Files\Mindjet\MindManager 6\Mm5WebExport.dll#Mm5webexport 2.0 Type Library
'#Uses "TOCHandler.cls"
'#Uses "ParameterNames.mmbas"
'#Uses "GlobalParameterNames.mmbas"
'#Uses "GlobalUtilities.mmbas"
'#Uses "GlobalTypes.mmbas"

Option Explicit

Sub Main

    Dim addin As Mm5WebExportAddIn
    Dim webex As WebExport
    Dim aPage As Mm5WebExportLib.Page

    Set addin = WebExportHelper.WebExportAddIn
    Set webex = addin.ActiveWebExport

    Dim oneTOCHandler As TOCHandler
    Dim oneTopic As Topic
    Dim topicIndex As Long
    Dim template As String
    Dim topicString As String
    Dim bodyString As String
    Dim fileName As String
    Dim fileBookmark As String

    On Error GoTo ReportError

    webex.Trace("Entering Body.mmbas", 2 )

    ' Get our list of topics for this page
    Set aPage = webex.ActivePage

    Set oneTOCHandler = New TOCHandler
    
    template = webex.ReadFile("Topic.htm")

    ' For each topic
    For topicIndex = 1 To aPage.TopicCount

        webex.ActiveTopic = aPage.GetTopic(topicIndex)
        Set oneTopic = webex.ActiveTopic

        ' Get TOC number if enabled
        webex.SetParameter(TcpTOCOutlineNumberToWrite, _
            oneTOCHandler.GetOutlineNumberForTopic(oneTopic, webex.GetParameter(TsShowNumberToLevel)))

        ' Read the appropriate template for this topic
        If oneTopic.IsCentralTopic Then
            topicString = webex.ReadFile("CentralTopic.htm")
        Else
            topicString = template
        End If

        ' Allow different topic formatting for central, main and subtopics
        If oneTopic.IsCentralTopic Then
            topicString = Replace(topicString, "#TopicClass#", "centralTopic")
        ElseIf oneTopic.IsMainTopic Then 
            topicString = Replace(topicString, "#TopicClass#", "mainTopic")
        Else
            topicString = Replace(topicString, "#TopicClass#", "subtopic")
	    End If

        ' Massage the topic text so we don't get anything unexpected
        webex.SetParameter(TcpCurrentTopicText, VerifyText(webex, webex.GetParameter(WeCurrentTopicText)))
        
        ' Get our topic bookmark
        webex.FilenameAndBookmarkFromTopic(oneTopic, fileName, fileBookmark)
        webex.SetParameter(TcpTopicBookmark, fileBookmark)

        ' Process all commands and parameters
        ProcessString webex, topicString

        ' Process #Rule#
        ProcessRule webex, topicString
        
        ' Process #Notes# (if any)
        ProcessNotes webex, topicString
        
        ' Process #RelatedItems# (if any)
        ProcessRelatedItems webex, topicString
        
        ' Process #TableOfContents# (if any)
        ProcessTableOfContents webex, topicString
        
        ' Append topic string to main body string
		bodyString = bodyString + topicString

    Next topicIndex

    ' Write out the result
    webex.PushString(bodyString)

    webex.Trace( "Exiting Topic.mmbas", 2 )

    Exit Sub

ReportError:
    ProcessError(webex)
    Exit Sub

End Sub

Sub ProcessNotes(webex As WebExport, ByRef topicString As String)

    Dim notesString As String
    
    If Not webex.ActiveTopic.Notes.IsEmpty Then
        notesString = Replace(ReadFileStripTrailingNewline(webex, "Notes.htm"), "#Notes#", GlobalExportNotes(webex, webex.ActiveTopic))
    End If

    topicString = Replace(topicString, "#Notes#", notesString)
    
End Sub

Sub ProcessRule(webex As WebExport, ByRef topicString As String)

    Dim ruleString As String
    
    If webex.GetParameter(TsShowHorizontalRule) And webex.ActiveTopic.IsMainTopic Then
        ruleString = ReadFileStripTrailingNewline(webex, "Rule.htm")
    End If

    topicString = Replace(topicString, "#Rule#", ruleString)
    
End Sub

Sub ProcessTableOfContents(webex As WebExport, ByRef topicString As String)

    ' If we even have the "#TableOfContents#" in our topic string
    If InStr(topicString, "#TableOfContents#") Then
    
        Dim tableOfContentsString As String
    
        If     webex.GetParameter(TsShowTableOfContents) _
           And (webex.ActivePage.TopicCount > 1) Then
           
            Dim aTopic As Topic
            Dim previousActiveTopic As Topic
            Dim level As Long
            
            ' Start at the active topic
            Set previousActiveTopic = webex.ActiveTopic
            Set aTopic = webex.ActiveTopic

            ' Recursive map traversal
            level = 0
            Call TocMapTraversal(aTopic, tableOfContentsString, webex, level)
            
            webex.ActiveTopic = previousActiveTopic
            
            tableOfContentsString = Replace(ReadFileStripTrailingNewline(webex, "Toc.htm"), "#TocItems#", tableOfContentsString)
            
        End If
    
        topicString = Replace(topicString, "#TableOfContents#", tableOfContentsString)
        
    End If
    
End Sub

Function TocMapTraversal(ByVal oneTopic As Topic, _
                         ByRef bodyString As String, _
                         ByRef webex As WebExport, _
                         ByRef level As Long)

    Dim oneTOCHandler As TOCHandler
    Dim nextTopic As Topic
    Dim TopicCount As Integer
    Dim LocalTemplate As String
    Dim LocalTopicString As String
    Dim k As Long
    Dim l As Long
    Dim TheTOCNumber As String
    Dim TopicText As String
    Dim TopicLink As HyperlinkData

    Set oneTOCHandler = New TOCHandler

    ' Keep track of "recurse level"
    level = level + 1

    TopicCount = oneTopic.SubTopics.Count

    For k = 1 To TopicCount

        Set nextTopic = oneTopic.SubTopics.Item(k)

        TheTOCNumber = oneTOCHandler.GetOutlineNumberForTopic(nextTopic, _
        webex.GetParameter(TsShowNumberToLevel))

        TopicLink = TopicHyperlink(webex, nextTopic)

        webex.SetParameter(TcpTopicHyperlink, TopicLink.Url)
        webex.SetParameter(TcpTopicText, VerifyTopicText(webex, nextTopic))
        webex.SetParameter(TcpTopicTarget, TargetAttribute(TopicLink))

        ' Enforce maximum "TOC level"
        webex.SetParameter(TcpTOCOutlineNumberToWrite, TheTOCNumber)

        ' Enforce maximum "indentation levels"
        If level > 5 Then
            webex.SetParameter(TcpTOCOutlineLevel, "x")
        Else
            webex.SetParameter(TcpTOCOutlineLevel, level)
        End If

	    LocalTemplate = ReadFileStripTrailingNewline(webex, "TocEntry.htm")
	    LocalTopicString = LocalTemplate

		If webex.GetParameter(TsShowTableofContents) Then
	        ' Process our template and replace parameters, then store new bodystring
	        ProcessString webex, LocalTopicString
	        bodyString = bodyString + LocalTopicString
		End If

	    ' Recursive call
        If webex.GetParameter(TdNavigationDepth) > level Then
	       	Call TocMapTraversal(nextTopic, bodyString, webex, level)
		End If

    Next k

    ' Keep track of recurse level
    level = level - 1

End Function

Function StripTrailingNewline(s As String) As String
    ' If the string ends in a newline (vbLf),
    ' then we strip this off.
    If Right(s, 1) = vbLf Then
        StripTrailingNewline = Left(s, Len(s) - 1)
    Else
        StripTrailingNewline = s
    End If
End Function

Function ReadFileStripTrailingNewline(webex As WebExport, filename As String) As String
    ' The normal "ReadFile" routine adds a newline at the end of all lines of text.
    ' To help keep our use whitespace in the HTML under control, we strip
    ' this trailing newline when reading certain template files.
    ReadFileStripTrailingNewline = StripTrailingNewline(webex.ReadFile(filename))
End Function

Sub ProcessRelatedItems(webex As WebExport, ByRef topicString As String)

    Dim relatedItemsString As String
    
    relatedItemsString = RelatedItems(webex)
    
    topicString = Replace(topicString, "#RelatedItems#", relatedItemsString)
    
End Sub

Function RelatedItems(webex As WebExport) As String

    Dim bodyString As String
    Dim template As String
    Dim RelationshipsString As String
    Dim RelationshipsStringBoundary As String
    Dim HyperlinksAndBookmarksString As String
    Dim MergedString As String

    Dim oneRelationshipCollection As Relationships
    Dim anotherRelationshipCollection As Relationships
    Dim oneTopic As Topic
    
    Set oneTopic = webex.ActiveTopic

    If DoExportRelatedSection_Links(oneTopic, webex) Then

        ' Read related section template
        template = ReadFileStripTrailingNewline(webex, "RelatedItems.htm")

        ' 1. Process relationships. First for topic itself, then for the topic boundary (if it exists)
        Set oneRelationshipCollection = oneTopic.Relationships(False)
        RelationshipsString = Process_Relationships(oneRelationshipCollection, webex)
        If oneTopic.HasBoundary Then
            Set anotherRelationshipCollection = oneTopic.Boundary.Relationships(False)
            RelationshipsStringBoundary = Process_Relationships(anotherRelationshipCollection, webex)
        End If

        ' 2. Process hyperlinks and bookmarks
        HyperlinksAndBookmarksString = Process_HyperlinksAndBookmarks(webex.ActiveTopic, webex)

        ' 3. Glue together relationship and hyperlink / bookmark strings
        MergedString = HyperlinksAndBookmarksString + RelationshipsString + RelationshipsStringBoundary

        ' Insert merged sections into the wrapper "related section" template
        RelatedItems = Replace(template, "#RelatedItemsHeader#", webex.GetParameter(TsLabelRelatedItemsHeader))
        RelatedItems = Replace(RelatedItems, "#RelatedItemsHyperlinks#", MergedString)

    End If

End Function

Function Process_Relationships(oneRelationshipCollection As Relationships, webex As WebExport) As String

    Dim oneRelationship As Relationship
    Dim oneCallout As Topic

    Dim localbodyString As String
    Dim localTemplate As String

    For Each oneRelationship In oneRelationshipCollection

        ' if a link is to be inserted for this type of relationship
        ' Process relationship item template
        If DoExportRelationshipSettings(oneRelationship, webex) Then

            ' Determine what template to use for export
            If oneRelationship.CalloutTopics(False).Count > 0 Then

                ' Determine if the relationship has an attached callout
                Set oneCallout = oneRelationship.CalloutTopics(False).Item(1)

                If webex.IsSimpleRelationshipCallout(oneCallout) Then
                    localTemplate = webex.ReadFile("SimpleCallout.htm")
                    webex.SetParameter(TcpCalloutText, "(" +  VerifyTopicText(webex, oneCallout) + ")")
                Else
                    ' Not supported
                    ' localTemplate = webex.ReadFile("SnipHypReLinkedCoPage.htm")

                    ' webex.SetParameter(TcpCalloutText,"")
                    ' webex.SetParameter("CustomParameter.CalloutHyperlinkName", VerifyTopicText(webex, oneCallout) )
                    ' webex.SetParameter("CustomParameter.CalloutHyperlinkTarget", "")
                    ' webex.SetParameter("CustomParameter.CalloutHyperlinkURL", webex.PathToUrl(webex.Pages.FindPage(oneCallout).Filename))
                End If

            Else

                ' No callouts, read "simple" template
                localTemplate = webex.ReadFile("SimpleCallout.htm")

                ' No callout text to export
                webex.SetParameter(TcpCalloutText, "")

            End If

            ' Process all commands and parameters
            ProcessString webex, localTemplate

            ' Our new hyperlink to merge into the related section body item template
            localbodyString = localbodyString + localTemplate

        Else

            ' No link for this relationship type
            localbodyString = localbodyString

        End If

    Next

    ' Assign return value to function name
    Process_Relationships = localbodyString

End Function

Function Process_HyperlinksAndBookmarks(oneTopic As Topic, webex As WebExport) As String

    Dim localbodyString As String
    Dim localTemplate As String
    Dim processedTemplate As String
    Dim oneHyperlink As Hyperlink

    Dim theURL As String
    Dim theText As String
    Dim theTarget As String

    If oneTopic.HasHyperlink Then

        Set oneHyperlink = oneTopic.Hyperlink

        webex.UrlFromHyperlink(oneHyperlink, theURL, theText, theTarget)
        
        ' If we could resolve the hyperlink to a valid URL
        If Len(theURL) > 0 Then
        
            webex.SetParameter(TcpHyperlinkName, theText)
            webex.SetParameter(TcpHyperlinkURL, theURL)
            webex.SetParameter(TcpHyperlinkTarget, theTarget)

            ' if this is a local bookmark
            ' read bookmark template
            localTemplate = webex.ReadFile("Hyperlink.htm")

            ' Process all commands and parameters
            ProcessString webex, localTemplate

            ' Our new hyperlink to merge into the related section body item template
            processedTemplate = localTemplate

            ' Our merged string to write back
            localbodyString = processedTemplate
        
        End If

    Else

       ' No link for this relationship type
       localbodyString = ""

    End If

    ' Assign return value to function name
    Process_HyperlinksAndBookmarks = localbodyString

End Function
