#!/usr/bin/perl
package CommunityAnnotation;
use strict;

######################################################################
# Author: Stan Dong
# Date:   January, 2003
# Comment: Contains all necessary methods for an on-line community
#          annotation form
######################################################################

use DBI;
use CGI qw/:all :html3/;
use CGI::Carp qw(fatalsToBrowser);
use lib "/usr/local/dicty/www_dictybase/db/lib/common";
use Login qw (ConnectToDatabase);
use TextUtil qw (DeleteUnwantedChar);
use lib "/usr/local/dicty/www_dictybase/db/lib/dictyBase";
use dictyBaseObject;
use dictyBaseCentralMod qw (:formatPage :navigateInfo :getInfo);
use lib "/usr/local/dicty/www_dictybase/db/lib/dictyBase/Objects";
use ConfigURLdictyBase;
use ConfigPathdictyBase;
use Colleague;
use Reference;

$| = 1;

######################################################################
# Class Globals
######################################################################

my $dbh;
my $db;
my $db1;
my $seperator;

if (!(user_agent() =~/Mac/i)) { # if it's not MAC IE
    $seperator = br; # need a seperator
}

my $configUrl = ConfigURLdictyBase->new;
my $dblink;
my $title;

my $configPath = ConfigPathdictyBase->new;

my $tempdir;

#temp file to store submitted data before confirmation
my $tmpfile;

#DataFile to store community annotation data
my ($min, $hour, $month, $day, $year)=(localtime())[1,2,4,3,5];
$year += 1900;

#the localtime function somehow returns last month
$month += 1;
if ($month < 10) {
    $month = '0'. $month;
}
if ($day < 10) {
    $day = '0' . $day;
}

#my $version;
my $anchorUrl;
my $dateStamp = $year. $month . $day . $hour . $min;
my $annotationFile;
my $SelfUrl;
my $getForm; #which GetForm button is pushed
my $fullSrh;

my $width = "90%";
my $DelBoxLabel;
if (param('EditConfirm')) {
    $width = "60%";
}

######################################################################
sub new {
######################################################################

    my ($self, %args) = @_;

    $self = {};

    bless $self;

    $self->{'_help'}     = $args{'help'};
    $self->{'_database'} = $args{'database'};

    $dbh = &ConnectToDatabase($self->database);
    $dblink = $configUrl->dblink($self->database);

    if ($args{'database'} eq 'dictyBase') {
        $db = 'dictyBase';
        $db1 = 'dictyBase';
#        $version = '';
    }
    else {
        $db = 'dictyBaseDEV';
        $db1 = 'SDEV';
#        $version = 'DEV';
    }
 
    $tempdir = $configPath->dataDir4web ."submission/community/$db1/";
    $annotationFile = $tempdir . "annotationSet.$dateStamp.$$";
    $anchorUrl = "'". $configUrl->dictyBaseCGIRoot . $db ."/communityAnnotation';"; 
    $SelfUrl = $configUrl->dictyBaseCGIRoot . $db ."/communityAnnotation";
    $DelBoxLabel = 'Delete this Research Highlight.';
    $fullSrh = "http://www.Dictyosteliumgenome.org/SearchContents.shtml";

    if (param('file')) {
	$tmpfile = param('file');
    }
    else {
	$tmpfile = $tempdir . "temp/communityAnnotation.$dateStamp.$$";
    }

    return $self;
}

sub database { $_[0]->{_database} }
sub help { $_[0]->{_help} }

######################################################################
sub DESTROY {   ############ destructor ##############################
######################################################################
    if (defined $dbh) {
        $dbh->disconnect;
    }
    exit;
}

######################################################################
sub print {
######################################################################
    my ($self) = @_;

    foreach my $eachItem (param()) {
        if ($eachItem =~ /^GetForm_(.*)$/) {
            $getForm = $1;
            last;
        }
    }

    if (param('EditConfirm')) {
#       $self->showparameters;
         $self->EditConfirm;
    }
    elsif (param('AfterFinalEdit')) {
#        $self->showparameters;
        $self->storeAnnotation;
    }
    elsif (param('change')) {
#        $self->showparameters;
        $self->changeContributor;
    }
    elsif (param('changeContributor')) {
#        $self->checkChangeContributor;
	$self->check1;
#        $self->showparameters;
    }
    elsif (param('newref') || param('Edit')) {
#        $self->showparameters;
	$self->restart1;
    }
    elsif (param('Add')) {
        $self->addColleague;
#        $self->showparameters;
    }
    elsif (param('All') || $getForm || param('OtherForm') || param('SubmitAnnotation') || param('StartOver')) {
#        $self->showparameters;
        $self->inputAll;
#        $self->showparameters;
    }
    elsif (param('lnameSearch') && param('pubmed')) {
#        $self->showparameters;
        $self->check1;
    }
    else {
#        $self->showparameters;
        if (param('colleagueid') || param('lname')) {
            my $errmssg = "You are required to click the appropriate submit button after completing your annotation. Please use the BACK button to go back and submit again. Thanks!";
            $self->err_report($errmssg);
        }
        else {
	    $self->StartForm;
        }
    }
    $self->DESTROY;
}

#######################################################################
sub StartForm {
#######################################################################
    my ($self) = @_;

    $title = "Community Annotation: Research Highlights". br."Specify Contributor and Reference";

    my $rows = $self->startTable;
    &printStartPage($self->database, $title, $self->help);

    print p, start_form;
    
    #pass emailReply parameter, which indicates the source of this
    #annotation is the result of a email we sent to the author earlier
    print hidden('emailReply', param('emailReply')) if (defined param('emailReply'));

    print $self->startMssg,
          table({-cellpadding=>'4', -cellspace=>'3', -border=>'0', -width=>'100%'}, $rows), end_form;

    &printEndPage;
    return;
}

#######################################################################
sub startTable {
####################################################################### 
    my ($self, $changContributor) = @_;

    my $row =
	Tr({-bgcolor=>"#a4abc2"},
          th({-align=>"left"}, font({-size=>'+1'}, "Contributor Submission"))
        ).
	Tr(td(b(u("All Research Highlights must be associated with a contributor.")). " The contributor's name will be publicly associated with the Research Highlight.". br. br. "Please enter your ". b("LAST name").  " into the box provided below, then continue on to the reference submission section."
        )).
	Tr(td({-valign=>"top"},
	   table({-cellpadding=>"4", -cellspacing=>"3", -border=>"0"},
             Tr(th({-bgcolor=>"#b7d8e4", -align=>'left'}, "Last (family) Name:"),
                td(textfield(-name=>'lnameSearch', -size=>'20') . " (" . i("e.g.") . "Chisholm, Jones, Smith)")
        )))) .
        Tr(td(br)).
        Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Reference Submission"))).
        Tr(td(b(u("All Research Highlights must be referenced.")). " The reference citation will be displayed alongside the research highlight.". br. br. "Specify the publication that you are citing by entering the ". b("PubMed ID"). " into the box provided below and then hit the \"Submit\" button, below. The PubMed ID can be found at the bottom of a publication's PubMed entry and is labeled \"PMID:\". If the publication that you wish to cite is not listed in PubMed, please contact dictyBase using the \"Send a message..\" link at the bottom of this page."
        )).
	Tr(td({-valign=>"top"},
	   table({-cellpadding=>"4", -cellspacing=>"3", -border=>"0"},
             Tr(th({-bgcolor=>"#b7d8e4", -align=>"left"}, "PubMed ID:"),
                td(textfield(-name=>"pubmed", -size=>"20"))
             ). 
             Tr(td({-colspan=>'2'}, a({-href=>"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi", -target=>'searchPubmed'}, "Search PubMed")))
           )
        )).
	Tr(td(br)).
        Tr(td(submit('Submit', 'Submit'), reset
        ));
    return $row;
}  

#######################################################################
sub check1 {
#######################################################################
    my ($self) = @_;
    my $search = param('lnameSearch');
    my $pubmedId = param('pubmed');

    if (!$search || !($search =~ /\w/) || !$pubmedId) {
        $self->err_report("You forgot to enter a query. Please go back and try again.");
    } 

    #check if a pubmedid in our DB    
    my $refObj = Reference->new(dbh=>$dbh, pubmed=>$pubmedId);

    if (!$refObj) {
	my $mssg = "Your PMID could not be processed. Either the PMID was entered incorrectly or this paper is not currently in our database. Please go back and re-enter the PMID. If you receive this message a second time, please report the problem to the dictyBase curators using the \"send a message\" form at the bottom of the page. Please include the PMID in your message.";
        $self->err_report($mssg);
    }
    

    my $result = $self->colleagueList($search);
    $title = "Community Annotation: Research Highlights". br."Confirm Contributor and Reference";

    my $formatedCitation = $self->formatedCitation($pubmedId);

    my $javascript =  "
      <SCRIPT language=\"JavaScript\"> 
      <!--
         function subAdd() { 
            document.check1.Add.value = 'Add';
            document.check1.All.value = '';
//            alert(document.check1.Add.value);
            document.check1.submit(); 
         } 
      //--> 
      </SCRIPT> "
    ;

    &printStartPage($self->database, $title, $self->help);

    print $javascript;

    print start_form({-method=>'POST', -name=>'check1'});
    print hidden('Add', "");
    print hidden('All', 'Submit');
    print hidden('pubmed', $pubmedId);
    print hidden('emailReply', param('emailReply')) if (defined param('emailReply'));

    print blockquote("Confirm the Contributor and reference information that you have submitted.");
    print table({-width=>'100%', -cellpadding=>'4', -cellspacing=>'3', -border=>'0'},      
	    Tr(td({-align=>'left', -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, b("Contributor Confirmation")))) . "\n" .
            Tr(td("Please choose your name from the table below. If your contact information is incorrect, click ".b("EDIT")." to open a new window and update your dictyBase colleague entry. After completing your update, select your name from the table below (your updated information will be added to dictyBase within 1-2 business days).")) ."\n"                        
	  ) .p;
    print blockquote($result) . br . p ."\n";
    print font({-color=>'red'}, b("If your name is not found in the table:")) . br;
    #the button name is 'Ad' to keep it different from the hidden field 'Add'
    print blockquote(button({-name=>'Ad', -value=>'Add', -onClick=>"subAdd();"}) . " - Click here to add minimal information about yourself to dictyBase's colleague database.") .p ."\n";

    print table({-width=>'100%', -cellpadding=>'4', -cellspacing=>'3', -border=>'0'},      
	    Tr(td({-align=>'left', -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, b("Reference Confirmation")))) . "\n" .
            Tr(td($formatedCitation))
	  ) .p;

    print blockquote(submit('Edit', 'Edit') . " - If the reference information is incorrect, click here to edit it.") , p;

    print "If all the above information is correct, please click here: ". submit('All', 'Submit');

    print end_form;
    &printEndPage;
    return;
}

