<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0"
  xmlns:tei="http://www.tei-c.org/ns/1.0"
  xmlns:o="http://piez.org/TEIoverlap/xslt/util"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all">

<!-- XSLT 2.0 overlap handling for Interedition demonstration
     by Wendell Piez, October 2011.
    
     Released under a Creative Commons Attribution 3.0 Unported License
     http://creativecommons.org/licenses/by/3.0/
-->
  
  <xsl:import href="p5o-simple-html.xsl"/>
  
  <xsl:strip-space elements="tei:TEI tei:teiHeader tei:fileDesc
    tei:titleStmt tei:editionStmt tei:publicationStmt 
    tei:availability tei:encodingDesc tei:editorialDecl 
    tei:text tei:body"/>

  <xsl:variable name="source" select="/"/>
  
  <xsl:template name="css">
    <xsl:call-template name="base-css"/>
    <style type="text/css">
      div.main { margin-left: 280px  }
      div.note { width: 280px; background-color: #CCCCFF; padding: 5px;
        border: thin solid black; font-size: 80%; line-height: 120%;
        margin-left: -310px; margin-top: -3ex; float: left; clear: both;
        position: absolute; visibility: hidden; text-indent: 0em }
      div.page { margin-top: 5px; margin-bottom: 5px;
        padding: 10px 30px; border: thin solid black }
      div.page-no { text-align: center; margin-top: 15px }
      div.text p.continued { text-indent: 0px }
      span.note-ref { background-color: #CCFFCC }
      div.notes { visibility: hidden }
    </style>
  </xsl:template>
  
  <xsl:template name="page-content">
    <xsl:apply-templates select="/*/tei:teiHeader"/>
    <xsl:apply-templates select="/*/tei:text" mode="main"/>
  </xsl:template>

  <xsl:template match="tei:text" mode="main">
    <div class="main">
      <!--<xsl:apply-templates/>-->
      <!--<xsl:apply-templates select="." mode="invert-pb"/>-->
      <xsl:variable name="paged">
        <xsl:apply-templates select="." mode="invert-pb"/>
      </xsl:variable>
      <xsl:variable name="amended">
        <xsl:apply-templates select="$paged" mode="amend"/>
      </xsl:variable>
      <!--<xsl:copy-of select="$amended"/>-->
      <xsl:for-each select="$amended">
        <xsl:apply-templates/>
      </xsl:for-each>
    </div>
  </xsl:template>

  <xsl:key name="element-by-generated-id" match="*" use="generate-id()"/>
  
  <xsl:template mode="invert-pb" match="node()">
    <xsl:variable name="here" select="."/>
    <xsl:for-each-group select="descendant::node()[empty(node())]" group-ending-with="tei:pb">
      <o:page>
        <xsl:apply-templates select="current-group()[1]/preceding::tei:pb[1]/@n" mode="page-num"/>
        <xsl:call-template name="build">
          <xsl:with-param name="from" select="$here" tunnel="yes"/>
        </xsl:call-template>
      </o:page>
    </xsl:for-each-group>
  </xsl:template>
  
  <xsl:template match="tei:pb/@n" mode="page-num">
    <xsl:attribute name="num" select="."/>
  </xsl:template>
  
  <xsl:template name="build">
    <xsl:param name="to-copy" select="current-group()"/>
    <xsl:param name="level" select="1" as="xs:integer"/>
    <xsl:param name="from" select="." tunnel="yes"/>
    <xsl:for-each-group select="current-group()"
      group-adjacent="generate-id((ancestor::* except $from/ancestor::*)[$level])">
      <xsl:variable name="copying" select="key('element-by-generated-id',current-grouping-key())"/>
      <xsl:sequence select="current-group()[empty($copying)]"/>
      <xsl:for-each select="$copying">
        <xsl:copy>
          <xsl:copy-of select="@* except @xml:id"/>
          <xsl:choose>
            <xsl:when
              test="$copying/descendant::node()[empty(node())][1] &lt;&lt; current-group()[1]">
              <!-- if the element we are copying has content preceding the current group, we
                map @xml:id to @sameAs and annotate its @rend -->
              <xsl:attribute name="rend"
                select="string-join((@rend,'continued'),' ')"/>
              <xsl:for-each select="@xml:id">
                <xsl:attribute name="sameAs" select="string-join((../@sameAs,concat('#',.)),' ')"/>
              </xsl:for-each>
            </xsl:when>
            <xsl:otherwise>
              <xsl:copy-of select="@xml:id"/>
            </xsl:otherwise>
          </xsl:choose>
          <xsl:call-template name="build">
            <xsl:with-param name="level" select="$level + 1"/>
          </xsl:call-template>
        </xsl:copy>
      </xsl:for-each>
    </xsl:for-each-group>
  </xsl:template>
  
  <!-- amend mode adds generated text -->
  <xsl:template match="node() | @*" mode="amend">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" mode="#current"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="tei:soCalled | tei:quote" mode="amend">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:text>&#8220;</xsl:text>
      <xsl:apply-templates mode="#current"/>
      <xsl:text>&#8221;</xsl:text>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="tei:said//tei:soCalled[not(ancestor::tei:note)] |
    tei:said//tei:quote[not(ancestor::tei:note)]" mode="amend">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:text>&#8216;</xsl:text>
      <xsl:apply-templates mode="#current"/>
      <xsl:text>&#8217;</xsl:text>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="tei:said" mode="amend">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:variable name="following" select="tokenize(@rend,'\s') = 'continued'"/>
      <xsl:variable name="followed"
        select="o:first-said(.) is o:first-said(following::tei:said[1])"/>
      <!-- inserting open quote only if not continuing -->
      <xsl:if test="not($following)">&#8220;</xsl:if>
      <xsl:apply-templates mode="#current"/>
      <!-- inserting close quote only if we are the last fragment of the
      'said' in the source or we are followed by text -->
      <xsl:if test="not($followed) or
      exists(following-sibling::text()|following-sibling::*)"
        >&#8221;</xsl:if>
    </xsl:copy>

  </xsl:template>
  
  <xsl:template match="tei:pb" mode="amend">
    <xsl:variable name="prev" select="preceding-sibling::node()[1]/self::text()"/>
    <xsl:variable name="next" select="following::text()[1][tokenize(../@rend,'\s+') = 'continued']"/>
    <!-- inserting a hyphen where pb appears between two non-space characters -->
    <xsl:if test="matches($prev,'\S$') and matches($next,'^\S')">-</xsl:if>
    </xsl:template>
  
  <xsl:template match="o:page">
    <xsl:if test="normalize-space() or exists(preceding-sibling::o:page)">
      <div class="page">
        <xsl:apply-templates/>
        <xsl:apply-templates select="@num"/>
      </div>
    </xsl:if>
  </xsl:template>
  
  <xsl:template match="o:page/@num">
    <div class="page-no">
      <xsl:text> - </xsl:text>
      <xsl:value-of select="."/>
      <xsl:text> - </xsl:text>
    </div>
  </xsl:template>
  <xsl:template match="tei:p[tokenize(@rend,'\s+')='continued']">
    <p class="continued">
      <xsl:apply-templates/>
    </p>
  </xsl:template>
  
  <!-- the id() function is supposed to work with @xml:id, but FF
       isn't managing, possibly because @xml:id values aren't unique
       after the post-process. -->
  <xsl:key name="by-id" match="*[@xml:id]" use="@xml:id"/>
  
  <xsl:key name="anchor-for-note" match="tei:anchor" use="replace(@corresp,'^#','')"/>
  
  <xsl:template match="tei:anchor[@type='spanStart'][@subtype='note']">
    <xsl:apply-templates select="id(replace(@corresp,'^#',''))" mode="show-note"/>
  </xsl:template>
  
  <xsl:template match="tei:note">
      <span class="note-ref" id="ref-{@xml:id}">
      <xsl:text>[</xsl:text>
      <xsl:number level="any"/>
      <xsl:text>]</xsl:text>
    </span>
  </xsl:template>
  
  <xsl:template match="tei:note" mode="show-note">
    <div class="note" id="note-{@xml:id}">
      <xsl:apply-templates/>
    </div>
  </xsl:template>
 
  <xsl:template match="tei:pb"/>
   
  <xsl:function name="o:first-said" as="element(tei:said)?">
    <!-- returns the first said element representing a quote: the argument
         node if it has no @prev, or following the chain of @prev elements
         until we find one that has none -->
    <!-- Note that if the source isn't valid to constraints on @prev assumed
         by this stylesheet, runtime errors will result! -->
    <xsl:param name="s" as="element(tei:said)?"/>
    <!-- If $s has no @prev, $s is given; if $s/@prev exists, an element
         whose id corresponds to @prev is given. Note that after page 
         splitting, more than one element with the @id may be present,
         so we get the first -->
    <xsl:sequence select="$s[empty(@prev)] (: $s is given if it has no $prev :),
        $s[exists(@prev)]/o:first-said(id($s/replace(@prev,'^#',''),$source))[1]
        (: if $s/@prev :)"/>
  </xsl:function>
  
  <xsl:template match="tei:said">
    <xsl:variable name="first" select="o:first-said(.)"/>
    <span class="said saidby{$first/@who} said-{$first/@xml:id}">
      <xsl:apply-templates/>
    </span>
  </xsl:template>

  <xsl:template match="tei:soCalled | tei:quote">
    <!-- don't have to provide quote marks since we do it in 'amend' mode -->
    <xsl:apply-templates/>
  </xsl:template>
  
  <xsl:function name="o:participates-in" as="element(tei:note)*">
    <xsl:param name="t" as="text()"/>
    <!-- for a text node, reports all notes whose annotated
      ranges, indicated by corresponding anchors in the source
      data, in which it participates -->
    <xsl:variable name="candidate-refs" select="$t/following::tei:note"/>
    <xsl:sequence select="$candidate-refs[key('anchor-for-note',@xml:id,root($t)) &lt;&lt; $t]"/>
  </xsl:function> 
  
  <xsl:template match="text()[empty(ancestor::tei:note)][exists(o:participates-in(.))]">
    <xsl:variable name="span" select="."/>
    <span>
      <xsl:attribute name="class"
        select="('annotated',o:participates-in(.)/concat('n-',@xml:id))"/>
      <xsl:value-of select="."/>
    </span>
  </xsl:template>
  
</xsl:stylesheet>