// orpFormS:  Contains methods to support the parameter screen  orpPForm.html,
// and subordinate pages which run relative to main parameter screen.
// Copyright (c) 2000-2007 James S. Welch, Jr. All Rights Reserved

//   document.domain='i-orp.com';              // Common domain with IIS1.
// saveParms:  Save the parameter table form as a cookie and restore it.
   var ORPid = "ORParms=";

// -- clearParms:  When the screen is cleared, if the save parameters is off as well clear cookies
// 1Sep00:  Not used in favor of adding clear button to input form.
   function clearParms()
   { 
       if( document.ORPform.SaveParms.checked )
          restoreParms();
       else
          resetParms();
       handleUNLOAD();             // Take down all subordinate windows.
   }

// -- resetParms:  Manual resetting of the screen. Clear all text boxes, set a radio button,
// clear the checkbox.  This has to be done manually because form.reset() gets called at awkward
// times, such as after the BODY unload and and before the screen is finished displaying.
// This means that even though the objects on the form have been initialized by body.onLoad, form
// reset blows them away, it we don't block it.
   function resetParms()
   {
       debugLog( "resetParms entered." );
       for( var i6 = 0; i6 < document.ORPform.elements.length; i6++ )
           if( document.ORPform.elements[i6].type == "radio" )
              document.ORPform.calcmode[0].checked = true;
           else if( document.ORPform.elements[i6].type == "checkbox" )
              document.ORPform.elements[i6].checked = false;
           else if( document.ORPform.elements[i6].type == "text" )
              document.ORPform.elements[i6].value = "";        // Text box
       debugLog( "resetParms exited." );
   }

// -- Before a run, check box willing, save the parameters as a cookie.
   function saveORPParms()
   {
       debugLog( "orpForms.saveORPParms entered." );
//       document.domain = 'i-orp.com';			// Domain common to IIS1.
       if( document.ORPform.SaveParms.checked )
       {				// Save box checked
          var text = ORPid;
       
          debugLog( "orpForms.saveORPPARMS:  saving parameters requested." );
          for( var i5 = 0; i5 < document.ORPform.elements.length; i5++ )
          {
              var type = document.ORPform.elements[i5].type;
              if( type == "button" )
                 break;
              if( type == "radio" )
              {
                 if( document.ORPform.elements[i5].checked )
           	       text += document.ORPform.elements[i5].value + "~:"; 
              }
              else if( type == "checkbox" )
              {
                 if( document.ORPform.elements[i5].checked )
           	       text += document.ORPform.elements[i5].value + "~:"; 
              }
              else if( document.ORPform.elements[i5].value.length > 0 )
              	 text += document.ORPform.elements[i5].name + "~" + document.ORPform.elements[i5].value + ":"; 
          }
          try {                            // Store the parameter cookies
             var nextyear = new Date();
             nextyear.setFullYear( nextyear.getFullYear() + 1 );
             text += "; expires=" + nextyear.toGMTString();
             document.cookie = text;
          } catch( ex ) {
             alert( ex );
             debugLog( "orpForms.saveORPPARMS:  exception: " + ex );
          }
          debugLog( "orpForms.saveORPPARMS:  cookie = " + text );
      }
      else
          debugLog( "orpForms.saveORPPARMS:  saving parameters NOT requested." );
      debugLog( "orpForms.saveORPParms making small window for solution results." ); 
      try {
          document.ORPform.target = makeWin();    // In smallWindow:  pre-open results window.
      } catch( ex1 ) {
          alert( ex1 );
          debugLog( "orpForms.saveORPParms - error opening results window:  " + ex1 );
      }
      debugLog( "orpForms.saveORPParms exited." );
   }                //  ### saveORPParms 

