package LocusPage;

##########################################################
#                                                        #
# dictyBase Extension of LocusPage                       #
#                                                        #
##########################################################

use LocusPage_base;

BEGIN { %LocusPage:: = %LocusPage_base:: }

use Data::Dumper;

my $seperator = br;

#############################################################################
sub new {
#############################################################################
# This constructor simply returns a blessed hash.  Three attributes, which
# holds the actual query, the database, and the help page url, are stored

    my $self = {};

    bless $self, shift;

    my (%args) = @_;

    ($self->{'_query'}, $self->{'_type'}) = &GetQueryAndType(%args);

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

    if ($self->{'_database'} eq "dictyBase"){

        $self->{'_linker'} = "dictyBase";

    }else{

        $self->{'_linker'} = "dictyBaseDEV";

    }

    $self->{'_dbh'}  = &ConnectToDatabase($self->{'_database'});

    return $self;

}


#
#  added "locus Page" to title
#
#############################################################################
sub printLocusPage{
#############################################################################
# This method prints out a locus page for a given query

    my ($self) = @_;

    my $dictyBase;

    $dictyBase = dictyBaseObject->new($self->{'_type'}=>$self->{'_query'},
                          database=>$self->{'_database'});

    # intercept if to more than one

    if ($dictyBase->isMultiple){ # the query maps to more than one entity

        $self->{'_title'} = "Search for : ".$self->{'_query'};
        $self->wildSearch;
        return;

    }else ### Added by Sohel to forward it ot the new gene page.
    {
        my $gene_name =  $self->{'_query'};
        if($gene_name =~ /DDB/)
        {
             print "Location: /db/cgi-bin/gene_page.pl?dictybaseid=$gene_name\n\n";
        }else
        {
             print "Location: /db/cgi-bin/gene_page.pl?gene_name=$gene_name\n\n";
        }
    }

    $self->{'_title'} = "Locus Page for ".$dictyBase->title; # get title

#    my $JScript = "

#    function switchAddress(list ){

#        location.href = list.options[list.selectedIndex].value;
#    }";

#    $self->pageTop(JScript=>$JScript);

    $self->pageTop;

    $self->{'_printedHeader'} = 1;

    $dictyBase->_initURLs; # need these for locus page - should rework

    if ($dictyBase->orf || $dictyBase->gene){

        if ($dictyBase->featureType =~ /Deleted/){
            print center(h1("This feature has been deleted from the Dictyostelium Database."));
        }elsif ($dictyBase->featureType =~ /Merged/){
            print center(h1("This feature has been merged into another feature."));
        }
        print $self->locusTable($dictyBase);

        if ($newParagraphDisplay =~ /on/i ) {
            my $uiModule = ParagraphUI->new();
            print $uiModule->displayParagraph(dictyBaseObject=>$dictyBase);
        }

    }elsif ($dictyBase->dictyBaseidType eq "Deleted"){

        $self->deleteddictyBaseID($dictyBase);

    }else{

        print center(h2("Your search for ".font({-color=>'red'}, $self->{'_query'})." did not return any hits."),
                     h2("Wild cards were prepended and appended to your query."));
        $self->{'_query'} = "*".$self->{'_query'}."*";
#        print h4("Search for ".$self->{'_query'}.":");
        $self->wildSearch;

    }

   $self->{'_dbh'}->disconnect;

}




