////
// Formatting of Apache mod_autoindex pages.
//
// Copyright 2004-2007, 2011, Michael Allan.  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Textbender Software"), to deal in the Textbender Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Textbender Software, and to permit persons to whom the Textbender Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Textbender Software. THE TEXTBENDER SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE TEXTBENDER SOFTWARE OR THE USE OR OTHER DEALINGS IN THE TEXTBENDER SOFTWARE.
//

var __autoindex_autoindex_js; if( !__autoindex_autoindex_js ) { __autoindex_autoindex_js = true; // prevent double-loading of this script from both /_/autoindex/header.html and ./_autoindex-summary.html


    var textbenderWaveHTML =  // pattern suggested by Adrian Gog // changing? grep for clones in other files, where it commonly appears as: <span style='position:relative; top: 0.00em;'>t</span><span style='position:relative; top:-0.05em;'>e</span><span style='position:relative; top:-0.10em;'>x</span><span style='position:relative; top:-0.15em;'>t</span><span style='position:relative; top: 0.20em;'>b</span><span style='position:relative; top: 0.15em;'>e</span><span style='position:relative; top: 0.10em;'>n</span><span style='position:relative; top: 0.00em;'>d</span><span style='position:relative; top:-0.05em;'>e</span><span style='position:relative; top:-0.10em;'>r</span>
        "<span style='position:relative; top: 0.00em;'>t</span>"
      + "<span style='position:relative; top:-0.05em;'>e</span>"
      + "<span style='position:relative; top:-0.10em;'>x</span>"
      + "<span style='position:relative; top:-0.15em;'>t</span>"
      + "<span style='position:relative; top: 0.20em;'>b</span>"
      + "<span style='position:relative; top: 0.15em;'>e</span>"
      + "<span style='position:relative; top: 0.10em;'>n</span>"
      + "<span style='position:relative; top: 0.00em;'>d</span>"
      + "<span style='position:relative; top:-0.05em;'>e</span>"
      + "<span style='position:relative; top:-0.10em;'>r</span>";



    /** Appends text after an anchor 'a' element of the autoindex listing.
      */
    function appendAfterListingA( a, extraString )
    {
     // alert( 'appendAfterListingA, this needs to be fixed' ); // Test on IE. I think the line ends in 2 chars (\r\n). Could try regexp replace instead (but see replaceAfterListingA).
     //// works, though why replaceAfterListingA had such trouble, is unclear
        var textAfterA = a.nextSibling;
        var i = textAfterA.data.length - 1; // insert before trailing newline
        textAfterA.insertData( i, extraString );
    }



    /** Appends text to the content of an anchor 'a' element of the autoindex listing.
      * Returns the span that encapsulates the text [not yet needed, not enabled].
      */
    function appendInListingA( a, extraString )
    {
        span = document.createElement( 'span' );
        a.appendChild( span );
        span.appendChild( document.createTextNode( extraString ));
//      span.setAttribute( 'class', 'appendInListingA' );
        span.className = 'appendInListingA';
     // return span;
    }



    function elementAddClass( element, className )
    {
        if( this.elementHasClass( element, className )) return;

        var separator = element.className? ' ': '';
        element.className += separator + className;
    }



    function elementHasClass( element, className )
    {
        return element.className.match(new RegExp('(?:^|\\s)'+className+'(?:\\s|$)')) != null;
    }



    function elementRemoveClass( element, className )
    {
        // modified from MooTools. [1]
        element.className = element.className.replace(
          new RegExp('(^|\\s)'+className+'(?:\\s|$)'), '$1' );
    }



    /** Assigns classes to 'a' elements that mimic the file-type style rules
      * that IE can't understand (because they select on atttributes).
      * See autoindex.css.
      */
    function fixFileTypeStylesForIE()
    {
        var pre;
        for( var child = document.body.firstChild; child != null; child = child.nextSibling )
        {
            if( child.nodeType != /*element*/1 ) continue;

            if( child.tagName.toLowerCase() == 'pre' )
            {
                pre = child;
                break;
            }
        }
        if( !pre ) return;

        for( var child = pre.firstChild; child != null; child = child.nextSibling )
        {
            if( child.nodeType != /*element*/1 ) continue;

            if( child.tagName.toLowerCase() != 'a' ) continue;

            var href = child.getAttribute( 'href' ); // IE messes href up by expanding it (per textbender/_/autoindex-summary.js) so must use regexp here
            if( href.match(/\?C=M;O=A$/) != null || href.match(/\?C=M;O=D$/) != null
             || href.match(/\?C=N;O=A$/) != null || href.match(/\?C=N;O=D$/) != null
             || href.match(/\?C=S;O=A$/) != null || href.match(/\?C=S;O=D$/) != null )
            {
                elementAddClass( child, 'list-header' );
                continue;
            }

            var img; // preceding the 'a' child
            for( var sib = child;;  )
            {
                sib = sib.previousSibling;
                if( sib == null ) break;

                if( sib.nodeType == /*element*/1 )
                {
                    if( sib.tagName.toLowerCase() == 'img' ) img = sib;
                    break;
                }
            }
            if( img == null ) continue;

            var alt = img.getAttribute( 'alt' );
            if( alt == '[DIR]' ) { elementAddClass( child, 'DIR-ie-fix' ); continue; }
            if( alt == '[ETC]' ) { elementAddClass( child, 'ETC' ); continue; }
            if( alt == '[htm]' ) { elementAddClass( child, 'htm' ); continue; }
            if( alt == '[jav]' ) { elementAddClass( child, 'jav' ); continue; }
            if( alt == '[jnl]' ) { elementAddClass( child, 'jnl' ); continue; }
            if( alt == '[PAR]' ) { elementAddClass( child, 'par' ); continue; }
            if( alt == '[-pm]' ) { elementAddClass( child, 'pm' ); continue; }
            if( alt == '[txt]' ) { elementAddClass( child, 'txt' ); continue; }
        }

    }



    /** Returns the title of the index page, based on the current location.
      *
      *     @param rootTitle title to return if the location is the root
      *         (which would otherwise yield an empty title)
      */
    function indexTitle( rootTitle )
    {
        var title = relativePathFromRoot();
        title = title.replace( /\/_autoindex-summary\.[a-z]+$/, "" ); // chop the name of the file when viewing footer (_autoindex-summary file) alone
        if( title == '' ) return rootTitle;

        var subrootTitle;
        subrootTitle = 'project/outcast';
        if( title == subrootTitle )
        {
            title = titleOutcast;
            return title;
        }

        subrootTitle = 'project/textbender';
        if( title.indexOf(subrootTitle) == 0 )
        {
            if( title == subrootTitle ) title = 'textbender';
            else title = 't' + title.substring( subrootTitle.length );
            return title;
        }

        subrootTitle = 'project/votorola';
        if( title.indexOf(subrootTitle) == 0 )
        {
            if( title == subrootTitle ) title = titleVotorola;
            else title = 'v' + title.substring( subrootTitle.length );
            return title;
        }

        return title;
    }



    /** Returns the relative path of the current location from the site root.
      * Any leading or trailing / is stripped.
      */
    function relativePathFromRoot()
    {
        var path = location.pathname;
        path = path.replace( /^\/?(.*?)\/?$/, "$1" ); // chop any leading and trailing '/'
        return path;
    }



    /** Replaces the text after an anchor 'a' element of the autoindex listing.
      */
    function replaceAfterListingA( a, replacementString )
    {
        var textAfterA = a.nextSibling;
     // textAfterA.replaceData( 0, 999, replacementString + '\n\r' ); // Number.MAX_VALUE fails here
     ////// fails on IE (JS does not convert to \r\n automatically?)
     // var data = textAfterA.data.replace( /^.*($)/m, replacementString + '$1' );
     // textAfterA.data = data;
     ////// fails on IE, the same way as plain '\n'
        textAfterA.replaceData( 0, 999, replacementString + '\n\r' ); // Number.MAX_VALUE fails here
     //////                                                 '\n\r' above is the reverse of what it ought to be, but amazingly this is the only thing that works on IE7.

        // BUG. When used on last item in the list, extra vertical space appears (Firefox 2).
        // Maybe because of the funny newline encoding '\n\r'?
    }



    var titleVotorola = 'Votorola source files';

    var titleOutcast = 'Outcast voting network';



    /** Writes the document header and title.  Called when locally viewing footer
      * (_autoindex-summary.html file).  Results in a document that mimics (somewhat)
      * Apache's complete autoindex output (without the actual index).
      * <p>
      *     Works in any file system where /_/autoindex/ is a copy (or link) of
      *     testbender/_/autoindex/
      *     </p>
      * <p>
      *     Works only for HTML, not XHTML.  The document needs a <script> element before
      *     it can call this method.  But that would become the document element, an
      *     invalid one for XHTML.  So the calling document (the mod_autoindex ReadmeName
      *     footer) must be text/html.  The full autoindex output (header + footer)
      *     generated by Apache might still be XHTML, however.
      *     </p>
      */
    function writeHeader()
    {
     // assert isHeaderWritten == false; // FIX how assert in JS?
        document.writeln( "<html><head>" );
        document.writeln( "    <head>" );
        document.writeln( "        <link rel='stylesheet' type='text/css' href=\'/_/autoindex/autoindex.css\'/>" );
        document.writeln( "        </head><body>" );
        document.writeln( "    <body>" );

        document.title = indexTitle( /*rootTitle*/"/" ); // though root probably never encountered, for local files
        writelnH1( /*rootTitle*/"&nbsp;" ); // for an empty one, use &nbsp;

        isHeaderWritten = true; // though never tested after this point
    }


        var isHeaderWritten; // FIX make name consistent with above



    /** Writes the <h1> element of the index page, based on the current location.
      *
      *     @param rootTitle per {@linkplain #indexTitle indexTitle}()
      */
    function writelnH1( rootTitle )
    {
        var title = indexTitle( rootTitle );

      // decorate titles
      // ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `
        if( title == titleOutcast )
        {
            title = "<span style='color:#B0B0B0'>" + title + "</span>";
        }

        else if( title == 'textbender' ) title = "&nbsp;"; // loading an image instead, in textbender/_/autoindex-summary.js
        else if( title.indexOf('t/') == 0 )
        {
            title = "<span class='home'>t/</span>" + title.substring( 2 );
        }

        else if( title == titleVotorola || title.indexOf('v/') == 0 )
        {
            var toWriteBackgroundImage = true; // till proven otherwise
            var ieIndex = navigator.appVersion.indexOf(" MSIE "); // 4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
            if( ieIndex > -1 )
            {
                var version = parseFloat( navigator.appVersion.substring( ieIndex + 6 ))
                if( version >= 5.5 && version < 7 ) // IE 7 does not need PNG fix
                {
                    toWriteBackgroundImage = false; // ie-png32-fix.js fails for background images
                }
            }
            if( toWriteBackgroundImage )
            {
                document.body.style.backgroundPosition = '6px 11px';
                document.body.style.backgroundRepeat = 'no-repeat';
            }
            if( title == titleVotorola )
            {
                if( toWriteBackgroundImage )
                {
                    document.body.style.backgroundImage = 'url("http://zelea.com/project/votorola/_/brand/logo-32.png")';
                }
                title = "&nbsp;";
            }
            else // sub-directory
            {
                if( toWriteBackgroundImage )
                {
                    document.body.style.backgroundImage = 'url("http://zelea.com/project/votorola/_/brand/logo-icon-32.png")';
                }
                title = "<span class='votorola-logo' style='margin-left:46px'>v/</span>"
                    + title.substring( 2 );                          // 46 = 6 postion + 32 image + 8 extra spacing
            }
        }

  //    var h1 = document.body.getElementsByTagName( 'h1' )[0];
  // // h1.firstChild.data = title;
  //    h1.innerHTML = title;
  //    if( title == rootTitle )
  //    {
  //        h1.setAttribute( 'class', 'root' );
  //    }
  ///// IE7 hangs with this approach. The idea was to hard-code <h1> in header.html, as a scriptless default; then alter it here. Now using scriptless-robots per autoindex.css, instead.

        document.write( '<h1' );
        if( title == rootTitle ) document.write( " class='root'" );

        document.writeln( '>' );
        document.writeln( title + '</h1>' );

    }



}

//
// NOTES
//
//   [1] MooTools.  Copyright 2006-2008, Valerio Proietti.  http://mootools.net/
//