// restoreParms:  Get the parameters from a cookie and restore them in the screen
// the ORP cookie is of the form:
//   ORParms=name~value:name~value:...:; 
   function restoreParms()
   {
       ORPid = "ORParms=";
 //      document.domain = 'i-orp.com';			// Domain common to IIS1.
       debugLog( "restoreParms entered:  domain = " + document.domain + "  ORPid = " + ORPid );
       var memory = document.cookie;			// All cookies for this document
       debugLog( "restoreParms Cookie = '" + memory + "'" );
       debugLog( 'restoreParm - vdlProgDefault = ' + vdlProgDefault );

       var pos = memory.indexOf( ORPid );    	      // ORP cookie begins here.
       if( pos < 0 )
       {
          document.ORPform.elements[ 'vdlProg' ].value = vdlProgDefault;
          debugLog( "restoreParms:  No cookie to process for " + ORPid );
          return;						// No ORP cookie present.
       }
       pos += ORPid.length;				// Start of ORP's cookie value
       var end = memory.indexOf( ";", pos );		// End of ORP's cookie
       if( end < 0 )
          end = memory.length;
       var values = memory.substring( pos, end );	// ORP cookie string

       debugLog( 'restoreParms - values = ' + values );
       
       resetParms();

       var last = 0;
       var formsX = -1;
       for( var h = 0; (last = values.indexOf( ":", h )) >= 0 && h < last; h = last + 1 )
       {
          var first = values.indexOf( "~", h );

          if( first < 0 )
          {  
              debugLog( "restoreParms:  no ~ seperator at h = " + h );
              break;
          }
          var id = values.substring( h, first );
                         // Search for this name in the form.
          for( ++formsX; formsX < document.ORPform.elements.length && ((document.ORPform.elements[formsX].type == "hidden" ||
               document.ORPform.elements[formsX].type == "text") ? document.ORPform.elements[formsX].name != id :
                    document.ORPform.elements[formsX].value != id); formsX++ ) {}

          var value = values.substring( first+1, last );

          if( formsX >= document.ORPform.elements.length )
          {
             debugLog( "restoreParms:  name = " + id + " not in form " );
             continue;
          }
          debugLog( 'restoreParms, resetting field ' + formsX +
              ' type ' + document.ORPform.elements[formsX].type + ' to ' + value );
          if( document.ORPform.elements[formsX].type == "radio" )
          {
             var i4 = 0;
             for( i4 = 0; i4 < document.ORPform.calcmode.length && document.ORPform.calcmode[i4].value != value; i4++ ){}
             if( i4 < document.ORPform.calcmode.length )
                document.ORPform.calcmode[i4].checked = true;
          }
          else if( document.ORPform.elements[formsX].type == "checkbox" )
             document.ORPform.elements[formsX].checked = true;
          else if( document.ORPform.elements[formsX].type == "text" )
             document.ORPform.elements[formsX].value = value;  
       }
       debugLog( 'restoreParms, vdlProgDefault = ' + vdlProgDefault );
                // Constant hidden values for 1 run only hidden parameters.
       document.ORPform.elements[ 'vdlProg' ].value = vdlProgDefault;
       document.ORPform.elements[ 'cname' ].value = "";
       debugLog( "restoreParms exited." );
   }			// ### restoreParms()

//  This section contains variables and software having to do with displaying the scenario summaries and are located in orpPform.html
var _memArray = new Array(); 			// Scenario Memory

function Xmemory( _window, _form )			// Add summary results from a form to the summary array
{
   debugLog( "Entered orpformS.Xmemory:  " + _form.elements[0].name + " = " + _form.elements[0].value );
   var a = new Array( _form.length + 1 );
   a[0] = _window;				// This is the window containing the report.
   for( var k = 0; k < _form.length; k++ )
       a[k+1] = _form.elements[k].value;		// Description and values from the form
   
   var n = _memArray.length;
   _memArray[n] = a;
   debugLog( "orpformS.Xmemory:   Stored in slot " + n + ":  " + _memArray[0][0] );
}		// ### Xmemory

