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

######################################################################
# Author: Stan Dong
# Date:   November, 2002
# Comment: Contains all necessary methods for an on-line interface
#          to process 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 :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 $configPath = ConfigPathdictyBase->new; 
my $annotationFile; # = $tempdir . "annotationSet.$$.$dateStamp";
my $baseUrl;
my $datadir;
my $archiveDir;
my $userInterfaceUrl;
my $curatorCenterUrl;
my $title = "dictyBase Community Annotation";
my $width = "60%";
my $DelBoxLabel;

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

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

    $self = {};

    bless $self;

    $self->{'_database'} = $args{'database'};
    $self->{'_user'}     = $args{'user'};

    $DelBoxLabel = 'Delete this Research Highlight.';

    return $self;
}

sub database { $_[0]->{_database} }
sub user { $_[0]->{_user} } 

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

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

    if ($self->database eq 'dictyBase') {
        $db = 'dictyBase';
        $db1 = 'dictyBase';
    }
    else {
        $db = 'dictyBaseDEV';
        $db1 = 'SDEV';
    }

    #use whatever in copy dir for testing
    $datadir = $configPath->dataDir4web ."submission/community/$db1";
    $archiveDir = $configPath->dataDir4web ."submission/community/$db1/archive";

    if (!$self->user) {
	print "location: ", $configUrl->dictyBaseCGIRoot, "$db/curatorLogin\n";
	print "Content-type: text/html\n\n";
	exit;
    }

    my $user = $self->user;
    $user = "\U$user";
    my ($dbuser, $dbpasswd) = &getUsernamePassword($user, $self->database);

    if (!$dbuser || !$dbpasswd) {
	print "location: ", $configUrl->dictyBaseCGIRoot, "$db/curatorLogin\n";
        print "Content-type: text/html\n\n";
        exit;
    }

    $dbh = &ConnectToDatabase($self->database, $dbuser, $dbpasswd);

    $baseUrl = $configUrl->dictyBaseCGIRoot . $db ."/curation/processCommuAnnotation?user=". $self->user;

    $userInterfaceUrl = $configUrl->dictyBaseCGIRoot . $db ."/DisplayCommuAnno?dictyBaseid=";

    $curatorCenterUrl = $configUrl->dictyBaseCGIRoot . $db ."/curatorLogin?user=". $self->user;

    if (param('AfterFinalEdit')) {
#        $self->showparameters;
        $self->Submission;
    }
    elsif (param('file')) {
	$self->diplayAnnotation;
#        $self->showparameters;
    }
    else {   #file list
        $self->todoList;
    }

    $self->DESTROY;
}

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

    my @files = `/bin/ls -l $datadir`;
    my $entryCount = 0;
    my %delay = $self->getDelayList;

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

    my $list;
    foreach my $fileline (@files) {
        chop;
        my @line = split(' ', $fileline);
        my $fn = $line[8];
        my $linkUrl = $baseUrl . "&file=" . $fn;
        my $date = "$line[5] $line[6] $line[7]";
        if ($fn =~ /^annotationSet/) {
	    my $showtxt = $self->getShowtxt($fn);
	    if ($delay{$fn}) {
		$showtxt .= " [". $delay{$fn} . "] ";
	    }
            $entryCount++;
	    $list .= li(b(a({-href=>$linkUrl}, $fn)) . $showtxt ." [".font({-color=>'red'}, $date)."]") . br;
	}
    }
    print h3(font({-color=>'red'}, $entryCount). " Community Annotation Entries:"),p;
    print blockquote(ul($list));
    &printEndPage;
    
    return;
}

######################################################################
sub diplayAnnotation1  {
######################################################################
    my ($self) = @_;
    my $fn = param('file');
    &printStartPage($self->database, $title);
    print p, $fn, p;
    &printEndPage;
    return;
}