#######################################################################
sub colleagueList {
#######################################################################
    my ($self, $name) = @_;
    my @colleagueNo;
    my $lastname;
    my $appendwildcard = 0;
    &DeleteUnwantedChar(\$name);
    $name =~ s/\*/\%/g;
    @colleagueNo = Colleague->GetColleagueNoBYlname(dbh=>$dbh, 
						 last_name=>$name);
    if (!@colleagueNo && $name !~ /\*/) {
        $appendwildcard = 1;
	$lastname .= $name . "%";
        @colleagueNo = Colleague->GetColleagueNoBYlname(dbh=>$dbh, 
						   last_name=>$lastname);
    }
    if (!$colleagueNo[0]) {
        my $addColUrl = $configUrl->dictyBaseCGIRoot. $db ."/communityAnnotation". "?Add=yes&pubmed=" . param('pubmed');
        my $mssg = "We cannot find you in our list of colleagues. In order to submit a research highlight we require you to register with dictyBase so that your name can be used as a reference for this annotation. Only minimal information is required to register.". p .center(b(a({-href=>$addColUrl}, "Add New Colleague")));
        
	$self->err_report( $mssg );
    }

    #create radio group
    my @radio = radio_group(-name=>'choice',
                                 -value=>[@colleagueNo],
                                 -nolabels=>1);

    my $collList;
    my $count = 0;
    foreach my $id (@colleagueNo) {
	my $collObject = Colleague->new(dbh=>$dbh,
					colleague_no=>$id);
	my $lname = $collObject->last_name; 
	my $fname = $collObject->first_name;

	my $fullname = a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/colleague/colleagueSearch?id=$id"}, "${lname}, ${fname}");

	my $institution = $collObject->institution; 
	my $contact;
	my $phoneRef = $collObject->phoneRef; 
	foreach my $rowRef (@$phoneRef) { 
	    my ($phoneNum, $phoneType, $phoneLoc) = @$rowRef;
	    if ($phoneLoc =~ /unspecified/i) { $phoneLoc = ""; }
	    my $phone = $phoneLoc." ".$phoneType." : ".$phoneNum;
	    $phone =~ s/^ //;
	    if ($contact) { $contact .= br; }
	    $contact .= $phone;
	}   
	my $emailRef = $collObject->emailRef; 
	foreach my $rowRef (@$emailRef) { 
	    my ($email) = @$rowRef;
	    if ($contact) { $contact .= br; }
	    $contact .= "E-mail : ".$email; 
	}
        my $urlRef = $collObject->urlRef; 
	foreach my $rowRef (@$urlRef) { 
	    my ($url, $wwwNm, $urlType) = @$rowRef;
            if ($contact) { $contact .= br; }
	    if (!$wwwNm) {
		$wwwNm = $url;
	    }
	    if (length($wwwNm) > 60) {
		$wwwNm = a({-href=>"$url"}, substr($wwwNm, 0, 57)) . "... ";
	    }
	    else {
		$wwwNm = a({-href=>"$url"}, $wwwNm);
	    }
	    $contact .= "WWW : ". $wwwNm;
	}
	if (!$institution) { $institution = br; }
	if (!$contact) { $contact = br; }
	$collList .= Tr({-align=>'center'},
			td({-align=>'left'}, $radio[$count] . "&nbsp;&nbsp" .$fullname).
			td($institution).
			td($contact . br . br .
                           a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/colleague/colleagueUpdate?id=$id", -target=>'editCollea'}, img({-src=>$configUrl->dictyBaseImages."edit-white.gif", -border=>'0'}))));	
        $count++;
    }

    return table({-border=>'3'},
		Tr({-align=>'center'},
		   th("Name (Last, First name)").
		   th("Organization").
		   th("Contact Info")). $collList);
}

#######################################################################
sub refSection {
#######################################################################
    my ($self) = @_;
    my $pubmed = param('pubmed');

    my $rows = 
      table({-cellpadding=>'4', -width=>'100%', -cellspacing=>'3', -border=>'0'},  
        Tr(td({-colspan=>'3', -bgcolor=>"#a4abc2", -align=>"left"}, font({-size=>'+1'}, b(a({-name=>'refsub'}, "Reference Submission"))))),
        Tr(td({-colspan=>'3'}, "All Community Annotations must be referenced. Please use the following form to specify the publication that you are citing.".br.br."Enter the PubMed ID (PMID) for the paper you wish to Highlight. You can find the  PMID at the bottom of the PubMed abstract. If the PMID is not yet in dictyBase, please contact dictyBase using the 'Send a message...' link at the bottom of this page.")
        ),
	Tr(td({-valign=>"top"},
	      table({-width=>"100%", -cellpadding=>"4", -cellspacing=>"3", -border=>"0"},
                Tr(th({-bgcolor=>"#b7d8e4", -align=>"left"}, "Pubmed ID:")), 
                Tr(td(textfield({-name=>"pubmed", -size=>"20", -default=>$pubmed}))),
                Tr(td(a({-name=>'searchPB', -href=>"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi", -target=>'newPubMedSrh'}, "Search PubMed")))))
        )
      );

    return $rows;
}

#######################################################################
sub addColleague {
#######################################################################
    my ($self) = @_;

    my $pubmedId = param('pubmed');

    if (!$pubmedId) {
	$self->err_report("No PubmedId!");
    }

    $title = "Community Annotation: Research Highlights" .br. "Specify Contributor and Confirm Reference";
    my $formatedCitation = $self->formatedCitation($pubmedId);
    &printStartPage($self->database, $title, $self->help);

    print start_form({-method=>'POST'});
    print hidden('pubmed', $pubmedId);
    print hidden('emailReply', param('emailReply')) if (defined param('emailReply'));

    print blockquote("Enter minimal Contributor information below, then confirm the reference information that you have already submitted.");
    
    print
      table({-width=>"100%", -cellpadding=>"4", -cellspacing=>"3", -border=>"0"},     
        Tr(td({-colspan=>'3', -align=>"left", -width=>"100%", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, b(a({-name=>'contributor'}, "Contributor Submission"))))),
        Tr(td({-colspan=>'3'}, "All fields are required. Note that this will become your \"dictyBase Colleague Entry\" and will be publicly available.")),
        Tr(
          td({-bgcolor=>"#ACBDCC", -align=>"left"}, b("Last (family) Name")),
	  td({-align=>"left"}, textfield({-name=>"lname", -size=>"20"})),
          td({-align=>"left"}, "(" . i("e.g.") . " Chisholm, Jones, Smith)")
        ),
        Tr(
          td({-bgcolor=>"#ACBDCC", -align=>"left"}, b("First Name")),
          td({-align=>"left"}, textfield({-name=>"fname", -size=>"20"})),
          td({-align=>"left"}, "(" . i("e.g.") . " David, John Q., Linda M.)")
        ),
        Tr(
          td({-bgcolor=>"#ACBDCC", -align=>"left"}, b("E-mail")),
	  td({-align=>"left"}, textfield({-name=>"email", -size=>"30"})),
          td({-align=>"left"}, "(if more than one, separate with a space)")
        ),
        Tr(
          td({-bgcolor=>"#ACBDCC", -align=>"left"}, b("Organization")),
	  td({-align=>"left"}, textfield({-name=>"institution", -size=>"30"})),
          td({-align=>"left"}, "(" . i("e.g.") . " Stanford University, Incyte)")
        )
      ) , p;

    print table({-width=>'100%', -cellpadding=>'4', -cellspacing=>'3', -border=>'0'},      
	    Tr(td({-align=>'left', -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, b("Reference Confirmation")))) . "\n" .
            Tr(td($formatedCitation))
	  ) .p;

    print blockquote(submit('Edit', 'Edit') . " - If the reference information is incorrect, click here to edit it.") , p;
    print "If all the above information is correct, please click here: ". submit('All', 'Submit');
    print end_form;
    &printEndPage;
    $self->DESTROY;
}

#######################################################################
sub inputAll {
#######################################################################
    my ($self) = @_;

    #To GetForm, check if any required field is filled-out. If so, remind user to summit current first.
    if  ($getForm) {    #  (param('GetForm')) {
        foreach my $para (param) {
	    if ((($para =~ /^gene/) || ($para =~ /^highlight/)) && (param($para)))
	    {  $self->err_report(font({-color=>'red', -size=>'+1'}, "Please submit this highlight before choosing another form. You can also delete the current form by selecting the 'StartOver' option."));
	    }
	}
    } 

    my $colId = param('choice') || param('colleagueid');
    my $pubmed = param('pubmed');

    if (param('updateemail')) {
        my $upEmail = param('updateemail');
	&DeleteUnwantedChar(\$upEmail);
        
        if (($upEmail !~ /\@/) || ($upEmail =~/\s/) || ($upEmail =~/[!(){}]/)) {
	    $self->err_report("This email address is invalid, please go back, edit it and submit again. Thanks!");
        }
        $self->saveCollEmail($colId, $upEmail);
    }

    my ($lname, $fname, $email, $institution, $emailRef, $collObject, $newColleaInfo, $colleaInfo);
    if (!$colId) { # from add new colleague page
	#all four fields required
        $lname = param('lname');
        $fname = param('fname');
        $email = param('email');
        $institution = param('institution');

        if (!($lname && $fname && $email && $institution) && param('All')) {
	    $self->err_report("All four fields of contributor's info are required. Please go back and complete them, Thanks!");
	}
        else {
            my $check = $self->checkColleageExist;
            if ($check) {
                $colId = $check;
            }
            else {
		$newColleaInfo = $fname . ' ' . $lname .','. $email . ',' . $institution;
	    }
        }
    }
    if ($colId) {
        $collObject = Colleague->new(dbh=>$dbh, colleague_no=>$colId);
        if (!$collObject) {
            $self->err_report("Wrong Colleague Info.");
        }
        $lname = $collObject->last_name; 
        $fname = $collObject->first_name;
        $emailRef = $collObject->emailRef; 
        $institution = $collObject->institution;
        foreach my $rowRef (@$emailRef) { 
            ($email) = @$rowRef;
        }
        
        #if the colleague has no email, ask to add one to DB
        if (!$email) {
	    $self->updateCollEmail($colId, $pubmed);
	}

        $colleaInfo = $fname . ' ' . $lname .','. $email;
    }

    my ($formatedCitation, $searchRef);
    if ($pubmed) {
        $pubmed = $self->checkPubmed($pubmed);
        param('pubmed', $pubmed);  #overwrite sticky
        $formatedCitation = $self->formatedCitation($pubmed);
    }
    else {
        $self->err_report("You must enter a reference in order to submit research highlights.");
    }

    my $newref = $colId || 'yes';
    my $thisURL = $configUrl->dictyBaseCGIRoot.$db."/communityAnnotation" . "?newref=$newref&colleagueid=$colId&lname=$lname&fname=$fname&email=$email&institution=$institution";

    my $javascript =  "
      <SCRIPT language=\"JavaScript\"> 
      <!--
         function newwindow() { 
            window.open('$thisURL', 'newwin'); 
         } 

         function textCounter(field, countfield, maxlimit) {
            if (field.value.length > maxlimit)
              {field.value = field.value.substring(0, maxlimit);}
            else
              {countfield.value = maxlimit - field.value.length;}
         }
      //--> 
      </SCRIPT> "
    ;

    #validate input data. genename and description are required. validate Gene/ORF name. Description limit to 240 characters.
    if (param('SubmitAnnotation')) {
        $self->validation;
    }

    my $startMssg = "This page is used to submit \"Research Highlights\" to dictyBase. Research Highlights are concise statements describing an important fact about an ". i("S. discoideum"). " gene or protein. Research Highlights should be used to draw attention to a single fact or concept, not to summarize a publication. All appropriate Research Highlights will be publicly posted on dictyBase, in the \"Community Annotation\" section for the genes that they address, along with the name of the contributor and the publication that is being referenced.";  

    my $contributorMssg = "The following contributor and reference will be displayed alongside any Research Highlights that you contribute from this page. To change the contributor information, click on \"Change\" (note that you do not have to be an author of this work to be a contributor).";  

    $title = 'Community Annotation: Research Highlights' .br. 'Input Form';
    &printStartPage($self->database, $title, $self->help);
    print $javascript;

    print start_form({-method=>'POST'});

    print hidden('colleagueid', $colId);
    print hidden('lname', $lname);
    print hidden('fname', $fname);
    print hidden('email', $email);
    print hidden('institution', $institution);
    print hidden('newColleaInfo', $newColleaInfo);
    print hidden('colleaInfo', $colleaInfo);
    print hidden('NoRefSearch', param('NoRefSearch'));
    print hidden('emailReply', param('emailReply')) if (defined param('emailReply'));

    if (param('formatedCitation')) {
        print hidden('formatedCitation', param('formatedCitation'));
    }

    my $leftCell = 
       td({-valign=>"top"}, br. font({-size=>'+1'}, "To obtain a Research Highlight submission form" .
          ul(li("Choose a topic from one of the pull-down menus on the right."),            li("Click on the \"Get Form\" button.")
          ). br.
          b(u("Note:")). " To learn more about the Topics and Forms, click on \"List & Descriptions\"")
       );

    my $forminstruction;

    if (param('SubmitAnnotation')) {
        $self->saveSubmittedData;
        $leftCell = td({-valign=>'top'}, $self->fork);
    }
    elsif (($getForm eq 'DNA') && (param('DNA') ne '-Select-')) {
        $forminstruction = $self->DNARNAInstruction;
        $leftCell = td($self->DNARNADetailForm);
        if (param('topic')) {
	    param('topic', 'DNA & RNA Details')
        }
        if (param('category')) {
	    param('category', param('DNA'))
	}
        print hidden('topic', 'DNA & RNA Details'),
              hidden('category', param('DNA'));    
        param('DNA', '-Select-');    
    }
    elsif (($getForm eq 'Protein') && (param('Protein') ne '-Select-') ) {
        $forminstruction = $self->ProteinInstruction;
        $leftCell = td($self->ProteinDetailForm);
        if (param('topic')) {
	    param('topic', 'Protein Details')
        }
        if (param('category')) {
	    param('category', param('Protein'))
	}
        print hidden('topic', 'Protein Details'),
              hidden('category', param('Protein'));
        param('Protein', '-Select-');
    }
    elsif (($getForm eq 'Techniques') && (param('Techniques') ne '-Select-')) {
        $forminstruction = $self->TechInstruction;
        $leftCell = td($self->TechForm);
        if (param('topic')) {
	    param('topic', 'Techniques & Reagents')
        }
        if (param('category')) {
	    param('category', param('Techniques'))
	}
        print hidden('topic', 'Techniques & Reagents'),
              hidden('category', param('Techniques'));
        param('Techniques', '-Select-');
    }
    elsif (($getForm eq 'Interactions') && (param('Interactions') ne '-Select-') ) {
	$forminstruction = $self->InteractionInstruction;
        $leftCell = td($self->InteractionForm);
        if (param('topic')) {
	    param('topic', 'Interactions')
        }
        if (param('category')) {
	    param('category', param('Interactions'))
	}
        print hidden('topic', 'Interactions'),
              hidden('category', param('Interactions'));
        param('Interactions', '-Select-');
    }    
    elsif (($getForm eq 'Phenotypes') && (param('Phenotypes') ne '-Select-')) {
	$forminstruction = $self->PhenotypeInstruction;
        $leftCell = td($self->PhenotypeForm);
        if (param('topic')) {
	    param('topic', 'Alleles, Strains, & Phenotypes')
        }
        if (param('category')) {
	    param('category', param('Phenotypes'))
	}
        print hidden('topic', 'Alleles, Strains, & Phenotypes'),
              hidden('category', param('Phenotypes'));
        param('Phenotypes', '-Select-');
    }
    elsif (param('OtherForm')) {
        $forminstruction = $self->OtherInstruction;
        $leftCell = td($self->OtherForm);

        if (param('topic')) {
	    param('topic', 'Other')
        }
        if (param('category')) {
	    param('category', 'Other')
	}
        print hidden('topic', 'Other'),
              hidden('category', 'Other');
    }
    elsif ($getForm) {
        $leftCell = td({-valign=>'top'}, font({-size=>'+2', -color=>'red'}, "Please go back and choose a specific type of form."));
    }

    if ($pubmed) {
        print hidden('pubmed', $pubmed);
    }
    else 
    {
    }

    print blockquote($startMssg);

    if (param('StartOver')) {
	$leftCell = td({-valign=>"top"}, font({-size=>'+2'}, br. blockquote("To obtain a submission form, please choose a topic from one of the pull-down menus on the left and hit the \"Get Form\" button.")));
    }

    print hidden('file', $tmpfile);

    my $listUrl = "http://www.Dictyosteliumgenome.org/help/highlights.html#list";

    if ($getForm || param('OtherForm')) {
	print table({-width=>"100%", -cellspacing=>"3", -cellpadding=>"4", -border=>"0"},
		    Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Research Highlight Submission"))),
                    $forminstruction,
		    Tr($leftCell)
        )
    }
    else {   #no 'GetForm' button pushed
	print
	    table({-width=>"100%", -cellspacing=>"3", -cellpadding=>"4", -border=>"0"},
		  Tr(th({-align=>"left", -bgcolor=>"#a4abc2", -colspan=>"2"}, font({-size=>'+1'}, "Research Highlight Submission"))),
		  Tr(td({-colspan=>'2'}, "Follow the directions that appear in the \"Submission Form & Instructions\" section, below. In all submission forms, \"". b(font({-color=>"red"}, '*')). "\" indicates a required field.")),
		  Tr(th({-width=>'325', -align=>"left", -bgcolor=>"#b7d8e4"}, "Submission Form & Instructions"),
		     th({-align=>"left", -bgcolor=>"#b7d8e4"}, a({-name=>'form'}, "Topic Options". "&nbsp" x 22 . a({-href=>$listUrl, -target=>'help'}, "List & Descriptions")))
		  ),
		  Tr($leftCell,
		     td({-valign=>"top"}, 
			table({-valign=>"top", -border=>'1', -cellpadding=>'4', -cellspacing=>'3', -width=>'325', -bgcolor=>"#d8d8d8"},
			      Tr(td($self->TopicOption)
			      ))
			)
		  )
      ); #table topics
    }

    my $changeButton = td({-align=>"right"}, submit("change", "change"));
    my $newButton = td({-align=>"right", -width=>'10'}, button(-name=>'New', -value=>'New', -onClick=>'newwindow()'));
    
    #pending highlights section
    if (-e $tmpfile) { #there is annotation submitted
	my $submittedRows = $self->researchHighlightConfirm($tmpfile);
        $changeButton = td({-bgcolor=>'white'}, "&nbsp");
        $newButton = td({-bgcolor=>'white'}, "&nbsp");
        $contributorMssg = "The following contributor and reference will be displayed alongside any Research Highlights that you contribute from this page.";
        print 
          table({-width=>"100%", -cellspacing=>"3", -cellpadding=>"4", -border=>"0"},      Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Submitted Research Highlights"))),
            Tr(td("The following table lists Research Highlights that you have already submitted during this session. If there are errors in these Research Highlights, please edit or delete them ". font({-color=>'red'}, "only after submitting all Research Highlights associated with this publication."))),
            Tr(td(table({-width=>"100%", -cellspacing=>'3', -cellpadding=>'4', -border=>'1'}, $submittedRows)))
            ), p;
    }

    print p,
      table({-width=>"100%", -cellspacing=>"4", -cellpadding=>"4", -border=>"0"},
	Tr(th({-align=>"left", -colspan=>'5', -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Contributor & Reference Information"))),
        Tr(td({-colspan=>'5'}, $contributorMssg)),
	Tr({-bgcolor=>"#b7d8e4"},
          th({-align=>"left"}, "Contributor"),
          $changeButton,
          td({-bgcolor=>"#FFFFFF"}, "&nbsp"),
          th({-align=>"left"}, "Reference"),
          $newButton
        ),
	Tr(td({-valign=>"top", -colspan=>'2'}, $lname . ", " . $fname .br. $email), 
           td({-bgcolor=>"#FFFFFF"}, "&nbsp"),
           td({-valign=>"top", -colspan=>'2'}, $formatedCitation)
        )
      );

    print end_form;
    &printEndPage;
}

#######################################################################
sub TopicOption {
#######################################################################
    my ($self) = @_;
    my @Val = ('-Select-', 'DNA Modification', 'Transcription Start', 'Regulatory Motifs', 'RNA Processing/Modification', 'RNA Degradation', 'RNA Function/Processing', 'Other DNA & RNA Details');
    my %Label;
    my $topicOption = $self->makePulldown("DNA & RNA Details", "DNA", \@Val, \%Label);
    @Val = ('-Select-', 'Protein Modification', 'Protein Degradation', 'Protein Localization', 'Protein Function/Process', 'Mature Length (direct evidence)', 'Nucleic Acid Binding', 'Other Protein Details');
    $topicOption .= br.br. $self->makePulldown("Protein Details", "Protein", \@Val, \%Label);
    @Val = ('-Select-', 'Antibodies', 'Protein Purification', 'Strains & Constructs', 'Unique Assays', 'Other Techniques & Reagents');
    $topicOption .= br.br. $self->makePulldown("Techniques & Reagents", "Techniques", \@Val, \%Label);
    @Val = ('-Select-', 'Genetic', 'Physical', 'Two Hybrid', 'Regulatory', 'Other Interactions');
    $topicOption .= br.br. $self->makePulldown("Interactions", "Interactions", \@Val, \%Label);
    @Val = ('-Select-', 'Complete Deletion', 'Partial Deletion', 'Point Mutation', 'Other Mutation', 'Multiple Knockout Strains', 'Overexpression', 'Other Alleles, Strains...');
    $topicOption .= br.br. $self->makePulldown("Alleles, Strains, & Mutant Phenotypes", "Phenotypes", \@Val, \%Label);
    $topicOption .= br.br. li(b("Other")) . "- if none of the above apply." . $seperator . submit(-name=>'OtherForm', -value=>'GetForm', -onClick=>"action=$anchorUrl");

    return $topicOption;
}

#######################################################################
sub DNARNADetailForm {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;
    my $type = param('DNA');

    my $cell = Tr(th({-align=>"left", -colspan=>'2'}, "DNA & RNA Details: " . u($type)));

    #SA: SubmittAnnotation. identify attributes from input form
    if (($type eq 'DNA Modification') || ($type eq 'RNA Processing/Modification')) {
        $cell .=
	  Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
 		  $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_DR_$tmpAnnoNo", '15'),
                  $self->makeTextBox("Chromosomal sequence coordinates: ", "chrSeqCoord_DR_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("highlight_DR_$tmpAnnoNo")
             )
	  );
    }
    elsif ($type eq 'Transcription Start') {
        $cell .=
	  Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
 		  $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_DR_$tmpAnnoNo", '15'),
                  $self->makeTextBox($self->redstar ."Chromosomal sequence coordinates: ", "chrSeqCoord_DR_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("highlight_DR_$tmpAnnoNo")
             )
	  );
    }
    elsif ($type eq 'Regulatory Motifs') {
	$cell .=
	  Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
 		  $self->makeTextBox($self->redstar ."Gene/ORF regulated by motif: ", "gene_DR_$tmpAnnoNo", '15'),
                  $self->makeTextBox("Name of motif: ", "motif_DR_$tmpAnnoNo", '15'),
                  Tr(td(u("Motif chromosomal sequence coordinates:"))),
                  $self->makeTextBox("Start: ", "startCoord_DR_$tmpAnnoNo", '15'),
                  $self->makeTextBox("Stop: ", "stopCoord_DR_$tmpAnnoNo", '15'),
                  $self->makeTextBox($self->redanchor. "Protein(s) shown to bind this motif: ", "motifboundPr_DR_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("highlight_DR_$tmpAnnoNo")
             )
	  );
    }
    else {
        if ($type eq 'Other DNA & RNA Details') {
	    $cell .= Tr(td({-colspan=>'2'}, $self->redstar."Other Topic: " . textfield({-name=>"other_DR_$tmpAnnoNo", -size=>'15'})));
        }
        $cell .=
	  Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
 		  $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_DR_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("highlight_DR_$tmpAnnoNo", $self->redstar)
             )
	  );
    }
        
    if (param('EditConfirm')) {
        $cell .= $self->makeDelBox('2', "Delete_$tmpAnnoNo");
    }
    else {
	$cell .= $self->makeBotSec;
    }

    return table({-align=>'center', -bgcolor=>"lightyellow", -width=>$width, -cellspacing=>"3", -cellpadding=>"4", -border=>"1"}, $cell);
}

#######################################################################
sub ProteinDetailForm {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;
    my $type = param('Protein') || param('category');
    my $column = '2';
    if ($type eq 'Protein Modification') {
	$column = '3';
    }
    my $cell = Tr(th({-colspan=>$column, -align=>"left"}, "Protein Details: " . u($type)));

    if ($type eq 'Other Protein Details') {
        $cell .= Tr(td({-colspan=>$column}, $self->redstar. "Other Topic:" . textfield({-name=>"other_PD_$tmpAnnoNo", -size=>'15'})));
    }    

    if ($type eq 'Protein Modification') {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_PD_$tmpAnnoNo", '15'),
			 $self->makeTextBox("Modified Amino Acid: ", "modifiedAA_PD_$tmpAnnoNo", '15')
                    )),
                    td($self->modificationType_PD($tmpAnnoNo)),
                    td($self->makeDescriptionBlock("highlight_PD_$tmpAnnoNo"))
	         );
    }
    elsif ($type eq 'Mature Length (direct evidence)') {
        $cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_PD_$tmpAnnoNo", '15'),
			 $self->makeTextBox($self->redstar ."Protein length (in Amino Acids): ", "proteinlength_PD_$tmpAnnoNo", '15')
                    )),
                    td($self->makeDescriptionBlock("highlight_PD_$tmpAnnoNo"))
	         );
    }
    elsif ($type eq 'Nucleic Acid Binding') {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_PD_$tmpAnnoNo", '15'),
                         Tr(td($self->redstar. u("Nucleotide Binding:"))),
                         Tr(td(checkbox({-name=>'BindsDNA_'.$tmpAnnoNo, -label=>'Binds DNA', -value=>'Binds DNA'}))),
                         Tr(td(checkbox({-name=>'BindsRNA_'.$tmpAnnoNo, -label=>'Binds RNA', -value=>'Binds RNA'}))),
                         $self->makeTextBox($self->redanchor. "Substrate Gene/ORF(s):", "substrate_PD_$tmpAnnoNo", '15')
                    )),
                    td($self->makeDescriptionBlock("highlight_PD_$tmpAnnoNo"))
	         );
    }
    else {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_PD_$tmpAnnoNo", '15'))),
                    td($self->makeDescriptionBlock("highlight_PD_$tmpAnnoNo", $self->redstar))
	         );
    }

    if (param('EditConfirm')) {
        $cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");
    }
    else {
        $cell .= $self->makeBotSec($column);
    }
    return table({-align=>'center', -bgcolor=>"lightyellow", -width=>$width, -cellspacing=>"3", -cellpadding=>"4", -border=>"1"}, $cell);
}

