#!/usr/local/bin/perl -I/home/users/dberansky/perl/lib

use CGI;
use CGI::Carp;

$NAV_FILE = "navigation.dat";

initNavTable();
initFormTable();
initFieldTable();

$data = new CGI;

#print $data->header;

if( !$data->param("action") )
{
   showMainScreen();
}
else
{
   $result = verifyInput();
   if( $result == 0 )
   {
      dispatchCall();
   }
   else
   {
      showError( $result );
   }
}

sub initFormTable
{
   $FORM_TABLE{'general_info'} = [
              'f_name','l_name','email','show_email',
              'curr_city','curr_state','curr_country', 'num_cities' 
              ];
   $FORM_TABLE{'city_info'} = [ 'city_name_$num_cities$',
              'hasSchoolInfo_$num_cities$','hasVuzInfo_$num_cities$',
              'hasWorkInfo_$num_cities$','hasResidenceInfo_$num_cities$',
              'num_schools_$num_cities$','num_vuzs_$num_cities$',
              'num_works_$num_cities$','num_residences_$num_cities$',
              ];
   $FORM_TABLE{'school_info'} = [ 
              'school_name','school_num',
              'schoolfrom','schoolto' 
              ];
   $FORM_TABLE{'vuz_info'} = [ 
              'vuz_name','vuz_num',
              'vuzfrom','vuzto' 
              ];
   $FORM_TABLE{'work_info'} = [ 
              'work_name','work_num',
              'workfrom','workto' 
              ];
   $FORM_TABLE{'residence_info'} = [ 
              'residence_name','residence_num',
              'residencefrom','residenceto' 
              ];
}

sub initFieldTable
{
    $FIELD_TABLE{'f_name'} = 
   +{
          'title' => 'First Name',
          'type' => 'String',
          'required' => 'yes',
    }; 

    $FIELD_TABLE{'l_name'} = 
   +{
          'title' => 'Last Name',
          'type' => 'String',
          'required' => 'yes',
    };

    $FIELD_TABLE{'email'} = 
   +{
          'title' => 'E-Mail',
          'type' => 'email',
          'required' => 'yes',
    }; 

    $FIELD_TABLE{'num_cities'} = 
   +{
          'title' => 'Number of Cities',
          'type' => 'integer',
          'required' => 'yes',
    }; 

    $FIELD_TABLE{'city_name'} = 
   +{
          'title' => 'City Name',
          'type' => 'String',
          'required' => 'yes',
    }; 
}

sub storeState
{
   local( $frameName, @fields, *fieldName, $val, $suf, $i );

   print "\n";
   foreach $frameName (keys(%FORM_TABLE))
   {
      foreach $fieldName (@{$FORM_TABLE{$frameName}})
      {
         $val = $data->param($fieldName);
         if( $fieldName =~ /.*\$.*/ )
         {
            $fieldName =~ /(.+)(_\$.+\$)+/;
            @fieldName = ($1);
            $suf = $2;
            while( $suf =~ /_\$(.+)\$(.*)/ )
            {
               $suf = $2;
               foreach $field (@fieldName)
               {
                  local($val, $var);

                  $var = '$data->param('.$1.')'; 
                  $val = eval($var);
                  for( $i=1;$i<=$val;$i++ )
                  {
                     local( $newFieldName ) = $field."_".$i;

                     print "<!--STATE: ($frameName.$newFieldName)-->";
                     print $data->hidden($newFieldName);
                     print "\n";
                  }
               }
            }
         }
         else
         {
            print "<!--STATE: ($frameName.$fieldName)-->";
            print $data->hidden( $fieldName);
            print "\n";
         }
      }
   }
}