#####################################################################
sub diplayAnnotation  {
#####################################################################
    my ($self) = @_;
    my $fn = param('file');
    my $dataFile = $datadir . "/" . $fn;
    my ($contributor, $pubmed, $colleaid); 
    my @content;

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

    while (<DAT>) {
        if (!/^</) {
	    next;
        }
        chomp;

        my @line = split(/\t/);
        next if (!@line);
        my %thisAnno = ();
        my $form;

	my $tmpStr = '';

        foreach my $tag (@line) {
            next if (!$tag);
	    $tag =~ /^<(\S+)>(.+)<\//;
            $thisAnno{$1} = $2;
            $tmpStr .= $1. '=' .$2;
        }

	my $annoNo = $thisAnno{'annotationid'} || $thisAnno{'annotationId'};
        if (!$annoNo) {
	    $self->err_report("No annotationid");
        }

        #for checkbox
        my ($pheno, $inter) = $self->parameterCheckbox;

        my $suplabel = 'is a suppressor of';

        foreach my $key (keys %thisAnno) {
	    #getpubmedid and contributor 
	    if ($key =~ /colleaInfo/) {
		$contributor = $thisAnno{$key};
            }
	    elsif ($key =~ /newColleaInfo/) {
		$contributor = $thisAnno{$key};
            }
	    elsif ($key =~ /pubmedid/) {
		$pubmed = $thisAnno{$key};
            }
	    elsif ($key =~ /colleagueid/) {
		$colleaid = $thisAnno{$key};
            }
            my $tmpkey = $key . '_' . $annoNo;
	    param($tmpkey, $thisAnno{$key});

            if ($key =~ /OtherModificationType/) {
		param('OtherMT_'. $annoNo , 'OtherMT');
            }

	    my $checkbox;
            if ($$pheno{$key}) {
		$checkbox = $$pheno{$key};
	    }
            elsif ($$inter{$key}) {
		$checkbox = $$inter{$key};

                #get gene2
		$thisAnno{$key} =~ /(\S+)$/;
		my $gene2 = $1;

		if ($gene2) {
		    my $gene2Para = 'with_'. $annoNo;

		    if ($thisAnno{$key} =~ /suppressed by/) {
			$checkbox = 'is suppressed by';
			$suplabel = $checkbox;
			$gene2Para = $checkbox."_".$annoNo;
		    }
		    elsif ($thisAnno{$key} =~ /suppressor/) {
			$checkbox = 'is a suppressor of';
			$gene2Para = $checkbox."_".$annoNo;
		    }
		    param($gene2Para, $gene2);
		}
            }
            if ($checkbox) {
		param($tmpkey, $checkbox);
            }
        }

        if (param("category_$annoNo") eq 'Immunoprecipitation') {
	    param("gene2_$annoNo", param("with_$annoNo"));
	}

        if (param("topic_$annoNo") eq 'DNA & RNA Details') { 
            param('DNA', param("category_$annoNo"));
	    $form = $self->DNARNADetailForm($annoNo);
        }
        elsif (param("topic_$annoNo") eq 'Protein Details') { 
            param('Protein', param("category_$annoNo"));
	    $form = $self->ProteinDetailForm($annoNo);
        }
        elsif (param("topic_$annoNo") eq 'Techniques & Reagents') { 
            param('Techniques', param("category_$annoNo"));
	    $form = $self->TechForm($annoNo);
        }
        elsif (param("topic_$annoNo") eq 'Interactions') { 
            param("Interactions", param("category_$annoNo"));
	    $form = $self->InteractionForm($annoNo, $suplabel);
        }
        elsif (param("topic_$annoNo") eq 'Alleles, Strains, & Phenotypes') { 
            param('Phenotypes', param("category_$annoNo"));
	    $form = $self->PhenotypeForm($annoNo);
        }
        elsif (param("topic_$annoNo") eq 'Other') { 
            param('Other', param("category_$annoNo"));
	    $form = $self->OtherForm($annoNo);
        }
        else {
            $self->err_report("param('topic_$annoNo') is not found!");
        }
        push (@content, $form);

        
    }

    close DAT;

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

    my $size = @content;

    if (!$contributor) {
	$self->err_report("No Contributor!");
    }
    elsif (!$pubmed) {
	$self->err_report("No PubmedID!");
    }
    
    my @contributor = split(/,/, $contributor);
    my $colleague;
    for (my $i=0; $i<@contributor; $i++) {
	$colleague .= $contributor[$i] . br;
    }

    if ($colleaid) {
	$colleague .= br. "colleague_no = $colleaid";
    }
    else { #new colleague
        #try to search if this colleague already exist
        my $colid = $self->checkColleague(\@contributor);
        if ($colid) {
	    $colleague .= br. "colleague_no = $colid";
            $colleaid = $colid;
        }
        else { 
	    my $newColFormId = $self->addToNewColl(\@contributor);
	    if (!$newColFormId) {
	        $self->err_report("No newColFormId!");
	    }

	    my $newcolUrl = $configUrl->dictyBaseCGIRoot. "$db/curation/colleagueNewEntry?id=$newColFormId&user=" . $self->user;
	    $colleague .= br. a({-href=>$newcolUrl, -target=>'newColleague'}, font({-color=>'red', -size=>'+1'}, "Submit new colleague before submitting annotation"));
        }
    }
    my $formatedCitation = $self->formatedCitation($pubmed);

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

    #parameters need to be carried over to the next page
    my %HiddenPara = $self->getHiddenPara;

    foreach my $para (param) {
	my $item = $para;
	$item =~ s/_\d+$//;
	if ($HiddenPara{$item}) {
	    print hidden($para, param($para));
        }
#        print hidden('colleagueid', $colleaid);
    }

    print hidden('colleagueid', $colleaid);

    print table({-width=>"100%", -cellspacing=>"4", -cellpadding=>"4", -border=>"0"},
      Tr(th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Contributor")),
         th({-align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Reference"))),
      Tr(td({-valign=>"top"}, $colleague),
         td({-valign=>"top"}, $formatedCitation)
      ),
      Tr(th({-colspan=>'2', -align=>"left", -bgcolor=>"#a4abc2"}, font({-size=>'+1'}, "Research Highlights")))  
    );


    for (my $i=0; $i<$size; $i++) {

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

    #for whole set
    print p,
        table({-align=>'center', -width=>$width}, 
	    Tr(td({-colspan=>'2', -bgcolor=>"#b7d8e4"}, checkbox({-name=>"Delay", -label=>"Delay submission.", -value=>"Delay"}) . "   Reason: ". textfield({-name=>"Delayreason", -size=>'60'}))),
            Tr(td({-colspan=>'2', -bgcolor=>'#FF9999'}, checkbox({-name=>"Delset", -label=>"Delete submission.", -value=>"Delset"}))));

    print submit('AfterFinalEdit', 'Submit'), reset;

    print end_form;
    &printEndPage;

    return;
}

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

    my $file = param('file');
    my $user = param('user');
    my $colleaNo = param('colleagueid');
#    $self->showparameters;
    if (param('Delset') eq 'Delset') { #delete the whole set
        system("/usr/bin/mv $datadir/$file $archiveDir");
	$self->DeleteSet;
    }
    elsif (param('Delay') eq 'Delay') { #delay the whole set
	$self->DelayFile;
    }

    my %Data;   #hold data to be saved in DB. hash of hash

    my ($annoSetNo, $pubmedid, $refNo, $collname);

    my %Exd = $self->ExdFromDetail;

    #save data for loading DB
    my @deleteCA;  #Annotations whose 'Delete' marker turned on
    
    #motifBoundPr need cross-posting to those gene names. store annotation_no
    my @regMotifProAnnoNo; 

    #substrates in Nucleic Acid Binding need cross-posting to those gene names.
    my @substrateGenes; 
                       
    foreach my $item (param) {
	next if (param($item) eq '');

	if ($item =~ /_(\d+)$/) {
	    my $tmpVal = param($item);
	    $item =~ s/_(\d+)$//;
            my $tmpAnNo = $1;

            #save data in hash 
	    $Data{ $1 }{ $item } = $tmpVal;

	    if ($item eq 'colleagueid') {
		$colleaNo = $tmpVal;
	    }
	    elsif ($item eq 'pubmedid') {
		$pubmedid = $tmpVal;
	    }
	    elsif ($item eq 'colleaInfo') {
		$collname = $tmpVal;
		$collname =~ s/,.*$//;
	    }
            elsif ($item eq 'Delete') {
		push(@deleteCA, $tmpAnNo);
	    }
            elsif ($item eq 'motifboundPr') {
		push(@regMotifProAnnoNo, $tmpAnNo);
	    }
	    elsif ($item eq 'substrate') {
		push(@substrateGenes, $tmpAnNo);
	    }
	}
	else {next;}
    }

    #For 'Regulatory Motifs' in 'DNA & RNA Details', do crossposting if 
    #there are proteins shown to bind motif, each protein create an annotation

    foreach my $rmAnNo (@regMotifProAnnoNo) {
        my %tmpHash = %{$Data{$rmAnNo}};
        my $primaryGene = $Data{$rmAnNo}{'gene'};
        my $motifPr = $Data{$rmAnNo}{'motifboundPr'};
	my $newAnnoNo = $rmAnNo + 100;

	my @prbindGenes = split(/:/, $motifPr);
	foreach my $pr (@prbindGenes) {
            
            $pr =~ s/p$//;  #trip the 'p' at the end
	    $newAnnoNo++;
	    while (defined $Data{$newAnnoNo}) {
		$newAnnoNo ++;
	    }

            foreach my $key (keys %tmpHash) {
		if ($key eq 'gene') {
		    $Data{$newAnnoNo}{'gene'} = $pr;
                }
                elsif ($key eq 'motifboundPr') {
		    $Data{$newAnnoNo}{'primaryGene'} = $primaryGene;
                }
                else {
		    $Data{$newAnnoNo}{$key} = $tmpHash{$key};
                }
            }
        }
    }

    #for nucleic acid binding in Protein Detail
    foreach my $rmAnNo (@substrateGenes) {
        my %tmpHash = %{$Data{$rmAnNo}};
        my $primaryGene = $Data{$rmAnNo}{'gene'};
        my $substrate = $Data{$rmAnNo}{'substrate'};
	my $newAnnoNo = $rmAnNo + 100;

	my @subGenes = split(/:/, $substrate);
	foreach my $pr (@subGenes) {
            
            $pr =~ s/p$//;  #trip the 'p' at the end
	    $newAnnoNo++;
	    while (defined $Data{$newAnnoNo}) {
		$newAnnoNo ++;
	    }

            foreach my $key (keys %tmpHash) {
		if ($key eq 'gene') {
		    $Data{$newAnnoNo}{'gene'} = $pr;
                }
                elsif ($key eq 'substrate') {
		    $Data{$newAnnoNo}{'primaryGene'} = $primaryGene;
                }
                else {
		    $Data{$newAnnoNo}{$key} = $tmpHash{$key};
                }
            }
        }
    }

    #for Interactions, if one form marked as 'Delete', the other one has to go
    #too (the annotation_no of the two records are next to each other).
    if (@deleteCA) {
	foreach my $tmpAnNo (@deleteCA) {
	    my $tmpTopic = $Data{$tmpAnNo}{'topic'};
            next if ($tmpTopic ne 'Interactions');  
	    my $tmpCat = $Data{$tmpAnNo}{'category'};
            my $tmpGene1 = $Data{$tmpAnNo}{'gene'};
            my $tmpGene2 = $Data{$tmpAnNo}{'with'} ||
                           $Data{$tmpAnNo}{'is suppressed by'} ||
			   $Data{$tmpAnNo}{'is a suppressor of'};

	    for (my $y= $tmpAnNo-1; $y<=$tmpAnNo+1; $y=$y+2) {
		#have to put '0's at front, evaluated as string
		my $howmanyZero = 6-length("$y");
                my $z = $y;
                if ($howmanyZero > 0) {
		    $z = '0' x $howmanyZero . $z;
                }

		next if (!$Data{$z});

		my $testTopic = $Data{$z}{'topic'};
		my $testCat = $Data{$z}{'category'};
		my $testGene1 = $Data{$z}{'gene'};
		my $testGene2 = $Data{$z}{'with'} || 
		                $Data{$z}{'is suppressed by'} ||
			        $Data{$z}{'is a suppressor of'};

                if (!$testTopic || !$testCat) {  #inexist annotation
		    $self->err_report("Invalid testNo $z");
#		    next;
		}

                if (($testTopic eq $tmpTopic) && ( $testCat eq $tmpCat) &&
		    ($testGene1 eq $tmpGene2) && ($testGene2 eq $tmpGene1)) {
		    $Data{$z}{'Delete'} = 'Yes';
		}
            }
        }
    }

    if (!$colleaNo || !$user || !$pubmedid) {
	$self->err_report("No ColleagueNo/user/pubmedid !");
    }

    my $getRefNo = $dbh->prepare( "
                       SELECT reference_no FROM CGM_DDB.reference
                       WHERE pubmed = ?
                   ");
    $getRefNo->execute($pubmedid);
    $refNo = $getRefNo->fetchrow();

    if (!$refNo) {
	$self->err_report("No refNo for $pubmedid!");
    } 

    #load the annotation_set table
    my $getAnnoSetNo = $dbh->prepare( "
                          SELECT CGM_DDB.annsetno_seq.nextval FROM dual
                       ");
    $getAnnoSetNo->execute;
    $annoSetNo = $getAnnoSetNo->fetchrow();
    $getAnnoSetNo->finish;

    if (!$annoSetNo) {
	$self->err_report("No AnnotationSetNo!");
    }

    my $annoSet_sth = $dbh->prepare( "
                          INSERT INTO CGM_DDB.annotation_set
                          (annotation_set_no, colleague_no, created_by, date_created)                     VALUES (?, ?, ?, sysdate)
                      ");

    my $commAn_sth = $dbh->prepare( "
                         INSERT INTO CGM_DDB.community_annotation
                         (community_annotation_no, annotation_set_no, dictyBaseid, topic, sub_topic, description)
                         VALUES (?, ?, ?, ?, ?, ?)
                     ");

    my $anDetail_sth = $dbh->prepare( "
                         INSERT INTO CGM_DDB.annotation_detail
                         (annotation_detail_no, community_annotation_no, detail_name, detail_value)
                         VALUES (CGM_DDB.anndetno_seq.nextval, ?, ?, ?)
                       ");

    my $reflink_sth = $dbh->prepare( "
                         INSERT INTO CGM_DDB.reflink
                         (reflink_no, reference_no, tab_name, primary_key, primary_key_col, date_created, created_by)
                         VALUES (CGM_DDB.reflinkno_seq.nextval, ?, 'annotation_set', ?, 'annotation_set_no', sysdate, ?)
                      ");

    #load annotation table
    $annoSet_sth->execute($annoSetNo, $colleaNo, $user);
    $dbh->commit();

    #insert a row in relink table for this reference
    $reflink_sth->execute($refNo, $annoSetNo, $user);
    $dbh->commit();
    
    my $getCommAnNo = $dbh->prepare( "
                          SELECT CGM_DDB.commannno_seq.nextval FROM dual
                      ");
    
    #start inserting data into community_annotatiion and annotation_detail
    my %geneSubmit;
    foreach my $key (keys %Data) {  #handle one annotation at a time
                                    #$key is annotation_no
        my %subHash = %{$Data{$key}};  #hold data of this annotation
        $subHash{'file'} = $file;  

        #skip if Dalete box checked
	next if ($subHash{'Delete'}); 
	
	my $prtStr;
	my ($commAnnoNo, $dictyBaseid, $topic, $subtop, $des);
	$topic = $subHash{'topic'};
	$subtop = $subHash{'category'};
	$des = $subHash{'description'} || 'None';

	#other topic
        if (($topic eq 'Other') && ($subHash{'OtherTopic'})) {
	    $subtop = $subHash{'OtherTopic'};
	}

	if (!$topic || !$subtop || !$des) {
	    $self->err_report("topic=$topic  subtop=$subtop  des=$des");
	}

        #prepare parameters for loading community_annotation table
        $getCommAnNo->execute;
	$commAnnoNo = $getCommAnNo->fetchrow();
	$getCommAnNo->finish;

	my $geneNm = $subHash{'gene'} || $subHash{'deletedGenes'} ;

	if ($geneNm) {
            $dictyBaseid = $self->getPrimarydictyBaseid($geneNm);
	}
	else { $self->err_report("No Gene Name!"); }

        #check if this community annotation have already exist
        my $checkCA = $self->checkExistCA($annoSetNo, $dictyBaseid, $topic, $subtop, $des);

	if (defined $checkCA) {
            #if annotation already exist, update the annotaion details.
            $self->updateAnDetail($checkCA, \%subHash);
	    next; #goto next annotation
        }

	#load community_annotation table
	$commAn_sth->execute($commAnnoNo, $annoSetNo, $dictyBaseid, $topic, $subtop, $des);
	$dbh->commit();

	#load annotation_detail table
	foreach my $subkey (keys %subHash) {

            #don't want to insert certain key-value pair          
	    if ($Exd{$subkey}) {
                if (!(($subkey eq 'with') && ($subtop eq 'Immunoprecipitation'))) {
		    next;
	        }
            }

	    my $tmpVal = $subHash{$subkey};

	    if (($subkey =~ /syntheticLethal/) || ($subkey =~ /epistatic/)) {
		$tmpVal = $subHash{'with'};
                if (!$tmpVal) {
		    $self->err_report('No with value!');
                }
            }
            elsif (($subkey =~ /regulator/) || ($subkey =~ /regulated/)) {
#		$tmpVal = $subHash{'regulator'} || $subHash{'regulated'};
		$tmpVal = $subHash{'with'};
		if (!$tmpVal) {
		    $self->err_report('No with value!');
                }
            }
            elsif (($subkey =~ /suppress/) && (!$subHash{'supressor'}))
            { #when supressor checkbox is unchecked, skip inserting even there
              #is valid para of is a suppressor/suppressed by.
		next;
            }

	    $anDetail_sth->execute($commAnnoNo, $subkey, $tmpVal);

	    $prtStr .= $subkey .'='. $tmpVal ."\t";
        }

	$geneNm = uc($geneNm);
	$geneSubmit{$geneNm} = $dictyBaseid;
    }

    $dbh->commit();

    #move this file to archive
    system("/usr/bin/mv $datadir/$file $archiveDir");
    
    #print the final page after submission
    &printStartPage($self->database, $title);

    print "Submitted the annotation from $collname for Pubmed = $pubmedid for genes:", br,br;
    if (%geneSubmit) {
	foreach my $gene (keys %geneSubmit) {
	    print a({-href=>$userInterfaceUrl. $geneSubmit{$gene}, -target=>'display'}, $gene) ,br;
	}
    }
    else {
	print "No annotation submitted!", br;
    }
    print br, a({-href=>$curatorCenterUrl}, "Return to Curator Central");

    &printEndPage;

    return;
}

#######################################################################
sub getPrimarydictyBaseid {
#######################################################################
    my ($self, $geneNm) = @_;
    &DeleteUnwantedChar(\$geneNm);
    my $dictyBaseid;
    my $object = dictyBaseObject->new(database=>$self->database, query=>$geneNm);
    if ($object->isLocusName) {
	$object = dictyBaseObject->new(database=>$self->database, locusName=>$geneNm);
    }
    elsif ($object->isFeatureName) {
	$object = dictyBaseObject->new(database=>$self->database, featureName=>$geneNm);
    }
    else {
   	$self->err_report("$geneNm Not a LocusName or FeatureName!");
    }
    $dictyBaseid = $object->primarydictyBaseID;
    if (!$dictyBaseid) {$self->err_report("No dictyBaseid retrieved for $geneNm!")}
    return $dictyBaseid;
}

#######################################################################
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_$tmpAnnoNo", '15'),
                  $self->makeTextBox("Chromosomal sequence coordinates: ", "ChrCoordinate_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("description_$tmpAnnoNo")
             )
	  );
    }
    elsif ($type eq 'Transcription Start') {
	$cell .=
	  Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
 		  $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_$tmpAnnoNo", '15'),
                  $self->makeTextBox($self->redstar ."Chromosomal sequence coordinates: ", "ChrCoordinate_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("description_$tmpAnnoNo")
             )
	  );
    }
    elsif ($type eq 'Regulatory Motifs') {
	$cell .=
	  Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
 		  $self->makeTextBox($self->redstar ."Gene/ORF: regulated by motif: ", "gene_$tmpAnnoNo", '15'),
                  $self->makeTextBox("Name of motif: ", "motif_$tmpAnnoNo", '15'),
                  Tr(td(u("Motif chromosomal sequence coordinates:"))),
                  $self->makeTextBox("Start: ", "startCoord_$tmpAnnoNo", '15'),
                  $self->makeTextBox("Stop: ", "stopCoord_$tmpAnnoNo", '15'),
                  $self->makeTextBox($self->redanchor. "Protein(s) shown to bind this motif: ", "motifboundPr_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("description_$tmpAnnoNo")
             )
	  );
    }
    else {
        if ($type eq 'Other DNA & RNA Details') {
	    $cell .= Tr(td({-colspan=>'2'}, $self->redstar."Other Topic: " . textfield({-name=>"otherTopic_$tmpAnnoNo", -size=>'15'})));
        }
        $cell .=
	  Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
 		  $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_$tmpAnnoNo", '15')
             )),
             td($self->makeDescriptionBlock("description_$tmpAnnoNo", $self->redstar)
             )
	  );
    }
        
    $cell .= $self->makeDelBox('2', "Delete_$tmpAnnoNo");

    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=>"otherTopic_$tmpAnnoNo", -size=>'15'})));
    }    

    if ($type eq 'Protein Modification') {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_$tmpAnnoNo", '15'),
			 $self->makeTextBox("Modified Amino Acid: ", "modifiedAA_$tmpAnnoNo", '15')
                    )),
                    td($self->modificationType_PD($tmpAnnoNo)),
                    td($self->makeDescriptionBlock("description_$tmpAnnoNo"))
	         );
    }
    elsif ($type eq 'Mature Length (direct evidence)') {
        $cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_$tmpAnnoNo", '15'),
			 $self->makeTextBox($self->redstar ."Protein length (in Amino Acids): ", "proteinlength_$tmpAnnoNo", '15')
                    )),
                    td($self->makeDescriptionBlock("description_$tmpAnnoNo"))
	         );
    }
    elsif ($type eq 'Nucleic Acid Binding') {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_$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_$tmpAnnoNo", '15')
                    )),
                    td($self->makeDescriptionBlock("description_$tmpAnnoNo"))
	         );
    }
    else {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
                         $self->makeTextBox($self->redstar ."Gene/ORF: ", "gene_$tmpAnnoNo", '15'))),
                    td($self->makeDescriptionBlock("description_$tmpAnnoNo", $self->redstar))
	         );
    }

    $cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");
    
    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=>"otherTopic_$tmpAnnoNo", -size=>'15'})));
    } 


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

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

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

    my $gene2Label = "with";
    my $regLabel = "with";

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

    if ($type eq 'Genetic') {
	my $tmpVal = param("supressor_$tmpAnnoNo");
	if ($tmpVal) {
	    $gene2Label = $tmpVal;
        }

        $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: ", "gene_$tmpAnnoNo", '15'),
			$self->makeTextBox("Mutation type: ", "mutation1_$tmpAnnoNo", '15')
	           )),
		   td({-valign=>'top', -align=>'left'}, table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td(b($self->redstar . u("Interaction Type")))
                        ),
	                Tr(td(checkbox({-name=>"syntheticLethal_$tmpAnnoNo", -value=>"is synthetic lethal with", -label=>"is synthetic lethal with"}))),
	                Tr(td(checkbox({-name=>"supressor_$tmpAnnoNo", -value=>$supLabel, -label=>$supLabel}))),
	                Tr(td(checkbox({-name=>"epistatic_$tmpAnnoNo", -value=>"is epistatic to", -label=>"is epistatic to"}))),
			Tr(td(checkbox({-name=>"OtherInteraction_$tmpAnnoNo", -value=>"Other", -label=>"Other"}) .': '. textfield({-name=>"OtherDesc_$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: ", $gene2Label ."_$tmpAnnoNo", '15'),
                        $self->makeTextBox("Mutation type: ", "mutation2_$tmpAnnoNo", '15')
	           ))
                 )))) .
		 Tr(td(
                   table({-cellspacing=>"3", -cellpadding=>"4"},
			$self->makeTextBox("Strain background: ", "strainBackground_$tmpAnnoNo", '15'),
			$self->makeTextBox("Strain name & genotype: ", "strainNameGenotype_$tmpAnnoNo", '15')
		    )),
		    td($self->makeDescriptionBlock("description_$tmpAnnoNo"))
		 );
    }
    elsif ($type eq 'Regulatory') {
	$cell .= Tr(td(
                      table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td($self->redstar . "Primary Gene/ORF: " . textfield({-name=>"gene_$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=>$gene2Label . "_$tmpAnnoNo", -size=>'15'})))
                      )),
		    td($self->makeDescriptionBlock("description_$tmpAnnoNo"))
		 );
    }
    elsif ( $type =~ /^Other/) { 
            $cell .= Tr(td({-colspan=>$column}, $self->redstar ."Other Topic: " . textfield({-name=>"otherTopic_$tmpAnnoNo", -size=>'15'})));
	    $cell .= Tr(td(
                      table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td($self->redstar . "Primary Gene/ORF: " . textfield({-name=>"gene_$tmpAnnoNo", -size=>'15'}) .' with')),
                        Tr(td($self->redstar . "Interacting Gene/ORF: " . textfield({-name=>$gene2Label ."_$tmpAnnoNo", -size=>'15'})))
                      )),
		    td($self->makeDescriptionBlock("description_$tmpAnnoNo", $self->redstar))
		     );
    }
    else {
        $cell .= Tr(td(
                      table({-cellspacing=>"3", -cellpadding=>"4"},
                        Tr(td($self->redstar . "Primary Gene/ORF: " . textfield({-name=>"gene_$tmpAnnoNo", -size=>'15'}) .' with')),
                        Tr(td($self->redstar . "Interacting Gene/ORF: " . textfield({-name=>$gene2Label ."_$tmpAnnoNo", -size=>'15'})))
                      )),
		    td($self->makeDescriptionBlock("description_$tmpAnnoNo"))
		  );
    }

    $cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");

    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=>"otherTopic_$tmpAnnoNo", -size=>'15'})));
    }
    elsif ( $type eq 'Other Mutation') { 
	$cell .= Tr(td({-colspan=>$column}, "Other Mutation: " . textfield({-name=>"otherMutation_$tmpAnnoNo", -size=>'15'})));
    }

    if ($type eq 'Partial Deletion') {
        $cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       $self->makeTextBox($self->redstar. "Gene/ORF: ", "gene_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Allele name: ", "allele_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Strain background: ", "strainBackground_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNameGenotype_$tmpAnnoNo", '15'),
                       Tr(td($self->redstar. u("Chromosomal sequence coordinates of deletion:"))),
                       $self->makeTextBox("From: ", "partialDelfrom_$tmpAnnoNo", '15'),
		       $self->makeTextBox("To: ", "partialDelTo_$tmpAnnoNo", '15'),
		    )),
                    $self->phenotypeDesc($tmpAnnoNo),    #middle column
                    td($self->makeDescriptionBlock("description_$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=>"gene_$tmpAnnoNo", -rows=>'10', -cols=>'20'}))),
		       $self->makeTextBox("Strain background: ", "strainBackground_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNameGenotype_$tmpAnnoNo", '15')
		   )),
		   $self->phenotypeDesc($tmpAnnoNo),    #middle column
                   td($self->makeDescriptionBlock("description_$tmpAnnoNo", $self->redstar)) 
                 );
    }
    elsif ($type eq 'Multiple Knockout Strains') {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       Tr(td($self->redstar. $self->redanchor. "Gene/ORF (& Allele name): ")), 
		       Tr(td(textarea({-name=>"gene_$tmpAnnoNo", -rows=>'10', -cols=>'20'}))),
		       $self->makeTextBox("Strain background: ", "strainBackground_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNameGenotype_$tmpAnnoNo", '15')
		   )),
		   $self->phenotypeDesc($tmpAnnoNo),    #middle column
                   td($self->makeDescriptionBlock("description_$tmpAnnoNo")) 
                 );
    }
    elsif ($type =~ /^Other Alleles/ ) { 
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       $self->makeTextBox($self->redstar. "Gene/ORF: ", "gene_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Allele name: ", "allele_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Strain background: ", "strainBackground_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNameGenotype_$tmpAnnoNo", '15')
		    )),
                    $self->phenotypeDesc($tmpAnnoNo),    #middle column
                    td($self->makeDescriptionBlock("description_$tmpAnnoNo", $self->redstar))
		    );
    }
    else {
	$cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"},
		       $self->makeTextBox($self->redstar. "Gene/ORF: ", "gene_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Allele name: ", "allele_$tmpAnnoNo", '15'),
		       $self->makeTextBox("Strain background: ", "strainBackground_$tmpAnnoNo", '15'),
		       $self->makeTextBox("strain name & genotype: ", "strainNameGenotype_$tmpAnnoNo", '15')
		    )),
                    $self->phenotypeDesc($tmpAnnoNo),    #middle column
                    td($self->makeDescriptionBlock("description_$tmpAnnoNo"))
		    );
    }

    $cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");

    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_$tmpAnnoNo", -size=>'15'})));

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

    $cell .= $self->makeDelBox($column, "Delete_$tmpAnnoNo");

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