#######################################################################
sub TechForm {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;
    my $type = param('Techniques');
    my $column = '2';

    my $cell = Tr(th({-colspan=>$column, -align=>"left"}, "Techniques & reagents: " . u($type)));

    if ($type =~ /^Other/) {
        $cell .= Tr(td({-colspan=>$column}, $self->redstar. "Other Topic:" . textfield({-name=>"other_TR_$tmpAnnoNo", -size=>'15'})));
    } 


    if ($type =~ /^Strains/) {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_TR_$tmpAnnoNo", '15'),
                         $self->makeTextBox($self->redstar ."Strain background: ", "strainBk_TR_$tmpAnnoNo", '15'),
                         $self->makeTextBox($self->redstar ."Strain name & genotype: ", "StrainNmGt_TR_$tmpAnnoNo", '15')
                    )),
                    td($self->makeDescriptionBlock("highlight_TR_$tmpAnnoNo"))
	         );
    }
    else {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_TR_$tmpAnnoNo", '15'))),
                    td($self->makeDescriptionBlock("highlight_TR_$tmpAnnoNo", $self->redstar))
	         );
    }
 
    if (param('EditConfirm')) {
        $cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");
    }
    else {
	$cell .= $self->makeBotSec($column);
    }

    return table({-align=>'center', -bgcolor=>"lightyellow", -width=>$width, -cellspacing=>"3", -cellpadding=>"4", -border=>"1"}, $cell);
}

#######################################################################
sub InteractionForm {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;
    my $type = param('Interactions');
    my $column = '2';

    my $cell = Tr(th({-colspan=>$column, -align=>"left"}, "Interactions: " . u($type)));

    if ($type eq 'Genetic') {
        $cell .= Tr(td({-colspan=>$column}, 
                  table(Tr( 
		   td({-valign=>'top', -align=>'left'}, table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td(b(u("Primary Gene/ORF")))
                        ),
		        $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene1_IN_$tmpAnnoNo", '15'),
			$self->makeTextBox("Mutation type: ", "mut1_IN_$tmpAnnoNo", '15')
	           )),
		   td({-valign=>'top', -align=>'left'}, table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td(b($self->redstar . u("Interaction Type")))
                        ),
	                Tr(td(checkbox({-name=>"synthetic_$tmpAnnoNo", -value=>"is synthetic lethal with", -label=>"is synthetic lethal with"}))),
	                Tr(td(checkbox({-name=>"supressor_$tmpAnnoNo", -value=>"is a supressor of", -label=>"is a supressor of"}))),
	                Tr(td(checkbox({-name=>"epistatic_$tmpAnnoNo", -value=>"is epistatic to", -label=>"is epistatic to"}))),
			Tr(td(checkbox({-name=>"OtherInter_$tmpAnnoNo", -value=>"OtherInteraction", -label=>"Other"}) .': '. textfield({-name=>"box4other_IN_$tmpAnnoNo", -size=>'15'})))
	           )),

	           td({-valign=>'top', -align=>'right'}, table({-cellspacing=>"3", -cellpadding=>"4"},
			Tr(td(b(u("Interacting Gene/ORF")))
		        ),
			$self->makeTextBox($self->redstar . "Gene/ORF: ", "gene2_IN_$tmpAnnoNo", '15'),
                        $self->makeTextBox("Mutation type: ", "mut2_IN_$tmpAnnoNo", '15')
	           ))
                 )))) .
		 Tr(td(
                   table({-cellspacing=>"3", -cellpadding=>"4"},
			$self->makeTextBox("Strain background: ", "strainBk_IN_$tmpAnnoNo", '15'),
			$self->makeTextBox("Strain name & genotype: ", "strainNm_IN_$tmpAnnoNo", '15')
		    )),
		    td($self->makeDescriptionBlock("highlight_IN_$tmpAnnoNo"))
		 );
    }
    elsif ($type eq 'Regulatory') {
	$cell .= Tr(td(
                      table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td($self->redstar . "Primary Gene/ORF: " . textfield({-name=>"gene1_IN_$tmpAnnoNo", -size=>'15'}))),
			Tr(td(checkbox({-name=>"regulated_$tmpAnnoNo", -value=>"This gene is regulated by", -label=>"is regulated by"}))),
                        Tr(td(checkbox({-name=>"regulator_$tmpAnnoNo", -value=>"This gene is a regulator of", -label=>"is a regulator of"}))),
                        Tr(td($self->redstar . "Interacting Gene/ORF: " . textfield({-name=>"gene2_IN_$tmpAnnoNo", -size=>'15'})))
                      )),
		    td($self->makeDescriptionBlock("highlight_IN_$tmpAnnoNo"))
		 );
    }
    elsif ( $type =~ /^Other/) {
	$cell .= Tr(td({-colspan=>$column}, $self->redstar. "Other Topic: " . textfield({-name=>"other_IN_$tmpAnnoNo", -size=>'15'})));
        $cell .= Tr(td(
                      table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td($self->redstar . "Primary Gene/ORF: " . textfield({-name=>"gene1_IN_$tmpAnnoNo", -size=>'15'}) .' with')),
                        Tr(td($self->redstar . "Interacting Gene/ORF: " . textfield({-name=>"gene2_IN_$tmpAnnoNo", -size=>'15'})))
                      )),
		    td($self->makeDescriptionBlock("highlight_IN_$tmpAnnoNo", $self->redstar))
		  );
    }
    else {
        $cell .= Tr(td(
                      table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td($self->redstar . "Primary Gene/ORF: " . textfield({-name=>"gene1_IN_$tmpAnnoNo", -size=>'15'}) .' with')),
                        Tr(td($self->redstar . "Interacting Gene/ORF: " . textfield({-name=>"gene2_IN_$tmpAnnoNo", -size=>'15'})))
                      )),
		    td($self->makeDescriptionBlock("highlight_IN_$tmpAnnoNo"))
		  );
    }

    if (param('EditConfirm')) {
        $cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");
    }
    else {
	$cell .= $self->makeBotSec($column);
    }

    return table({-align=>'center', -bgcolor=>"lightyellow", -width=>$width, -cellspacing=>"3", -cellpadding=>"4", -border=>"1"}, $cell);
}

#######################################################################
sub PhenotypeForm {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;

    my $type = param('Phenotypes');
    my $column = '3';

    my $cell = Tr(th({-colspan=>$column, -align=>"left"}, "Alleles, Strains, & Phenotypes: " . u($type)));

    if ( $type =~ /^Other Alleles/ ) { 
        $cell .= Tr(td({-colspan=>$column}, $self->redstar."Other Topic: " . textfield({-name=>"other_PH_$tmpAnnoNo", -size=>'15'})));
    }
    elsif ( $type eq 'Other Mutation') { 
	$cell .= Tr(td({-colspan=>$column}, "Other Mutation: " . textfield({-name=>"otherMutPH_$tmpAnnoNo", -size=>'15'})));
    }

    if ($type eq 'Partial Deletion') {
        $cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       $self->makeTextBox($self->redstar. "Gene/ORF: ", "gene_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Allele name: ", "allele_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Strain background: ", "strainBk_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNm_PH_$tmpAnnoNo", '15'),
                       Tr(td($self->redstar. u("Chromosomal sequence coordinates of deletion:"))),
                       $self->makeTextBox("From: ", "PDfromPH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("To: ", "PDtoPH_$tmpAnnoNo", '15'),
		    )),
                    $self->phenotypeDesc($tmpAnnoNo),    #middle column
                    td($self->makeDescriptionBlock("highlight_PH_$tmpAnnoNo"))
		    );
    }
    elsif ($type eq 'Other Mutation')  {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       Tr(td($self->redstar. $self->redanchor. "Gene/ORF (& Allele name): ")) , 
		       Tr(td(textarea({-name=>"OthMutGenePH_$tmpAnnoNo", -rows=>'10', -cols=>'20'}))),
		       $self->makeTextBox("Strain background: ", "strainBk_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNm_PH_$tmpAnnoNo", '15')
		   )),
		   $self->phenotypeDesc($tmpAnnoNo),    #middle column
                   td($self->makeDescriptionBlock("highlight_PH_$tmpAnnoNo", $self->redstar)) 
                 );

    }
    elsif ($type eq 'Multiple Knockout Strains') {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       Tr(td($self->redstar. $self->redanchor. "Deleted Genes/ORFs: ")),
		       Tr(td(textarea({-name=>"deltGenePH_$tmpAnnoNo", -rows=>'10', -cols=>'20'}))),
		       $self->makeTextBox("Strain background: ", "strainBk_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNm_PH_$tmpAnnoNo", '15')
		   )),
		   $self->phenotypeDesc($tmpAnnoNo),    #middle column
                   td($self->makeDescriptionBlock("highlight_PH_$tmpAnnoNo")) 
                 );
    }
    else {
	my $descBox;
        if ( $type =~ /^Other Alleles/ ) {
	    $descBox = td($self->makeDescriptionBlock("highlight_PH_$tmpAnnoNo", $self->redstar));
	}
        else {
	    $descBox = td($self->makeDescriptionBlock("highlight_PH_$tmpAnnoNo"));
        }
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       $self->makeTextBox($self->redstar. "Gene/ORF: ", "gene_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Allele name: ", "allele_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Strain background: ", "strainBk_PH_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNm_PH_$tmpAnnoNo", '15')
		    )),
                    $self->phenotypeDesc($tmpAnnoNo),    #middle column
                    $descBox
		    );
    }

    if (param('EditConfirm')) {
	$cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");
    }
    else {
	$cell .= $self->makeBotSec($column);
    }

    return table({-align=>'center', -bgcolor=>"lightyellow", -width=>$width, -cellspacing=>"3", -cellpadding=>"4", -border=>"1"}, $cell);   
}

#######################################################################
sub OtherForm {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;
    my $column = '2';
    my $cell = Tr(th({-align=>"left", -colspan=>$column}, "Other Category" )) . Tr(th({-align=>"left", -colspan=>$column}, $self->redstar. "Other Topic: " . textfield({-name=>"OtherTopic_OT_$tmpAnnoNo", -size=>'15'})));

    $cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       $self->makeTextBox($self->redstar. "Gene/ORF: ", "gene_OT_$tmpAnnoNo", '15'),
		    )),
                td($self->makeDescriptionBlock("highlight_OT_$tmpAnnoNo", $self->redstar))
	     );

    if (param('EditConfirm')) {
	$cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");
    }
    else {
	$cell .= $self->makeBotSec($column);
    }

    return table({-align=>'center', -bgcolor=>"lightyellow", -width=>$width, -cellspacing=>"3", -cellpadding=>"4", -border=>"1"}, $cell);
}

#######################################################################
sub modificationType_PD {
#######################################################################
    my ($self, $annoId) = @_;
    my $rows = table({-cellspacing=>"3", -cellpadding=>"4"},
	         Tr(td($self->redstar. "Modification Type")),
                 Tr(td(checkbox({-name=>'Glycosylation_'.$annoId, -label=>'Glycosylation', -value=>'Glycosylation'}))),
                 Tr(td(checkbox({-name=>'Phosphorylation_'.$annoId, -label=>'Phosphorylation', -value=>'Phosphorylation'}))),
                 Tr(td(checkbox({-name=>'N-terminal_'.$annoId, -label=>'N-terminal', -value=>'N-terminal'}))),
                 Tr(td(checkbox({-name=>'C-terminal_'.$annoId, -label=>'C-terminal', -value=>'C-terminal'}))),
                 Tr(td(checkbox({-name=>'OtherMT_'.$annoId, -label=>'Other: ', -value=>'OtherMT'}). textfield({-name=>'OMT_'.$annoId, -size=>'15'})))
	       );
    return $rows;
}

#######################################################################
sub phenotypeDesc {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;

    my $rows .=
           td(
	      table({-cellspacing=>"3", -cellpadding=>"4", -border=>"0"},
	        Tr(td({-colspan=>'2'}, b($self->redstar. u("Phenotype description")))),
		Tr(td(checkbox({-name=>"Dominant_$tmpAnnoNo", -label=>"Dominant", -value=>"Dominant"})),
	           td(checkbox({-name=>"Recessive_$tmpAnnoNo", -label=>"Recessive", -value=>"Recessive"}))
                ),
		Tr(td(checkbox({-name=>"Viable_$tmpAnnoNo", -label=>"Viable", -value=>"Viable"})),
	           td(checkbox({-name=>"Inviable_$tmpAnnoNo" , -label=>"Inviable", -value=>"Inviable"}))
                ),
	        Tr(td(checkbox({-name=>"TemperatureSensitive_$tmpAnnoNo", -label=>"Temperature(Heat) Sensitive", -value=>"Temperature (Heat) Sensitive"})),
	           td(checkbox({-name=>"ColdSensitive_$tmpAnnoNo", -label=>"Cold Sensitive", -value=>"Cold Sensitive"}))
                ),
		Tr(td(checkbox({-name=>"LossFunction_$tmpAnnoNo", -label=>"Loss of function (Null)", -value=>"Loss of function (Null)"})),
	           td(checkbox({-name=>"GainFunction_$tmpAnnoNo", -label=>"Gain of function", -value=>"Gain of function"}))
                ),
		Tr(td(checkbox({-name=>"Revertable_$tmpAnnoNo", -label=>"Revertable", -value=>"Revertable"})),
	           td(checkbox({-name=>"NoPhenotype_$tmpAnnoNo", -label=>"No Phenotype", -value=>"No Phenotype"})                )),
		Tr(td({-colspan=>'2'}, checkbox({-name=>"OtherPhenotypeDescription_$tmpAnnoNo", -label=>"Other:", -value=>"OtherPhenotypeDescription"}) . textfield({-name=>"OtherTxtBoxPH_$tmpAnnoNo", -size=>'15'}))),
		Tr(td({-colspan=>'2'}, checkbox({-name=>"inviableWhen_$tmpAnnoNo", -label=>"Conditionally inviable when ", -value=>"Conditionally inviable when "}) . textfield({-name=>"CondiTxtBoxPH_$tmpAnnoNo", -size=>'15'})))
	     ));
    return $rows;
}

#######################################################################
sub makeBotSec {
#######################################################################
    my ($self, $column) = @_;
    $column = '2' if (!$column);
    return Tr(td({-colspan=>$column}, reset . " - Click here to reset the submission form" . br.br. submit(-name=>"SubmitAnnotation", -value=>"Submit", -onClick=>"action=$anchorUrl") . " - Click here to submit this Research Highlight" .br.br. submit(-name=>"StartOver", -value=>"StartOver", -onClick=>"action=$anchorUrl") . " - Click here to delete current form and choose a new form"));
}

#######################################################################
sub makeDelBox {
#######################################################################
    my ($self, $column, $nm) = @_;
    return  Tr(td({-colspan=>$column}, checkbox({-name=>$nm, -label=>$DelBoxLabel, -value=>"Delete"})));
}

#######################################################################
sub makeTextBox {
#######################################################################
    my ($self, $pre, $Nm, $size) = @_;
 
    my $box = Tr(td($pre . textfield({-name=>$Nm, -size=>$size})));
    return $box;
}

#######################################################################
sub makeDescriptionBlock {
#######################################################################
    my ($self, $Nm, $star) = @_;
    my $rows = table({-cellspacing=>"3", -cellpadding=>"4"},
                 Tr(td($star . "Research Highlight Description:" . br . textarea({-name=> $Nm, -rows=>'3', -cols=>'40', -onKeyDown=>"textCounter(this.form.$Nm,this.form.remLentext,480);", -onKeyUp=>"textCounter(this.form.$Nm,this.form.remLentext,480);"}),
                 Tr(td("Length limit = 480 characters")),
		 Tr(td("Characters remaining: ". textfield(-name=>'remLentext',, -size=>'4', -default=>'480', -disabled=>'1')))
	       )));
    return $rows;
}

#######################################################################
sub makePulldown {
#######################################################################
    my ($self, $title, $name, $valref, $labref ) = @_;
    my $default = '-Select-';

    return li(b($title)).$seperator.
                    popup_menu(-name=>$name,
                               -values=>$valref,
                               -labels=>$labref
                               -default=>$default) .
                              submit(-name=>"GetForm_$name", 
                                     -value=>"GetForm",
                                     -onClick=>"action=$anchorUrl"
                                    );
}

