#!/usr/local/bin/perl
use lib '/home/users/dberansky/perl/lib';
use CGI;

$data = new CGI;

print $data->header;

$form_step = $data->param('step');

processMain( $data) if ($form_step =~ /main/);
processInterm( $data) if ($form_step =~ /intermediate/);
processOptional( $data) if ($form_step =~ /optional/);

sub processMain
{
   my($data) = @_;

   print $data->p();
   @paramNames = $data->param();

   foreach $param (@paramNames)
   {
         $fieldInfo = new CGI($param);
         $value =  $data->param($param);
         print $fieldInfo->param(name).": $value";

         if( $fieldInfo->param(required) =~ /true/ )
         {
            print " (Error: must specify a value)" unless $value =~ /\S+/; 
         }
         
         $fieldType = $fieldInfo->param(type);
         if( $fieldType )
         {
            if( !isValid( $value, $fieldType ) )
            {
               print " (Error: invalid value; must be of type $fieldType)";
            }
         }
         print $data->br();
   }      
}

sub processInterm 
{
   my($data) = @_;

   print $data->h1("Processing intermediate" );
   print $data->p;
   print $data->dump;
}

sub  processOptional
{
   my($data) = @_;

   print $data->h1("Processing optional" );
   print $data->p;
   print $data->dump;
}

sub isValid
{
   my($value, $type) = @_;

   return $value =~ /[a-zA-Z]+/ if( $type =~ alpha );
   return $value =~ /\d+/ if( $type =~ numeric );
   return $value =~ /\w+/ if( $type =~ alphanumeric );
   return 1 if( $type =~ email );
   print " $type: unknown type";
}

   
