/* ReadFile.js                                          version: 2.82

And whatever you ask for in my name, that will I do, so that the Father
may be glorified in the Son. John 14:13

   Date       | Change/Update/Fix etc.
   -----------|----------------------------------------------------------
   ver 2.40
   11/14/2002 - When we search for an anchor and then load a new DB
                that has no anchors, the anchor search is still triggered
                since the old value (to search for) is still in the var.
                To get around this I added a new var BADAnchor to tell
                us when it would be bad to search for anchors.
                I tried changing: document.Lookup.MyAnchors.value but
                that didn't work. I guess because it no longer exists!???
                -----
              - Added the loading file-name to the display on the screen.  

   ver 2.41
   12/02/2002 - Added a second anchor catching section for IE web use.
                Look for: 12/02/2002

   ver 2.41-b
   12/12/2002 - Added a second way to check for the DB done being read in.
                In IE we can use the window.document.readyState, NS does
                not allow this. In NS this attribute is undefined.

   ver 2.50
   02/10/2003 - Added check for  Netscap6, see NS6Flg
   
   ver 2.51
   02/24/2003 - Moved the location of the NS6Flg check and setting so that
                it checks only once per file.

   ver 2.52
   04/01/2003 - NSFlg was not being reset to 0 for the next page, placed
                NSFlg = 0; before the test that sets it.
                -----------
              - For anchors to work in NS they must be saved as upper case.
                This is because even tho' we save lower case anchor names
                in the list NS searches for upper case anchors. All anchor 
                lines are now saved as upper case.
                -----------
              - GotAnchor now used as the valid length of the # of anchors
                for this page instdead of: AutoAnchors.length.

   ver 2.60
   04/24/2003 - Added function ParseEmail(PgDat) so that we can hide
                the email addresses in the txt files and put them back
                together both on the display page and the pfind search 
                page.
              - Added function REmail(who,...) to recombine the email
                address needed in ParseEmail().

   ver 2.70
   04/25/2003 - Added function BuildIt(PgDat) so that we can hide email
                addresses.
   ver 2.71   - Changed BuildIt so it works with all lines not just E:
              - Minor text changes

   ver 2.72
   01/12/2004 - Had to change tmp.length-1 to: tmp.lastIndexOf('"') when
                getting the anchors for the AutoAnchor list. We are now
                compatible with the new XML as well as the HTML standards.

   ver 2.73
   06/06/2004 - Added code to check that a link length > 1 to eliminate
                all the blank links.

   ver 2.80
   02/06/2004 - Added typ='E' to FindMe for phone & email line retruns.
   
?  ver 2.81
   06/06/2004 - Added code to check that a link length > 1 to eliminate
                all the blank links.
   
?  ver 2.82
   05/05/2010 - Added edu & de to BuildIt
   -----------|----------------------------------------------------------                
*/
   var GotAnchor = 0; 
   var AutoAnchors = new Array(); // To hold the names of all the AutoAnchors
   var ThisAnchor = "-----";
   var Page = "";
   var Pointer=0;
   var MyDoc = "";
   var MyKey = "";
   var Title = document.title;
   var srch = "head>";
   var TmpStng = "";
   var count = 0; // the waiting counter. pktst 3/27/02
   var LastLength = 0; // last length of innerHTML read
   var SetUpChk = 0;
   var link = links[0];
   var BadAnchor = 0; // if set to 1 then we have No Anchors!
   var TextBox = 0;

   // --------------------------------------------------------
   // Come here to open the default or given file for loading
   // --------------------------------------------------------
   function Init() {
     var name = "DataPage";
     PfindInit();
     
     if(Bad) {
        document.location = links[0];
     }

     if(!document.documentElement.innerHTML) {
        alert("Sorry, this browser can NOT download the data file.");
        return;
     }
     if(document.FileName.file.value != "") {
        link = document.FileName.file.value;
     }

     TmpStng = link.toLowerCase();
     if(TmpStng.indexOf("htm") == -1) {
        srch = "html>";
     }

     MyKey = window.open(link, name);  
     //alert("MyKey.document.readyState = "+MyKey.document.readyState);
     //alert("MyKey.document.onDocComplete() = "+MyKey.document.onDocComplete());
     MyKey.blur();
     Msg("Loading file: - "+link+" - Data, please wait."); // Display this!

     count = 0;      // Clear the time counter
     LastLength = 0; // clear this so we can test it for THIS file.
     Pointer = window.setTimeout("ContinueRead();", 100); // 0.1 sec
   }


   // ----------------------------------------------------
   // Come here to get the inner HTML after the delay
   // ----------------------------------------------------
   function ContinueRead() {
     clearTimeout(Pointer); // 0.5 sec

     if(MyKey.document.documentElement == null) {
        count += 0.1; // add 0.1 second to the time counter
        var Scount = OnePlace(count);
        Pointer = window.setTimeout("ContinueRead();", 100); // 0.1 sec
        window.status="Still waiting..."+Scount+" sec.";
        return;
     }
     while (MyKey.document.documentElement.innerHTML.length != LastLength) {
        count += 0.5; // add 1/2 second to the time counter
        var Scount = OnePlace(count);
        LastLength = MyKey.document.documentElement.innerHTML.length;
        window.status="Still working..."+Scount+" sec. - "+LastLength+" Bytes read.";
        Pointer = window.setTimeout("ContinueRead();", 500); // 0.5 sec
        return;
     }
     // alert("Are we done?"); // Now wait till the sub-window MyKey is done loading!
     // If we wait, then clear this alert all data is read in AOK!

     // ------------------------------------------------------------
     // On the server we have problems with this line, no object
     // I can only assume that since the page takes too long to
     // load, it doesn't yet have the innerHTML
     // ------------------------------------------------------------
     All = Page = MyKey.document.documentElement.innerHTML; // pk01
     // ------------------------------------------------------------
     //alert("Page = "+Page); // pk test

     // -----------------------------------------------------------
     // One last check, did we really get the bottom of this file?
     // For some reason we can NOT check for </pre> or </PRE> if
     // the file is on the WWW. It ALWAYS puts </PRE></BODY> at
     // the end of the file! So, we MUST put something at the end
     // that we can search for. I put: "<end></end>"
     // Also, the web does NOT show the </html> EVER!
     //
     // The &lt;end&gt; etc are needed for NetScape 6.0 to end
     // its search of the data. 03/28/2002 pk
     // -----------------------------------------------------------
     var done = 0;
     // First if works for Netscape, else if works for IE5.50
     if (!MyKey.document.readyState && All.indexOf("***end***end***", LastLength-100) != -1 ) {
         done = 1;
         //alert("Had to use: \"* ***end***end*** *\"");
     }
     else if (MyKey.document.readyState == "complete") {  
         done = 1;
         //alert("MyKey.document.readyState, worked.");
     }
     if(!done) {
        count += 0.1; // add 1/2 second to the time counter
        var Scount = OnePlace(count); // Only one decimal place.

        window.status="Still working * "+Scount+" sec. - "+LastLength+" Bytes read.";
        //var Stng = All.substring(LastLength-100, LastLength);
        //alert("Are we there yet?\n\n"+Stng);

        Pointer = window.setTimeout("ContinueRead();", 100); // 0.1 sec
        return;
     }
     else {
        //var Stng = All.substring(LastLength-100, LastLength);
        //alert("Yup, we're at the bottom of the file!\n\n"+Stng);

        // ------------------------------------------------------------
        // BuildIt changes email lines from the form:
        //          E: |BuildIt|ke3fl|ya|hoo|0|
        // TA[#] =  0      1      2    3  4  5  6
        // to the form:
        //          E: @yahoo.com 
        // ------------------------------------------------------------
        All = Page = BuildIt(Page); // Needed by the Pfind.js functions

        //alert(Page); pk01
     }
     // -----------------------------------------------------------

     MyKey.close();

     // Need this delay to actually read the data.
     Pointer = window.setTimeout("GetIt();", 500); // 0.5 sec
   }


   // ---------------------------------------------------------------------
   // It seems that once this loop is entered not even a setTimeout
   // is able to break out of it to do a display!
   // ---------------------------------------------------------------------
   // There is no SelectBox box here but below in SetUp() there is, why?
   // ---------------------------------------------------------------------

   // ----------------------------------------------------
   // Come here to load the data into an Array of lines
   // ----------------------------------------------------
   function GetIt() {

     if(All) {
       var Lines = Page.split("\n");
       MyDoc="<b>The data from ["+link+"] is: </b><br><hr>";
       var first = 0;
       var last = 0;
       var done = 0;

       // -------------------------------------------------------
       // Find the actual data lines, data starts with "*" and
       // ends with "*" as the first chars on the lines
       // -------------------------------------------------------
       for(i=0; i<Lines.length && !done; ++i) {
         TmpStng = Lines[i].toLowerCase();
         if(TmpStng.indexOf(srch) != -1 && !first) {
            first = i+1;
         }
         else if(TmpStng.indexOf(srch) != -1 && first) {
            last = i-1;
            done = 1;
         }
         else {
            last = i-1;
         }
       }
       ++last; // Need to get the last line as well.
       // -------------------------------------------------------

       // -----------------------------------------------------------
       // Build up the inner HTML with the loaded data & display it.
       // -----------------------------------------------------------
       MyDoc += "<pre>\n"; // Just get the data as it is (as much as we can.)

       NSFlg  = 0; // added 04/01/2003 ver 2.52
       NS6Flg = 0; // Moved here in Version 2.51, 02/24/2003
       if(navigator.userAgent.indexOf('Netscape6') != -1) {
          NS6Flg = 1;
       }

       var count = 0;
       for(i=first; i<last; ++i) { // Display the data lines pk05
         // -----------------------------------------------------------
         // This section is needed so that the data will display
         // correctly in NetScape. NS replaces all < > with &lt; &gt;
         // and these MUST be replaced with < > if we are to get the
         // HTML saved in the txt file. IE doesn't do this!
         // -----------------------------------------------------------
         if(TextBox) {  // Need this reset each time ONLY for ReadText.htm
            NSFlg  = 0; // added 04/01/2003 ver 2.52
         }
         if(Lines[i].indexOf("&lt;") != -1 || Lines[i].indexOf("&gt;") != -1) {
            NSFlg = 1; // Yup, might be Netscape!
            
            var old = Lines[i];
            while(Lines[i].indexOf("&lt;") != -1) {
               //alert("Got one &lt;"); // debug
               var pntr = Lines[i].indexOf("&lt;");
               var stn = Lines[i].substring(0, pntr);
               stn += "<";
               stn += Lines[i].substring(pntr+4, Lines[i].length);
               Lines[i] = stn;
            }
            while(Lines[i].indexOf("&gt;") != -1) {
               //alert("Got one &gt;"); // debug
               var pntr = Lines[i].indexOf("&gt;");
               var stn = Lines[i].substring(0, pntr);
               stn += ">";
               stn += Lines[i].substring(pntr+4, Lines[i].length);
               Lines[i] = stn;
            }
         }
         // -----------------------------------------------------------

         // -----------------------------------------------------------
         // Check for Anchors in this file, get the names of each
         //
         // 12/02/2002 additions:
         // When IE reads the txt database file from the web it changes
         // the way in which it "reads" the data. The biggest problem
         // I've seen is that from the hard-drive <a name="KE3FL">
         // reads in as is, but from the web it becomes: <A name=KE3FL>
         // notice no quote marks and <a becomes <A so the check below
         // wouldn't even find the line!
         //
         // I added an else if to catch the <A name=KE3FL> type anchors
         // and adjusted the removal of characters as needed to 
         // insure that we get the actual anchor names.    (12/02/2002)
         //
         // Possible problem with this is that NS always searches for
         // upper case anchor names even if they were put in as ke3fl!
         // changes: pk 04/01/2003 - ver 2.52
         // -----------------------------------------------------------          
         if(Lines[i].indexOf("<a name=") != -1 ||
            Lines[i].indexOf("<A name=") != -1) { // IE & NS matches

            // ------------------------------------------------------
            // Convert all anchor lines to upper case to there'll be
            // no problems with any browsers! NS searches for upper 
            // case names even if they are not upper case & wrose is
            // that they are not found! - pk 04/01/2003
            // ------------------------------------------------------
            Lines[i] = Lines[i].toUpperCase(); 
            // ------------------------------------------------------

            var pntr = Lines[i].indexOf("<A NAME=");
            var chop = 2;

            var tmp = Lines[i].substring(pntr+9, Lines[i].length-chop);
            //alert(tmp); // pk test 

            // --------------------------------------------------------------
            // This check is needed because NS doesn't count CR-LF as
            // part of the length of the string when the string comes
            // from a txt file. Yet if I search on \n or \r they are found!
            // --------------------------------------------------------------
            if(tmp.indexOf('"') != -1 || tmp.indexOf("'") != -1) { // ver 2.72
               tmp = tmp.substring(0, tmp.lastIndexOf('"')); // remove last char ' or "
            }
            // --------------------------------------------------------------

            AutoAnchors[count] = tmp;
            ++count;
         }
         GotAnchor = count;
         // -----------------------------------------------------------

         MyDoc += Lines[i]; // Just get the data pk05
         if(!NSFlg || NS6Flg) // for IE type browsers & Netscape 6.1, 6.2??
            MyDoc += "<br>"; // Needed in IE

         window.status="Line "+i+" loaded.";  // Lines Loaded Status Message
       }

       MyDoc += "</pre>\n<hr><br>done.<br>";
       // -----------------------------------------------------------
     }

     id = document.getElementById("data"); // innerHTML("data")...
     id.innerHTML = MyDoc;

     TmpStng = "***** Got the Page! ***** "+Title+" ***** Got the Page! ***** ";
     window.status = TmpStng;

     SetUp(); // Now set up the select list of allowed files

     // -----------------------------------------------------------
     // Check for Anchors & if we have them, make a select box!
     // -----------------------------------------------------------
     if(!GotAnchor) { // Remove anchor searching if no AutoAnchors found
        var obj2 = document.getElementById("AnchorsHere");

        obj2.innerHTML="<center><b>Select a search </b><input type='text' size='11' value='  removed' class='pkRed'></center>";
        
        BadAnchor = 1; // No anchors, so searching for them is BAD!
     }
     else {
        var obj2 = document.getElementById("AnchorsHere");
        var Stn = "<b>Select "+AnchorName+"</b> ";
        
        Stn += "<select name='MyAnchors' onChange='FindAnchor();'>\n";
        Stn += '<option value="-----">-----</option>\n';

        AutoAnchors = AutoAnchors.sort();

        // If we use AutoAnchors.length it never gets smaller, the largest
        // value is kept from the previous page!, thus use the real length
        // for this page: GotAnchor. - ver 2.52
        for (var j=0; j<GotAnchor; ++j) {
           if(AutoAnchors[j].length >= 1) { // 06/06/2004 to get rid of "empty" links
             Stn += '<option value="'+AutoAnchors[j]+'">'+AutoAnchors[j]+'</option>\n';
           }
        }
        Stn += "</select> Link\n";
        obj2.innerHTML = Stn;

        BadAnchor = 0; // We have anchors, so searching for them is OK!
     }
     // -----------------------------------------------------------

   } // end of: GetIt()
   
   

   // ********************************************************************
   // ********************************************************************
   //                               Utilities
   // ********************************************************************
   // ********************************************************************


   // -------------------------------------------------------------------
   // The needed look-up sections for the Pfind.js search routines.
   // -------------------------------------------------------------------
   function FindMe() {
     //var GoTo = "#"+document.Lookup.Anchor.value;
     var GoTo = "#"+ThisAnchor;
     GoTo = GoTo.toUpperCase(); // Make sure we can match Anchor names

     if (GoTo != "#-----" && !BadAnchor) { // Don't search if we don't have!
       document.location = GoTo; // Looking for an Anchor
     }
     else if (document.Lookup.Pfind[0].checked) {
       Pfind("R"); // Return complete records containing matched lines
     }
     else if (document.Lookup.Pfind[1].checked) {
       Pfind("A"); // Return Address lines for record containing matched line
     }
     else if (document.Lookup.Pfind[2].checked) {
       Pfind("E"); // Return Address, phone, & e-mail lines.
     }
     else if (document.Lookup.Pfind[3].checked) {
       Pfind("L"); // Just return the lines that match.
     }
     return false;
   }


   // -------------------------------------------------------------------
   // Add your status line message for roll-over an image here
   // -------------------------------------------------------------------
   function Click() {
     window.status="Click here to view larger image."
   }



   // -------------------------------------------------------------------
   // Add your Default status line message here
   // -------------------------------------------------------------------
   function Base() {
     window.status = Title; // Same as Page title now
   }
   // -------------------------------------------------------------------

   // -------------------------------------------------------------------
   // Return a string of a decimal number of only one decimal place
   //
   // inputs:   the decimal number
   // outputs:  none
   // actions:  none
   // returns:  the string of the number with one decimal place
   // -------------------------------------------------------------------
   function OnePlace(num) {
      var Scount= ""+num;
      var pnt = Scount.indexOf(".");
      if(Scount.length > pnt + 1 && pnt > -1) {
         Scount = Scount.substring(0,pnt+2);
         //alert("In Here 001\n\nlength: "+Scount.length+"\npnt: "+pnt);
      }
      else if (pnt == Scount.length-1) {
         Scount += "0";
      }
      else {
         Scount += ".0";
      }

      //alert("returning: "+Scount);
      return Scount;
   }
   // -------------------------------------------------------------------


   // -------------------------------------------------------------------
   // SetUp sets up the select box of valid file names that can be read
   // It uses the values stored in the links Array.
   // -------------------------------------------------------------------
   function SetUp() {
      var Stng = "<select NAME='ListBox' onChange='LoadMe();'>\n";
      for(var j=0; j<links.length; ++j) {
         Stng += '<option value="'+links[j]+'"';
         if(j == SetUpChk)
            Stng += " selected ";
         Stng += '>'+links[j]+'</option>\n';
      }


      Stng += "</select> - Select the file to load and search.\n\n";
      var obj = document.getElementById("SelectBox");
      if(obj) { // Do only if SelectBox has been found 
        obj.innerHTML = Stng; // IE problem line?
      }
   }
   // -------------------------------------------------------------------

   // -------------------------------------------------------------------
   // LoadMe - Loads the selectBox file name and loads that file.
   // -------------------------------------------------------------------
   function LoadMe() {
      //alert(document.Lookup.ListBox.value);

      document.FileName.file.value = links[0];

      if(document.Lookup.ListBox.value) {
         document.FileName.file.value = document.Lookup.ListBox.value;
         var done = 0;
         for (var j=0; j<links.length && !done; ++j) {
            if (links[j] == document.FileName.file.value) {
              SetUpChk = j;
              done = 1;
            }
         }
      }

      Init();
   }
   // -------------------------------------------------------------------


   // -------------------------------------------------------------------
   // FindAnchor - Loads the MyAnchors selectBox file name and loads that
   //              file.
   // -------------------------------------------------------------------
   function FindAnchor() {

      // ----------------------------------------------------------
      // This should be: Object/HTML form element, but for some reason
      // even tho' the select list is there, the object is not in NS!?
      // Problem was in the caret.htm file at the title lines! fixed!
      // -------------------------------------------------------------
      ThisAnchor = document.Lookup.MyAnchors.value;
      if(ThisAnchor != "-----") {
         FindMe();
      }
   }
   // -------------------------------------------------------------------

   // -------------------------------------------------------------------
   // Display a message in the status line & on the screen
   //
   // inputs:   The message string
   // outputs:  Message to the status line & the screen
   // actions:  none
   // returns:  none
   // -------------------------------------------------------------------
   function Msg(Txt) {
      window.status = Txt;

      var obj = document.getElementById("SelectBox");
      obj.innerHTML = "<font color='red'><h2>"+Txt+"</h2></font>";
   }
   // -------------------------------------------------------------------


   // -------------------------------------------------------------------
   // -------------------------------------------------------------------
   function whatFile() {
      //window.location= 'file:///' + document.Lookup.cmuds.value;
      window.open('file:///' + document.Lookup.cmuds.value, "Text");
   }
   // -------------------------------------------------------------------


   // -------------------------------------------------------------------
   // Prints the email address given in the Email() function.
   // -------------------------------------------------------------------
   function Email(who, typ, server) {
      //alert("Building email address for: "+who);
      var Str = who + "@";
      Str += server + "." + typ;
      document.write(Str);
   }
   // -------------------------------------------------------------------


   // -------------------------------------------------------------------
   // Returns the email address string from data given.
   // -------------------------------------------------------------------
   function REmail(who, server, typ) {
      //alert("Building email address for: "+who);
      var Str = who + "@";
      Str += server + "." + typ;
      return(Str);
   }
   // -------------------------------------------------------------------



   // -------------------------------------------------------------------
   // Parses all innerHTML sent to find Email(... and replace it with the
   // actual email address.
   // form of the email line is:
   // E: <script  language='JavaScript' type='text/javascript'>Email('dwel', 'stabilant', 'com');</script>
   // -------------------------------------------------------------------
   function ParseEmail(PgDat0) { // pk01
      var PgDat = BuildIt(PgDat0); // Clean it this way first
      
      var BigA = new Array();
      BigA = PgDat.split("\n"); // split into array lines

      // Find lines with Email in them & replace them!
      for(var ii=0; ii<BigA.length; ++ii) {
         
         if(BigA[ii].indexOf('Email(') != -1) { // got one!
           var Strt = BigA[ii].substring(0, 3);
           //alert("BigA[ii] = [["+BigA[ii]+"]]\nBiga[ii+1] = [["+BigA[ii+1]+"]]");
           var TA = new Array();
           TA = BigA[ii].split("(");
           TA = TA[1].split(")");
           
           for(var j=0; j<TA.length; ++j) {
              var o_re;
	         
	      o_re    = /"/;
	      while(TA[j].indexOf('"') != -1)
                 TA[j] = TA[j].replace(o_re, "");

	      o_re    = /'/;
	      while(TA[j].indexOf("'") != -1)
                 TA[j] = TA[j].replace(o_re, "");
           }
           
           TA = TA[0].split(", "); // get the email address parts

           // --------------------------------------------------------
           // I added the +"<br>" so that the on-page display
           // looks good, for some reason it was as if the CRLF
           // gets lost for these lines & trying to add it back
           // in here doesn't do any good. The problem is that
           // now on the search page we have an "extra" blank line
           // between this line & the next, but then without it
           // on the on-page display the two lines form one line!
           // --------------------------------------------------------
           // Re-combine the email address parts into a valid address
           // --------------------------------------------------------
           BigA[ii] = Strt + REmail(TA[0], TA[1], TA[2])+"<br>";

         } // end of: if(BigA[i]...
         
      } // end of: for(ii=0; ...
      
      var JBigA = BigA.join("\n");
      //DeBugW(JBigA);
      return(JBigA);
           
   }
   // -------------------------------------------------------------------




   // -------------------------------------------------------------------
   // Parses all innerHTML sent to find E: & BuildIt and replace it with
   // the actual email address.
   // Form of the email address line is:
   // Email line form: E: |BuildIt|ke3fl|ya|hoo|0|
   //         TA[#] =  0      1      2    3  4  5  6
   //
   // inputs:  PgDat - the full html page
   // outputs: none
   // actions: email addresses are rebuilt and replace the email lines
   // returns: The corrected full html page
   // -------------------------------------------------------------------
   function BuildIt(PgDat) { // pk01
      var BigA = new Array();
      BigA = PgDat.split("\n"); // split into array lines


      // Find lines with Email in them & replace them!
      for(var ii=0; ii<BigA.length; ++ii) {
         
         if(BigA[ii].indexOf('|BuildIt|') != -1) { // got one!

           var TA = new Array();
           var Stng = ""; // This line being built up
           
           TA = BigA[ii].split("|");
           Stng = TA[0] + TA[2] + "@" + TA[3] + TA[4];
           switch (TA[5]/1) { // Make sure it's a number! '
              case 0:
                Stng += ".com";
                break;
              case 1:
                Stng += ".net";
                break;
              case 2:
                Stng += ".org";
                break;
              case 3:
                Stng += ".gov";
                break;
              case 4:
                Stng += ".edu";
                break;
              case 5:
                Stng += ".de";
                break;
              case 6:
                Stng += ".ca";
                break;
              case 7:
                Stng += ".us";
                break;
              case 8:
                Stng += ".se";
                break;
              default:
                Stng += "";
           }
           BigA[ii] = Stng + TA[6];
           //alert(BigA[ii]); // OK to here
         }

      } // end of: for(var ii=0;...

      var JBigA = BigA.join("\n");
      //DeBugW(JBigA);
      return(JBigA);
      
   } // end of: BuildIt(PgDat)