#######################################################################
sub restart1 {
#######################################################################
    my ($self) = @_;
    my ($lname, $fname, $email, $institution, $colid);

    $colid = param('colleagueid') || param('choice');

    $title = 'Community Annotation: Research Highlights' .br.  'Specify Reference';
    &printStartPage($self->database, $title);
    print start_form({-method=>'POST'});
    print hidden('emailReply', param('emailReply')) if (defined (param('emailReply')));

    if ($colid) {
        my $collObject = Colleague->new(dbh=>$dbh, colleague_no=>$colid);
        if (!$collObject) {
            $self->err_report("Wrong Colleague Info.");
        }
        $lname = $collObject->last_name; 
        $fname = $collObject->first_name;
        my $emailRef = $collObject->emailRef; 
        $institution = $collObject->institution;
        foreach my $rowRef (@$emailRef) { 
            ($email) = @$rowRef;
        }
	print hidden('colleagueid', $colid);
    }
    else { #without colleague Id
        $lname = param('lname'); 
        $fname = param('fname');
	$email = param('email');
	$institution = param('institution');
    } 
    
    print blockquote("Go to the \"Reference Submission\" section to identify the publication that you are citing.");
    print p,
      table({-cellpadding=>"4", -width=>"100%", -cellspacing=>"3", -border=>"0"},      
        Tr(td({-colspan=>'2', -width=>"100%", -bgcolor=>"#a4abc2", -align=>"left"}, font({-size=>"+1"}, b("Contributor")))
        ),
        Tr(td({-colspan=>'2'}, b(u("All Research Highlights must be associated with a contributor.")). " The Contributor information that you have already provided is: ")
        ),
        Tr(td($lname . ", " . $fname),
           td($email)
        ),
        Tr(th({-colspan=>'2', -align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Reference Submission"))).
        Tr(td({-colspan=>'2'}, b(u("All Research Highlights must be referenced.")). " The reference citation will be displayed alongside the research highlight.". br. br. "Specify the publication that you are citing by entering the ". b("PubMed ID"). " into the box provided below and then hit the \"submit\" button, below. The PubMed ID can be found at the bottom of a publication's PubMed entry and is labeled \"PMID:\". If the publication that you wish to cite is not listed in PubMed, please contact dictyBase using the \"Send a message..\" link at the bottom of this page."
        )).
	Tr(td({-valign=>"top", -colspan=>'2'},
	   table({-cellpadding=>"4", -cellspacing=>"3", -border=>"0"},
             Tr(th({-bgcolor=>"#b7d8e4", -align=>"left"}, "PubMed ID:"),
                td(textfield(-name=>"pubmed", -size=>"20"))
             ). 
             Tr(td({-colspan=>'2'}, a({-href=>"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi", -target=>'searchPubmed'}, "Search PubMed")))
           )
        ))
      ), p;
    print submit('All', 'Submit'), reset;
    print end_form;
    &printEndPage;
    $self->DESTROY;
}

#######################################################################
sub showparameters {
#######################################################################
    my ($self) = @_;
    &printStartPage($self->database, $title);
    foreach my $nm (param) {
        print $nm . "=" . param($nm) . br;
    }
    &printEndPage;
    return;
}

#######################################################################
sub changeContributor {
#######################################################################
    my ($self) = @_;

    my $rows; # = Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, "Contributor"));
    my $pubmed = param('pubmed');

    my ($formatedCitation, $searchRef);
    if ($pubmed) {
        $formatedCitation = $self->formatedCitation($pubmed);
    }
    else {
	$self->err_report("No pubmed when changeContributor!");
    }

    my $newInstr = "The reference you have already provided is displayed in the \"Reference\" section, at the bottom of the page. Each Research Highlight must be accompanied by a published reference; we cannot post unpublished or pre-publication data at this time. You do not have to be an author on this publication in order to cite it.";

    $rows .= Tr({-bgcolor=>"#a4abc2"},
          th({-align=>"left"}, font({-size=>'+1'}, "Contributor Submission"))
        ).
	    Tr(td(b(u("All Research Highlights must be associated with a contributor.")). " The contributor's name will be publicly associated with the Research Highlight.". br. br. "Please enter your ". b("LAST name").  "into the box provided below, then continue on to the reference submission section."
        )).
	    Tr(td({-valign=>"top"},
	      table({-cellpadding=>"4", -cellspacing=>"3", -border=>"0"},
	        Tr(th({-bgcolor=>"#b7d8e4", -align=>'left'}, "Last (family) Name:"),
                   td(textfield(-name=>'lnameSearch', -size=>'20') . " (" . i("e.g.") . "Chisholm, Jones, Smith)")
        )))) .
	    Tr(td(submit('Submit', 'Submit'), reset)).
	    Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Reference Information"))).
            Tr(td(b(u("All Research Highlights must be referenced.")) . "&nbsp". "The reference information that you have already provided is:")).
            Tr(td($formatedCitation));

    $title = "Community Annotation: Research Highlights" .br. "Specify Contributor";
    &printStartPage($self->database, $title);
    print p, start_form, hidden('changeContributor', 'yes'), hidden('pubmed', $pubmed), table({-cellpadding=>'4', -cellspace=>'3', -border=>'0', -width=>'100%'}, $rows);
    print hidden('formatedCitation', $formatedCitation) if (!$pubmed);
    print hidden('emailReply', param('emailReply')) if (defined (param('emailReply')));

    print end_form;
   
    &printEndPage;
}

#####################################################################
sub checkChangeContributor {
#####################################################################
    my ($self) = @_;
    my $search = param('lnameSearch');

    if (!$search || !($search =~ /\w/)) {
        $self->err_report("You forgot to enter a last name for searching. Please go back and try again.");
    }

    my $pubmed = param('pubmed');

    my $result = $self->colleagueList($search);
    my $formatedCitation;
    if ($pubmed) {
        $formatedCitation = $self->formatedCitation($pubmed);
    }
    else {
        $formatedCitation = param('formatedCitation');
    }

    my $instructions =
	Tr({-bgcolor=>"#a4abc2"},
          th({-align=>"left"}, font({-size=>'+1'}, "Instructions")),
          td({-align=>"left"}, b("Jump to " . a({-href=>"#contributor"}, "Contributor Conformation")))
        ).
        Tr(td({-colspan=>'2'}, "This page starts the second step in submitting a community annotated \"Research Highlight\" to dictyBase. Research Highlights are concise statements describing an important fact or discovery about an ". i("S. discoideum")." gene or protein. Research Highlights are not meant to summarize a publication or body of research, but should be used to draw attention to a single fact or concept. All appropriate Research Highlights will be publicly posted on dictyBase, in the \"Community Annotation\" section for the gene or genes that they address.")
        ).
        Tr(td({-colspan=>'2'}, "There are three steps in \"Research Highlight\" submission:"
        )).
        Tr(td({-colspan=>'2'},
          ol(li(b("Identify yourself.". font({-color=>'red'}, " You are finishing this step")). br . "In the ". a({-href=>"#contributor"}, "Contributor Confirmation") ." section, below, please either choose your name from the list or request an abbreviated Colleague Registration form. The Research Highlight you submit will be labeled with your name. You will not be cited as the author of this research, but merely as the highlight contributor, i.e. the person who brought this research to the attention of dictyBase. We ask that you list minimal contact information with dictyBase in order to submit a Research Highlight."),
             li(b("Identify the publication you are citing.") . br . "The citation you have already provided is displayed in the ". a({-href=>"#ref"}, "Reference") ." section, below. Each Research Highlight must be accompanied by a published reference: we cannot post unpublished or pre-publication data as a Reasearch Highlight. You do not have to be an author on this publication in order to cite it."),

	     li(b("Enter your Research Highlight") . br . "After entering your colleague and reference information, you will recieve a Research Highlight submission form and detailed instructions. Each Research Highlight must be associated with at least one gene/ORF, must be associated with a defined topic (eg: \"DNA/RNA Details\"), and must include a concise text description.")
          )  #ol
    ));
 
    my $rows = Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, a({-name=>'ref'}, "Reference"))));
    $rows .= Tr(td($formatedCitation));

    $title .= " - Specify Contributor";
    &printStartPage($self->database, $title);
#    print $self->betaVersionMssg;
    print start_form({-method=>'POST'}), hidden('pubmed', $pubmed);
    print hidden('emailReply', param('emailReply')) if (defined (param('emailReply')));
    print table({-width=>'100%', -cellpadding=>'4', -cellspacing=>'3', -border=>'0'},      $instructions . 
	    Tr(td({-align=>'left', -bgcolor=>"#a4abc2", -colspan=>'2'}, font({-size=>'+1'}, b(a({-name=>'contributor'}, "Contributor Confirmation"))))) . "\n" .
            Tr(td({-colspan=>'2'}, "Please choose your name from the table below. and then hit the \"Submit\" button. If your contact information is incorrect, click ".b("EDIT")." to update your dictyBase colleague entry.")) ."\n"                        
	  ) .p;
    print blockquote($result .br. submit('All', 'Submit'). " - Click here to continue") . p ."\n";
#    print blockquote(submit('All', 'Submit') . " - Click here to continue"), p;
    print font({-color=>'red'}, b("If your name is not found in the table:")) . br;
    print blockquote(submit({-name=>'Add', -value=>'Add'}) . " - Click here to add minimal information about yourself to dictyBase's colleague database.") .p ."\n";
    print table({-cellpadding=>'4', -cellspace=>'3', -border=>'0', -width=>'100%'}, $rows),p;
    print hidden('formatedCitation', $formatedCitation) if (!$pubmed);
    print end_form;
    &printEndPage;
}

#####################################################################
sub fork {
#####################################################################
    my ($self) = @_;
    my $cell = font({-size=>'+1'}, blockquote("Please choose one of the following options:" . br .
      ol(li("To enter another Research Highlight associated with this publication, choose another topic from the pull-down menus on the right, and fill out another submission form." .br.br) .
         font({-color=>"red"}, 'OR') .br.br.
	 li("To finish entering Research Highlights, click on the \"confirm\" button to confirm, edit or delete all submitted Research Highlights.".br. submit("EditConfirm", "Confirm"))
	 )));
    
    return $cell;
}

