//*
//| WebLoadFile.js
//|------------------------------------------------------------------------------
//| Copyright 2000 by GalaSoft Laurent Bugnion
//|------------------------------------------------------------------------------
//| Website                : www.galasoft.ch
//| Language               : JavaScript
//| Author                 : Laurent Bugnion (laurent@galasoft.ch)
//|------------------------------------------------------------------------------
//| Description:
//|   Contains the functions triggering the applet WebLoadFile.
//|   Developed for demo purpose.
//|
//| History:
//|   05.10.2000 Lbu : Created.
//|   09.10.2000 Lbu : Due to problems with IE, demo rewritten from scratch.
//|   12.10.2000 Lbu : Finished rewriting.
//|   15.10.2000 Lbu : Added refresh.
//|------------------------------------------------------------------------------
//*

/*******************************************************************************/
/* Global variables ************************************************************/
/*******************************************************************************/

/* Windows */
var fileListWin = null;
var fileWin = null;

/* This variable stores the applet's codebase */
var m_strCodeBase = null;

/* Stores the relative path to the dir shown in the file list */
var m_strRelativeDirPath = "";

/* Stores the relative path to the upper dir */
var m_strUpperDirPath = null;

/* Stores the file */
var m_strFile = null;
var m_aabFile = null;
var m_iLength = -1;

/* Reference to the applet */
var theApplet = null;

/*******************************************************************************/
/* Functions accessed by the applet ********************************************/
/*******************************************************************************/

/* This function must be here. */
/* It is called by the applet when it is started */
/* Use it to save the files' codebase */

function receiveCodeBase( strCodeBase )
{
  m_strCodeBase = strCodeBase + ""; //convert to JavaScript string

  /* Make sure that it ends with '/' */
  if ( m_strCodeBase.charAt( m_strCodeBase.length - 1 ) != '/' )
  {
    m_strCodeBase += "/";
  }
}

/*******************************************************************************/
/* Functions accessing the applet **********************************************/
/*******************************************************************************/

/* Loads the directory listing *************************************************/

function loadFileList( appletNumber, strRelativeDirPath )
{
  theApplet = document.applets[ "WebLoadFile" + appletNumber ];

  if ( m_strCodeBase == null )
  {
    currentAlert( "Please wait, the applet is not fully loaded yet!" );
  }
  else
  {
    /* Make sure that it ends with '/' */
    if ( ( strRelativeDirPath != "" )
      && ( strRelativeDirPath.charAt( strRelativeDirPath.length - 1 ) != '/' ) )
    {
      strRelativeDirPath += "/";
    }

    /* Save relative path */
    var oldRelativeDirPath = m_strRelativeDirPath;
    m_strRelativeDirPath = strRelativeDirPath;

    /* Save upper dir for faster navigation */
    var oldUpperDirPath = m_strUpperDirPath;

    if ( m_strRelativeDirPath == "" )
    {
      m_strUpperDirPath = null;
    }
    else
    {
      var anteLastIndex;

      if ( ( anteLastIndex = m_strRelativeDirPath.lastIndexOf( '/', m_strRelativeDirPath.length - 2 ) ) != -1 )
      {
        m_strUpperDirPath = m_strRelativeDirPath.substring( 0, anteLastIndex + 1 );
      }
      else
      {
        m_strUpperDirPath = "";
      }
    }

    currentStatus( "Loading the file list..." );

    /* Make the full directory name */
    var strDirName = m_strCodeBase + strRelativeDirPath;

    /* Call the applet's method */
    var strFileList = theApplet.loadFileList( strDirName );

    if ( strFileList == null )
    {
      currentAlert( "The file list is null\n(there was a problem)" );
      m_strUpperDirPath = oldUpperDirPath;
      m_strRelativeDirPath = oldRelativeDirPath;
    }
    else
    {
      if ( strFileList == "" )
      {
        currentAlert( "Nothing found." );
        m_strUpperDirPath = oldUpperDirPath;
        m_strRelativeDirPath = oldRelativeDirPath;
      }
      else
      {
        currentStatus( "File list loaded, converting..." );

        strFileList = unescape( strFileList );
        strFileList = convertFileList( appletNumber, strFileList + "" );

        /* Display the result */
        openFileListWin( appletNumber, strFileList );
      }
    }

    currentStatus( "" );
  }
}