#
# took out community annotation piece, moved 'alternative Single page' link
# into table, widened table
#
#  took out uniform/nonuniform alias disinction
#
#############################################################################
sub locusTable{
############################################################################
# This subroutine returns the table that contains all the locus info in it

    my ($self, $dictyBase) = @_;

    my $formCell = $self->formCell($dictyBase);
    my $positionWord = "Sequence Coordinates";
    my $nameHead = "Standard Name ";
    my $standardName = $dictyBase->gene;
    if ($dictyBase->isReserved){
        $nameHead = "Reserved Name ";
        $standardName .= br.br.i("This name is reserved with dictyBase according to the ".a({-href=>$configUrl->breadServerRoot."gene_guidelines.html"}, "Gene Naming Guidelines")." agreed upon by the Dictyostelium community.").br."For more information about this reservation please see the ".a({-href=>$dictyBase->history},        "Locus History").".";
    }

#    my $uniformAlias = $dictyBase->getUniformAliases;
#    my $nonUniformProteinNameAlias = $dictyBase->getNonUniformProteinNameAliases;
    my $alias = $dictyBase->alias;
    my $orf   = $dictyBase->orf;
    my $goRow = $self->getGoRow($dictyBase);
    my $pathway = $self->getPathway($dictyBase);
    my $description = $dictyBase->description;
    my $nameDescription = $dictyBase->nameDescription;
    my $product = join (br, @{$dictyBase->product});
    my $phenotype = $self->phenotype($dictyBase);
    my $positionalInfo = $dictyBase->positionalInfo;
    my $externalLinks = $dictyBase->externalLinks;
    my $primarydictyBaseID = $dictyBase->primarydictyBaseID;
    my $featureType = $dictyBase->featureType;




    my $lastUpdate;
    my $interactionType = $self->relatedInteractors($dictyBase, "forTopLink");

#    if (($description) && ($nonUniformProteinNameAlias)) {
#        $description .= br . "Also known as: " . i($nonUniformProteinNameAlias);
#    }
#    if ((! $description) && ($nonUniformProteinNameAlias)) {
#        $description = "Also known as: $nonUniformProteinNameAlias";
#    }
    if ($standardName && $interactionType) {
        $standardName .= " ( see ".a({-href=>'#interactionNote'}, $interactionType)." )";
    }

    if ($featureType =~ /Deleted/){
        $positionWord = "Position prior to deletion";
    }

    my @rows;




#
#    push (@rows, $self->oneRow($nameHead, i($standardName))) if $standardName;
#    push (@rows, $self->oneRow("Alias ", i($uniformAlias))) if $uniformAlias;
#    push (@rows, $self->oneRow("Systematic Name ", $orf)) if $orf;
#    push (@rows, $self->oneRow("Feature Type ", $featureType)) if $featureType;
#    push (@rows, $goRow) if ($goRow);
#    push (@rows, $pathway) if ($pathway);
#    push (@rows, $self->oneRow("Name Description ", $nameDescription)) if $nameDescription;
#    push (@rows, $self->oneRow("Description ", $description)) if $description;
#    push (@rows, $self->oneRow("Gene Product ", $product)) if $product;
#    push (@rows, $phenotype) if ($phenotype);
#    push (@rows, $self->oneRow($positionWord, $positionalInfo)) if $positionalInfo;
#    push (@rows, $self->oneRow("External Links ", $externalLinks)) if $externalLinks;
#    push (@rows, $self->oneRow("Primary dictyBaseID ", $primarydictyBaseID));
#    push (@rows, $self->oneRow("Last Update ", $lastUpdate)) if $lastUpdate;
#



    push (@rows, $self->oneRow($nameHead, i($standardName))) if $standardName;
    push (@rows, $self->oneRow("Alias ", i($alias))) if $alias;
    push (@rows, $self->oneRow("External Links ", $externalLinks)) if $externalLinks;
    push (@rows, $self->oneRow("Gene Product ", $product)) if $product;
    push (@rows, $self->oneRow("Systematic Name ", $orf)) if $orf;
    push (@rows, $self->oneRow("Feature Type ", $featureType)) if $featureType;
    push (@rows, $self->oneRow("Description ", $description)) if $description;
    push (@rows, $self->oneRow("History ", $history)) if $history;

    push(@rows, $goRow) if ($goRow);
    push (@rows, $pathway) if ($pathway);
    push (@rows, $self->oneRow("Name Description ", $nameDescription)) if $nameDescription;

    push(@rows, $phenotype) if ($phenotype);
    push (@rows, $self->oneRow($positionWord, $positionalInfo)) if $positionalInfo;
    push (@rows, $self->oneRow("Last Update ", $lastUpdate)) if $lastUpdate;
    push (@rows, $self->oneRow("Primary dictyBaseID ", $primarydictyBaseID));




    my $rows = @rows;

    $rows[0] .= td({-rowspan=>$rows,
                    -bgcolor=>'#d8d8d8',
                    -valign=>'top'},
                   $formCell) if $formCell;

    my $formHeading;

    if ($formCell){

        $formHeading = td(center(b(font({-color=>'red',
                                              -size=>'+1'},
                                             $dictyBase->standardName),
                                        font({-size=>'+1'},
                                             " RESOURCES"))));

    }

#    unshift (@rows, td({-colspan=>3}, br));
#
#    unshift (@rows, td({-colspan=>2},
#                               b(font({-color=>'red',
#                                       -size=>'+1'},
#                                      $dictyBase->standardName),
#                                 font({-size=>'+1'},
#                                      " BASIC INFORMATION"))).$formHeading);

    #link to single page format
    my $singlepageUrl = $dictyBase->singlepageUrl;
    unshift (
             @rows, td( {-colspan=>2},
                                   h3( a( {-href=>$singlepageUrl}, "Alternative single page format")
                      )
                    )
             );

    push (@rows, td({-colspan=>3},
                    p,

                    $self->additionalInfo($dictyBase)));



#    push (@rows, td({-colspan=>3},
#                    p,
#                    $self->communityAnnotation($dictyBase)));

    push (@rows, td({-colspan=>3},
                    p,
                    $self->relatedInteractors($dictyBase)));






#
#    return h3(a({-href=>$singlepageUrl}, "Alternative single page format") .
#              img({-src=>'http://165.124.55.143/db/images/new.gif'})) .p.
#           center(

return
center (table( {-border=>0,
        -cellspacing=>3,
        -cellpadding=>3,
        -width=>'90%'},
       Tr(
           [@rows]
                        )
     ));

}