// Create and display summary window, _summary. _summary shows an overview
// of all scenarios run during this session. 
// _summary is define in smallwin.js
function summary2Screen()		
{
    alert( 'orpformS.summary2screen() entered from below;  ' );
   if( _summary != null && !_summary.closed )
   {
      debugLog( "orpFromS.summary2Screen closing _summary window." );
      _summary.close();			// Start over fresh
      _summary = null;
   }
                     // Open a document in the window to display gened html doc.
   debugLog( "orpFromS.summary2Screen  _summary window:  open  " + (_summary != null) );

   var args = "width=600,height=600,resizeable=yes,scrollbars=yes";
      debugLog( window.name + ".orpFromS.summary2Screen for Netscape, args = " + args );
      _summary = window.open( "summary2Screen.html", "summary", args );
//      summary2ScreenX( _summary );		// Netscape

   debugLog( 'summary2Screen finished' );
}
function getSummary()
{
   alert( 'orpformS.getSummary returning memory to lower screen.' );
   try{ return _memArray; }
   catch( exgs ) {
      alert('orpformS.getSummary failed on return  ' + exgs );
   }
}
function getMemLength()
{
   alert( 'orpformS.getLength returning length ' + _memArray.length + ' to lower screen.' );
   try{ return _memArray.length; }
   catch( exgx ) {
      alert('orpformS.getLength failed on return  ' + exgx );
   }
}
 

// Netscape allows you to open a window and write into., which is how we create the
// summary file here.  Microsoft does not allow touching a window after window has 
// opened it.  Therefore, the window is loaded off up disk and generated internally.
function summary2ScreenX( _summary )		
{
   debugLog( "orpformS.summary2ScreenX entered 1st time"  );
   var headX = [ '<HTML><HEAD><TITLE>ORP Scenario Summary</TITLE>\n',
                 '</HEAD><BODY BGCOLOR=F7E8F7 onLoad="document.domain=\'i-orp.com\';">\n',
                 '<CENTER><H1><FONT COLOR="#800000">ORP Scenario Summary</FONT></H1>\n',
                 '<TABLE border=0 cellspacing=0 cellpadding=5><TR><TH>Scenario\n',
              // '<TH>Parameter<TH>Parameter\n',
                 '<TH>Spending<TH>Value At<BR>Retirement<TH>Total<BR>Value</TR>\n' ];

    var tail1 = ["</TABLE><P>",
                 '<TABLE><TR>\n', 
                 '<TD ALIGN="LEFT"><A HREF="Javascript:OnClick=window.print()" >Print</A> this report.\n',
                 '<TD ALIGN="CENTER"><A HREF="Javascript:OnClick=window.opener.summary2Screen(); debugLog(\'returned to Summary\');">',
                         'Refresh</A> this display.\n',
                 '<TD ALIGN="RIGHT"><A HREF="Javascript:OnClick=window.opener._scenarioMenu();" >',
                         'What-if</A> scenario menu.',
                 '<TD ALIGN="RIGHT"><A HREF="Javascript:OnClick=window.opener.focus();" >',
                         'Back</A> to Parameter Screen',
                 '</TR></TABLE>\n',
                 '<P><FONT SIZE=-1>&copy; 2000-2007, James S. Welch, Jr.</FONT></CENTER>\n',
                 '</BODY></HTML>\n'];

   debugLog( "orpFromS.summary2ScreenX  _summary window:  " + (_summary != null)) ;
                     // Open a document in the window to display gened html doc.
   debugLog( "orpFromS.summary2ScreenX  _summary window:  open  " + (_summary != null) );
   
   try{ _summary.document.open( "text/html" ); }
   catch( excpq ) {
       alert( 'orpformS.summary2Screen, document.open  ' + excpq );
   }

   debugLog( "orpFromS.summary2ScreenX  _summary window:  memArray # elements = " + _memArray.length );

   for( var i1 = 0; i1 < headX.length; i1++ )     //  Titling and start of display table. 
   {  
      try{ _summary.document.write( headX[i1] ); }
      catch( excpt ) {
         alert( 'orpformS.summary2ScreenX, write headX  ' + excpt );
      }
   }     
   debugLog( "orpFromS.summary2ScreenX:  header written, lines = " + headX.length );

   for( var i2 = 0; i2 < _memArray.length; i2++ )
   {
       if( _memArray[i2][0] != null && !_memArray[i2][0].closed )
       {
      	    debugLog( "orpFromS.summary2ScreenX:  Starting row " + i2 + "  length " + _memArray[i2].length );
          _summary.document.write( '<TR><TD ALIGN="left">' + '<A HREF="Javascript:OnClick=window.opener._sicm(\'' + i2 + '\' )">' + 
              _memArray[i2][1] + '</A>' );
          for( var j = 2; j < _memArray[i2].length; j++ )
          {  _summary.document.write( '<TD ALIGN="right">' + _memArray[i2][j] + '\n' ); }
          _summary.document.write( "</TR>\n" );
      }
   } 
   debugLog( "orpFromS.summary2ScreenX:  body written, lines = " + _memArray.length );

   for( var i3 = 0; i3 < tail1.length; i3++ )   // End display table, and end of html document
   {   _summary.document.write( tail1[i3] ); }

   _summary.document.close();
   _summary.focus();
   debugLog( "orpformS.summary2ScreenX exited."  );
}               // ### summary2ScreenX()
 