/* Reads a file as text, binary or hexadecimal *********************************/

function readFile( strRelativeFileName, bText )
{
  if ( m_strCodeBase == null )
  {
    currentAlert( "Please wait, the applet is not fully loaded yet!" );
  }
  else
  {
    currentStatus( "Loading file..." );

    /* Make the full directory name */
    var strFileName = m_strCodeBase + strRelativeFileName;

    /* Call the applet's method */

    if ( bText )
    {
      /* Text file */
      m_abFile = null; //free memory
      m_iLength = -1;
      m_strFile = theApplet.readASCIIFile( strFileName ) + "";

      if ( m_strFile == "null" )
      {
        m_strFile = null;
      }

      currentStatus( "Done, converting for display..." );
    }
    else
    {
      m_strFile = null; //free memory

      /* Load as binary file */
      if ( theApplet.readBINARYFile( strFileName ) )
      {
        currentStatus( "Done, converting for display..." );

        m_aabFile = new Array();
        m_iLength = theApplet.readByteArrayLength();
        var iIndexInFileArray = -1;

        for ( index = 0; index < m_iLength; index++ )
        {
          if ( ( ( index ) % 5000  ) == 0 )
          {
            m_aabFile[ ++iIndexInFileArray ] = new Array();
          }

          m_aabFile[ iIndexInFileArray ][ index ] = theApplet.readOneByteHex( index ) + " ";

          if ( ( index % 10 ) == 0 )
          {
            m_aabFile[ iIndexInFileArray ][ index ] = "\n" + get9Digits( index ) + " -> " + m_aabFile[ iIndexInFileArray ][ index ];
          }

          if ( ( ( index + 1 ) % 100 ) == 0 )
          {
            fileListWin.status = ( index + 1 ) + "/" + m_iLength;
          }
        }

        /* Make strings */
        for ( index = 0; index < m_aabFile.length; index++ )
        {
          m_aabFile[ index ] = m_aabFile[ index ].join( "" );
        }
      }
      else
      {
        m_aabFile = null;
        m_iLength = -1;
      }
    }

    if ( ( m_strFile == null )
      && ( m_aabFile == null ) )
    {
      currentAlert( "There was a problem" );
    }
    else
    {
      openFileWin( strFileName, bText );
    }

    currentStatus( "" );
  }
}

/*******************************************************************************/
/* Utilities *******************************************************************/
/*******************************************************************************/

/* Converts the file list for display ******************************************/

function convertFileList( appletNumber, strFileList )
{
  var astrFileList = strFileList.split( "\n" );

  var strFileListConverted = '<TABLE WIDTH="100%" CELLPACING="0" CELLPADDING="10" BORDER="1">';

  for ( index = 0; index < astrFileList.length - 1; index++ )
  {
    var astrFileName = astrFileList[ index ].split( ":" );

    strFileListConverted += '\n<TR><TD WIDTH="70%"><B>'
                          + astrFileName[0] + ' <I>(' + astrFileName[1] + ')</I></B></TD>'
                          + '\n<TD WIDTH="40%">'

                          + ( ( ( astrFileName[1] == "Directory" )
                             || ( astrFileName[1] == "Unknown" ) ) ?
                              '<A HREF="#"'
                            + ' ONMOUSEOVER="self.status=\'browse directory\';return true;"'
                            + ' ONMOUSEOUT="self.status=\'\';return true;"'
                            + ' ONCLICK="opener.loadFileList(' + appletNumber + ', opener.m_strRelativeDirPath + \'' + astrFileName[0] + '\');return false;">'
                            + 'DIR</A>' : '' )

                          + ( ( astrFileName[1] == "Unknown" ) ? ' / \n' : '' )

                          + ( ( ( astrFileName[1] == "File" )
                             || ( astrFileName[1] == "Unknown" ) ) ?
                              '<A HREF="#"'
                            + ' ONMOUSEOVER="self.status=\'open as text file\';return true;"'
                            + ' ONMOUSEOUT="self.status=\'\';return true;"'
                            + ' ONCLICK="opener.readFile(opener.m_strRelativeDirPath + \'' + astrFileName[0] + '\',true,false);return false;">'
                            + 'TXT</A> /'
                            + '\n<A HREF="#"'
                            + ' ONMOUSEOVER="self.status=\'open as binary file (hexa)\';return true;"'
                            + ' ONMOUSEOUT="self.status=\'\';return true;"'
                            + ' ONCLICK="opener.readFile(opener.m_strRelativeDirPath + \'' + astrFileName[0] + '\',false,true);return false;">'
                            + 'HEX</A>' : '' )

                          + '</TD></TR>';
  }

  strFileListConverted += '</TABLE>';

  return strFileListConverted;
}