#####################################################################
sub confirmPage {
#####################################################################
    my ($self) = @_;
    my $colId = param('colleagueid');
    my $pubmed = param('pubmed');
    my ($formatedCitation , $searchRef);

    my $lname = param('lname');
    my $fname = param('fname');
    my $email = param('email');

    if ($pubmed) {
        $formatedCitation = $self->formatedCitation($pubmed);
    }
    elsif (param('formatedCitation')) {
        $formatedCitation = param('formatedCitation');
    }
    else {
        ($formatedCitation, $searchRef) = $self->ConstructCitation;
    }

    my $file = param('file');
    if (!$file) {
        $self->err_report('No Data File!');
    }

    my $rhRows = $self->researchHighlightConfirm($file);

    if (!$rhRows) {
        $self->err_report("You haven't submitted any research highlights! ".br . a({-href=>$SelfUrl}, "Start over and do community annotation."));
    }

    my $contributor = $lname . ", " . $fname .br. $email;
    
    &printStartPage($self->database, $title);
#    print $self->betaVersionMssg; 
    print start_form({-method=>'POST'});
    print hidden('file', $file);
    print hidden('lname', $lname);
    print hidden('fname', $fname);
    print hidden('email', $email);
    print hidden('emailReply', param('emailReply')) if (defined (param('emailReply')));

    if ($pubmed) {
        print hidden('pubmed', $pubmed);
    }
    else {
        print hidden('formatedCitation', $formatedCitation);
    }
    print table({-width=>"100%", -cellspacing=>"4", -cellpadding=>"4", -border=>"0"},
      Tr(td({-colspan=>'2'}, font({-size=>'+1'}, "Please confirm the information you have just submitted." . br))),
      Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Contributor")),
         th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Reference"))),
      Tr(td({-valign=>"top"}, $contributor),
         td({-valign=>"top"}, $formatedCitation)
      ),
      Tr(th({-colspan=>'2', -align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Research Highlights")))  
    );
    print table({-width=>"100%", -cellspacing=>'3', -cellpadding=>'4', -border=>'1'}, $rhRows);

    print p, table(
      Tr(td({-align=>"right"}, submit("EditConfirm", "Edit")),
         td({-align=>"left"}, "- Click here to edit the research highlight(s) listed above.")
      ),
      Tr(td({-align=>"right"}, submit("FinalConfirm", "FinalSubmission")),
         td({-align=>"left"}, "- Click here to confirm the research highlight(s) listed above.")
      )
    );

    print end_form;
    &printEndPage;
    return;
}

#####################################################################
sub researchHighlightConfirm {
#####################################################################
    my ($self, $file) = @_;
    my $rows;

    open(DATA, $file) || die "Can't open $file for reading: $!\n";
    while (<DATA>) {
        chomp;

        my @line = split(/\t/);
        my ($topic, $category); 
        foreach my $pair (@line) {
            my ($key, $value) = split(/=/, $pair);
            if ($key eq 'topic') {
                $topic = $value;
            }
            elsif ($key eq 'category') {
                $category = $value;
            }
        }

        if ($topic eq "DNA & RNA Details") {
            $rows .= $self->processDNARNA($category, @line);
        }
        elsif ($topic eq "Protein Details") {
            $rows .= $self->processProtein($category, @line);
        }
        elsif ($topic eq "Techniques & Reagents") {
            $rows .= $self->processTech($category, @line);
        }
        elsif ($topic eq "Interactions") {
            $rows .= $self->processInteractions($category, @line);
        }
        elsif ($topic eq "Alleles, Strains, & Phenotypes") {
            $rows .= $self->processPhenotype($category, @line);
        }
        elsif ($topic eq "Other") {
            $rows .= $self->processOther($category, @line);
        }
    }
    close DATA;

    if ($rows) {
	return $self->rhTitleRow . $rows;
    }
    else {
	return;
    }
}

#####################################################################
sub processDNARNA {
#####################################################################
    my ($self, $category, @line) = @_;
    my $row; #the returned html row

    my ($topic, $gene, $highlight);
    my $option = '---';

    $topic = "DNA & RNA Details: ". $category;

    if (($category eq 'DNA Modification') || ($category eq 'Transcription Start') || ($category eq 'RNA Processing/Modification'))    {
        my $coord;
        foreach my $pair (@line) {
            my ($key, $value) = split(/=/, $pair);
            if ($key =~ /^gene_DR/) {
                $gene = $value;
            }
	    elsif ($key =~ /^chrSeqCoord_DR/) {
		$coord = $value;
	    }
	    elsif ($key =~ /^highlight_DR/) {
		$highlight = $value;
	    }
	}

	$option = ul(li("Chromosomal sequence coordinates:" . $coord)) if $coord;
    }
    elsif ($category eq 'Regulatory Motifs') {
        my ($start, $stop, $protein, $motif);
        foreach my $pair (@line) {
            my ($key, $value) = split(/=/, $pair);
            if ($key =~ /^gene_DR/) {
                $gene = $value;
            }
            elsif ($key =~ /^motif_DR/) { 
		$motif = $value;
            }
	    elsif ($key =~ /^startCoord_DR/) {
		$start = $value;
	    }
            elsif ($key =~ /^stopCoord_DR/) {
		$stop = $value;
	    }
	    elsif ($key =~ /^highlight_DR/) {
		$highlight = $value;
	    }
            elsif ($key =~ /^motifboundPr_DR/) {
		$protein = $value;
	    }
	}
	my $preopt;
        $preopt = li("Name of motif: ". $motif) if ($motif);
        $preopt .= li("Chromosomal sequence coordinates: Start=" . $start . "     Stop=". $stop) if ($start || $stop);
        $preopt .= li("Protein(s) shown to bind this motif: " . $protein) if ($protein);
        $option = ul($preopt) if ($preopt); 
    }
    elsif (($category eq 'RNA Degradation') || ($category eq 'RNA Function/Processing'))  {
        foreach my $pair (@line) {
            my ($key, $value) = split(/=/, $pair);
            if ($key =~ /gene_DR/) {
                $gene = $value;
            }
	    elsif ($key =~ /^highlight_DR/) {
		$highlight = $value;
	    }
	}
    }
    elsif ($category eq 'Other DNA & RNA Details') {
        my $other;
        foreach my $pair (@line) {
            my ($key, $value) = split(/=/, $pair);
            if ($key =~ /gene_DR/) {
                $gene = $value;
            }
	    elsif ($key =~ /^other_DR/) {
		$other = $value;
	    }
	    elsif ($key =~ /^highlight_DR/) {
		$highlight = $value;
	    }
	}

	$option = ul(li("Other Topic: " . $other)) if $other;
    }

    $highlight = '---' if (!$highlight);
    
    $row = $self->rhDataRow($topic, $gene, $highlight, $option);

    return $row;
}

#####################################################################
sub processProtein {
#####################################################################
    my ($self, $category, @line) = @_;
    my $row; #the returned html row
    
    my ($topic, $gene, $highlight, $option, $other, $modAA, $prLen, $substrate);

    my @modType;
    my @nucBind;
    my %ModType = ('Glycosylation_'=>'1',  'Phosphorylation_'=>'1',
                   'N-terminal_'=>'1',     'C-terminal_'=>'1');
#                   'OtherMT_' => '1'); deal it separately

    $topic = "Protein Details: ". $category;

    if ($category eq 'Protein Modification') {
	foreach my $pair (@line) {
	    my ($key, $value) = split(/=/, $pair);
	    if ($key =~ /^gene_PD/) {
		$gene = $value;
	    }
	    elsif ($key =~ /^modifiedAA_PD/) {
		$modAA = $value;
	    }
	    elsif ($key =~ /^highlight_PD/) {
		$highlight = $value;
	    }
            elsif ($ModType{$key}) {
                push(@modType, $value);
            }
            elsif (($key =~ /^OMT_/) && ($value =~ /\w+/)) {
		$value = "Other Modification Type - ". $value;
                push(@modType, $value);
            }
	}
        $option .= ul(li("Modified Amino Acid: ". $modAA)) if $modAA;
        $option .= ul(li("Modification Type: ". join(', ', @modType))) if (@modType);
    }
    elsif ($category eq 'Nucleic Acid Binding') {
	foreach my $pair (@line) {
	    my ($key, $value) = split(/=/, $pair);
	    if ($key =~ /^gene_PD/) {
		$gene = $value;
	    }
	    elsif ($key =~ /^highlight_PD/) {
		$highlight = $value;
	    }
            elsif ($key =~ /^Binds/) {
		push(@nucBind, $value);
	    }
            elsif ($key =~ /^substrate_PD/) {
		$substrate = $value;
            }
	}
        if (@nucBind) {
	    $option .= ul(li("Nucleotide Binding: " . join(', ', @nucBind)));
        }

        if ($substrate) {
	    $option .= ul(li("Substrate Gene/ORF(s): " . $substrate));
        }
    }
    else {
	foreach my $pair (@line) {
	    my ($key, $value) = split(/=/, $pair);
	    if ($key =~ /^gene_PD/) {
		$gene = $value;
	    }
	    elsif ($key =~ /^highlight_PD/) {
		$highlight = $value;
	    }
            elsif ($key =~ /^other_PD/) {
		$other = $value;
	    }
            elsif ($key =~ /^proteinlength_PD/) {
		$prLen = $value;
            }
	}
        $option .= ul(li("Other Topic: ". $other)) if ($other);
        $option .= ul(li("Protein length (in Amino Acids): ". $prLen)) if ($prLen);
    }  

    $option = '---' if (!$option);


    $row = $self->rhDataRow($topic, $gene, $highlight, $option);

    return $row; 
}

#####################################################################
sub processTech {
#####################################################################
    my ($self, $category, @line) = @_;
    my $row; #the returned html row
    
    my ($gene, $option, $other, $highlight, $strainBk, $strainNmGt);
    my $topic = "Techniques & Reagents: ". $category;

    foreach my $pair (@line) {
        my ($key, $value) = split(/=/, $pair);
        if ($key =~ /^gene_TR/) {
            $gene = $value;
        }
        elsif ($key =~ /^other_TR/) {
	    $other = $value;
	}
	elsif ($key =~ /^highlight_TR/) {
            $highlight = $value;
	}
        elsif ($key =~ /^strainBk_TR/) {
            $strainBk = $value;
	}
        elsif ($key =~ /^StrainNmGt_TR/) {
            $strainNmGt = $value;
	}
    }

    
    $option .= ul(li("Other Topics: " . $other)) if ($other);
    $option .= ul(li("Strain background: " . $strainBk)) if ($strainBk);
    $option .= ul(li("Strain name & genotype: " . $strainNmGt)) if ($strainNmGt);
    
    $option = '---' if (!$option);

    $row = $self->rhDataRow($topic, $gene, $highlight, $option);

    return $row;
}

#####################################################################
sub processInteractions {
#####################################################################
    my ($self, $category, @line) = @_;
    my $row; #the returned html row

    my $topic = "Interactions: ". $category;
    my ($gene1, $mut1, $isSynLethal, $isSuppressor, $isEpi, $gene2, $mut2, $other, $OtherInter, $highlight, $strainBk, $strainNmGt, $regulated, $regulator, $option);

    foreach my $pair (@line) {
        my ($key, $value) = split(/=/, $pair);
        if ($key =~ /^gene1_IN/) {
            $gene1 = $value;
        }
        elsif ($key =~ /^mut1_IN/) {
            $mut1 = $value;
        }
        elsif ($key =~ /^synthetic/) {
            $isSynLethal = $value;
        }
        elsif ($key =~ /^supressor/) {
            $isSuppressor = $value;
        }
        elsif ($key =~ /^epistatic/) {
            $isEpi = $value;
        }
        elsif ($key =~ /^other_IN/) {
	    $other = $value;
	}
        elsif ($key =~ /^box4other_IN/) {
	    $OtherInter = $value;
	}
        elsif ($key =~ /^gene2_IN/) {
	    $gene2 = $value;
	}
        elsif ($key =~ /^mut2_IN/) {
	    $mut2 = $value;
	}
	elsif ($key =~ /^highlight_IN/) {
            $highlight = $value;
	}
        elsif ($key =~ /^strainBk_IN/) {
            $strainBk = $value;
	}
        elsif ($key =~ /^strainNm_IN/) {
            $strainNmGt = $value;
	}
	elsif ($key =~ /^regulated/) {
            $regulated = $value;
	}
	elsif ($key =~ /^regulator/) {
            $regulator = $value;
	}
    }

#    my $topPart;
    if ($category eq 'Other Interactions') {
        my $list = li("with " . $gene2);
        $list .= li("Other Topics: " . $other) if $other;
        $option = ul($list);
    }
    elsif ($category eq 'Genetic') {
        my @interactions;
        push(@interactions, $isSynLethal) if ($isSynLethal);
        push(@interactions, $isSuppressor) if ($isSuppressor);
        push(@interactions, $isEpi) if ($isEpi);
        push(@interactions, 'Other-' . $OtherInter) if ($OtherInter);

        my $list = li("with " . $gene2);
       
        my @mutationType;
        if ($mut1) {
	    push(@mutationType, "$mut1 for $gene1");
	}
	if ($mut2) {
	    push(@mutationType, "$mut2 for $gene2");
	}
        if (@mutationType) {
	    $list .= li("Mutation Type: ". join(', ', @mutationType));
        }

        if (@interactions) {
            $list .= li("Interactions: " . join(' | ', @interactions));
        }
        if ($strainBk) {
            $list .= li("Strain background: " . $strainBk);
        }
        if ($strainNmGt) {
            $list .= li("Strain name & genotype: " . $strainNmGt);
        }
        $option = ul($list);
    }
    elsif ($category eq 'Regulatory') {
	$option = ul(li("is regulated by: " . $gene2)) if ($regulated);
	$option .= ul(li("is a regulator of: " . $gene2)) if ($regulator);
    }
    else {
        $option = ul(li("with " . $gene2));
    }

    $option = '---' if (!$option);
    $row = $self->rhDataRow($topic, $gene1, $highlight, $option);

    return $row;
}

#####################################################################
sub processPhenotype {
#####################################################################
    my ($self, $category, @line) = @_;
    my $row; #the returned html row

    #pheno description
    my @phenodesc;
    my %phenoDesc = ("Dominant_"=>'1', "Recessive_"=>'1', "Viable_"=>'1',
                     "Inviable_"=>'1', "TemperatureSensitive_"=>'1',
                     "ColdSensitive_"=>'1', "LossFunction_"=>'1',
                     "GainFunction_"=>'1', "Revertable_"=>'1', 
                     "NoPhenotype_"=>'1', "OtherPhenotypeDescription_"=>'1', 
                     "inviableWhen_"=>'1');

    my $topic = "Alleles, Strains, & Mutant Phenotypes: ". $category;
    my ($gene, $option, $delgene, $otmGene, $pdFrom, $pdTo, $othTopic, $othPhe, $condition, $othMut, $allele, $highlight, $strainBk, $strainNmGt);

    foreach my $pair (@line) {
        my ($key, $value) = split(/=/, $pair);

        if ($key =~ /^gene_PH/) {
            $gene = $value;
        }
        elsif ($key =~ /^allele_PH/) {
            $allele = $value;
        }
        elsif ($key =~ /^deltGenePH/) {
            $delgene = $value;
        }
	elsif ($key =~ /^OthMutGenePH/) {
            $otmGene = $value;
        }
        elsif ($key =~ /^OtherTxtBoxPH/) {
            $othPhe = $value;
        }
        elsif ($key =~ /^CondiTxtBoxPH/) {
            $condition = $value;
        }
        elsif ($key =~ /^other_PH/) {
	    $othTopic = $value;
	}
        elsif ($key =~ /^otherMutPH/) {
	    $othMut = $value;
	}
        elsif ($key =~ /^PDtoPH/) {
	    $pdTo = $value;
	}
        elsif ($key =~ /^PDfromPH/) {
	    $pdFrom = $value;
	}
	elsif ($key =~ /^highlight_PH/) {
            $highlight = $value;
	}
        elsif ($key =~ /^strainBk_PH/) {
            $strainBk = $value;
	}
        elsif ($key =~ /^strainNm_PH/) {
            $strainNmGt = $value;
	}
    }

    foreach my $pair (@line) {
        my ($key, $value) = split(/=/, $pair);

        #get phenodescription
        if ($phenoDesc{$key}) {
            if ($key =~ /^OtherPhenotypeDescription/) {
		if ($othPhe) {
		    $value .= ": " . $othPhe;
		}
		else {next;}
            }
            if ($key =~ /inviableWhen/) {
		if ($condition) {
                    $value .= ": " . $condition;
		}
		else {next;}
	    }
            push(@phenodesc, $value);
            next;
        }
    }

    my $description = join('|', @phenodesc);

    $gene = $delgene || $otmGene if (!$gene);

    if ($category =~ /^Other Alleles/) {
        $option = li("Other Topics: " . $othTopic) if $othTopic;
    }
    elsif ($category =~ /^Other Mutation/) {
        $option = li("Other mutation: " . $othMut) if $othMut;
    }

    $option .= li("Allele name: " . $allele) if $allele;
    $option .= li("Strain background: " . $strainBk) if $strainBk;
    $option .= li("Strain name & genotype: " . $strainNmGt) if $strainNmGt;

    if ($category eq 'Partial Deletion') {
        $option .= li("Deletion chromosomal sequence coordinates: " . "From " . $pdFrom . " To " . $pdTo) if ($pdFrom || $pdTo);
    }

    $option .= li("Phenotype description: " . $description) if $description;

    my $prlist;
    if ($option) {
        $prlist = ul($option);
    }
    else {
	$prlist = '---';
    }

    $row = $self->rhDataRow($topic, $gene, $highlight, $prlist);

    return $row;
}

#####################################################################
sub processOther {
#####################################################################
    my ($self, $category, @line) = @_;
    my $row; #the returned html row

    my ($topic, $gene, $otherTopic, $highlight);
        foreach my $pair (@line) {
            my ($key, $value) = split(/=/, $pair);
            if ($key =~ /^gene_OT/) {
                $gene = $value;
            }
	    elsif ($key =~ /^OtherTopic_OT/) {
		$otherTopic = 'Other Topic: '. $value if $value;
	    }
	    elsif ($key =~ /^highlight_OT/) {
		$highlight = $value;
	    }
	} 

    $topic = 'Other';
    $otherTopic = '---' if (!$otherTopic);
    $row .=  $self->rhDataRow($topic, $gene, $highlight, $otherTopic);
    
    return $row;
}

#####################################################################
sub rhTitleRow {
#####################################################################
    my ($self) = @_ ;
    return Tr({-bgcolor=>"#b7d8e4"},
	      th("Topic"),
	      th("Gene/ORF"),
	      th("Research Highlight"),
	      th("Interacting Gene or Optional Info"));
}

#####################################################################
sub rhDataRow {
#####################################################################
    my ($self, $topic, $gene, $desc, $other) = @_ ;
    return Tr(td($topic), td($gene), td($desc), td($other)
	   );
}

#####################################################################
sub formatedCitation {
#####################################################################
    my ($self, $pubmed) = @_ ;
    my $formatedCitation;
    if ($pubmed) {
        my $refObj = Reference->new(dbh=>$dbh, pubmed=>$pubmed);

        if (!$refObj) {
            $self->err_report("Your PMID could not be processed. Either the PMID was entered incorrectly or this paper is not currently in our database. Please go back and re-enter the PMID. If you receive this message a second time, please report the problem to the dictyBase curators using the \"send a message\" form at the bottom of the page. Please include the PMID in your message.");
        }

        $formatedCitation = $refObj->formatedCitation;
        $formatedCitation .= br.br. "PubMed ID: " . $pubmed; 
    }

    return $formatedCitation;
}

#####################################################################
sub ConstructCitation {
#####################################################################
#no pubmedid, based on whatever user input search by volume and 
#page first. If get single result, go with it, otherwise take user's
#input and construct a fake citation.
    my ($self) = @_;
    my $citation;
    my @author;
    push(@author, param('author1')) if (param('author1'));
    push(@author, param('author2')) if (param('author2'));
    push(@author, param('author3')) if (param('author3'));
    push(@author, param('author4')) if (param('author4'));
    push(@author, param('author5')) if (param('author5'));
    push(@author, param('author6')) if (param('author6'));
    my $title = param('Reftitle');
    my $journal = param('journal');
    my $volume = param('volume');
    my $pages = param('pages');
    my $year = param('year');

    my $pg = $pages;
    $pg =~ s/-.*//;
    if ($volume && $pages && !(param('NoRefSearch') eq 'Yes')) {
        my $sth = $dbh->prepare("
            SELECT reference_no, pubmed 
            FROM CGM_DDB.reference
            WHERE volume = ? AND
                  page like ?
        ");

        $sth->execute($volume, $pg.'%');

        my @result;
        my @pubmed;
        while (my ($result, $pubmed) = $sth->fetchrow()) {
            push(@result, $result);
            push(@pubmed, $pubmed);
        }
        my $size = @pubmed;
        if ($size == 1) {
            my $refObj = Reference->new(dbh=>$dbh, pubmed=>$pubmed[0]);
            if (!$refObj) {
                $self->err_report("Invalid Pubmed: ".$pubmed[0]);
            }
            $citation = $refObj->formatedCitation;
            $citation .= br.br. "PubMed ID: " . $pubmed[0];
            return  ($citation, $pubmed[0]);
        }
    }

    #clean-up
    for (my $i=0; $i<@author; $i++) {
        $author[$i] =~ s/,/ /g;
    }
    $citation = b(join(', ', @author));
    $citation .= b(' ('. $year .') ') if ($year);
    $citation .= b($title) . ' ' if ($title);
    $citation .= i($journal) . ' ' if ($journal);
    $citation .= b($volume) if ($volume);
    $citation .= b(':' . $pages) if ($pages);
   
    return $citation;
}

#####################################################################
sub getParaStr {
#####################################################################
    my ($self) = @_;
    my $string;
    if (param('paraStr')) {
        $string = param('paraStr') . "@@@\n";
    }
    foreach my $item (param) {
        if ($item eq 'paraStr') {
            next;
        }
        $string .= $item . '==' . param($item) . '|||';
    }
#    $self->err_report($string);
    return $string;
}

#####################################################################
sub validation {
#####################################################################
    my ($self) = @_;

    my ($what, $multiGene) = $self->getThingsToValidate;

    if (param('SubmitAnnotation')) { #check one form just submitted
	my $subtopic = param('category');
        my $topic = param('topic');

        if (!$subtopic) {
	    $self->err_report("No category!");
        }

	my $fieldToCk = $$what{$subtopic};
        if (!$fieldToCk) {
	    $self->err_report("No field to check!");
        }

        my $errmssg;

        #check required fields
        foreach my $item (@$fieldToCk) {
            my $mssg;

#keep as one to one for release one
#	    if ($item =~ /^gene2/) {  
                #interacting genes multiple and required
#		$mssg = $self->validateMultiRequiredGenes($item, 'Interacting Gene/ORF');
#            }
	    if ($item =~ /^OthMutGenePH_/) {  
                #Other Mutations of Phenotype
		$mssg = $self->validateMultiRequiredGenes($item, 'Gene/ORF (& Allele name)');
            }
	    elsif ($item =~ /^deltGenePH_/) {  
                #MultiKnockoutStrain of Phenotype
		$mssg = $self->validateMultiRequiredGenes($item, 'Deleted Genes/ORFs');
            }
	    elsif ($item =~ /^gene/) { #gene1 also checked here
		$mssg = $self->validateGeneName(param($item));
            }
	    elsif ($item =~ /^chrSeqCoord/) {
		$mssg = $self->validateChrSeqCoord(param($item));
            }
            elsif ($item =~ /^highlight/) {
		$mssg = $self->validateHighlight(param($item));
            }
	    elsif ($item =~ /^other_/) {
		$mssg = $self->validateOtherTopic(param($item));
            }
            elsif ($item =~ /^proteinlength_/) {
		$mssg = $self->validateProLength(param($item));
            }
            elsif ($item =~ /^strainBk_/) {
		$mssg = $self->validateTextBox(param($item), "Strain background");
            }
            elsif ($item =~ /^StrainNmGt_/) {
		$mssg = $self->validateTextBox(param($item), "Strain name & genotype");
            }
            elsif ($item =~ /^PDfromPH_/) {
		$mssg = $self->validateNumberBox(param($item), "Sequence coordinate from which the deletion starts");
            }
            elsif ($item =~ /^PDtoPH_/) {
		$mssg = $self->validateNumberBox(param($item), "Sequence coordinate at which the deletion ends");
            }
	    $errmssg .= $mssg .br.br if ($mssg);
        }

	#check multiple genes fields
        my $errMulti = $self->validatemultiGene($multiGene);
        $errmssg .= $errMulti if ($errMulti);

        #check some of other non-required fields
        my $errOther = $self->validateOther;
        $errmssg .= $errOther .br.br if ($errOther);

        #check modification type for protein modification
        if ($subtopic eq 'Protein Modification') {
	    my $errModType = $self->validateModType;
            $errmssg .= $errModType .br.br if ($errModType);
        }

        #check nucleotide binding for Nucleic Acid Binding
        if ($subtopic eq 'Nucleic Acid Binding') {
	    my $errNuc = $self->validateNucBinding;
            $errmssg .= $errNuc .br.br if ($errNuc);
        }

        #check interaction type for Genetic interaction
        if ($subtopic eq 'Genetic') {
	    my $errInt = $self->validateInteractionType;
            $errmssg .= $errInt .br.br if ($errInt);
        }

        #check regulatory relationship for Regulatory interaction
        if ($subtopic eq 'Regulatory') {
	    my $errInt = $self->validateRegulatoryRelation;
            $errmssg .= $errInt .br.br if ($errInt);
        }

        #check phenotpe desc for Phenotype forms
        if ($topic eq 'Alleles, Strains, & Phenotypes') {
	    my $errPhe = $self->validatePhenotypeDesc;
            $errmssg .= $errPhe .br.br if ($errPhe);
        }

	if ($errmssg) {
	    $self->err_report($errmssg);
        }
        
    }
    else { #after final edit/confirm
	#get all subtopics (each has a unique annotationid appended to the end
	my %Subtopics;    #category vs uniqueId
	foreach my $item (param) {
	    if ($item =~ /category(\d+)$/) {
                $Subtopics{$1} = param($item);
            }
	}
        return if (!%Subtopics);

	my %Err;
        foreach my $id (keys %Subtopics) {
	    #skip if this annotation is to be deleted
	    my $delitem = 'Delete_' . $id;
	    next if param($delitem);  

	    my $subtopic = $Subtopics{$id};
            my $topic = param('topic'. $id);
            my $fieldToCk = $$what{$subtopic};
	    if (!$fieldToCk) {
		$self->err_report("No field to check!");
	    }

	    my $errmssg;

	    #check required fields
	    foreach my $field (@$fieldToCk) {
		my $mssg;
                my $item = $field. $id; #append id at end

#		if ($item =~ /^gene2/) {  
		    #interacting genes multiple and required
#		    $mssg = $self->validateMultiRequiredGenes($item, 'Interacting Gene/ORF');
#                }
		if ($item =~ /^OthMutGenePH_/) {  
                    
		    #Other Mutations of Phenotype
		    $mssg = $self->validateMultiRequiredGenes($item, 'Gene/ORF (& Allele name)');
		}
		elsif ($item =~ /^deltGenePH_/) {  
		    #MultiKnockoutStrain of Phenotype
		    $mssg = $self->validateMultiRequiredGenes($item, 'Deleted Genes/ORFs');
		}
		elsif ($item =~ /^gene/) {
		    $mssg = $self->validateGeneName(param($item));
		}
		elsif ($item =~ /^chrSeqCoord/) {
		    $mssg = $self->validateChrSeqCoord(param($item));
		}
		elsif ($item =~ /^highlight/) {
		    $mssg = $self->validateHighlight(param($item));
		}
		elsif ($item =~ /^other_/) {
		    $mssg = $self->validateOtherTopic(param($item));
		}
		elsif ($item =~ /^proteinlength_/) {
		    $mssg = $self->validateProLength(param($item));
                }
		elsif ($item =~ /^strainBk_/) {
		$mssg = $self->validateTextBox(param($item), "Strain background");
                }
		elsif ($item =~ /^StrainNmGt_/) {
		    $mssg = $self->validateTextBox(param($item), "Strain name & genotype");
		}
		elsif ($item =~ /^PDfromPH_/) {
		    $mssg = $self->validateNumberBox(param($item), "Sequence coordinate from which the deletion starts");
		}
		elsif ($item =~ /^PDtoPH_/) {
		    $mssg = $self->validateNumberBox(param($item), "Sequence coordinate at which the deletion ends");
		}
		$errmssg .= $mssg .br.br if ($mssg);
	    }

	    #check multiple genes fields
	    my $errMulti = $self->validatemultiGene($multiGene, $id);
	    $errmssg .= $errMulti if ($errMulti);

	    #check some of other non-required fields
	    my $errOther = $self->validateOther($id);
	    $errmssg .= $errOther .br.br if ($errOther);

            #check modification type for protein modification
	    if ($subtopic eq 'Protein Modification') {
		my $errModType = $self->validateModType($id);
		$errmssg .= $errModType .br.br if ($errModType);
	    }

	    #check nucleotide binding for Nucleic Acid Binding
	    if ($subtopic eq 'Nucleic Acid Binding') {
		my $errNuc = $self->validateNucBinding($id);
		$errmssg .= $errNuc .br.br if ($errNuc);
	    }

            #check interaction type for Genetic interaction
	    if ($subtopic eq 'Genetic') {
		my $errInt = $self->validateInteractionType($id);
		$errmssg .= $errInt .br.br if ($errInt);
	    }
	    
	    #check regulatory relationship for Regulatory interaction
	    if ($subtopic eq 'Regulatory') {
		my $errInt = $self->validateRegulatoryRelation($id);
		$errmssg .= $errInt .br.br if ($errInt);
	    }

	    #check phenotpe desc for Phenotype forms
	    if ($topic eq 'Alleles, Strains, & Phenotypes') {
		my $errPhe = $self->validatePhenotypeDesc($id);
		$errmssg .= $errPhe .br.br if ($errPhe);
	    }

	    if ($errmssg) {
		$Err{$id} = $errmssg;
	    }
        } # each id

        return if (!%Err);

        #print err messages.
        my $prtErr;
        foreach my $id (sort(keys %Err)) {
	    my $topic = param("topic$id");
            my $subtopic = $Subtopics{$id};
            $prtErr .= u($topic .':'.  $subtopic) .br.br . $Err{$id} . p; 
        }
        $self->err_report($prtErr);
    }

    return;
}

#####################################################################
sub validateGeneName {
#####################################################################
    my ($self, $gene) = @_;
#    my $gene = param($item);
    my $mssg;
    if (!$gene) {
        $mssg = font({-color=>'red'},"Gene/ORF"). " is required. Please go back and add it. Thanks!";
    }
    else { #check if the Gene/ORF name is valid
        &DeleteUnwantedChar(\$gene);
        $gene = uc($gene);
	
        if ($gene !~ /\w+/) {
	    $mssg = "Gene/ORF name (". font({-color=>'red'}, $gene) .") is invalid (note that we do not accept Alias name for now). Please " . a({-href=>$fullSrh, -target=>'fullsearch'}, "click here") . " to open a new window to search for the gene you want. Then you may use the BACK button on this page to edit and submit again. Thanks!";
        }
        else {
	    my $object = dictyBaseObject->new(database=>$self->database, query=>$gene);
	    if (!$object || !($object->isFeatureName || $object->isLocusName)) {
	    $mssg = "Gene/ORF name (". font({-color=>'red'}, $gene) .") is invalid (note that we do not accept Alias name for now). Please " . a({-href=>$fullSrh, -target=>'fullsearch'}, "click here") . " to open a new window to search for the gene you want. Then you may use the BACK button on this page to edit and submit again. Thanks!";
            }
        }
    }
    return $mssg;
}

#####################################################################
sub validateMultiRequiredGenes {
#####################################################################
    my ($self, $item, $Nm) = @_;
    my $errMssg;
    
    my $intgenes = param($item);
    $intgenes =~ s/\s//g;
    param($item, $intgenes);

    if (!$intgenes)  {
	$errMssg .= font({-color=>'red'}, $Nm). " is required. Please go back and add it. Thanks!";
    }
    else {
	my @genesToCk = split(/:/, $intgenes);
        my $count = 0;
        foreach my $gene (@genesToCk) {
	    my $mssg = $self->validateGeneName($gene);
            if ($mssg) {
                $count++;
                if ($count == 1) {
		    $errMssg .= $mssg;
	        }
                else {
		    $errMssg .= br.br. $mssg;
                }
	    }
        }
    }    

    return $errMssg;
}

#####################################################################
sub validatemultiGene {
#####################################################################
    my ($self, $toCk, $id) = @_;

    my $errMssg;

    foreach my $key (param) {
        my $tmpKey = $key;
        $tmpKey =~ s/(\d+)$//;
        if ($id) {  #check only thsoe belong to this annotation form
	    next if ($id ne $1);
        }
        
        if ($$toCk{$tmpKey}) {
            my $multigeneStr = param($key);
            $multigeneStr =~ s/\s//g;
            param($key, $multigeneStr);
	    my @genesToCk = split(/:/, $multigeneStr);
            next if (!@genesToCk);  #field may not be required

            foreach my $gene (@genesToCk) {
                #for motifboundPr, strip 'p' off
                $gene =~ s/p$//;
		my $mssg = $self->validateGeneName($gene);
                $errMssg .= $mssg .br.br if ($mssg);
            }
        }
    }

    return $errMssg;
}

#####################################################################
sub validateChrSeqCoord {
#####################################################################
    my ($self, $coord) = @_;
    my $mssg;
    if (!$coord) {
        $mssg = font({-color=>'red'},"Chromosomal sequence coordinates "). " is required. Please go back and add it. Thanks!";
    }
    else {
	if ($coord !~ /^[\d,\s]+$/) {
	    $mssg = "Invalid input (". font({-color=>'red'}, $coord) . "). Chromosomal sequence coordinates can only be numbers separated by ','. Please go back and modify it. Thanks!";
        }
    }

    return $mssg;
}

#####################################################################
sub validateHighlight {
#####################################################################
    my ($self, $desc) = @_;
    my $errMssg;
    &DeleteUnwantedChar(\$desc);
    
    if (!$desc) {
	$errMssg .= font({-color=>'red'}, "Research Highlight Description") . " is required. Please go back and add it. Thanks!";
    }
    elsif (length($desc) > 480)  {
	$errMssg .= "The description cannot exceed ". font({-color=>'red'}, '480'). " characters. Please go back and edit it. Thanks!";
    }

    return $errMssg;
}

#####################################################################
sub validateProLength {
#####################################################################
    my ($self, $len) = @_;
    my $errMssg;
    &DeleteUnwantedChar(\$len);
    if (!$len) {
	$errMssg .= font({-color=>'red'}, "Protein length (in Amino Acids)") . " is required. Please go back and add it. Thanks!";
    }
    elsif ($len !~ /^\d+$/)  {
	$errMssg .= "Invalid input (". font({-color=>'red'}, $len) . "). Protein length can only be numbers. Please go back and modify it. Thanks!";
    }

    return $errMssg;
}

#####################################################################
sub validateTextBox {
#####################################################################
    my ($self, $content, $boxNm) = @_;
    my $errMssg;
    &DeleteUnwantedChar(\$content);

    if (!$content) {
	$errMssg .= font({-color=>'red'}, $boxNm) . " is required. Please go back and add it. Thanks!";
    }
    elsif (length($content) > 100)  {
	$errMssg .= "The $boxNm cannot exceed ". font({-color=>'red'}, '100'). " characters. Please go back and edit it. Thanks!";
    }
    return $errMssg; 
}

#####################################################################
sub validateNumberBox {
#####################################################################
    my ($self, $content, $boxNm) = @_;
    my $errMssg;
    &DeleteUnwantedChar(\$content);

    if (!$content) {
	$errMssg .= font({-color=>'red'}, $boxNm) . " is required. Please go back and add it. Thanks!";
    }
    elsif ($content =~ /\D/)  {
	$errMssg .= "Invalid input (". font({-color=>'red'}, $content) ."). The $boxNm can only be a number. Please go back and edit it. Thanks!";
    }
    return $errMssg;

}

#####################################################################
sub validateOtherTopic {
#####################################################################
    my ($self, $othTopic) = @_;
    my $errMssg;
    &DeleteUnwantedChar(\$othTopic);

    if (!$othTopic) {
	$errMssg .= font({-color=>'red'}, "Other Topic") . " is required. Please go back and add it. Thanks!";
    }

    return $errMssg;
}

#####################################################################
sub validateModType {
#####################################################################
    my ($self, $id) = @_;
    my $errMssg;

    my @modType = ( 'Glycosylation_'.$id , 'Phosphorylation_'.$id , 'N-terminal_'.$id , 'C-terminal_'.$id , 'OMT_'.$id );

    foreach my $item (@modType) {
	if (param($item) ne '') {
	    return;   #found
        }
    }

    $errMssg = font({-color=>'red'}, "Modification type") . " is required. Please go back and add it. Thanks!";

    return $errMssg;
}

#####################################################################
sub validateNucBinding {
#####################################################################
    my ($self, $id) = @_;
    my $errMssg;

    my @nuc = ( 'BindsDNA_'.$id , 'BindsRNA_'.$id);

    foreach my $item (@nuc) {
	if (param($item) ne '') {
	    return;   #found
        }
    }

    $errMssg = font({-color=>'red'}, "Nucleotide Binding") . " is required. Please go back and add it. Thanks!";

    return $errMssg;
}

#####################################################################
sub validateInteractionType {
#####################################################################
    my ($self, $id) = @_;
    my $errMssg;

    my @intType = ( 'synthetic_'.$id , 'supressor_'.$id , 'epistatic_'.$id , 'box4other_IN_'.$id);

    foreach my $item (@intType) {
	if (param($item) ne '') {
	    return;   #found
        }
    }

    $errMssg = font({-color=>'red'}, "Interaction type") . " is required. Please go back and add it. Thanks!";

    return $errMssg;
}

#####################################################################
sub validateRegulatoryRelation {
#####################################################################
    my ($self, $id) = @_;
    my $errMssg;

    my @regType = ( 'regulated_'.$id , 'regulator_'.$id );

    foreach my $item (@regType) {
	if (param($item) ne '') {
	    return;   #found
        }
    }

    $errMssg = font({-color=>'red'}, "Regulatory relationship") . " is required. Please go back and check either/both. Thanks!";

    return $errMssg;
}

#####################################################################
sub validatePhenotypeDesc {
#####################################################################
    my ($self, $id) = @_;
    my $errMssg;

    my @pheType = ( 'Dominant_'.$id , 'Recessive_'.$id, 
                    'Viable_'.$id,    'Inviable_'.$id,
		    'TemperatureSensitive_'.$id,
                    'ColdSensitive_'.$id, 'LossFunction_'.$id,
                    'GainFunction_'.$id, 'Revertable_'.$id,
                    'NoPhenotype_'.$id, 'OtherTxtBoxPH_'.$id,
                    'CondiTxtBoxPH_'.$id
                  );

    foreach my $item (@pheType) {
	if (param($item) ne '') {
	    return;   #found
        }
    }

    $errMssg = font({-color=>'red'}, "Phenotype description") . " is required. Please go back and add it. Thanks!";

    return $errMssg;
}

#####################################################################
sub validateOther {
#####################################################################
    my ($self, $id) = @_;
    my $errMssg;

    foreach my $para (param) {
        $para =~ /(\d+)$/;
        if ($id) {  #check only thsoe belong to this annotation form
	    next if ($id ne $1);
        }
	if ($para =~ /^chrSeqCoord/) {
            my $coord = param($para);
	    &DeleteUnwantedChar(\$coord);
            next if (!$coord);
	    my $mssg = $self->validateChrSeqCoord($coord);
	    $errMssg .= $mssg .br.br if ($mssg);
        }
	elsif ($para =~ /^highlight/) {  #check it anyway
	    my $desc = param($para);
	    if (length($desc) > 480)  {
		$errMssg .= "The description cannot exceed ". font({-color=>'red'}, '480'). " characters. Please go back and edit it. Thanks!";
            }
        }
    }

    return $errMssg;
}

#####################################################################
sub saveSubmittedData  {
#####################################################################
    my ($self) = @_;

    open (DATA, ">>$tmpfile") || die "Can't open $tmpfile: $!\n";

    #get annotation no unique to this form
    my $serialNo = $self->getAnnoNum('temp');
    if (!$serialNo) {$self->err_report('No Serial')};
    print DATA "tmpAnnoNo=$serialNo\t";

    foreach my $item (param) {
        #have to get rid of any '\n'
        my $saveItem = param($item);
        $saveItem =~ s/\n//;
        print DATA $item . "=" . $saveItem . "\t";
    }
    print DATA "\n";    

    close $tmpfile;
    return;
}

#####################################################################
sub err_report {
#####################################################################
    my ($self, $err) = @_ ;
    my $title = "Community Annotation: Research Highlights" .br. "Error Report";
    &printStartPage($self->database, $title, "colleague.html");
    print p, b($err);
    &printEndPage;
    $self->DESTROY;
}

#####################################################################
sub EditConfirm  {
#####################################################################
    my ($self) = @_;
    my $dataFile = param('file');
    my $pubmed = param('pubmed');
    my $formatedCitation;

    my $lname = param('lname');
    my $fname = param('fname');
    my $email = param('email');
    my $contributor = $lname . ", " . $fname .br. $email;

    if ($pubmed) {
        $formatedCitation = $self->formatedCitation($pubmed);
    }
    else {
        $formatedCitation = param('formatedCitation');
    }

    my @content;
    open (DAT, "$dataFile") || die "Can't open $dataFile for read: $!\n";

    my $javascript =  "
      <SCRIPT language=\"JavaScript\"> 
      <!--
         function textCounter(field, countfield, maxlimit) {
            if (field.value.length > maxlimit)
              {field.value = field.value.substring(0, maxlimit);}
            else
              {countfield.value = maxlimit - field.value.length;}
         }
      //--> 
      </SCRIPT> "
    ;

    $title = 'Community Annotation: Research Highlights' .br. 'Edit or Confirm';
    &printStartPage($self->database, $title, $self->help);
    print $javascript;
    print start_form({-method=>'POST'});
    print hidden('emailReply', param('emailReply')) if (defined (param('emailReply')));

    while (<DAT>) {
        chomp;
        my @line = split(/\t/);
        my ($form, $first, $tmpAnnoNo);
        ($first, $tmpAnnoNo) = split(/=/, $line[0]);
        if (!$tmpAnnoNo) {
	    $self->err_report($tmpAnnoNo);
        }

        foreach my $pair (@line) {
            my ($key, $value) = split(/=/, $pair);
            $key .= $tmpAnnoNo;

            #spit out all data stored in file and let the table pick them up
            param($key, $value);
        }

        #pass topic and subtopic(category) to the next page
        print hidden( "topic$tmpAnnoNo", param("topic$tmpAnnoNo") );
	print hidden( "category$tmpAnnoNo", param("category$tmpAnnoNo") );

        if (param("topic$tmpAnnoNo") eq 'DNA & RNA Details') { 
            param('DNA', param("category$tmpAnnoNo"));
	    $form = $self->DNARNADetailForm($tmpAnnoNo);
        }
        elsif (param("topic$tmpAnnoNo") eq 'Protein Details') { 
            param('Protein', param("category$tmpAnnoNo"));
	    $form = $self->ProteinDetailForm($tmpAnnoNo);
        }
        elsif (param("topic$tmpAnnoNo") eq 'Techniques & Reagents') { 
            param('Techniques', param("category$tmpAnnoNo"));
	    $form = $self->TechForm($tmpAnnoNo);
        }
        elsif (param("topic$tmpAnnoNo") eq 'Interactions') { 
            param("Interactions", param("category$tmpAnnoNo"));
	    $form = $self->InteractionForm($tmpAnnoNo);
        }
        elsif (param("topic$tmpAnnoNo") eq 'Alleles, Strains, & Phenotypes') { 
            param('Phenotypes', param("category$tmpAnnoNo"));
	    $form = $self->PhenotypeForm($tmpAnnoNo);
        }
        elsif (param("topic$tmpAnnoNo") eq 'Other') { 
            param('Other', param("category$tmpAnnoNo"));
	    $form = $self->OtherForm($tmpAnnoNo);
        }
        else {
            $self->err_report("param('topic') is not found!");
        }
        push (@content, $form);  #save forms to display later        
    }
    close DAT;

    my $size = @content;

    print hidden('file', $dataFile);
    print hidden('lname', $lname);
    print hidden('fname', $fname);
    print hidden('email', $email);

    if ($pubmed) {
        print hidden('pubmed', $pubmed);
    }
    else {
        print hidden('formatedCitation', $formatedCitation);
    }

    print blockquote("Please review your submitted Research Highlights and edit or delete them if necessary. Then click on the \"Submit\" button for the final submission.");
    print table({-width=>"100%", -cellspacing=>"4", -cellpadding=>"4", -border=>"0"},
      Tr(th({-colspan=>'2', -align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Submitted Research Highlights")))  
    );

    print hr({- size=>"2"}), submit('AfterFinalEdit', 'Submit'), reset , " - Final confirmation and submission of all Research Highlights listed below.", hr({- size=>"2"}), br;

    #print annotation forms
    for (my $i=0; $i<$size; $i++) {

        print $content[$i];   #print all forms
        print br. hr({- size=>"2", -width=>"70%"}) . br if ($i != $size-1);
    }

    print hidden('file', $dataFile);
    print br, hr({- size=>"2"}), submit('AfterFinalEdit', 'Submit'), reset , " - Final confirmation and submission of all Research Highlights listed above.", hr({- size=>"2"}), br;
#    print $javascript;
#    print submit(-name=>'AfterFinalEdit', -value=>'Submit', -onClick=>'formsubmit()');

    print table({-width=>"100%", -cellspacing=>"4", -cellpadding=>"2", -border=>"0"},
      Tr(th({-align=>"left", -colspan=>'3', -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Contributor & Reference Information"))),
      Tr(td({-colspan=>'3'}, "The following contributor and reference will be
displayed alongside the Research Highlights listed above.")),
      Tr({-bgcolor=>"#b7d8e4"},
         th({-align=>"left"}, 'Contributor'),
         td({-bgcolor=>"#FFFFFF"}, "&nbsp"),
         th({-align=>"left"}, 'Reference')
      ),
      Tr(td({-valign=>"top"}, $contributor),
	 td({-valign=>"top"}, "&nbsp"),
         td({-valign=>"top"}, $formatedCitation)
      ),
    );

    print end_form;
    &printEndPage;

    $self->DESTROY;
}

#####################################################################
sub storeAnnotation  {
#####################################################################
    my ($self) = @_;

    $self->validation;

    my $dataFile = param('file');
    my $paraHref = $self->parametersForStorage;
    my $sepStr = '*' x 50;
    
    open (DAT, "$dataFile") || die "Can't open $dataFile for read: $!\n";
    open (STORE, ">>$annotationFile") || die "Can't open $annotationFile for writing: $!\n";
    
    my $count = 0;
    my ($colInfo, $pubmedID);
    while (<DAT>) {
	chomp;
        
        #check if this annotation is deleted
        $_ =~ /^tmpAnnoNo=(\d+)\s/;
        if (!$1) {$self->err_report('No tmpAnnoNo!')}
        my $check = 'Delete_'. $1;

        if (param($check)) {  #Delete box checked
            next;
        }

        $count++;     #how many anotation stored

        my @line = split(/\t/);

	#multiple genes, record in multiple records
	my ($topic, $category);
        foreach my $pair (@line) {
	    my ($key, $value) = split(/=/, $pair);
	    if ($key =~ /^topic/) {
		$topic = $value;
	    }
	    elsif ($key =~ /^category/) {
		$category = $value;
	    }
            elsif ($key =~ /^colleaInfo/) {
		$colInfo = $value;
	    }
            elsif ($key =~ /^pubmed/) {
		$pubmedID = $value;
            }
        }

	if ($topic =~ /^Interactions/) {
	    $self->storeInteraction($category, \*STORE, \@line, );
        }
        elsif (($category =~ /^Multiple Knockout/) || ($category =~ /^Other Mutation/)) {
	    $self->storeInteraction($category, \*STORE, \@line, );
        }
        else {
	    my $serialNo = $self->getAnnoNum('final');
	    print STORE "\n" . $sepStr . "\n"; # . $_ . "\n\n";
	    print STORE "<annotationid>" . $serialNo . "</annotationid>\t";

	    foreach my $pair (@line) {
		my ($key, $value) = split(/=/, $pair);
		my $tmpKey = $key;
		$tmpKey =~ s/_.*$/_/; #get rid of tmpAnnoNo

		next if ((!$value) || (!$$paraHref{$tmpKey}));

		#get dictyBaseID
		if ($tmpKey =~ /^gene_/) {
		    my $object = dictyBaseObject->new(database=>$self->database, query=>$value);
		    my $dictyBaseid = $object->primarydictyBaseID;
		    print STORE "<dictyBaseid>". $dictyBaseid ."</dictyBaseid>\t";
		}

                &DeleteUnwantedChar(\$value);
		print STORE "<" . $$paraHref{$tmpKey} . ">" . $value . "</" . $$paraHref{$tmpKey} . ">" . "\t";
	    }
        }
    }

    close DAT;
    close STORE;

    $title = 'Community Annotation: Research Highlights';
    &printStartPage($self->database, $title, $self->help);
    if ($count == 0) {
        print b("You haven't submitted any annotation!") .p. "To contribute more Research Highlights, please ". a({-href=>$SelfUrl}, "Click Here.");
    }
    else {
        print
            table({-cellpadding=>"4", -width=>"100%", -cellspacing=>"3", -border=>"0"},
              Tr(td({-align=>'center'}, font({-size=>'+1'}, "Your Research Highlight submission has been received by dictyBase.") .br.br. font({-size=>'+2', -color=>"green"}, b("Thank You!") .br))),
              Tr(td(br. "We will send you a confirmation e-mail in 1-2 business days and your Research Highlights will be posted at that time.")),
#              Tr(td(br. $annotationFile)),
              Tr(td(br. "To contribute more Research Highlights, please ". a({-href=>$SelfUrl}, "Click Here.")))
	    );

	#send email to curator
        $self->notifyCurator($colInfo, $pubmedID);

        #store if it's reply from dictyBase's email to corresponding  author of paper.
	if (defined (param('emailReply'))) {
	    $self->saveEmailReply($colInfo, $pubmedID);
	}
    }
    &printEndPage;

    $self->DESTROY;
}

#####################################################################
sub storeInteraction {
#####################################################################
    my ($self, $category, $fh, $aref) = @_;
    my $sepStr = '*' x 50;
    my $paraHref = $self->parametersForStorage;
    my %storeList;
    my @gene = ();
    foreach my $pair (@$aref) {
	my ($key, $value) = split(/=/, $pair);
        &DeleteUnwantedChar(\$value);
        if ($key =~ /^gene1/) {
	    $gene[0] = $value;
	}
	elsif ($key =~ /^gene2/) {
	    $gene[1] = $value;
	}
	elsif (($key =~ /^deltGene/) || ($key =~ /^OthMutGene/)) {
	    @gene = split(/:/, $value);
	}
	else {
	    my $tmpKey = $key;
	    $tmpKey =~ s/_.*$/_/;
	    next if ((!$value) || (!$$paraHref{$tmpKey}));
	    $storeList{$tmpKey} =  "<" . $$paraHref{$tmpKey} . ">" . $value . "</" . $$paraHref{$tmpKey} . ">";
        }
    }

    #deal with gene1, gene2, mut1, mut2...
    if ($category =~ /^Genetic/) {
	for (my $i=0; $i<@gene; $i++) {
	    &DeleteUnwantedChar(\$gene[$i]);
	    my $serialNo = $self->getAnnoNum('final');
	    if ($i == 0) {
		$storeList{'gene'} = "<gene>". $gene[$i] . "</gene>";
		if ($storeList{'synthetic_'}) {
		    $storeList{'synthetic_'} = "<" . $$paraHref{'synthetic_'} . ">is synthetic lethal with " . $gene[1] . "</" . $$paraHref{'synthetic_'} . ">";
		}
		if ($storeList{'supressor_'}) {
		    $storeList{'supressor_'} = "<" . $$paraHref{'supressor_'} . ">is a suppressor of " . $gene[1] . "</" . $$paraHref{'supressor_'} . ">";
		}
		if ($storeList{'epistatic_'}) {
		    $storeList{'epistatic_'} = "<" . $$paraHref{'epistatic_'} . ">is epistatic to " . $gene[1] . "</" . $$paraHref{'epistatic_'} . ">";
		}
		if ($storeList{'OtherInter_'}) {
		    $storeList{'OtherInter_'} = "<" . $$paraHref{'OtherInter_'} . ">" . $gene[1] . "</" . $$paraHref{'OtherInter_'} . ">";
		}
	    }
	    else {
		$storeList{'gene'} = "<gene>". $gene[$i] . "</gene>";

                if ($i == 1) { #swap mut1 and mut2
                    my ($newMut1, $newMut2);
		    if ($storeList{'mut1_'}) {
                        $newMut2 = $storeList{'mut1_'};
			$newMut2 =~ s/mutation1/mutation2/g;
		    }	    
		    if ($storeList{'mut2_'}) {
			$newMut1 = $storeList{'mut2_'};
			$newMut1 =~ s/mutation2/mutation1/g;
		    }
		    $storeList{'mut1_'} = $newMut1;
                    $storeList{'mut2_'} = $newMut2;
	        }

		if ($storeList{'synthetic_'}) {
		    $storeList{'synthetic_'} = "<" . $$paraHref{'synthetic_'} . ">is synthetic lethal with " . $gene[0] . "</" . $$paraHref{'synthetic_'} . ">";
		}
		if ($storeList{'supressor_'}) {
		    $storeList{'supressor_'} = "<" . $$paraHref{'supressor_'} . ">is suppressed by " . $gene[0] . "</" . $$paraHref{'supressor_'} . ">";
		}
		if ($storeList{'epistatic_'}) {
		    $storeList{'epistatic_'} = "<" . $$paraHref{'epistatic_'} . ">is epistatic to " . $gene[0] . "</" . $$paraHref{'epistatic_'} . ">";
		}
		if ($storeList{'OtherInter_'}) {
		    $storeList{'OtherInter_'} = "<" . $$paraHref{'OtherInter_'} . ">" . $gene[0] . "</" . $$paraHref{'OtherInter_'} . ">";
		}
	    }

	    #get dictyBaseID for this gene
	    my $object = dictyBaseObject->new(database=>$self->database, query=>$gene[$i]);
	    my $dictyBaseid = $object->primarydictyBaseID;
	    
	    print $fh "\n$sepStr\n" . "<annotationId>". $serialNo ."</annotationId>\t" . "<dictyBaseid>". $dictyBaseid ."</dictyBaseid>\t"; 
	    foreach my $key (keys %storeList) {
		print $fh $storeList{$key}."\t";
            }
	}
    }
    elsif ($category =~ /^Regulatory/) {
	for (my $i=0; $i<@gene; $i++) {
	    &DeleteUnwantedChar(\$gene[$i]);
	    my $serialNo = $self->getAnnoNum('final');
	    if ($i == 0) {
		$storeList{'gene'} = "<gene>". $gene[0] . "</gene>";
		$storeList{'with'} = "<with>". $gene[1] . "</with>";
		my $regulator = $storeList{'regulator_'};
                my $regulated = $storeList{'regulated_'};
	    }
	    else {
		$storeList{'gene'} = "<gene>". $gene[1] . "</gene>";
		$storeList{'with'} = "<with>". $gene[0] . "</with>";

		my $regulator = $storeList{'regulator_'};
                my $regulated = $storeList{'regulated_'};

		if ($regulated) {
		    $storeList{'regulated_'} = "<regulator>This gene is a regulator of</regulator>";
		}
		if ($regulator) {
		    $storeList{'regulator_'} = "<regulated>This gene is regulated by</regulated>";
	        }
	    }

	    #get dictyBaseID for this gene
	    my $object = dictyBaseObject->new(database=>$self->database, query=>$gene[$i]);
	    my $dictyBaseid = $object->primarydictyBaseID;

	    print $fh "\n$sepStr\n" . "<annotationId>". $serialNo ."</annotationId>\t" . "<dictyBaseid>". $dictyBaseid ."</dictyBaseid>\t";
	    foreach my $key (keys %storeList) {
		print $fh $storeList{$key}."\t";
	    }
        }
    }
    else {
	for (my $i=0; $i<@gene; $i++) {
	    &DeleteUnwantedChar(\$gene[$i]);
	    my $serialNo = $self->getAnnoNum('final');
	    $storeList{'gene'} = "<gene>". $gene[$i] . "</gene>";
	    if (($category !~ /^Multiple Knock/) && ($category !~ /^OthMutGene/)) {
                #when two genes, save another one in 'with'
		$storeList{'with'} = "<with>". $gene[$i-1] . "</with>";
	    }

	    #get dictyBaseID for this gene
	    my $object = dictyBaseObject->new(database=>$self->database, query=>$gene[$i]);
	    my $dictyBaseid = $object->primarydictyBaseID;
	    print $fh "\n$sepStr\n" . "<annotationId>". $serialNo ."</annotationId>\t". "<dictyBaseid>". $dictyBaseid . "</dictyBaseid>\t";
	    foreach my $key (keys %storeList) {
		print $fh $storeList{$key}."\t";
            }
        } 
    }

    return;
}

#####################################################################
sub storeRegulatoryMotifs {
#####################################################################
    my ($self, $category, $fh, $aref) = @_;
    my $sepStr = '*' x 50;
    my $paraHref = $self->parametersForStorage;

    my %storeList;
    my $primaryGene;
    my @motifBindGene;
    foreach my $pair (@$aref) {
	my ($key, $value) = split(/=/, $pair);
        &DeleteUnwantedChar(\$value);

	my $tmpKey = $key;
	$tmpKey =~ s/_.*$/_/;
	next if ((!$value) || (!$$paraHref{$tmpKey}));
	$storeList{$tmpKey} =  "<" . $$paraHref{$tmpKey} . ">" . $value . "</" . $$paraHref{$tmpKey} . ">";
    }

    my $serialNo = $self->getAnnoNum('final');

    #get dictyBaseID for this gene
    my $gene = $storeList{'gene_'};
    my $object = dictyBaseObject->new(database=>$self->database, query=>$gene);
    my $dictyBaseid = $object->primarydictyBaseID;
    print $fh "\n$sepStr\n" . "<annotationId>". $serialNo ."</annotationId>\t". "<dictyBaseid>". $dictyBaseid . "</dictyBaseid>\t";

    foreach my $key (keys %storeList) {
	    print $fh $storeList{$key}."\t";
    } 

    return;
}

#####################################################################
sub getParaList  {
#####################################################################
    my ($self, $pubmed) = @_;
    my %paraList;
    my $Obj = Reference->new(dbh=>$dbh, pubmed=>$pubmed);
    my @author = ('author1', 'author2', 'author3', 'author4', 'author5', 'author6');
    my $authorList = $Obj->authorList;
    my @refAuthor = split(/,/, $authorList);
    for (my $i=0; $i<@refAuthor; $i++) {
        $paraList{$author[$i]} = $refAuthor[$i];
        last if ($i == 5);
    }
    $paraList{'journal'} = $Obj->journal;
    my $row = $Obj->getRow;
    my @row = split(/\t/, $row);
    $paraList{'Reftitle'} = $row[11];
    $paraList{'volume'} = $row[10];
    $paraList{'pages'} = $row[9];
    $paraList{'year'} = $row[4];   

    return %paraList;
}

#####################################################################
sub getAnnoNum {
#####################################################################
    my ($self, $which) = @_;

    # number file name
    
    my $NUMFILE = $configPath->dataDir4web ."submission/community/$db1/serialNumber.$which";
    # lock file name
#    my $NUMLOCK = "/usr/local/dicty/www_dictybase/db/html/html/dictyBase/submission/CommuAnnotation/number.lock";
    my $NUMLOCK = $configPath->dataDir4web ."submission/community/$db1/number.lock";

    # abstract number
    my $annonum = 0;

    # should we get the number, yes
    my $getnum = 1;

    while ($getnum) {
    #
    # check is lock file exists
    #
         my  
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat "$NUMLOCK";

    #
    # if lock file does not exist $atime is blank
    #
        if ($atime eq '') {
    #
    # opening the lockfile will create it on disk
    #
            open (numlock, ">$NUMLOCK") || die("cannot open lockfile\n");
    #
    # open and read in the number file
    #
            open (numfile, "$NUMFILE") || die("could not open numfile\n");
            read(numfile, $annonum, 6);
            if (!$annonum) {
                 die("got no annotationid number\n");
            }
            $annonum = $annonum + 1;
    #
    # close the number file for reading and open for writing
    #
            close(numfile);
            open (numfile, ">$NUMFILE") || die("could not write to numfile\n");
            $annonum = sprintf "%6s", $annonum;
            $annonum =~ s/ /0/g;
            print numfile "$annonum\n";

    #
    # close the number and lock files
            close(numfile);
            close(numlock);

    # we got the abstract number so now, get the number should be FALSE
            $getnum = 0;
        }  
        else {
    #
    # if lock file is present then wait a second and stat again
    #
         sleep 1;
        }
    }
    unlink($NUMLOCK);
    return $annonum;
}

#####################################################################
sub checkPubmed  {
#####################################################################
    my ($self, $pubmed) = @_;

    &DeleteUnwantedChar(\$pubmed);
    #pubmed should be all digits.
    if ($pubmed =~ /\D/) {
        my $mssg = "Pubmed ID cannot contain non-digit. Pls check your input (". font({-color=>'red'}, $pubmed) .") and try again. Thanks!";
        $self->err_report($mssg);
    }

    my $sth = $dbh->prepare("
            SELECT reference_no
            FROM CGM_DDB.reference
            WHERE pubmed = ?
        ");
    $sth->execute($pubmed);
    if ($sth->fetchrow()) {
        return $pubmed;
    }
    else {
        my $mssg = "The Pubmed ID (". font({-color=>'red'}, $pubmed) .") you entered is not found in dictyBase.  Please select the BACK button in your browser and enter a different PMID. You can find papers in dictyBase by entering an author name in the search box at the top of any dictyBase page. The PubMed link next to each reference will take you to an abstract page. At the bottom of the abstract page you will find the PubMed ID.";
        $self->err_report($mssg);
    }
}

#####################################################################
sub parametersForStorage  {
#####################################################################
    my ($self) = @_;

    #map between parameter name and its corresponding tag in storage file
    my %ParaStore = ('colleagueid' => 'colleagueid',
                     'pubmed' => 'pubmedid',
                     'topic' => 'topic',
                     'category' => 'category',
                     'gene_' => 'gene',
                     'chrSeqCoord_' => 'ChrCoordinate',
                     'highlight_' => 'description',
                     'motif_' => 'motif',
                     'startCoord_' => 'startCoord',
                     'stopCoord_' => 'stopCoord',
                     'motifboundPr_' => 'motifboundPr',
                     'other_' => 'otherTopic',
                     'modifiedAA_' => 'modifiedAA',
                     'OMT_' => 'OtherModificationType',
                     'Glycosylation_' => 'Glycosylation',
                     'Phosphorylation_' => 'Phosphorylation',
                     'N-terminal_' => 'N-terminal',
                     'C-terminal_' => 'C-terminal',
                     'proteinlength_' => 'proteinlength',
                     'BindsDNA_' => 'BindsDNA',
                     'BindsRNA_' => 'BindsRNA',
                     'substrate_' => 'substrate',
                     'strainBk_' => 'strainBackground',
                     'StrainNmGt_' => 'strainNameGenotype',
                     'gene1_' => 'gene1',
                     'mut1_' => 'mutation1',
                     'synthetic_' => 'syntheticLethal',
                     'supressor_' => 'supressor',
                     'epistatic_' => 'epistatic',
                     'box4other_' => 'OtherDesc',
                     'gene2_' => 'gene2',
                     'mut2_' => 'mutation2',
		     'regulated_' => 'regulated',
		     'regulator_' => 'regulator',
                     'strainNm_' => 'strainNameGenotype',
                     'strainBg_' => 'strainBackground',
                     'Dominant_'=>'Dominant', 
                     'Recessive_'=>'Recessive', 
                     'Viable_'=>'Viable',
                     'Inviable_'=>'Inviable', 
                     'TemperatureSensitive_'=>'TemperatureSensitive',
                     'ColdSensitive_'=>'ColdSensitive', 
                     'LossFunction_'=>'LossFunction',
                     'GainFunction_'=>'GainFunction', 
                     'Revertable_'=>'Revertable', 
                     'NoPhenotype_'=>'NoPhenotype', 
                     'OtherPhenotypeDescription_'=>'OtherPhenotypeDescription', 
                     'OtherInter_'=>'OtherInteraction',
                     'inviableWhen_'=>'inviableWhen',
                     'allele_' => 'allele',
                     'deltGene_' => 'deletedGenes',
		     'OthMutGene_' => 'otherMutationGenes',
                     'OtherTxtBoxPH_' => 'OtherPhenotype',
                     'CondiTxtBoxPH_' => 'condition',
                     'otherMutPH_' => 'otherMutation',
                     'PDtoPH_' => 'partialDelTo',
                     'PDfromPH_' => 'partialDelfrom',
                    # 'strainBk_Pheno'=> 'strainBackground',
                    # 'strainNm_' => 'strainName',
                     'OtherTopic_' => 'OtherTopic',
                     'newColleaInfo' => 'newColleaInfo',
                     'colleaInfo' => 'colleaInfo',
                     'author1' => 'author1', 
                     'author2' => 'author2', 
                     'author3' => 'author3', 
                     'author4' => 'author4', 
                     'author5' => 'author5', 
                     'author6' => 'author6', 
                     'Reftitle' => 'Reftitle', 
                     'journal' => 'journal', 
                     'volume' => 'volume', 
                     'pages' => 'pages', 
                     'year' => 'year' );
    return \%ParaStore;
}

#####################################################################
sub parametersToSpare  {
#####################################################################
    my ($self) = @_;

    my %ParaSpare = ('colleagueid' => 'colleagueid',
                     'tmpAnnoNo' => 'tmpAnnoNo',
                     'pubmed' => 'pubmedid',
                     'newColleaInfo' => 'newColleaInfo',
                     'colleaInfo' => 'colleaInfo',
                     'file' => 'file',
                     'author1' => 'author1', 
                     'author2' => 'author2', 
                     'author3' => 'author3', 
                     'author4' => 'author4', 
                     'author5' => 'author5', 
                     'author6' => 'author6', 
                     'Reftitle' => 'Reftitle', 
                     'journal' => 'journal', 
                     'volume' => 'volume', 
                     'pages' => 'pages', 
                     'year' => 'year' );
    return \%ParaSpare;
}

#####################################################################
sub parameterCheckbox  {
#####################################################################
    my ($self) = @_;
    my %Pheno = ('Dominant_'=>'Dominant', 
                     'Recessive_'=>'Recessive', 
                     'Viable_'=>'Viable',
                     'Inviable_'=>'Inviable', 
                     'TemperatureSensitive_'=>'TemperatureSensitive',
                     'ColdSensitive_'=>'ColdSensitive', 
                     'LossFunction_'=>'LossFunction',
                     'GainFunction_'=>'GainFunction', 
                     'Revertable_'=>'Revertable', 
                     'NoPhenotype_'=>'NoPhenotype', 
                     'OtherPhenotypeDescription_'=>'OtherPhenotypeDescription', 
      		     'inviableWhen_'=>'inviableWhen');
    my %Inter = ('synthetic_' => 'syntheticLethal',
                     'supressor_' => 'supressor',
                     'epistatic_' => 'epistatic',
                     'OtherInter_'=>'OtherInteraction',
                     'regulated' => 'is_regulated_by',
                      'regulator' => 'is_a_regulator_of'
		 );
    return (\%Pheno, \%Inter);
}

#######################################################################
sub redstar {
#######################################################################
    my ($self) = @_;
    return font({-color=>'red'}, '*');
}

#######################################################################
sub redanchor {
#######################################################################
    my ($self) = @_;
    return font({-color=>'red'}, '^');
}

#######################################################################
sub updateCollEmail {
#######################################################################
    my ($self, $colId, $pubmed) = @_;

    $title = 'Community Annotation: Research Highlights' .br. 'Update Email Address';
    &printStartPage($self->database, $title, $self->help);
    print start_form({-method=>'POST'});
    print hidden('colleagueid', $colId);
    print hidden('pubmed', $pubmed);
    print hidden('emailReply', param('emailReply')) if (defined (param('emailReply')));

    print font({-color=>'red'}, "The email address is required and you don't have it in our database. Please give your email in the textbox below and click 'Submit'. Thanks!") , br, br;

    print textfield({-name=>"updateemail", -size=>"30"}), br;
    print submit('All', 'Submit');

    print end_form;
    &printEndPage;

    $self->DESTROY;
}

#######################################################################
sub saveCollEmail {
#######################################################################
    my ($self, $colId, $email) = @_;

    #connect to database as 'OTTO'
    my ($dbuser, $dbpasswd) = &getUsernamePassword("OTTO", $self->database);

    my $dbhWrite = &ConnectToDatabase($self->database, $dbuser, $dbpasswd);
    if (!$dbhWrite) {
	$self->err_report("No db handle!");
    }

    my $getEmailNo = $dbhWrite->prepare("
                        SELECT CGM_DDB.emailno_seq.nextval FROM dual
                     ");
    $getEmailNo->execute;
    my $eNo= $getEmailNo->fetchrow();
    $getEmailNo->finish;

    if (!$eNo) { $self->err_report("No email Number!"); }

    my $inertEmail = $dbhWrite->prepare("
                  INSERT INTO CGM_DDB.email
                  (email_no, email, date_created, created_by)
                  VALUES (?, ?, sysdate, ?)
              ");

    my $insertCollEmail = $dbhWrite->prepare("
                  INSERT INTO CGM_DDB.coll_email
                  (colleague_no, email_no)
                  VALUES (?, ?)
              ");

    $inertEmail->execute($eNo, $email, 'OTTO');
    $insertCollEmail->execute($colId, $eNo);
    $dbhWrite->commit();

    $dbhWrite->disconnect;

    return;
}

#######################################################################
sub checkColleageExist {
#######################################################################
    my ($self) = @_;
    my $lname = param('lname');
    my $fname = param('fname');
    my $email = param('email');
    my $institution = param('institution');
    
    my $sth = $dbh->prepare("
        SELECT c.colleague_no
        FROM CGM_DDB.colleague c, CGM_DDB.coll_email ce, CGM_DDB.email e
        WHERE c.last_name = ? AND
              c.first_name = ? AND
              c.institution = ? AND 
              c.colleague_no = ce.colleague_no AND
              ce.email_no = e.email_no AND
              e.email = ?
    ");
    $sth->execute($lname, $fname, $institution, $email);

    my $check = $sth->fetchrow();
    return $check;
}

#######################################################################
sub startMssg   {
#######################################################################
    my ($self) = @_;
    my $mssg = blockquote("The first step in submitting a \"Research Highlight\" to dictyBase is identifying yourself and the publication you are citing. Fill in both sections below and then hit the \"Submit\" button.");

    return $mssg; 
}

#######################################################################
sub getThingsToValidate {
#######################################################################
    my ($self) = @_;

    #each array contain a list of required fields for that subtopic
    my @dnamod = ('gene_DR_');
    my @transtart = ('gene_DR_', 'chrSeqCoord_DR_');
    my @regmotif = ('gene_DR_');
    my @rnaprocess = ('gene_DR_');
    my @rnadegrade = ('gene_DR_', 'highlight_DR_');
    my @rnafunction = ('gene_DR_', 'highlight_DR_');
    my @otherdna = ('gene_DR_', 'highlight_DR_', 'other_DR_');

    my @promod = ('gene_PD_');
    my @promature = ('gene_PD_', 'proteinlength_PD_');
    my @probinding = ('gene_PD_');
    my @proother = ('gene_PD_', 'highlight_PD_', 'other_PD_');
    my @proelse = ('gene_PD_', 'highlight_PD_');

    my @techstrain = ('gene_TR_', 'strainBk_TR_', 'StrainNmGt_TR_'); 
    my @techother = ('gene_TR_', 'highlight_TR_', 'other_TR_'); 
    my @techelse =  ('gene_TR_', 'highlight_TR_'); 

    my @intelse = ('gene1_IN_', 'gene2_IN_');
    my @intother = ('gene1_IN_', 'gene2_IN_', 'highlight_IN_', 'other_IN_');

    my @phenoelse = ('gene_PH_');
    my @partdel = ('gene_PH_', 'PDfromPH_', 'PDtoPH_');
    my @othermut = ('OthMutGenePH_', 'highlight_PH_');
    my @multiknock = ('deltGenePH_');
    my @phenoother = ('gene_PH_', 'highlight_PH_', 'other_PH_');

    my @other = ('gene_OT_', 'highlight_OT_', 'OtherTopic_OT_');

    #hold all required fields.
    my %required = ('DNA Modification' => \@dnamod,
                  'Transcription Start' => \@transtart,
                  'Regulatory Motifs' => \@regmotif,
                  'RNA Processing/Modification' => \@rnaprocess,
		  'RNA Degradation' => \@rnadegrade,
		  'RNA Function/Processing' => \@rnafunction,
                  'Other DNA & RNA Details' => \@otherdna,
		         ##############
                  'Protein Modification' => \@promod, 
                  'Protein Degradation' => \@proelse, 
                  'Protein Localization' => \@proelse, 
                  'Protein Function/Process' => \@proelse, 
                  'Mature Length (direct evidence)' => \@promature, 
                  'Nucleic Acid Binding' => \@probinding, 
                  'Other Protein Details'=> \@proother,
		         ##############
                  'Antibodies' => \@techelse, 
		  'Protein Purification' => \@techelse, 
		  'Strains & Constructs' => \@techstrain, 
                  'Unique Assays' => \@techelse, 
                  'Other Techniques & Reagents' => \@techother,
                         ##############
                  'Genetic' => \@intelse, 
                  'Physical' => \@intelse, 
                  'Two Hybrid' => \@intelse, 
                  'Regulatory' => \@intelse, 
                  'Other Interactions' => \@intother,
                         ##############
		   'Complete Deletion' => \@phenoelse, 
		   'Partial Deletion' => \@partdel, 
		   'Point Mutation' => \@phenoelse, 
                   'Other Mutation' => \@othermut, 
                   'Multiple Knockout Strains' => \@multiknock, 
		   'Overexpression' => \@phenoelse, 
                   'Other Alleles, Strains...' => \@phenoother,
		         ##############
                   'Other' => \@other
                 );

    #other field to check but not a required field
    my %multipleGene = ('motifboundPr_DR_' => '1',
                        'substrate_PD_' => '1'
		       );

    return (\%required, \%multipleGene);
}

#######################################################################
sub DNARNAInstruction {
#######################################################################
    my ($self) = @_;
    my $instruction;
    my $type = param('DNA');

    if ($type eq 'DNA Modification') {
	$instruction = Tr(td("Use the following form for any information on the chemical or structural modification of DNA near or in a gene (e.g. methylation sites, chromatin structure).")) . 
                       Tr(td(ul(li("If the modification occurs over a range of sequence coordinates, rather than at a discrete site, please enter this information into the \"Research Highlight Description\" field. "))));
    }
    elsif ($type eq 'Transcription Start') {
	$instruction = Tr(td("Use the following form for experimentally determined transcription start sites"));
    }
    elsif ($type eq 'Regulatory Motifs') {
	$instruction = Tr(td("Use the following form for information on DNA encoded motifs that contribute to the regulation of a gene")).
                       Tr(td(ul(li("When entering protein information, please use the standard gene name (e.g. ACT1p) rather than a common protein name (e.g. actin)."), li("\"".$self->redanchor. "\" indicates that multiple genes/ORFs can be entered into this field; separate with colons (\":\")."), li("Note that this information will be linked to all the genes that are entered into this form. "))));
    }
    elsif ($type eq 'RNA Processing/Modification') {
	$instruction = Tr(td("Use the following form for any details on the processing or modification of RNA (e.g. experimental demonstration of intron splicing, pseudouridylation, etc.)"));
    }
    elsif ($type eq 'RNA Degradation') {
	$instruction = Tr(td("Use the following form for description of the degradation of an RNA molecule"));
    }
    elsif ($type eq 'RNA Function/Processing') {
	$instruction = Tr(td("Use the following form for description of the function or process of RNA molecules other than mRNA."));
    }
    else {
	$instruction = Tr(td("Use the following form for any information pertaining to DNA or RNA that doesn't fit into any of the given topics - specify your own topic in the \"DNA & RNA Details\" category")).
	    Tr(td(ul(li("Use this submission form only when none of the given \"DNA & RNA Details\" topics apply."), li("Specify your own topic heading in the \"Other Topic\" field."))));
    }

    return $instruction;
}

#######################################################################
sub ProteinInstruction {
#######################################################################
    my ($self) = @_;
    my $instruction;
    my $type = param('Protein');

    if ($type eq 'Protein Modification') {
	$instruction = Tr(td("Use the following form for experimentally determined information on the modification of a protein (e.g.glycosylation, phosphorylation, N-terminal modification, C-terminal modification, etc.")).
                       Tr(td(ul(li("To indicate the type of protein modification, choose at least one checkbox from the \"Modification Type\" section. Check all that apply "))));
    }
    elsif ($type eq 'Protein Degradation') {
	$instruction = Tr(td("Use the following form for description of the degradation of a protein."));
    }
    elsif ($type eq 'Protein Localization') {
	$instruction = Tr(td("Use the following form for information on the localization of a protein, including both the site and process of localization."));
    }
    elsif ($type eq 'Protein Function/Process') {
	$instruction = Tr(td("Use the following form for brief description of the function that a protein performs or the biological process in which it is involved."));
    }
    elsif ($type eq 'Mature Length (direct evidence)') {
	$instruction = Tr(td("Use the following form for the experimentally determined mature length of a protein."));
    }
    elsif ($type eq 'Nucleic Acid Binding') {
	$instruction = Tr(td("Use the following form for information about the nucleic acid binding properties of a protein.")).
	    Tr(td(ul(li("To indicate which type of nucletides this protein binds, select at least one checkboxe from the \"Nucleic Acid Binding\" section"), li("\"". $self->redanchor."\" indicates that multiple genes/ORFs can be entered into this field; separate with colons (\":\")."), li("Note that this information will be linked to all the genes that are entered into this form."))));
    }
    else {
	$instruction = Tr(td("Use the following form for any information pertaining to a protein that doesn't fit into any of the given topics - specify your own topic in the \"Protein details\" category.")).
	    Tr(td(ul(li("Use this form only when none of the given \"Protein Details\" topics apply."), li("Specify your own topic heading in the \"Other Topic\" Field."))));
    }

    return $instruction;
}

#######################################################################
sub TechInstruction {
#######################################################################
    my ($self) = @_;
    my $instruction;
    my $type = param('Techniques');

    if ($type eq 'Antibodies') {
	$instruction = Tr(td("Use the following form for information on the generation, use, or availability of antibodies specific for a protein."));
    }
    elsif ($type eq 'Protein Purification') {
	$instruction = Tr(td("Use the following form for descriptions of protein purification procedures."));
    }
    elsif ($type eq 'Strains & Constructs') {
	$instruction = Tr(td("Use the following form for descriptions of useful strains and constructs."));
    }
    elsif ($type eq 'Unique Assays') {
	$instruction = Tr(td("Use the following form for descriptions of useful assays for function of a protein, expression of a gene, etc."));
    }
    else {
	$instruction = Tr(td("Use the following form for any information pertaining to techniques or reagents that doesn't fit into any of the given topics - specify your own topic in the \"Techniques & Reagents\" category.")) .
	    Tr(td(ul(li("Use this form only when none of the given \"Techniques & Reagents\" topics apply."), li("Specify your own topic heading in the \"Other Topic\" Field."))));
    }
    return $instruction;
}

#######################################################################
sub InteractionInstruction {
#######################################################################
    my ($self) = @_;
    my $instruction;
    my $type = param('Interactions');

    if ($type eq 'Genetic') {
	$instruction = Tr(td("Use the following form for any type of genetic interaction between one gene and another gene or genes.")) .
	    Tr(td(ul(li("To indicate the genes involved in the interaction, you must enter at least one gene name in both \"Gene/ORF\" fields. All genes entered into the \"Interacting Gene/ORF\" field must have the same interaction with the gene entered in the \"Primary Gene/ORF\" field. "), li("To indicate the type of genetic interaction, click at least one checkbox in the \"Interaction Type\" section. Choose all that apply. "), li("Note that this information will be linked to all the genes that are entered into this form."))));
    }
    elsif ($type eq 'Physical') {
	$instruction = Tr(td("Use the following form for experimentally determined physical interaction between two or more proteins (e.g. immunoprecipitation).")) .
	    Tr(td(ul(
#li("\"". $self->redanchor."\" indicates that multiple genes/ORFs can be entered into this field; separate with colons (\":\")."), 
		     li("To indicate the genes involved in the interaction, you must enter at least one gene name in both \"Gene/ORF\" fields. All genes entered into the \"Interacting Gene/ORF\" field must have the same interaction with the gene entered in the \"Primary Gene/ORF\" field. "), li("Note that this information will be linked to all the genes that are entered into this form."))));
    }
    elsif ($type eq 'Two Hybrid') {
	$instruction = Tr(td("Use the following form for interaction between two or more proteins, as determinded by a two-hybrid assay.")).
	 Tr(td(ul(
#li("\"". $self->redanchor."\" indicates that multiple genes/ORFs can be entered into this field; separate with colons (\":\")."), 
		  li("To indicate the genes involved in the interaction, you must enter at least one gene name in both \"Gene/ORF\" fields. All genes entered into the \"Interacting Gene/ORF\" field must have the same interaction with the gene entered in the \"Primary Gene/ORF\" field. "), li("Note that this information will be linked to all the genes that are entered into this form."))));
    }
    elsif ($type eq 'Regulatory') {
	$instruction = Tr(td("Use the following form for regulation of a gene or protein by one or more other proteins. Also regulation by a protein of one or more other proteins.")). 	    
	    Tr(td(ul(
#li("\"". $self->redanchor."\" indicates that multiple genes/ORFs can be entered into this field; separate with colons (\":\")."), 
		     li("To indicate the genes involved in the interaction, you must enter at least one gene name in both \"Gene/ORF\" fields. All genes entered into the \"Interacting Gene/ORF\" field must have the same interaction with the gene entered in the \"Primary Gene/ORF\" field."), li("To indicate the type of interaction, choose at least one checkbox (choose both if appropriate)."), li("Note that this information will be linked to all the genes that are entered into this form."))));
    }
    else {
	$instruction = Tr(td("Use the following form for any information pertaining to protein or gene interactions that doesn't fit into any of the given topics - specify your own topic in the \"Interactions\" category.")).
	    Tr(td(ul(li("Use this form only when none of the given topics apply."), li("Specify your own topic heading in the \"Other Topic\" Field."), 
#li("\"". $self->redanchor."\" indicates that multiple genes/ORFs can be entered into this field; separate with colons (\":\")."), 
		     li("To indicate the genes involved in the interaction, you must enter at least one gene name in both \"Gene/ORF\" fields. All genes entered into the \"Interacting Gene/ORF\" field must have the same interaction with the gene entered in the \"Primary Gene/ORF\" field."), li("Note that this information will be linked to all the genes that are entered into this form."))));
    }

    return $instruction;
}

#######################################################################
sub PhenotypeInstruction {
#######################################################################
    my ($self) = @_;
    my $instruction;
    my $type = param('Phenotypes');
    my $phetype = li("To indicate mutant phenotype, choose at least one checkbox from the \"Phenotype Description\" section. Check all that apply");

    if ($type eq 'Complete Deletion') {
	$instruction = Tr(td("Use the following form for description of mutants that have a complete deletion of a gene.")). 
	    Tr(td(ul($phetype)));
    }
    elsif ($type eq 'Partial Deletion') {
	$instruction = Tr(td("Use the following form for description of mutants that have a partial deletion of a gene.")). 
	    Tr(td(ul($phetype)));
    }
    elsif ($type eq 'Point Mutation') {
	$instruction = Tr(td("Use the following form for description of point mutations in a gene (e.g. insertions, deletions, or sequence changes.)")). 
	    Tr(td(ul($phetype)));
    }
    elsif ($type eq 'Other Mutation') {
	$instruction = Tr(td("Use the following form for description of mutations where none (or more than one) of the other topics applies. This form can also be used to describe multiple genes that have the same mutant phenotype (e.g. list several genes retrieved from a single mutant screen.)")).
	    Tr(td(ul(li("Use this form only when none (or more than one) of the other \"Alleles, Strains, & Mutant Phenotypes\" topics apply."), li($self->redanchor. "This form can be used to submit phenotype information that applies to individual mutations in several different genes (e.g. list several different genes retrieved from a single mutant screen). Separate genes with a colon (\":\")."), li("Allele names are optional but encouraged. To submit this allele names when entering several genes, enter the allele name in parentheses after the gene name. e.g. GENE1(allele1): GENE2(allele2): GENE3(allele3)."), $phetype, li("Note that this information will be linked to all the genes that are entered into this form."))));
    }
    elsif ($type eq 'Multiple Knockout Strains') {
	$instruction = Tr(td("Use the following form for description of strains that contain complete deletions of more than one gene.")).
	    Tr(td(ul(li("\"". $self->redanchor."\" indicates that multiple genes/ORFs can be entered into this field; separate with colons (\":\")."), $phetype, li("Note that this information will be linked to all the genes that are entered into this form."))));
    }
    elsif ($type eq 'Overexpression') {
	$instruction = Tr(td("Use the following form for description of the phenotype caused by overexpression of a gene.")) .
	    Tr(td(ul($phetype)));
    }
    else {
	$instruction = Tr(td("Use the following form for any information pertaining to alleles, strains, or mutant phenotypes that doesn't fit into any of the given topics - specify your own topic in the \"Alleles, Strains, & Mutant Phenotypes\" category.")) .
	    Tr(td(ul(li("Use this form only when none of the given \"Alleles, Strains, & Mutant Phenotypes\" topics apply."), li("Specify your own topic heading in the \"Other Topic\" Field."), $phetype)));
    }

    return $instruction;
}

#######################################################################
sub OtherInstruction {
#######################################################################
    my ($self) = @_;
    my $instruction = Tr(td("Use the following form for any information that doesn't fit into any of the given topics - specify your own topic.")) .
	Tr(td(ul(li("Use this form only when none of the given topics apply."), li("Specify your own topic heading in the \"Other Topic\" Field."))));

    return $instruction;
}

#######################################################################
sub notifyCurator {
#######################################################################
    my ($self, $colInfo, $pubmedId) = @_;

    my $refUrl =$configUrl->dictyBaseCGIRoot . $db ."/reference/reference.pl?pubmed=" .$pubmedId;

    open (MAIL, "|/usr/lib/sendmail -oi -t")||die "Can't open mail : $!\n";
            
print MAIL <<Mail_Headers;
From: <e-just\\\northwestern.edu>
To: <e-just\\\northwestern.edu>
Reply-To: <e-just\\\northwestern.edu>
Subject: new Community Annotation submitted
Mail_Headers

    print MAIL "\nThis is an automated email to notify curators of the newly submitted community annotation set.\n";

    print MAIL "\n$colInfo\n";
    print MAIL $refUrl ."\n";

    close MAIL;
    return;
}

#######################################################################
sub saveEmailReply {
#######################################################################
    my ($self, $colInfo, $pubmed) = @_;
    my $file = "/share/". $self->database . "/data/CommuAnnotation/emailReplyLog.txt";

    open (FHW, ">>$file") || die "Cannot open $file to write: $!\n";
    print FHW $pubmed. "\t". $colInfo . "\t". localtime. "\n";
    close FHW;

    system("/usr/bin/chgrp dictyBase $file");

    return;
}

#######################################################################
1;
#######################################################################