sub initNavTable
{
   local( @temp, $i );

   open( NAV, $NAV_FILE ) || die "Can't open $NAV_FILE\n";

   while( <NAV> )
   {
      chop;
      $temp[++$#temp] = $_; 
   }

   for( $i=0; $i<=$#temp; $i++ )
   {
      $NAV_TABLE{$temp[$i],"prev"} = $temp[$i-1];
      $NAV_TABLE{$temp[$i],"next"} = $temp[$i+1];
   }
}

sub dispatchCall
{
   local( $nextScreen );

   if( $data->param("action") eq "Next >>" )
   {
      $nextScreen = getScreen( "next", $data->param("form_name") );
   }
   elsif( $data->param("action") eq "<< Previous" )
   {
      $nextScreen = getScreen( "prev", $data->param("form_name") );
   }
   else
   {
      $nextScreen = $data->param("action");
   }

   if( $nextScreen eq "city_info" )
   {
      showCityInfoScreen();
   }
   elsif( $nextScreen eq "school_info" )
   {
      showSchoolInfoScreen( $data->param($lastCity)+1 );
   }
   elsif( $nextScreen eq "vuz_info" )
   {
      showVuzInfoScreen( $data->param($lastCity)+1 );
   }
   else
   {
      showMainScreen();
   }
}

sub verifyInput
{
   local( @fields, $hasErrors, $result );

   @fields = getFieldList( $data->param('form_name') );

   foreach $field (@fields)
   {
      if( $result = verifyField( $field ) )
      {
         if (!$hasErrors) 
         {
            print $data->header;
            print $data->start_html(-title=>'Error in Input!');
         }
         print "$result<BR>\n";

         $hasErrors = $hasErrors + 1;
      } 
   }

   return $hasErrors;
}

sub verifyField
{
   local( $fieldName ) = @_;

   $fieldName =~ /(.+)(_\$.+\$)+/;
   $fieldStem = $1;

   if( $FIELD_TABLE{$fieldStem}{'required'} && !$data->param($fieldName) )
   {
      return "'".$FIELD_TABLE{$fieldStem}{'title'}."' can't be empty";
   }
   else
   {
      return "";
   }
}
sub showError
{
   local( $error ) = @_;
} 

sub getScreen
{
   local( $nav, $currentScreen ) = @_;

   return $NAV_TABLE{$currentScreen,$nav};
} 

sub getFieldList
{
   local( $form_name, @temp ) = @_;

   $temp = $FORM_TABLE{$form_name};

   return @$temp;
}

sub showMainScreen
{
   print $data->header;
   print $data->start_html( -title=>'Registry: Add', 
                            -author=>'Dmitry Beransky (dberansky@ucsd.edu)'
                          );
   print $data->h1("General Info");

   print $data->startform( -name=>'add to registry',
                           -method=>'GET',
              -action=> 'http://www-biology.ucsd.edu:443/beransky-cgi/add.pl');

#   print $data->hidden( "form_name", "general_info" );
   print "<INPUT TYPE=\"hidden\" NAME=\"form_name\" VALUE=\"general_info\">\n";

   storeState();

   print $data->p; print "\n";
   print "*First Name: ";
   $val = $data->param('f_name');
   print $data->textfield( 'f_name', $val, 30, 50 );
   print "<BR>\n";

   print "*Last Name: ";
   $val = $data->param('l_name');
   print $data->textfield( 'l_name', $val, 30, 50 );
   print "<BR>\n";

   print "*E-Mail: ";
   $val = $data->param('email');
   print $data->textfield( 'email', $val, 30, 50 );

   print " ";
   $val = $data->param('show_email');
   print $data->checkbox('show_email',$val,'on'," Don't Disclose");
   print $data->p; print "\n";

   print "<B>Current Residence:</B>\n";
   print "<BLOCKQUOTE>\n"; print "\n";

   print "City: ";
   $val = $data->param('curr_city');
   print $data->textfield( 'curr_city', $val, 30, 50 );
   print $data->br; print "\n";

   print "State/Province: ";
   $val = $data->param('curr_state');
   print $data->textfield( 'curr_state', $val, 30, 50 );
   print $data->br; print "\n";

   print "Country: ";
   $val = $data->param('curr_country');
   print $data->textfield( 'curr_country', $val, 30, 50 );
   print $data->br; print "\n";

   print "</BLOCKQUOTE>\n";
   print $data->br;

   print $data->reset("Clear" );
   print $data->submit( "action", "Subscribe" );

   print $data->endform;

   print $data->end_html;

}

sub showCityInfoScreen
{
   local( $i );

   print $data->header;
   print $data->start_html( -title=>'Registry: Add', 
                            -author=>'Dmitry Beransky (dberansky@ucsd.edu)'
                          );

   print $data->h1("City Info");

   print $data->startform( -name=>'add to registry',
                           -method=>'GET',
              -action=> 'http://www-biology.ucsd.edu:443/beransky-cgi/add.pl');

   print "<INPUT TYPE=\"hidden\" NAME=\"form_name\" VALUE=\"city_info\">\n";
   storeState();

   print $data->p;

   for( $i=1; $i<=$data->param("num_cities"); $i++ )
   {
      print "*City Name: ";
      print $data->textfield( "city_name_$i", '', 30, 50 );
      print $data->p;

      print "<B>Resources</B>\n";
      print "<BLOCKQUOTE>\n";
         print "<TABLE BORDER=0>\n";
         print "<TR>\n";
         print "<TH></TH><TH>Type</TH><TH>Quantity</TH>\n";
         print "</TR>\n";
     
         print "<TR>\n";
         print "<TD>".$data->checkbox("has_school_info_$i",'checked','true','')."</TD>";
         print "<TD>Schools</TD>\n";
         print "<TD>".$data->textfield("num_schools_$i",'1',3,2,)."</TD>";
         print "</TR>\n";
          
         print "<TR>\n";
         print "<TD>".$data->checkbox("has_vuz_info_$i",'checked','true','')."</TD>";
         print "<TD>Institutes/<BR>Universities</TD>\n";
         print "<TD>".$data->textfield("num_vuzs_$i",'1',3,2,)."</TD>";
         print "</TR>\n";
          
         print "<TR>\n";
         print "<TD>".$data->checkbox("has_work_info_$i",'checked','true','')."</TD>";
         print "<TD>Organizations</TD>\n";
         print "<TD>".$data->textfield("num_works_$i",'1',3,2,)."</TD>";
         print "</TR>\n";
          
         print "<TR>\n";
         print "<TD>".$data->checkbox("has_residence_info_$i",'checked','true','')."</TD>";
         print "<TD>Places of residence</TD>\n";
         print "<TD>".$data->textfield("num_residences_$i",'1',3,2,)."</TD>";
         print "</TR>\n";
         
         print "</TABLE>\n";
     print "</BLOCKQUOTE>\n";
   } 

   print $data->p;
   print $data->reset("Clear" );
   print $data->submit( "action", "<< Previous" );
   print $data->submit( "action", "Next >>" );


   print $data->endform();

   print $data->end_html;
}

sub showSchoolInfoScreen
{
   local( $city ) = @_;

   print $data->header;
   print $data->start_html( -title=>'Registry: Add', 
                            -author=>'Dmitry Beransky (dberansky@ucsd.edu)'
                          );

   print $data->h1( "School Info (for ".$data->param( "city_name_$city" ).")");
   print $data->startform( -name=>'add to registry',
                           -method=>'GET',
              -action=> 'http://www-biology.ucsd.edu:443/beransky-cgi/add.pl');

   print "<INPUT TYPE=\"hidden\" NAME=\"form_name\" VALUE=\"school_info\">\n";
   storeState();

   print "<INPUT TYPE=\"hidden\" NAME=\"city_num\" VALUE=\"$city\">\n";
   print $data->p;

   print "<TABLE BORDER=1>\n";
   print "<TR>\n";
   print "<TH ROWSPAN=2>School #</TH>\n";
   print "<TH ROWSPAN=2>School Name</TH>\n";
   print "<TH COLSPAN=2>Years Attended</TH>\n";
   print "</TR>\n";
   print "<TR><TH>From</TH><TH>To</TH>\n";
   
   for( $i=1; $i<=$data->param("num_schools_$city"); $i++ )
   {
      print "<TR>\n";
      print "<TD ALIGN=\"Center\">\n";
      print $data->textfield("schoolnum_$city"."_$i", '', 3, 3 );
      print "</TD><TD ALIGN=\"Center\">\n";
      print $data->textfield("schoolname_$city"."_$i", '', 15, 30 );
      print "</TD><TD ALIGN=\"Center\">\n";
      print $data->textfield("schoolfrom_$city"."_$i", '', 4, 4 );
      print "</TD><TD ALIGN=\"Center\">\n";
      print $data->textfield("schoolto_$city"."_$i", '', 4, 4 );
      print "</TD>\n"
   }
   print "</TABLE>\n";

   print $data->p;
   print $data->reset("Clear" );
   print $data->submit( "action", "<< Previous" );
   print $data->submit( "action", "Next >>" );

   print $data->endform;
  
   print $data->end_html;
}

sub showVuzInfoScreen
{
   local( $city ) = @_;

   print $data->header;
   print $data->start_html( -title=>'Registry: Add', 
                            -author=>'Dmitry Beransky (dberansky@ucsd.edu)'
                          );

   print $data->h1( "University/Institute(VUZ) Info (for ".$data->param( "city_name_$city" ).")");
   print $data->startform( -name=>'add to registry',
                           -method=>'GET',
              -action=> 'http://www-biology.ucsd.edu:443/beransky-cgi/add.pl');

#   print $data->hidden( 'form_name', "vuz_info_$city" );
   print "<INPUT TYPE=\"hidden\" NAME=\"form_name\" VALUE=\"vuz_info\">\n";
   storeState();

   print "<INPUT TYPE=\"hidden\" NAME=\"city_num\" VALUE=\"$city\">\n";
   print $data->p;

   print "<TABLE BORDER=1>\n";
   print "<TR>\n";
   print "<TH ROWSPAN=2>VUZ Name</TH>\n";
   print "<TH COLSPAN=2>Years Attended</TH>\n";
   print "</TR>\n";
   print "<TR><TH>From</TH><TH>To</TH>\n";
   
   for( $i=1; $i<=$data->param("num_vuzs_$city"); $i++ )
   {
      print "<TR>\n";
      print "<TD ALIGN=\"Center\">\n";
      print $data->textfield("vuzname_$city"."_$i", '', 15, 30 );
      print "</TD><TD ALIGN=\"Center\">\n";
      print $data->textfield("vuzfrom_$city"."_$i", '', 4, 4 );
      print "</TD><TD ALIGN=\"Center\">\n";
      print $data->textfield("vuzto_$city"."_$i", '', 4, 4 );
      print "</TD>\n"
   }
   print "</TABLE>\n";

   print $data->p;
   print $data->reset("Clear" );
   print $data->submit( "action", "<< Previous" );
   print $data->submit( "action", "Next >>" );

   print $data->endform;
  
   print $data->end_html;
}