/* Opens a new window and show the file list passed as parameter ***************/

function openFileListWin( appletNumber, strTextToShow )
{
  if ( ( fileListWin == null )
    || fileListWin.closed )
  {
    var locX = ( screen.width - 600 ) / 2;
    var locY = 20;

    var strFeatures = "width=600,height=500,scrollbars=1,status=1"
                    + ",screenX=" + locX + ",screenY=" + locY //Netscape
                    + ",left=" + locX + ",top=" + locY;       //IE

    fileListWin = open( "", "fileListWin", strFeatures );
  }
  else
  {
    fileListWin.focus();
  }

  fileListWin.document.writeln( '<HEAD><TITLE>Directory listing</TITLE></HEAD>'
                              + '<BODY BGCOLOR="#FFFFFF"><B><I><FONT SIZE="-1">'
                              + m_strCodeBase + m_strRelativeDirPath
                              + '</FONT></I></B><BR>'

                              + ( ( m_strUpperDirPath == null ) ? '' :
                                  '\n<A HREF="#"'
                                + ' ONMOUSEOVER="self.status=\'Up one dir\';return true;"'
                                + ' ONMOUSEOUT="self.status=\'\';return true;"'
                                + ' ONCLICK="opener.loadFileList(' + appletNumber + ', \'' + m_strUpperDirPath + '\');return false;">'
                                + 'Upper dir</A> /' )

                              + '\n<A HREF="#"'
                              + ' ONMOUSEOVER="self.status=\'Refresh current view\';return true;"'
                              + ' ONMOUSEOUT="self.status=\'\';return true;"'
                              + ' ONCLICK="opener.loadFileList(' + appletNumber + ', \'' + m_strRelativeDirPath + '\');return false;">'
                              + 'Refresh</A>'

                              + '<BR><BR>\n'
                              + strTextToShow
                              + '\n<CENTER><BR><BR><A HREF="#"'
                              + ' ONMOUSEOVER="self.status=\'close this window\';return true;"'
                              + ' ONMOUSEOUT="self.status=\'\';return true;"'
                              + ' ONCLICK="self.close();return false;">'
                              + 'close</A></CENTER></BODY>' );
  fileListWin.document.close();
}

/* Opens a new window and show the file list passed as parameter ***************/

function openFileWin( strFileName, bText )
{
  if ( ( fileWin == null )
    || fileWin.closed )
  {
    var locX = ( screen.width - 700 ) / 2;
    var locY = 20;

    var strFeatures = "width=700,height=500,scrollbars=0"
                    + ",screenX=" + locX + ",screenY=" + locY //Netscape
                    + ",left=" + locX + ",top=" + locY;       //IE

    fileWin = open( "", "fileWin", strFeatures );
  }
  else
  {
    fileWin.focus();
  }

  fileWin.document.writeln( '<HEAD><TITLE>File content</TITLE></HEAD>'
                            + '<BODY BGCOLOR="#FFFFFF"><B><I>'
                            + '<FONT SIZE="-1">' + strFileName
                            + '</FONT></I></B><CENTER>'
                            + '<FORM NAME="myForm">'
                            + '\n<TEXTAREA COLS="82" ROWS="24" NAME="display" WRAP="off">'
                            + '</TEXTAREA>\n</FORM>'

                            + ( bText ? '' : '\n<A HREF="#"'
                              + ' ONMOUSEOVER="self.status=\'previous xxxx bytes\';return true;"'
                              + ' ONMOUSEOUT="self.status=\'\';return true;"'
                              + ' ONCLICK="opener.prevBytes();return false;">&lt;&lt; prev bytes</A> | ' )

                            + '\n<A HREF="#"'
                            + ' ONMOUSEOVER="self.status=\'close this windows\';return true;"'
                            + ' ONMOUSEOUT="self.status=\'\';return true;"'
                            + ' ONCLICK="self.close();return false;">close</A>'

                            + ( bText ? '' : '\n | <A HREF="#"'
                              + ' ONMOUSEOVER="self.status=\'next xxxx bytes\';return true;"'
                              + ' ONMOUSEOUT="self.status=\'\';return true;"'
                              + ' ONCLICK="opener.nextBytes();return false;">next bytes &gt;&gt;</A>' )

                            + '</CENTER></BODY>' );

  fileWin.document.close();

  if ( bText )
  {
    fileWin.document.myForm.display.value = m_strFile;
  }
  else
  {
    firstBytes();
  }

}