#######################################################################
sub OtherForm1 {
#######################################################################
    my ($self, $tmpAnnoNo) = @_;
    my $cell = Tr(th({-bgcolor=>"#b7d8e4", -align=>"left"}, "Other Topic: " . textfield({-name=>"OtherTopic_$tmpAnnoNo", -size=>'15'})));
    my $tableRow = Tr(td(b($self->redstar . "Gene/ORF: ") . textfield({-name=>"gene_$tmpAnnoNo", -size=>'15'}))) . Tr(td(b($self->redstar . "Research Highlight Description:") . br . textarea({-name=>"description_$tmpAnnoNo", -rows=>'3', -cols=>'40'})));

    $cell .= Tr(td(table({-cellspacing=>"3", -cellpadding=>"4"}, $tableRow)));

    $cell .= Tr(td(checkbox({-name=>"Delete_$tmpAnnoNo", -label=>"Delete Other Topic", -value=>"Delete"})));

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

#######################################################################
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=>"OtherPhenotype_$tmpAnnoNo", -size=>'15'}))),
		Tr(td({-colspan=>'2'}, checkbox({-name=>"inviableWhen_$tmpAnnoNo", -label=>"Conditionally inviable when", -value=>"Conditionally inviable when"}) . textfield({-name=>"condition_$tmpAnnoNo", -size=>'15'})))
	     ));
    return $rows;
}