#
#  had to add /db/ to go URL
#
#
######################################################################
sub getGoRow {
######################################################################
    my ($self, $dictyBase) = @_;

    my ($molFunction, $molFunctionBrNum) = $self->molFunction($dictyBase);
    my ($bioProcess, $bioProcessBrNum) = $self->bioProcess($dictyBase);
    my ($cellComponent, $cellComponentBrNum) = $self->cellComponent($dictyBase);

    my ($golist1, $golist2);
    if ($molFunction) {
        $golist1 = "&nbsp;&nbsp;Molecular Function".
                   $self->linebreak($molFunctionBrNum);
        $golist2 = $molFunction.p;

    }
    if ($bioProcess) {
        $golist1 .= "&nbsp;&nbsp;Biological Process".
                    $self->linebreak($bioProcessBrNum);
        $golist2 .= $bioProcess.p;
    }
    if ($cellComponent) {
        $golist1 .= "&nbsp;&nbsp;Cellular Component".
                    $self->linebreak($cellComponentBrNum);
        $golist2 .= $cellComponent.p;
    }
    if (!$golist1) { return; }
    my $name;
    if ($dictyBase->locusName) { $name = $dictyBase->locusName; }
    else { $name = $dictyBase->featureName; }
    my $goAnnotUrl = "/db/cgi-bin/".$self->{'_linker'}."/GO/goAnnotation.pl?locus=".$name;
    return td({-nowrap=>'',
               -bgcolor=>'#a4abc2',
               -valign=>'top'},
               b("GO Annotations").p.
               $golist1).
           td({-nowrap=>'',
               -valign=>'top'},
               a({-href=>"$goAnnotUrl"},
                i(b($name." GO evidence and references"))).p.
                $golist2);
}


##########################################################################################################
sub makeOntologyString{
##########################################################################################################
#
   my ($self, $arrayRef, $goidHashRef, $refHashRef, $goAspect) = @_;

   my $string;
   my $imageUrl  = "/db/images/blackdot.gif";
   my $image2Url = "/db/images/amigo_sm.png";

   my $dbh = $self->{'_dbh'};

   foreach my $term (@{$arrayRef}){

     my $goObj = Go->new(dbh  => $dbh,
                                        goid => $$goidHashRef{$term});

     my $amigoUrl = $goObj->getAmiGoLinkUrl;
     my $goUrl     = "/db/cgi-bin/".$self->{'_linker'}."/GO/go.pl?goid=".$$goidHashRef{$term};

      my $refNo    = $$refHashRef{$term};

      my $title    = "See other dicty genes associated with\n$term (GOID:$$goidHashRef{$term}).";

      $term = a({-href=>$goUrl, -title=>$title}, $term);

      if ($refNo) {
         # $refNo =~ s/^([0-9]+)\:\:.+$/$1/;
         # my $isNot = a({-href=>"/cgi-bin/".$self->{'_linker'}."/reference/reference.pl?refNo=$refNo"}, b(i("NOT")));
         my $isNot = a({-href=>"/html/help/GO.html#not"},
                     b(i("NOT")));

         if ($goAspect eq "F") {
            $term = $isNot." a ".$term;
         }
         elsif ($goAspect eq "P") {
            $term = $isNot." involved in ".$term;
         }
         else {
            $term = $isNot." part of ".$term;
         }
      }

      $string .= img({-src    => $imageUrl,
                      -valign => "MIDDLE",
                      -alt    => "*",
                      -border => 0}
                     )
                 ."&nbsp;&nbsp;".
                a({-href=>$amigoUrl},
                   img({ -src   => $image2Url,
                        -valign => "MIDDLE",
                        -alt    => "Pops up an Amigo window: View this item in a tree view, and see associated genes from other organisms.",
                        -border => 0}
                      )
                 ).
             "&nbsp;&nbsp;".
             $term.br;
   }

   $string =~ s/\<br\>$//;

   return $string;

}

#
#  took out some sections (interactions, fucntions, companalysis) added checks
#  to make sure sequence exists
#
#
##########################################################################################################
sub formCell{
##########################################################################################################
# This subroutine prints returns a cell that contains all the elements of the right hand cell of the table
# on the locus page

    my ($self, $dictyBase) = @_;

    #return if !($self->{'begCoord'}); # don't give this section if there's no associated sequence

    my $cell;
    my $deleted;
    my $merged;
    my $type = $dictyBase->featureType;

    if ($dictyBase->featureType =~ /Deleted/){
        $deleted =1;
    }

    if ($dictyBase->featureType =~ /Merged/){
        $merged =1;
    }


    $dictyBase->getSequenceAvailable;

#    $cell .= $self->mapSection($dictyBase) if ($dictyBase->begCoord && !$deleted && !$merged && $type ne 'Contig');
    $cell .= $self->mapSection($dictyBase) if (!$deleted && !$merged && $dictyBase->{'miniORFMap'});
    $cell .= $self->litSection($dictyBase) if (!$deleted && !$merged);
    $cell .= $self->seqSection($dictyBase) if (!$deleted && !$merged);
    $cell .= $self->analysisSection($dictyBase) if ( @{ $dictyBase->allSequence_types } );
    $cell .= $self->proteinSection($dictyBase) if ($dictyBase->{'hasProteinSeq'} && !$deleted && !$merged);

####### Gene Expression ###########################
   $cell .= $self->expressionSection($dictyBase);
#####################################################
   $cell .= $self->mutantSection($dictyBase);
   ###################################################

   # $cell .= $self->interactionSection($dictyBase) if ($dictyBase->begCoord && !$deleted && !$merged);
#    $cell .= $self->displaysSection($dictyBase) if ($dictyBase->begCoord && !$deleted && !$merged);
#    $cell .= $self->compSection($dictyBase) if ($dictyBase->begCoord && !$deleted && !$merged);
#    $cell .= $self->functionSection($dictyBase) if ($dictyBase->begCoord && !$deleted && !$merged);

    return $cell;

}