/* Loads the the bytes 5000 per 5000 *******************************************/

var m_iByteIndex = 0;

function firstBytes()
{
  m_iByteIndex = 0;
  showCurrentBytes();
}

function prevBytes()
{
  var oldByteIndex = m_iByteIndex;
  m_iByteIndex--;
  if ( m_iByteIndex < 0 )
  {
    m_iByteIndex = Math.round( ( m_iLength / 5000 ) - 0.5 );
  }

  if ( oldByteIndex != m_iByteIndex )
  {
    showCurrentBytes();
  }
}

function nextBytes()
{
  var oldByteIndex = m_iByteIndex;
  m_iByteIndex++;

  if ( m_iByteIndex > ( m_iLength / 5000 ) )
  {
    m_iByteIndex = 0;
  }

  if ( oldByteIndex != m_iByteIndex )
  {
    showCurrentBytes();
  }
}

function showCurrentBytes()
{
  fileWin.document.myForm.display.value = "Bytes " + ( m_iByteIndex * 5000 ) + " - "
                                        + ( ( m_iLength < ( 5000 + m_iByteIndex * 5000 ) )
                                          ? ( m_iLength - 1 ) : ( ( m_iByteIndex + 1 ) * 5000 - 1 ) )
                                        + " (total: " + m_iLength + " bytes)"
                                        + "\n------------------------------------------\n"
                                        + "xxxxxxxxx -> 00 01 02 03 04 05 06 07 08 09\n"
                                        + "------------------------------------------"
                                        + m_aabFile[ m_iByteIndex ]
                                        + "\n------------------------------------------\n"
                                        + "xxxxxxxxx -> 00 01 02 03 04 05 06 07 08 09";
}

/* Cleans up when leaving ******************************************************/

function unloadMe()
{
  if ( ( fileListWin != null )
    && !fileListWin.closed )
  {
    fileListWin.close();
  }
  fileListWin = null;

  if ( ( fileWin != null )
    && !fileWin.closed )
  {
    fileWin.close();
  }
  fileWin = null;
}

/* Alerts in the current window ***********************************************/

function currentAlert( strMessage )
{
  if ( ( fileWin != null )
    && !fileWin.closed )
  {
    fileWin.alert( strMessage );
  }
  else
  {
    if ( ( fileListWin != null )
      && !fileListWin.closed )
    {
      fileListWin.alert( strMessage );
    }
    else
    {
      alert( strMessage );
    }
  }
}

/* Shows status in the main window and the file list **************************/

function currentStatus( strMessage )
{
  if ( ( fileListWin != null )
    && !fileListWin.closed )
  {
    fileListWin.status = strMessage;
  }
  status = strMessage;
}

/* Get 9 digits out of a number ***********************************************/

function get9Digits( iNumber )
{
  var strReturn = ( ( iNumber < 100000000 ) ? "0" : "" )
                + ( ( iNumber < 10000000 ) ? "0" : "" )
                + ( ( iNumber < 1000000 ) ? "0" : "" )
                + ( ( iNumber < 100000 ) ? "0" : "" )
                + ( ( iNumber < 10000 ) ? "0" : "" )
                + ( ( iNumber < 1000 ) ? "0" : "" )
                + ( ( iNumber < 100 ) ? "0" : "" )
                + ( ( iNumber < 10 ) ? "0" : "" )
                + iNumber;
  return strReturn;
}