#####################################################################
sub parameterCheckbox  {
#####################################################################
    my ($self) = @_;
    my %Pheno = ('Dominant'=>'Dominant', 
                     'Recessive'=>'Recessive', 
                     'Viable'=>'Viable',
                     'Inviable'=>'Inviable', 
                     'TemperatureSensitive'=>'Temperature(Heat) Sensitive',
                     'ColdSensitive'=>'Cold Sensitive', 
                     'LossFunction'=>'Loss of function (Null)',
                     'GainFunction'=>'Gain of function', 
                     'Revertable'=>'Revertable', 
                     'NoPhenotype'=>'No Phenotype', 
                     'OtherPhenotypeDescription'=>'OtherPhenotypeDescription', 
      		     'inviableWhen'=>'Conditionally inviable when');
    my %Inter = ('syntheticLethal' => 'is synthetic lethal with',
                     'supressor' => 'is a suppressor of',
                     'epistatic' => 'is epistatic to',
                     'OtherInteraction'=>'Other'
		 );
    return (\%Pheno, \%Inter);
}

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

        if (!$refObj) {
            $self->err_report("Invalid Reference.");
        }

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

    return $formatedCitation;
}

#######################################################################
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, $redstar) = @_;
    my $rows = table({-cellspacing=>"3", -cellpadding=>"4"},
                 Tr(td($redstar . "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 err_report {
######################################################################
    my ($self, $mssg) = @_;

    &printStartPage($self->database, $title);
    print h4($mssg);
    &printEndPage;

    $self->DESTROY;
}

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

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

#######################################################################
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=>'OtherModificationType_'.$annoId, -size=>'15'})))
	       );
    return $rows;
}

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