#
# calls new method in dictyBaseobject to write form
#
#
########################################################################################################
sub seqSection{
########################################################################################################
# This subroutine returns the section of the right hand cell on the locus page that contains links to
# retrieve various sequences associated with the locus

   my ($self, $dictyBase) = @_;

   my $header = li(b("Retrieve Sequences")).$seperator;

   return
      $dictyBase->write_sequence_retreival_selector( $header );

}


########################################################################################################
sub expressionSection{
########################################################################################################
# This subroutine returns the section of the right hand cell on the locus page that contains links to
# retrieve various sequences associated with the locus

   my ($self, $dictyBase) = @_;

   my $header = li(b("Expression Information")).$seperator;

   return
      $dictyBase->write_expression_selector( $header );

}

########################################################################################################
sub mutantSection{
########################################################################################################
# This subroutine returns the section of the right hand cell on the locus page that contains links to
# retrieve various sequences associated with the locus

   my ($self, $dictyBase) = @_;

   my $header = li(b("Mutant Information")).$seperator;

   return
      $dictyBase->write_mutant_selector( $header );

}


#
#
# calls new method in dictyBaseobject to write form
#
#
#########################################################################################################
sub analysisSection{
#########################################################################################################
# This subroutine returns the section of the right hand cell on the locus page that contains links to
# various sequence analysis tools.  The links don't yet work, as I haven't come up with a good idea as
# to how to do them

    my ($self, $dictyBase) = @_;

    my $header = li(b("Sequence Analysis Tools")).$seperator;

    return
       $dictyBase->write_analysis_selector( $header );

}


#
#  took out links to functionjunction, expression connection, proteininfo, structural info
#   added logic to only display locus history link when there is something to display
#
# use $self->{'_dbh'};
#
#######################################################################################################
sub additionalInfo{
#######################################################################################################
#

    my ($self, $dictyBase) = @_;


    my $dbh = $self->{'_dbh'};
    my $bgColor="#b7d8e4";

    my ($paragraphCell, $researchersCell, $mappingCell, $protInfoCell,
        $structInfoCell, $seqResourcesCell, $locusHistoryCell);

    my $paragraph = $dictyBase->paragraph;
    my $researchers = $dictyBase->researchers;
    my $mappingData = $dictyBase->mappingData;
    my $protInfo = $dictyBase->protInfo;
    my $seqResources = $dictyBase->seqResources;
    my $motif = $dictyBase->motifInfo;
    my $pdb = $dictyBase->pdbInfo;
    my $notes = $dictyBase->public_curator_notes;

   #
   #  set hashistory flag to true if something would show up on locushistory.pl
   #
#    my $hashistory;
#    if ($dictyBase->{'_locusName'}) {
#              my $locusObj = Locus->new( dbh        => $dbh,
#                                                        locus_name => $dictyBase->{'_locusName'});
#         if (
#             $locusObj->geneReservationInfo                  or
##             @{$locusObj->unPublishedPaperInfoArrayRef}  > 0 or
##             @{$locusObj->updateLogInfoArrayRef}         > 0 or
#             @{$locusObj->publicCuratorNoteInfoArrayRef} > 0
#         ) { $hashistory++; }
#    }
#    elsif ($dictyBase->{'_featureName'}) {
#         my $featObj = Feature->new( dbh          => $dbh,
#                                     feature_name => $dictyBase->{'_featureName'});
#         if (
#             @{$featObj->curatorNoteInfoArrayRef} > 0 or
#             @{$featObj->updateLogInfoArrayRef}  > 0
#         ) { $hashistory++; }
#    }
#
#
#
#
#     $locusHistoryCell = td({-bgcolor=>$bgColor,
#                               -nowrap=>''},
#                              a({-href=>$dictyBase->history},
#                                "Locus History")) if $hashistory;
    my $globalGeneHunterCell = td({-bgcolor=>$bgColor,
                                   -nowrap=>''},
                                  a({-href=>$dictyBase->globalGH},
                                    "Global Gene Hunter"));
    my $funcJuncCell = td({-bgcolor=>$bgColor,
                           -nowrap=>''},
                          a({-href=>$dictyBase->FuncJunc},
                            "Function Junction"));


    my $expressionCell = td({-bgcolor=>$bgColor,
                             -nowrap=>''},
                            a({-href=>$dictyBase->exprConn},
                              "Expression Connection"));

    if ($paragraph){
        $paragraphCell = td({-bgcolor=>$bgColor,
                             -nowrap=>''},
                            a({-href=>$paragraph},
                              "Summary Paragraph"));
    }

    if ($researchers){
        $researchersCell = td({-bgcolor=>$bgColor,
                               -nowrap=>''},
                            a({-href=>$researchers},
                              "Researchers"));
    }

    if ($mappingData){
        $mappingCell = td({-bgcolor=>$bgColor,
                           -nowrap=>''},
                            a({-href=>$mappingData},
                              "Mapping Data"));
    }

    if ($protInfo){
        $protInfoCell = td({-bgcolor=>$bgColor,
                             -nowrap=>''},
                            a({-href=>$protInfo},
                              "Protein Info & Composition"));
    }

    if ($motif || $pdb) {
        my $structCell;
        if ($motif) {
            $structCell = a({-href=>$motif},
                            "Motifs");
        }
        if ($pdb) {
            if ($structCell) { $structCell .= " | "; }
            $structCell .= a({-href=>$pdb},
                            "PDB Homologs");
        }
        $structInfoCell = td({-bgcolor=>$bgColor,
                              -nowrap=>''},
                             $structCell);
    }

    if ($seqResources){
        $seqResourcesCell = td({-bgcolor=>$bgColor,
                             -nowrap=>''},
                            a({-href=>$seqResources},
                              "Gene/Sequence Resources"));
    }

    my ($firstRowNum, $secondRowNum, $thirdRowNum);
    my ($firstRow, $secondRow, $thirdRow);

#    foreach my $cell ($paragraphCell, $locusHistoryCell,
#                      $globalGeneHunterCell, $funcJuncCell,
#                      $expressionCell, $researchersCell,
#                      $mappingCell, $protInfoCell, $structInfoCell,
#                      $seqResourcesCell) {

    foreach my $cell ($paragraphCell,
                      $globalGeneHunterCell, $researchersCell,
                      $mappingCell) {
        if (!$cell) { next; }
        if ($firstRowNum < 4) {
            $firstRow .= $cell;
            $firstRowNum++;
            next;
        }
        if ($secondRowNum < 4) {
            $secondRow .= $cell;
            $secondRowNum++;
            next;
        }
        $thirdRow .= $cell;
    }
    my $rows = Tr($firstRow);
    if ($secondRow) { $rows .= Tr($secondRow); }
    if ($thirdRow) { $rows .= Tr($thirdRow); }

    my $noteTable;

    $noteTable = $self->note_table($dictyBase) if $notes;


    return center(table({-border=>0,
                         -cellspacing=>3,
                         -cellpadding=>2,
                         -width=>'100%'},
                 Tr(
                    td(font({-size=>3},
                            b("ADDITIONAL INFORMATION for ").i($dictyBase->standardName)))
                    )
                        ).
$noteTable.

                  table({-border=>0,
                         -cellspacing=>3,
                         -cellpadding=>2,
                         -width=>'100%'},
                        $rows
                  ));

}