// Send focus to the ith report window.
function _sicm( h )
{
    if( h >= _memArray.length )
    {   debugLog( "orpformS._sicm:  illegal index onto _memArray - " + h ); }
    else if( _memArray[h].closed )
    {   debugLog( "orpformS._sicm: window is closed for h = ", h ); }
    else
    {  _memArray[h][0].focus(); }
}

// Functions used by scenario summary screen and results screen to open orpScenarios.html.
// _scenario is defined in smallwin.js
function scenarioChoices()
{
// alert( 'scenarioChoices from URL = ' + window.URL );
   debugLog( "orpformS.scenarioChoices entered from URL = " + window.opener.URL  );
   if( _scenario != null && !_scenario.closed )
   {
      _scenario.focus();
      debugLog( 'scenarioChoices - window already up' );
      return;
   }
   _scenario = window.open( 'orpScenarios.html', 'ORP_Scenario_Menu', 
                            'width=600,height=600,resizable=yes,scrollbars=yes' );
   if( navigator.appName.indexOf( "Microsoft" ) == -1 )   
      _scenario.focus();
   debugLog( "scenarioChoices exited."  );
}

// Return the value for the named input parameter in orpPform.html.
function _getInputValue( _name )
{
    debugLog( window.name + "._getInputValue:  " + _name + " = " + document.ORPform.elements[ _name ].value );
    if( document.ORPform.elements[ _name ].type == "checkbox" )
       return document.ORPform.elements[ _name ].checked;
    else
       return document.ORPform.elements[ _name ].value;
}


// Set the value of the input parameter in orpPform.html from the given input item, of the same name.
function _setInputValue( _item )
{
   debugLog( window.name + "._setInputValue:  " + typeof( _item ) + "  " + _item );
    if( document.ORPform.elements[ _item._name ].type == "checkbox" )
       document.ORPform.elements[ _item._name ].checked = _item.checked;
    else
       document.ORPform.elements[ _item.name ].value = _item.value;
}

// Clear a form cell so that its default value will be used.
function _clearInputValue( _name )
{
   if( _name == 'vdlProg' )
      document.ORPform.elements[ _name ].value = vdlProgDefault;
   else
      document.ORPform.elements[ _name ].value = '';
}

// Method for orpScenarios.html to run the current parameter form in orpPform.html.
function _runForm( _describeS )
{  
   debugLog( "orpFormS._runForm entered:  _describe = " + _describeS  );
   document.ORPform.describe.value = _describeS;
   document.ORPform.target = makeWin();    // In smallWindow:  pre-open results window.
   document.ORPform.submit();
   debugLog( "orpFormS._runForm exited."  );
}

function _launch( _urlS, _nameS, _argsS )
{
   debugLog( "orpFormS._launch:  opening " + _nameS + "  at " + _urlS );
   var subWin = window.open( _urlS, _nameS, _argsS );
   if( navigator.appName.indexOf( "Microsoft" ) == -1 )   
      debugLog( "orpFormS._launch:  end open " + subWin.name );
   else
      debugLog( "orpFormS._launch:  end open " );
   return subWin;
}
//-->