#######################################################################
sub getHiddenPara {
#######################################################################
    my ($self) = @_;
    my %hash = ('user'=>'1',           'file'=>'1',
		'pubmedid'=>'1',       'category'=>'1',
		'colleagueid'=>'1',    'colleaInfo'=>'1',
		'topic'=>'1',          'with' => '1'
		);
    return %hash;
}

#######################################################################
sub ExdFromDetail {
#######################################################################
    my ($self) = @_;
    my %hash = ('pubmedid'=>'1',       'gene'=>'1',
		'category'=>'1',       'colleagueid'=>'1',
		'colleaInfo'=>'1',     'topic'=>'1',
		'description'=>'1',   
		'OtherInteraction'=>'1', 'OtherTopic' => '1',
                'deletedGenes' => '1', 'OtherMT' => '1',
                'regulates' => '1',    'isRegulatedBy' => '1'
		);
    return %hash;
}

######################################################################
sub addToNewColl {
######################################################################
    my ($self, $collAref) = @_;
    my $file = param('file');
    $file =~ /\.(\d+)\.(\d+)$/;
    my $id = $1;
    my $date = $2;
    my $writeFile = $configPath->dataDir4web ."submission/colleague/$id.newEntry";
    my $content;

    if (-e $writeFile) {
	$id .= '0';
	$writeFile = $configPath->dataDir4web ."submission/colleague/$id.newEntry";
    }

    my @name = split(/ /, $$collAref[0]);
    my $lnm = $name[-1];
    my $fnm = $name[0];
    my $internet = $$collAref[1];
    my $org = $$collAref[2];

    if (!$lnm || !$fnm) {
	$self->err_report("No lastName or firstName!");
    }
    if (!$internet || !$org) {
	$self->err_report("No email or org!");
    }

    $date =~ /^(\d{4})(\d{2})(\d+)$/;
    $date = $1. '-' . $2 . '-' .$3;
    
    $content = "Last_Name = $lnm\n";
    $content .= "First_Name = $fnm\n";
    $content .= "Internet = $internet\n";
    $content .= "Organization = $org\n";
    $content .= "Country = USA\n". "Obtained_from = Direct Submission\n"; 
    $content .= "Last_Update = $date\n";

    open(WRT, ">$writeFile") || die "Can't open $writeFile for write: $!\n";
    print WRT $content;

    return $id;
}