#
#
# changed query to exclude secondary features and rolled up alias query into locus query (one unified query()
#
# use $self->{'_dbh'};
#
########################################################################################################
sub wildSearch{
########################################################################################################
# This method takes the query, which has a wild card, and searches for all possible hits, and presents
# them back to the user - can we use the dictyBase object itself to make this a lot easier?

    my ($self) = @_;

    my $dbh = $self->{'_dbh'};

    my (@hits, %seenF, %seenL, %name);

    my $query = $self->{'_query'};

    $query=~s/\*/\%/g;

    $query = uc($query);


   #
   # look for loci or aliases associated with loci
   #  inner join v_primary_feature so that deleted loci will
   #   not show up, also while we show feature information (like coordinates),
   #   we do not want more than one feature to show up
   #
   # we will probably retool this in the future
   #
   # IF NUMBERS FROM TEXTSEARCH.PM DO NOT MATCH THIS,
   # IT IS PROBABLY BECAUSE THERE ARE MORE THAN ONE
   # PRIMARY FEATURES ASSOCIATED WITH A LOCUS
   #
    $sth = $dbh->prepare("
           SELECT DISTINCT L.LOCUS_NAME, L.LOCUS_NO, F.FEATURE_NO
             FROM CGM_DDB.LOCUS L
       INNER JOIN CGM_DDB.V_PRIMARY_FEATURE F
               ON L.LOCUS_NO  = F.LOCUS_NO
  LEFT OUTER JOIN CGM_DDB.LOCUS_ALIAS LA
               ON LA.LOCUS_NO = L.LOCUS_NO
  LEFT OUTER JOIN CGM_DDB.ALIAS A
               ON A.ALIAS_NO = LA.ALIAS_NO
            WHERE UPPER(l.LOCUS_NAME) LIKE ?
               OR UPPER(ALIAS_NAME)   LIKE ?
    ");

    $sth->execute($query,$query);



    while (my @data = $sth->fetchrow_array){

        $seenL{$data[1]} = 1;

        next if ($seenF{$data[2]} && $data[0] eq $seenF{$data[2]}); # don't want in the table twice if orf is same as gene

        if ($data[2]){ # it's has a feature, so use that

            $data[1] = $data[2];
            $data[2] = "featureNo";

        }else{

            $data[2] = "locusNo";

        }

        push (@hits, \@data); # this is locus name

    }

    $sth->finish;

   #
   # now look for loci with no feature (reserved loci, or some acedb loci)
   #
   #
    my $sth = $dbh->prepare("
        SELECT L.LOCUS_NAME, L.LOCUS_NO
          FROM CGM_DDB.LOCUS L
         WHERE NOT EXISTS (
                 SELECT 'A'
                   FROM CGM_DDB.FEATURE F
                  WHERE F.LOCUS_NO = L.LOCUS_NO
              )
          AND UPPER(L.LOCUS_NAME) LIKE ?
    ");
    $sth->execute($query);


    while (my @data = $sth->fetchrow_array){

            $data[2] = "locusNo";

        push (@hits, \@data); # this is locus name

    }


    $sth->finish;

    $dbh->disconnect;

    $self->wildResults("hits"=>\@hits);



}


#
#  add border
#
##########################################################################################################
sub mapSection{
##########################################################################################################
# This subroutine returns the section of the right hand cell on the locus page that contains the clickable
# mini orf map

    my ($self, $dictyBase) = @_;

    return center(font({-size=>'-1'},
                       "Click on map for expanded view"),
                  br,
                  a({-href=>$dictyBase->orfMap},
                    img({-src=>$dictyBase->miniORFMap,
                         -border=>1,
                         -alt=>'ORFmap'})));

}



#
#  took out links that do not currently apply to dictyBase
#
#
#########################################################################################################
sub proteinSection{
########################################################################################################
# This subroutine returns the section of the right hand cell on the
# locus page that contains links to protein info & structure pages
#

    my ($self, $dictyBase) = @_;

    my $pdb = $dictyBase->pdbInfo;
    my $motif = $dictyBase->motifInfo;
    my $ypd = $dictyBase->protInfo;
    my $scop = $dictyBase->scop;

    my %prot = (
               $motif=>"Motifs",
               $pdb=>"PDB Homologs",
               $ypd=>"Protein Info",
               $scop=>"SCOP superfamily (MRC/Stanford)"
    );

    my @values;

    push (@values, $ypd) if $ypd;
#    push (@values, $motif) if $motif;
#    push (@values, $pdb) if $pdb;
#    push (@values, $scop) if $scop;

    if (@values){

        return
            start_form.
                li(b("Protein Info & Structure")).$separator.
                    popup_menu(-name=>'prot',
                               -"values"=>\@values,
                               -labels=>\%prot).
                                   button(-onClick=>'switchAddress(this.form.prot)',
                                          -name=>'View').
                                              end_form;

    }
    return;

}

#
# changed $phenotypeUrl from "/cgi-bin/..." to "/db/cgi-bin/..."
#  re addded support for saccdb phenotypes
#
###########################
sub phenotype {
##########################################################################################################
# This function returns a formatted string for phenotype

    my ($self, $dictyBase) = @_;

#    my $sacchdbPhenotype = $dictyBase->SacchdbPhenotype;
    my $phenotypeArrayRef = $dictyBase->phenotype;

    my $imageUrl = $configUrl->breadServerRoot."images/blackdot.gif";
    my $phenotypeUrl = "/db/cgi-bin/".$self->{'_linker'}."/phenotype/phenotype.pl";

    my $string;

    my ($left, $right);

#    print "This is for test: Browser=", $ENV{'HTTP_USER_AGENT'}, p;

    ### try to fix the alignment a bit for OmniWeb & Safari broswers

    if ($ENV{'HTTP_USER_AGENT'} =~ /OmniWeb/i) {

        $left = b("Phenotype").br.br;

    }
    elsif ($ENV{'HTTP_USER_AGENT'} =~ /Safari/i) {

        $left = b("Phenotype").br.br;

    }
    else {

        $left = b("Phenotype").br.br;

    }

    my ($phenoDetailsLinkText, $lenLimit);
#
# jmc comment out addition of extra br if locusName > 4
# this does not seem to be needed.
#    if (!$dictyBase->locusName || length($dictyBase->locusName) > 4) {
#        $left .= br;
#        $phenoDetailsLinkText = " Phenotype details and".br." references";
#        $lenLimit = 34;
#    }
#    else {
        $phenoDetailsLinkText = " Phenotype details and references";
        # $lenLimit = 43;

          $lenLimit = 80;
#    }

    my $preType;
    my $countBreak = 0;

    foreach my $rowRef (@$phenotypeArrayRef) {
        my ($type, $phenotype, $phenotypeNo) = @$rowRef;

        if ($type ne $preType) {

            $left .= $self->linebreak($countBreak);
            $left .= "&nbsp;&nbsp;".$type;
            $right .= p;
            $countBreak = 1;

        }
        else {
            $countBreak++;
        }

        my $phenotypeText;

        while (length($phenotype) > $lenLimit) {

            $countBreak++;

            my @phenoWord = split(/ /, $phenotype);

            my $rest = pop(@phenoWord);

            $phenotype = join(' ', @phenoWord);

            while (length($phenotype) > $lenLimit) {

                     my $word = pop(@phenoWord);

                $phenotype = join(' ', @phenoWord);

                $rest = $word." ".$rest;
            }

            # $phenotype .= br."&nbsp;&nbsp;&nbsp;".$rest;
            # $phenotype .= br.$rest;

            $phenotypeText .= a({-href=>$phenotypeUrl."?phenotype=".$phenotypeNo. "&display=no"}, $phenotype).br;
            if ($rest) {
                $phenotypeText .= "&nbsp;&nbsp;&nbsp;";
            }
            $phenotype = $rest;


        }

        if ($phenotype) {

            $phenotypeText .= a({-href=>$phenotypeUrl."?phenotype=".$phenotypeNo. "&display=no"}, $phenotype).br;

        }

        $right .= img({-src=>$imageUrl, -valign=>"MIDDLE", -alt=>"*",
                       -border=>0}) . "&nbsp;&nbsp;" . $phenotypeText;

        $preType = $type;

    }

#
# dictyBase uncommented following block
#
    if ($sacchdbPhenotype) {
        $left .= $self->linebreak($countBreak);
        $left .= "&nbsp;&nbsp;"."Free text";
        $right .= p. img({-src=>$imageUrl,
                      -valign=>"MIDDLE",
                      -alt=>"*",
                      -border=>0})."&nbsp;&nbsp;".
                 $sacchdbPhenotype;
    }
#
#
    if ($preType) {
        my ($PTurl, $linkNm);
        if ($dictyBase->locusName) {
            $linkNm = $dictyBase->locusName;
            $PTurl =  $phenotypeUrl."?feat=".$linkNm."&type=locus";
        }
        else {
            $linkNm = $dictyBase->featureName;
            $PTurl =  $phenotypeUrl."?feat=".$linkNm."&type=feature";
        }

        my $phenoFirstLine = a({-href=>$PTurl}, $linkNm.$phenoDetailsLinkText);

        #add link to open biosystems
        my $openBioUrl = $dictyBase->openBio;
# stan's original
#        $phenoFirstLine .= br. br. a({-href=>$openBioUrl}, "Order mutant strains used in the systematic deletion " .br. "project") if $phenoFirstLine;
#        $phenoFirstLine .= br. br. a({-href=>$openBioUrl}, "Order mutant strains used in the systematic deletion project") . br .br if $phenoFirstLine;
         $phenoFirstLine .= br. br if $phenoFirstLine;
         $right = b(i($phenoFirstLine)) .$right;
#        $right = b(i(a({-href=>$PTurl}, $linkNm.$phenoDetailsLinkText))).$right;
    }

    if (!$right) { return; }

    return td({-bgcolor=>'#a4abc2',-valign=>'top'},
              $left) .
           td({-valign=>'top'}, $right);

}




##########################################################################################################
sub litSection{
##########################################################################################################
# This subroutine returns the section of the right hand cell on the locus page that contains links to do
# with literature for the gene

    my ($self, $dictyBase) = @_;

    my $literatureGuide = $dictyBase->litGuide;
    my $pubMedSearch = $dictyBase->pubMed;
    my $paragraph = $dictyBase->paragraph;
    my $communityAnnotation = $dictyBase->communityAnnotation;
    my $germOnline = $dictyBase->germOnline;

#    my @values = ($literatureGuide, $pubMedSearch, $communityAnnotation);
#
#    if ($newParagraphDisplay eq "off") {
#        push (@values, $paragraph) if $paragraph;
#    }
#    else {
#        if (defined $paragraph) {
#            $paragraph = "#summaryParagraph";
#            push (@values, $paragraph);
#        }
#    }
#
#    if (defined $germOnline) {
#        push (@values, $germOnline);
#    }


    my @values = ($literatureGuide, $pubMedSearch );

    my %lit = (
               $literatureGuide =>"Literature Guide",
               $pubMedSearch => "PubMed Search",
               $communityAnnotation=>"Community Annotation",
               $paragraph => "Summary Paragraph",
               $germOnline => "GermOnline"
               );

    return
        start_form.
            li(b("Literature")).$separator.
                popup_menu(-name=>'lit',
                           -"values"=>\@values,
                           -labels=>\%lit).
                               button(-onClick=>'switchAddress(this.form.lit)',
                                      -name=>'View').
                                          end_form;

}


#######################################################################
sub note_table {
#######################################################################
    my ($self, $dictyBase) = @_;

    my $noteArrayRef = $dictyBase->public_curator_notes();

    my $html;

            $html = a({-name=>'locus_notes'}).table({-width=>"100%"},
                        Tr({-align=>'left'},
                           td({-width=>"100%",
                               -align=>'left',
                               -bgcolor=>"#b7d8e4"},
                              font({-size=>"3"},strong('Locus Notes')))));

    if (!@$noteArrayRef) { return; }


    $html = a({-name=>'locus_notes'}).table({-width=>"100%"},
                        Tr({-align=>'left'},
                           td({-width=>"100%",
                               -align=>'left',
                               -bgcolor=>"#b7d8e4"},
                              font({-size=>"3"},strong('Locus Notes')))));

    my $count;
    foreach my $rowRef (@$noteArrayRef) {
        my ($noteNo, $note, $isPublic) = @$rowRef;

        $count++;

     $html .= table({-width=>"100%"},
                    Tr({-align=>'left'},
                       td({-width=>"100%",
                           -align=>'left'},
                          $note))),br;
    }

    $hasHistory += $count;
    return $html;
}

#
# took out hr's and call to end_html since that is included in the footer
#
#############################################################################
sub pageBottom{
#############################################################################
# This simply prints out stuff to go at the botttom of the page

    my ($self) = @_;
    &copyright;
    &FooterReturnEmail;
}


###########################################################################################
sub printWildTable{
###########################################################################################
# This subroutine returns a table of the results from a wild card search
# want to have the name in the first column, systematic name in the second, aliases in the third
# chromosome + coordinate in the next, function in the last

    my ($self, %args) = @_;
    my $hitsRef = $args{'hits'};
    my $string = "<B style=\"color:black;background-color:#ffff66\">";

    my ($hit, $gene, $orf, $alias, $pos, $match, $function, $orig, $functionRef, $object);

    my $show;

    my $query = $self->{'_query'};
    $query =~ s/\*//g; # get rid of the wild cards when doing the regex

#
# escape the parenthesis, tRNAs have parenthesis in their name
#
    $query =~ s#\(#\\\(#g;
    $query =~ s#\)#\\\)#g;

    my $hitmax = 100;

    if (@{$hitsRef}){

        my $count = @{$hitsRef};

        my $summaryLine = "";
        if ($count > $hitmax) {
            $summaryLine = "The query matches a large number of loci in the database.  Tables are available from the FTP site \<<a href=\"ftp://genome-ftp.stanford.edu/Dictyostelium/data_download/\">ftp://genome-ftp.stanford.edu/Dictyostelium/data_download/</a>\> that provide information from dictyBase.  Check the <a href=\"ftp://genome-ftp.stanford.edu/Dictyostelium/data_download/README\">README</a> file for a description of the available files.  In particular, check out the TAB delimited <a href=\"ftp://genome-ftp.stanford.edu/Dictyostelium/data_download/chromosomal_feature/chromosomal_feature.tab\">chromosomal_feature.tab</a> and its <a href=\"ftp://genome-ftp.stanford.edu/Dictyostelium/data_download/chromosomal_feature/README\">README</a> for a table of all annotated <i>S. discoideum</i> genomic features.  Hint: 1) Press the Control key and then click on the link to download the file to your computer's disk.  2) Change the extension from .tab to .xls to open with MS Excel.\n";
            $summaryLine .= "<p>Because your query matches so many names, an abbreviated table of the hits is provided below.  The hits below are matches to standard gene names, ORF names, or aliases.  Click on a name to go to that gene's locus page, or explore the files on the FTP site described above to find more information.<p>\n";

            print STDERR "LocusPage.pm: query = \"$query\" had $count matches, limited to summary page\n";
        }

        $summaryLine .= "Your query ".font({-color=>'#FF0000'},$self->{'_query'})." returned ".font({-color=>'#FF0000'},$count)." hits to the following gene names:";

        print h4($summaryLine);

        my @list;
        my $functionCount;
        my $aliasCount;
        foreach $hit (sort by_Dictyostelium @{$hitsRef}){
            if ($count <= $hitmax) {

                $object = dictyBaseObject->new($$hit[2]=>$$hit[1],
                                         database=>$self->{'_database'});

                $gene = $object->gene;
                $orf  = $object->orf;
                $alias = $object->alias;
                if ($alias) { $aliasCount++; }

                $orf=~s/($query)/$string$1<\/B>/i;
                $orf ||= "&nbsp;";
                $gene =~s/($query)/$string$1<\/B>/i;
                $gene ||= "&nbsp;";
                $alias=~s/($query)/$string$1<\/B>/i;
                $alias ||="&nbsp;";
                $pos = $object->positionalInfo || "&nbsp;";
                ($functionRef) = $object->molFunction;
                if ($$functionRef[0]) {
                    $functionCount++;
                }
                $function = $$functionRef[0] || "&nbsp;";

             #    if ($object->primarydictyBaseID){
#
#                     $$hit[0] = a({-href=>url."?dictyBaseid=".$object->primarydictyBaseID},
#                                  $$hit[0]);
#
#                 }else{
#
#                     $$hit[0] = a({-href=>url."?featureNo=".$object->featureNo},
#                                  $$hit[0]);
#
#                 }


                my $gene_page_url = "/db/cgi-bin/gene_page.pl?dictybaseid=";
                if ($object->primarydictyBaseID){
                    $$hit[0] = a({-href=>$gene_page_url.$object->primarydictyBaseID},$$hit[0]);

                }else{

                    $$hit[0] = a({-href=>url."?featureNo=".$object->featureNo},
                                 $$hit[0]);

                }

            }

            push(@list, $$hit[0]."\t".$gene."\t".$orf."\t".$alias."\t".$pos."\t".$function);

        }

        if ($count <= $hitmax) {
            my $rows = th("Match").
                th("Gene Name").
                    th("Systematic Name");
            if ($aliasCount) {
                $rows .= th("Alias(es)");
            }
            $rows .= th("Position Info");
            if ($functionCount) {
                $rows .= th("Function");
            }
            $rows = Tr($rows);
            foreach my $list (@list) {
                my ($hit, $gene, $orf, $alias, $pos, $func) = split(/\t/, $list);
                my $row = td(b($hit)).td($gene).td($orf);
                if ($aliasCount) { $row .= td($alias); }
                $row .= td($pos);
                if ($functionCount) { $row .= td($func); }
                $rows .= Tr($row);
            }
            print table({-align=>'center',
                         -border=>3},
                        $rows), "\n";
        } else {
            my $rows_count = 1;
            my $row = "";
            my $rows = "";
            foreach my $genename (@list) {

                $genename =~ s/\t//g;
                $row .= td(a({-href=>url."?locus=$genename"},$genename));
                if (($rows_count++ % 5 == 0) && ($rows_count != 0)) {
                    $rows .= Tr($row), "\n";
                    $row = "";
                }
            }
            $rows .= Tr($row);
            print table({-align=>'center',
                         -border=>3},
                        $rows), "\n";
        }
    } else {

        print center(h2("Your search for ".$self->{'_query'}." did not return any hits."),
                     h2("Please try again."),
                     $self->searchFormTable($self->{'_query'}));

    }

}

1; # to keep require happy