#####################################################################
sub checkColleague {
#####################################################################
    my ($self, $collAref) = @_;

    my @name = split(/ /, $$collAref[0]);
    my $lnm = uc($name[-1]);
    my $fnm = uc($name[0]);
    my $internet = uc($$collAref[1]);
    my $org = $$collAref[2];

    if (!$lnm || !$fnm) {
	$self->err_report("No lastName or firstName!");
    }
    if (!$internet || !$org) {
	$self->err_report("No email or org!");
    }

    my $sth = $dbh->prepare("
              SELECT c.colleague_no
              FROM CGM_DDB.colleague c, CGM_DDB.coll_email ce, CGM_DDB.email e
              WHERE upper(c.last_name) = ? AND
                    upper(c.first_name) = ? AND
                    c.colleague_no = ce.colleague_no AND
                    ce.email_no = e.email_no AND
                    upper(e.email) = ?
    ");
    $sth->execute($lnm, $fnm, $internet);
        
    my $colid = $sth->fetchrow();
    return $colid;
}

#####################################################################
sub getShowtxt {
#####################################################################
    my ($self, $fn) = @_;
    my $showtxt;
    my $file = "$datadir/$fn";
    my ($collInfo, $pubmed);

    open(DAT, $file) || die "Can't open $file for read: $!\n";
    while (<DAT>) {
	if (/<colleaInfo>(.+)<\/colleaInfo>/) {
	    $collInfo = $1;
	}
	elsif (/<newColleaInfo>(.+)<\/newColleaInfo>/) {
	    $collInfo = $1;
	}

	if (/<pubmedid>(.+)<\/pubmedid>/) {
	    $pubmed = $1;
	}

	if ($collInfo && $pubmed) {
	    last;
	}
    }

    if (!$collInfo) {
	$self->err_report("$fn No CollInfo!");
    }
    elsif (!$pubmed) {
        $self->err_report("$fn No pubmed!");
    }

    $collInfo =~ s/,.+//;

    $showtxt = " submitted by $collInfo for Pubmed = $pubmed ";

    close DAT;

    return $showtxt;
}

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

    my $delayComment = param('Delayreason');
    my $delayfile = "$datadir/delay.list";
    my $fname = param('file');
    my $mssg;
    if (open(OUT, ">>$delayfile")) {
        print OUT "$fname\tdelay by ".$self->user;
        if ($delayComment) {
            print OUT ", $delayComment";
        }
        print OUT "\n";
        $mssg = "The data has been returned to the list with delay mark.";
    }
    else {
        $mssg = "Can't open '$delayfile' for appending: ".$!; 
    }
    close OUT;

    &printStartPage($self->database, $title);
    print p, b($mssg), br;
    print br, a({-href=>$curatorCenterUrl}, "Return to Curator Central");
    &printEndPage;

    $self->DESTROY;
}

######################################################################
sub getDelayList {
######################################################################
    my ($self) = @_;
    my %delay;
    my $file = "$datadir/delay.list";

    if (-e $file) {
	open(DELAY, $file) || die "Can't open $file for read: $!\n";
	while (<DELAY>) {
	    my ($fn, $text) = split(/\t/);
	    $delay{$fn} = $text;
	}

	close DELAY;
    }
    return %delay;
}

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

    my $mssg = "This annotation set is moved to archive directory without saving anything into database.";
    &printStartPage($self->database, $title);
    print b($mssg), br;
    print br, a({-href=>$curatorCenterUrl}, "Return to Curator Central");
    &printEndPage;

    $self->DESTROY;
}

######################################################################
sub checkExistCA {
######################################################################
    my ($self, $annoSetNo, $dictyBaseid, $topic, $subtop, $des) = @_;

    my $sth = $dbh->prepare("
        SELECT community_annotation_no
        FROM CGM_DDB.community_annotation
        WHERE annotation_set_no = ? AND
              dictyBaseid = ?             AND
              topic = ?             AND
              sub_topic = ?         AND
              description = ?
    ");
    $sth->execute($annoSetNo, $dictyBaseid, $topic, $subtop, $des);

    my $caNo = $sth->fetchrow;
    $sth->finish;

    if (defined $caNo) {
	return $caNo;
    }
    else { return; }
}

######################################################################
sub updateAnDetail {
######################################################################
    my ($self, $caNo, $hashref) = @_;

    my $newGene = $$hashref{'with'};

    return if (!$newGene);

    my $sth = $dbh->prepare("
        SELECT annotation_detail_no, detail_value
        FROM CGM_DDB.annotation_detail 
        WHERE detail_name = 'with' AND
              community_annotation_no = ?
    ");

    my $update = $dbh->prepare("
        UPDATE CGM_DDB.annotation_detail
        SET detail_value = ?
        WHERE annotation_detail_no = ?
    ");

    $sth->execute($caNo);

    my ($detailNo, $deVal) = $sth->fetchrow;
    $sth->finish;

    if ( $deVal eq $newGene) {
	return;
    }
    else {
	$deVal .= ', '. $newGene;
    }

    $update->execute($deVal, $detailNo);

    return;
}

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