package UserCP::Messenger;
use strict;
#################################################################################
# Ikonboard v3 by Jarvis Entertainment Group, Inc.
#
# No part of this script can be used outside Ikonboard without prior consent.
#
# More information available from <ib-license@jarvisgroup.net>
# (c)2001-2002 Jarvis Entertainment Group, Inc.
# 
# http://www.ikonboard.com | http://www.jarvisgroup.net
#
# Please read the license for more information
#
# Messenger: Messenger Fucntions.
# Module Authors: Matthew Mecham <matt@ikonboard.com>
#                 Infection
#                 KevG
#
#################################################################################

BEGIN {
    require 'Lib/FUNC.pm';
    require 'iTextparser.pm';
}

my $output       = FUNC::Output->new();
my $mem          = FUNC::Member->new();
my $std          = FUNC::STD->new();
my $txt          = iTextparser->new();
$Messenger::lang = $std->LoadLanguage('MessengerWords');

sub new {
  my $pkg = shift;
  my $obj = { R_MEMBER => $iB::MEMBER, NEW_MSG_DATA => '', '.to_member' => '', '.html' => '' };
  bless $obj, $pkg;
  return $obj;
}

#+------------------------------------------------------------------------------------------------------

sub Splash ($) {
    my ($obj, $db) = @_;
    $obj->{'MSG_DATA'} = $obj->Check_new($db);
    $obj->{'MSG_DATA'}->{'ICON'} = $obj->{'MSG_DATA'}->{'NEW_MESSAGES'} ? $iB::SKIN->{M_NEW} : $iB::SKIN->{M_NNEW};
    $obj->{'MSG_DATA'}->{'TEXT'} = $obj->{'MSG_DATA'}->{'NEW_MESSAGES'} ? $Messenger::lang->{'msg_new'} : $Messenger::lang->{'msg_no_new'};
    $obj->{'MSG_DATA'}->{'TEXT'} =~ s!<#NEW_MESSAGES#>!$obj->{'MSG_DATA'}->{'NEW_MESSAGES'}!;
    if ($obj->{'MSG_DATA'}->{'NEW_MESSAGES'}) {
        $obj->{'MSG_DATA'}->{'LAST_SENT'} = $std->get_date( TIME => $obj->{'MSG_DATA'}->{'LAST_SENT'}, METHOD => 'LONG');
        $obj->{'MSG_DATA'}->{'LAST_TEXT'} = $Messenger::lang->{'last_txt'};
        $obj->{'MSG_DATA'}->{'LAST_TEXT'} =~ s!<#LAST_FROM_NAME#>!<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Profile;CODE=03;MID=$obj->{'MSG_DATA'}->{'LAST_FROM_ID'}'><u><b>$obj->{'MSG_DATA'}->{'LAST_FROM_NAME'}</b></u></a>!;
        $obj->{'MSG_DATA'}->{'LAST_TEXT'} =~ s!<#LAST_MSG_TITLE#>!<a href='$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=01;MODE=01;MSID=$obj->{'MSG_DATA'}->{'LAST_MSG_ID'}'><u><b>$obj->{'MSG_DATA'}->{'LAST_MSG_TITLE'}</b></u></a>!;
        $obj->{'MSG_DATA'}->{'LAST_TEXT'} =~ s!<#LAST_SENT#>!$obj->{'MSG_DATA'}->{'LAST_SENT'}!;
        $obj->{'MSG_DATA'}->{'LAST_TEXT'} = qq[<br>$obj->{'MSG_DATA'}->{'LAST_TEXT'}];
    }
    $obj->{'.html'} .= MessengerView::splash($obj->{'R_MEMBER'},$obj->{'MSG_DATA'});
    $obj->{'.html'} .= MessengerView::CP_end();

    $output->print_ikonboard( DB      => $db,
                              TITLE   => $Messenger::lang->{'t_welcome'},
                              NAV     => [qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00">$Messenger::lang->{'t_title'}</a>!],
                              OUTPUT  => $obj->{'.html'}
                            );
}

sub Check_new ($$) {
    my ($obj, $db) = @_;
    my $stats;
    $stats = $db->select(TABLE => 'message_stats', ID => $obj->{'R_MEMBER'}->{'MEMBER_ID'}, KEY => $obj->{'R_MEMBER'}->{'MEMBER_ID'} );
    return $stats->{'NEW_MESSAGES'} ? $stats : { NEW_MESSAGES => 0 };
}

#+------------------------------------------------------------------------------------------------------

sub _get_new ($$) {
    my ($obj, $db) = @_;
    $obj->{'NEW_MSG_DATA'} = $db->select(TABLE => 'message_stats', ID => $obj->{'R_MEMBER'}->{'MEMBER_ID'}, KEY => $obj->{'R_MEMBER'}->{'MEMBER_ID'} );
}

#+------------------------------------------------------------------------------------------------------

sub _get_blank ($$) {
    my ($obj, $db) = @_;
    $obj->{'NEW_MSG_DATA'} = { NEW_MESSAGES => 0 };
}

#+------------------------------------------------------------------------------------------------------


sub view_msg ($$$) {
    my ($obj,$db, $mode) = @_;

    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_such_msg')    unless $iB::IN{'MSID'};

    my $Row = $db->select( TABLE   => 'message_data',
#                           ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
			   ID      => $iB::MEMBER->{'MEMBER_ID'},
                           KEY     => $iB::IN{'MSID'}
                         );
#    my $Row = $db->query( TABLE => 'message_data',
#                          WHERE => "MESSAGE_ID == $iB::IN{'MSID'} and MEMBER_ID == '$iB::MEMBER->{'MEMBER_ID'}'",
#			  
#			);                          
#    $Row = @{$Row}[0];
    
    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_such_msg')    unless $Row->{'MEMBER_ID'} == $iB::MEMBER->{'MEMBER_ID'};

    $obj->my_get_stats($db);
    
    if ($Row->{'READ_STATE'} < 1) {
        if ($Row->{'READ_STATE' } == -1) {
            # this message is being tracked. Send return receipt
            my $rr_show_popup = (split/&/, $Row->{'FROM_ID'})[1];
            my $rr_id = $db->insert( TABLE  => 'message_data',
                                     ID     => $Row->{'FROM_ID'},
                                     VALUES => { DATE         => time,
                                                 READ_STATE   => 0,
                                                 TITLE        => $Messenger::lang->{read_rec_title}.' '.$Row->{'TITLE'},
                                                 MESSAGE      => "<b>$Messenger::lang->{read_rec_text} ".$std->get_date( TIME => $Row->{'DATE'}, METHOD => 'LONG').':</b><BR>'.$Row->{'MESSAGE'}."<br><br><b>".$obj->{R_MEMBER}->{MEMBER_NAME}." $Messenger::lang->{mem_read_msg}</b>",
                                                 MESSAGE_ICON => '',
                                                 FROM_ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                                 FROM_NAME    => $obj->{'R_MEMBER'}->{'MEMBER_NAME'},
                                                 REPLY        => '',
                                                 REPLY_DATE   => '',
                                                 VIRTUAL_DIR  => 'in',
                                                 MEMBER_ID    => $Row->{'FROM_ID'}
                                   }
                        );
             my $msg_stats = { };
             $msg_stats = $db->select( TABLE  => 'message_stats',
                                       ID     => $Row->{'FROM_ID'},
                                       KEY    => $Row->{'FROM_ID'},
                                     );
             if ($msg_stats->{'MEMBER_ID'}) {
                 $msg_stats->{'TOTAL_MESSAGES'}++;
                 $msg_stats->{'NEW_MESSAGES'}++;
                 $db->update(  TABLE  => 'message_stats',
                               ID     => $Row->{'FROM_ID'},
                               KEY    => $Row->{'FROM_ID'},
                               VALUES => { TOTAL_MESSAGES => $msg_stats->{'TOTAL_MESSAGES'},
                                           NEW_MESSAGES   => $msg_stats->{'NEW_MESSAGES'},
                                           LAST_FROM_NAME => $obj->{'R_MEMBER'}->{'MEMBER_NAME'},
                                           LAST_FROM_ID   => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                           LAST_SENT      => time,
                                           LAST_MSG_ID    => $rr_id,
                                           LAST_MSG_TITLE => $Messenger::lang->{read_rec_title}.' '.$Row->{'TITLE'},
                                           SHOW_POPUP     => $rr_show_popup,
                                         }
                            );
             } else {
                 $db->insert(  TABLE  => 'message_stats',
                               ID     =>  $Row->{'FROM_ID'},
                               KEY    =>  $Row->{'FROM_ID'},
                               VALUES => { MEMBER_ID          => $Row->{'FROM_ID'},
                                           LAST_READ          => '',
                                           NEW_MESSAGES       => 1,
                                           LAST_FROM_NAME     => $obj->{'R_MEMBER'}->{'MEMBER_NAME'},
                                           LAST_FROM_ID       => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                           LAST_MSG_ID        => $rr_id,
                                           LAST_MSG_TITLE     => $Messenger::lang->{read_rec_title}.' '.$Row->{'TITLE'},
                                           LAST_SENT          => time,
                                           TOTAL_MESSAGES     => 1,
                                           VIRTUAL_DIR        => "in:Inbox|sent:Sent Items|",
                                           SHOW_POPUP         => $rr_show_popup,
                                         }
                           );
             }
       } #// end read state = -1
       
       # Read state must be 0 - lets make it 1 to inform the member that
       # they have read this message already
       
       $db->update(       TABLE   => 'message_data',
                          KEY     => $iB::IN{'MSID'},
                          ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                          VALUES  => { READ_STATE => 1 }
                  );
   }

    $Row->{'DATE'}    = $std->get_date( TIME => $Row->{'DATE'}, METHOD => 'LONG');


    $Row->{'MESSAGE_ICON'} = $Row->{'MESSAGE_ICON'}
                           ? $iB::INFO->{'IMAGES_URL'}.'/PostIcons/icon'.$Row->{'MESSAGE_ICON'}.'.gif'
                           : $iB::INFO->{'IMAGES_URL'}.'/PostIcons/icon0.gif';

    my $member = {};
    
    # MEMBER_ID 001 is reserved by internal ikonboard functions such
    # as the "report this post to a moderator feature" - we create a dummy profile for this "member"
    
    if ($Row->{FROM_ID} eq '001') {
        $member = { MEMBER_NAME   => "Ikonboard Bot",
                    MEMBER_ID     => "001",
                    MEMBER_GROUP  => "--",
                    MEMBER_POSTS  => "--",
                  };
    } else {
        $member = $db->select( TABLE    => 'member_profiles',
                               ID       => $Row->{'FROM_ID'},
                               KEY      => $Row->{'FROM_ID'}
                             );
        $member = $obj->do_member( $db, $member );
    }
    
    $Row->{'MESSAGE'} = $txt->Convert_for_db( TEXT    => $Row->{'MESSAGE'},
                                          SMILIES => 1,
                                          IB_CODE => $iB::INFO->{'MSG_ALLOW_CODE'},
                                          HTML    => $iB::INFO->{'MSG_ALLOW_HTML'},
                                          USER    => $member->{MEMBER_NAME},
                                        );
    
    #+---------------------------------------------------------
    # Grab the member groups and push into a hash
    #+---------------------------------------------------------

    my $mem_groups = $db->query( TABLE      => 'mem_groups',
                                 COLUMNS    => ['ID', 'TITLE', 'TEAM_ICON'],
                                 SORT_KEY   => 'TITLE',
                                 SORT_BY    => 'A-Z',
                               );

    my %temp_table = map { $_->{'ID'} => { TITLE  => $_->{'TITLE'},
                                           ICON   => $_->{'TEAM_ICON'}
                                         }
                         } @{$mem_groups};
    $obj->{'group_table'} = \%temp_table;
    #+---------------------------------------------------------
    # Grab the member titles and push into a hash
    #+---------------------------------------------------------

    my $mem_titles = $db->query( TABLE      => 'member_titles',
                                 COLUMNS    => ['ID', 'TITLE', 'PIPS'],
                                 SORT_KEY   => 'TITLE',
                                 SORT_BY    => 'A-Z',
                               );

    my %temp_titles = map { $_->{'ID'} => { TITLE => $_->{'TITLE'},
                                            PIPS  => $_->{'PIPS'}
                                          }
                          } @{$mem_titles};
    $obj->{'title_table'} = \%temp_titles;

    unless( $obj->{'group_table'}->{ $member->{'MEMBER_GROUP'} }->{'ICON'} ) {
        $member->{'MEMBER_PIPS'} = $obj->{'title_table'}->{ $member->{'MEMBER_LEVEL'}  }->{'PIPS'};
        if (defined $member->{'MEMBER_PIPS'}) {
            if ($member->{'MEMBER_PIPS'} !~ /^\d+$/) {
                 $member->{'MEMBER_PIPS_IMG'} = qq!<img src="$iB::INFO->{'TEAM_ICON_URL'}/$member->{'MEMBER_PIPS'}" border='0'>!;
            } else {
                 $member->{'MEMBER_PIPS_IMG'} = qq!$iB::SKIN->{'A_STAR'}! x $member->{'MEMBER_PIPS'};
            }
        }
    } else {
        $member->{'MEMBER_PIPS_IMG'} = qq!<img src="$iB::INFO->{'TEAM_ICON_URL'}/$obj->{'group_table'}->{ $member->{'MEMBER_GROUP'} }->{'ICON'}" border='0'>!
    }
    
    # Fix up the siggie
    
    my $VIEW_SIGS  = $obj->{'R_MEMBER'}->{'VIEW_SIGS'};
    if ($VIEW_SIGS) {
        $member->{SIGNATURE} = $txt->Convert_for_db( TEXT    => $member->{SIGNATURE},
                                                     SMILIES => $iB::INFO->{'SIG_ALLOW_EMOTICONS'},                                                              SMILIES => 0,
                                                     IB_CODE => $iB::INFO->{'SIG_ALLOW_IBC'},
                                                     HTML    => $iB::INFO->{'SIG_ALLOW_HTML'},
                                                     SIG     => 1
                                                   );
    } else {
        $member->{SIGNATURE} = "";
    }

    $member->{'VID'}    = $obj->{'R_MEMBER'}->{'CURRENT_ID'};

    $obj->{'.html'} .= MessengerView::Render_msg( 
                                                  {
                                                    MSG    => $Row,
                                                    MEMBER => $member,
                                                    JUMP   => $obj->{'.jump_html'}
                                                  }
                                                );

    $obj->{'.html'} .= MessengerView::CP_end();

    $output->print_ikonboard( DB      => $db,
                              TITLE   => $Messenger::lang->{'t_welcome'},
                              NAV     => [
                                           qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00" class='nav'>$Messenger::lang->{'t_title'}</a>!,
                                           qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=01;VID=$obj->{'R_MEMBER'}->{'CURRENT_ID'}" class='nav'>$obj->{'R_MEMBER'}->{'CURRENT_DIR'}</a>!,
                                           "$Row->{'TITLE'}",
                                         ],
                              OUTPUT  => $obj->{'.html'}
                            );
}

sub delete {
    my ($obj, $db) = @_;

    $iB::IN{'VID'} ||= 'in';

    $std->Error( DB => $db,  LEVEL => 1, MESSAGE => 'no_msg_chosen') unless $iB::IN{'MSID'};

    $db->delete(  TABLE   => 'message_data',
                  ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                  KEY     => $iB::IN{'MSID'},
               ) || die $db->{'error'};
               
    my $msg_stats = { };
    $msg_stats = $db->select( TABLE  => 'message_stats',
                              ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                              KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                            );
    if ($msg_stats->{'MEMBER_ID'}) {
        $msg_stats->{'TOTAL_MESSAGES'}--;
        $db->update(  TABLE  => 'message_stats',
                      ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                      KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                      VALUES => { TOTAL_MESSAGES => $msg_stats->{'TOTAL_MESSAGES'} }
                   );
    }

    $output->pure_redirect( URL => "act=Msg;CODE=01;VID=$iB::IN{'VID'}" );
}


sub multiact {
    my ($obj, $db) = @_;

    $iB::IN{'VID'} ||= 'in';

    my @ids = map  {    (split/-/)[1]   } 
              grep {   /^msgid-(\d+)$/  } $iB::CGI->param();

    $std->Error( DB => $db,  LEVEL => 1, MESSAGE => 'no_msg_chosen') unless @ids > 0;

    if ($iB::IN{'delete'}) {

        $db->delete(  TABLE   => 'message_data',
                      ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                      KEY     => \@ids,
                   ) || die $db->{error};
                   
        my $msg_stats = { };
        $msg_stats = $db->select( TABLE  => 'message_stats',
                                  ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                  KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                );
        if ($msg_stats->{'MEMBER_ID'}) {
            my $count = scalar @ids;
            $msg_stats->{'TOTAL_MESSAGES'} -= $count;
            $db->update(  TABLE  => 'message_stats',
                          ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                          KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                          VALUES => { TOTAL_MESSAGES => $msg_stats->{'TOTAL_MESSAGES'} }
                       );
        }

        $output->pure_redirect( URL => "act=Msg;CODE=01;VID=$iB::IN{'VID'}" );

    }
    elsif ($iB::IN{'move'}) {
        for my $id (@ids) {
            $db->update(  TABLE   => 'message_data',
                          ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                          KEY     => $id,
                          VALUES  => { VIRTUAL_DIR => $iB::IN{'VID'} }
                       );
        }
        $output->pure_redirect( URL => "act=Msg;CODE=01;VID=$iB::IN{'VID'}" );
    }
    else {
        $std->Error( DB => $db,  LEVEL => 1, MESSAGE => 'no_msg_chosen');
    }
        

}


sub prefs {
    my ($obj, $db) = @_;

    $obj->my_get_stats($db);

    $obj->{'.html'} .= MessengerView::prefs_header();

    my $cnt = 0;

    for my $i (@{$obj->{'R_MEMBER'}->{'DIR_DATA'}}) {
            my $extra;
            if ($i->{'ID'} eq 'in' or $i->{'ID'} eq 'sent') {
                $extra = "&nbsp;&nbsp;( ".$i->{'REAL'}." - $Messenger::lang->{'cannot_remove'} )";
            }
            $obj->{'.html'} .= MessengerView::prefs_row( { ID => $i->{'ID'}, REAL => $i->{'REAL'}, EXTRA => $extra } );
            ++$cnt;
    }

    $obj->{'.html'} .= MessengerView::prefs_add_dirs();

    for ($cnt .. $cnt+3) {
        $obj->{'.html'} .= MessengerView::prefs_row( { ID => 'dir_'.$_ , REAL => '' } );
    }

    $obj->{'.html'} .= MessengerView::prefs_footer();

    $obj->{'.html'} .= MessengerView::CP_end();

    $output->print_ikonboard( DB      => $db,
                              TITLE   => $Messenger::lang->{'t_welcome'},
                              NAV     => [
                                           qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00">$Messenger::lang->{'t_title'}</a>!,
                                         ],
                              OUTPUT  => $obj->{'.html'}
                            );
}


sub do_prefs {
    my ($obj, $db) = @_;

    $std->Error( DB      => $db,
                 LEVEL   => 1,
                 MESSAGE => 'cannot_remove_dir'
               ) unless $iB::IN{'in'} and $iB::IN{'sent'};

    my $v_dirs = 'in:'.$iB::IN{'in'}.'|sent:'.$iB::IN{'sent'};

    my @dirs   = grep { /^dir_\d+$/ } keys %iB::IN;

    for my $d (@dirs) {
        next unless $iB::IN{$d};
        $v_dirs .= '|'.$d.':'.$iB::IN{$d};
    }
    $db->update( TABLE  => 'message_stats',
                 ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                 KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                 VALUES => { VIRTUAL_DIR => $v_dirs }
               );

    $output->pure_redirect( URL => "act=Msg;CODE=07" );
}



sub my_get_stats {
    my ($obj, $db) = @_;

    $obj->{'R_MEMBER'}->{'DIR_DATA'} = [];

    my $v_dir = $iB::IN{'VID'} || 'in';

    $obj->{'.jump_html'} = qq[<select name='VID' class='forminput'>\n];

    my $stats = $db->select(  TABLE  => 'message_stats',
                              ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                              KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'}
                           );

    $stats = undef unless $stats->{'MEMBER_ID'};

    $obj->{'.cur_stats'} = $stats || { MEMBER_ID    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                       NEW_MESSAGES => 0,
                                       VIRTUAL_DIR  => "in:Inbox|sent:Sent Items|",
                                       '_FAKED'     => 1,
                                     };

    for (split (/\|/, $obj->{'.cur_stats'}->{'VIRTUAL_DIR'}) ) {
        my ($id, $real) = split /\:/, $_;
            push @{$obj->{'R_MEMBER'}->{'DIR_DATA'}}, { ID => $id, REAL => $real };
        if ($v_dir eq $id) {
            $obj->{'R_MEMBER'}->{'CURRENT_DIR'} = $real;
            $obj->{'R_MEMBER'}->{'CURRENT_ID'}  = $id;
            $obj->{'.jump_html'} .= qq[<option value='$id' selected>$real\n];
        } else {
            $obj->{'.jump_html'} .= qq[<option value='$id'>$real\n];
        }
    }
        
    $obj->{'.jump_html'} .= qq[</select>];
}



sub msg_list ($$) {
    my ($obj, $db) = @_;
    
    my $v_dir = $iB::IN{'VID'} || 'in';

    $obj->my_get_stats($db);
    
    my $sort_key   = $iB::IN{'sort_key'}   || 'DATE';
    my $sort_order = $iB::IN{'sort_order'} || 'Z-A';
    
    # A "bug" in earlier versions of messenger.pm didn't remove messages that were deleted
    # from the total messages counter, so we'll need to do a quick count check.
    
    my $all_messages   = [];
    my $msg_count      = 0;

    my $total_messages = $db->query(  TABLE    => 'message_data',
                                      ID       => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                      WHERE    => qq[MEMBER_ID eq '$obj->{'R_MEMBER'}->{'MEMBER_ID'}'],
                                      SORT_KEY => $sort_key,
                                      SORT_BY  => $sort_order,
                                   );
                                   
    # Count and filter out messages not in this virtual folder
    
    for (@{$total_messages}) {
        ++$msg_count;
        if ($_->{VIRTUAL_DIR} eq $obj->{'R_MEMBER'}->{'CURRENT_ID'}) {
            push @{$all_messages}, $_;
        }
    }
    
    # Check to see if the "real" message count equals the stored one.
    
    unless ($obj->{'.cur_stats'}->{'_FAKED'}) {
        # Member has stored stats...
        # so, lets check the counter
        if ($msg_count != $obj->{'.cur_stats'}->{TOTAL_MESSAGES}) {
            $obj->{'.cur_stats'}->{TOTAL_MESSAGES} = $msg_count;
            #Save out the real count
            $db->update( TABLE  => 'message_stats',
                         ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                         KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                         VALUES => { TOTAL_MESSAGES => $msg_count }
                       );
        }
    }
    
    # sort out some stats.
    
    $Messenger::lang->{c_msg_total} =~ s!<#NUM#>!$msg_count!g;
    
    if ($iB::INFO->{'MAX_MESSAGES'}) {
        if ($obj->{'.cur_stats'}->{TOTAL_MESSAGES} >= $iB::INFO->{'MAX_MESSAGES'}) {
            $Messenger::lang->{c_msg_info} = $Messenger::lang->{c_msg_full};
        } else {
            my $t_cnt = $iB::INFO->{'MAX_MESSAGES'} - $msg_count;
            $Messenger::lang->{c_msg_info} =~ s!<#NUM#>!$t_cnt!g;
        }
    } else {
        $Messenger::lang->{c_msg_info} = "";
    }

    

    $obj->{'.html'} .= MessengerView::inbox_header($obj->{'R_MEMBER'}, $obj->{'.jump_html'});
    if ($v_dir =~/^sent/i) {
         $obj->{'.html'} .= MessengerView::sent_table_header($obj->{'R_MEMBER'});
    } else {
         $obj->{'.html'} .= MessengerView::inbox_table_header($obj->{'R_MEMBER'});
    }



    if (scalar @{$all_messages} > 0) {

        for my $this_message (@{$all_messages}) {

            $this_message->{'ICON'}     = $this_message->{'READ_STATE'} == 1 ? $iB::SKIN->{M_READ} : $iB::SKIN->{M_UNREAD};
            $this_message->{'DATE'}     = $std->get_date( TIME => $this_message->{'DATE'}, METHOD => 'LONG');

            if ($v_dir =~/^sent/i) {
                $obj->{'.html'} .= MessengerView::sent_row(
                                                            {
                                                              MSG    => $this_message,
                                                              MEMBER => $obj->{'R_MEMBER'}
                                                            }
                                                           );
             } else {
                $obj->{'.html'} .= MessengerView::inbox_row(
                                                            {
                                                              MSG    => $this_message,
                                                              MEMBER => $obj->{'R_MEMBER'}
                                                            }
                                                           );
             };
        }
    } else {

        $obj->{'.html'} .= MessengerView::No_msg_inbox();

    }
   
    my $sorted_by = 'from_'.$sort_key ;
    $obj->{'.html'} .= MessengerView::end_inbox($obj->{'.jump_html'});

    if ($obj->{'R_MEMBER'}->{'CURRENT_ID'} eq 'in') {  
        $db->update(  TABLE  => 'message_stats',
                      ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                      KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                      VALUES => { NEW_MESSAGES => 0 }
                   );
    }

    $obj->{'.html'} .= MessengerView::CP_end();

    $output->print_ikonboard( DB      => $db,
                              TITLE   => $Messenger::lang->{'t_welcome'},
                              NAV     => [ qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00">$Messenger::lang->{'t_title'}</a>! ],
                              OUTPUT  => $obj->{'.html'}
                            );
}

#+------------------------------------------------------------------------------------------------------

sub add_member ($) {
    my ($obj, $db) = @_;

    $std->Error( DB     => $db,
                 LEVEL  => '1',
                 MESSAGE=>'no_user'
               ) unless $iB::IN{'mem_name'};

 
    my $mem_to_add = $mem->LoadMember( DB     => $db,
                                       KEY    => $iB::IN{'mem_name'},
                                       METHOD => 'by name'
                                     );

    $std->Error( DB     => $db,
                 LEVEL  => '1',
                 MESSAGE=>'no_user'
               ) unless $mem_to_add->{'MEMBER_ID'};

    my $check = $db->query( TABLE     => 'address_books',
                            ID        => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                            WHERE     => qq[MEMBER_ID eq "$iB::MEMBER->{'MEMBER_ID'}" and IN_MEMBER_ID eq "$mem_to_add->{'MEMBER_ID'}"],
                          ) || die $db->{'error'};

    $std->Error( DB     => $db,
                 LEVEL  => '1',
                 MESSAGE=>'member_in_add_book'
               ) if scalar @{$check} > 0;
 

    $iB::IN{'allow_msg'} =  $iB::IN{'allow_msg'} eq 'yes' ? 1 : 0;

    $db->insert( TABLE   => 'address_books',
                 ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                 VALUES  => { MEMBER_ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                              IN_MEMBER_NAME => $iB::IN{'mem_name'},
                              RECEIVE_MSG    => $iB::IN{'allow_msg'},
                              IN_MEMBER_DESC => $iB::IN{'mem_desc'},
                              IN_MEMBER_ID   => $mem_to_add->{'MEMBER_ID'}
                           },
                );
  
    $output->pure_redirect( URL => "act=Msg;CODE=02" );
}

sub del_member {
    my ($obj, $db) = @_;

    $std->Error( DB     => $db,
                 LEVEL  => '1',
                 MESSAGE=>'no_user'
               ) unless $iB::IN{'MID'};
    
    $db->delete( TABLE   => 'address_books',
                 ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                 WHERE   => "IN_MEMBER_ID eq '$iB::IN{'MID'}'"
               );

    $output->pure_redirect( URL => "act=Msg;CODE=02" );
}


sub edit_member {
    my ($obj, $db) = @_;

    $std->Error( DB     => $db,
                 LEVEL  => '1',
                 MESSAGE=>'no_user'
               ) unless $iB::IN{'MID'};
    
    my $addressee = $db->query( TABLE   => 'address_books',
                                MATCH   => 'ONE',
                                WHERE  => "IN_MEMBER_ID eq '$iB::IN{'MID'}' and MEMBER_ID eq '$iB::MEMBER->{'MEMBER_ID'}'"
                             );

    my $s_html = qq[<select name='allow_msg' class='forminput'>];

    if ($addressee->{'RECEIVE_MSG'}) {
        $s_html .= qq[<option value='yes' selected>$Messenger::lang->{'yes'}<option value='no'>$Messenger::lang->{'no'}];
    } else {
        $s_html .= qq[<option value='yes'>$Messenger::lang->{'yes'}<option value='no' selected>$Messenger::lang->{'no'}];
    }

    $s_html .= "</select>";

    $obj->{'.html'} .= MessengerView::address_edit( 
                                                    {
                                                      SELECT => $s_html,
                                                      MEMBER => $addressee
                                                    }
                                                  );
    $obj->{'.html'} .= MessengerView::CP_end();

    $output->print_ikonboard( DB      => $db,
                              TITLE   => $Messenger::lang->{'t_welcome'},
                              NAV     => [
                                           qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00">$Messenger::lang->{'t_title'}</a>!,
                                           qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=02">$Messenger::lang->{'t_book'}</a>!,
                                         ],
                              OUTPUT  => $obj->{'.html'}
                            );
}

sub do_edit {
    my ($obj, $db) = @_;

    $std->Error( DB     => $db,
                 LEVEL  => '1',
                 MESSAGE=>'no_user'
               ) unless $iB::IN{'MID'};

    $iB::IN{'allow_msg'} =  $iB::IN{'allow_msg'} eq 'yes' ? 1 : 0;

    my $entry = $db->query( TABLE  => 'address_books',
                            MATCH  => 'ONE',
                            WHERE  => "IN_MEMBER_ID eq '$iB::IN{'MID'}' and MEMBER_ID eq '$iB::MEMBER->{'MEMBER_ID'}'"
                          );

    $std->Error( DB     => $db,
                 LEVEL  => '1',
                 MESSAGE=>'no_user'
               ) unless $entry->{'ID'};
    
    $db->update( TABLE   => 'address_books',
                 KEY     => $entry->{'ID'},
                 VALUES  => { IN_MEMBER_DESC  => $iB::IN{'mem_desc'},
                              RECEIVE_MSG     => $iB::IN{'allow_msg'}
                            }
               );

    $output->pure_redirect( URL => "act=Msg;CODE=02" );
}

#+------------------------------------------------------------------------------------------------------

sub contact {
    my ($obj, $db) = @_;

    $obj->{'.html'} .= MessengerView::Address_header();

    my $address = $db->query( TABLE    => 'address_books',
                              WHERE    => "MEMBER_ID eq '$iB::MEMBER->{'MEMBER_ID'}'",
                              SORT_KEY => 'IN_MEMBER_NAME',
                            ) || die $db->{'error'};

    if (scalar @{$address} > 0) {
        $obj->{'.html'} .=  MessengerView::Address_table_header();
        
        for my $entry (@{$address}) {
            $entry->{'TEXT'} = $entry->{'RECEIVE_MSG'}
                             ? $Messenger::lang->{'can_contact'}
                             : $Messenger::lang->{'cannot_contact'};
            $obj->{'.html'} .=  MessengerView::render_address_row($entry);
        }
    
        $obj->{'.html'} .=  MessengerView::end_address_table();
        
    } else {
        $obj->{'.html'} .=  MessengerView::Address_none();
    }

    my $name_to_enter;
    if ($iB::IN{'MID'}) {
        my $temp_mem = $mem->LoadMember( DB     => $db,
                                         METHOD => 'by id',
                                         KEY    => $iB::IN{'MID'}
                                        );

        $name_to_enter = $temp_mem->{'MEMBER_NAME'} if $temp_mem->{'MEMBER_ID'};
    }

    $obj->{'.html'} .= MessengerView::address_add($name_to_enter);
    $obj->{'.html'} .= MessengerView::CP_end();

    $output->print_ikonboard( DB      => $db,
                              TITLE   => $Messenger::lang->{'t_welcome'},
                              NAV     => [ qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00">$Messenger::lang->{'t_title'}</a>! ],
                              OUTPUT  => $obj->{'.html'}
                            );
}


#+------------------------------------------------------------------------------------------------------

sub send {
    my ($obj, $db) = @_;
    $iB::IN{'MODE'} ? $obj->send_msg($db) : $obj->send_form($db);
}

#+------------------------------------------------------------------------------------------------------

sub send_msg {
    #
    # Additional Code by KevG (Message tracking and Max messages allowed)
    #
    my ($obj,$db) = @_;
    
    $iB::IN{'from_contact'} ||= '-';
    $iB::IN{'iconid'} ||= 0;

    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'incorrect_use')    unless $iB::IN{'MODE'} == '01';
    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_msg_title')     unless $iB::IN{'msg_title'};
    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_msg')           unless $iB::IN{'Post'};
    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_chosen_member') unless $iB::IN{'entered_name'} or $iB::IN{'from_contact'};

    $obj->{'.to_member'} = $iB::IN{'from_contact'} eq '-'
                         ? $mem->LoadMember( DB => $db, KEY => $iB::IN{'entered_name'}, METHOD => 'by name')
                         : $mem->LoadMember( DB => $db, KEY => $iB::IN{'from_contact'}, METHOD => 'by id');

    undef $obj->{'.to_member'}->{'MEMBER_PASSWORD'};
    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_to_member')     unless $obj->{'.to_member'}->{'MEMBER_ID'};
    
    ####################
    # Added by Infection
    # Check to make sure the recipient can use the messenger. If they can't display an error and exit
    
    my $allow = $db->select(  TABLE   =>'mem_groups',
                              COLUMNS =>['USE_PM'],
                              KEY     => $obj->{'.to_member'}->{'MEMBER_GROUP'}
                           );
                           
    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_usepm_member')  unless $allow->{'USE_PM'};
    #
    #
    ####################

    my $can_msg = $db->query( TABLE  => 'address_books',
                              WHERE  => "IN_MEMBER_ID eq '$iB::MEMBER->{'MEMBER_ID'}' and MEMBER_ID eq '$obj->{'.to_member'}->{'MEMBER_ID'}'",
                              MATCH  => 'ONE',
                            );

    if ($can_msg->{'IN_MEMBER_ID'}) {
        $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'msg_blocked') unless $can_msg->{'RECEIVE_MSG'};
    }
    
    if ($iB::IN{'add_sent'}) {
        my $temp_msg_stats = { };
        $temp_msg_stats = $db->select( TABLE => 'message_stats',
                                       ID    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                       KEY   => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                     );
                      
        if ($temp_msg_stats->{'MEMBER_ID'}) {
            if($temp_msg_stats->{'TOTAL_MESSAGES'} >= $iB::INFO->{'MAX_MESSAGES'}) {
                # Current member can not receive anymore PMs per Board setting (max pms)
                $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'max_message_from');
            }
        }
    }

    # Get the SHOW_POPUP based on the .to_members last byte setting
    # in PM_REMINDER

    my $show_popup = (split/&/, $obj->{'.to_member'}->{'PM_REMINDER'})[1];
    
    my $trackingid = 0;
    # Are we tracking this ?
    if ($iB::IN{'add_tracking'}) {
        $trackingid = -1;
    }
    my $msg_stats = { };
    $msg_stats = $db->select( TABLE => 'message_stats',
                              ID    => $obj->{'.to_member'}->{'MEMBER_ID'},
                              KEY   => $obj->{'.to_member'}->{'MEMBER_ID'},
                            );

    if ($msg_stats->{'MEMBER_ID'}) {
        if($msg_stats->{'TOTAL_MESSAGES'} >= $iB::INFO->{'MAX_MESSAGES'}) {
            # Target member can not receive anymore PMs per Board setting (max pms)
            $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'max_message_to');
        }
    }

    my $new_id = $db->insert( TABLE  => 'message_data',
                              ID     => $obj->{'.to_member'}->{'MEMBER_ID'},
                              VALUES => { DATE              => time,
                                          READ_STATE        => $trackingid,
                                          TITLE             => $iB::IN{'msg_title'},
                                          MESSAGE           => $iB::IN{'Post'},
                                          MESSAGE_ICON      => $iB::IN{'iconid'},
                                          FROM_ID           => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                          FROM_NAME         => $obj->{'R_MEMBER'}->{'MEMBER_NAME'},
                                          REPLY             => '',
                                          REPLY_DATE        => '',
                                          VIRTUAL_DIR       => 'in',
                                          MEMBER_ID         => $obj->{'.to_member'}->{'MEMBER_ID'},
                                          RECIPIENT_ID      => $obj->{'.to_member'}->{'MEMBER_ID'},
                                          RECIPIENT_NAME    => $obj->{'.to_member'}->{'MEMBER_NAME'}
                                        }
                             );

    if ($msg_stats->{'MEMBER_ID'}) {

        $msg_stats->{'TOTAL_MESSAGES'}++;
        $msg_stats->{'NEW_MESSAGES'}++;
  
        $db->update(  TABLE  => 'message_stats',
                      ID     => $obj->{'.to_member'}->{'MEMBER_ID'},
                      KEY    => $obj->{'.to_member'}->{'MEMBER_ID'},
                      VALUES => { TOTAL_MESSAGES => $msg_stats->{'TOTAL_MESSAGES'},
                                  NEW_MESSAGES   => $msg_stats->{'NEW_MESSAGES'},
                                  LAST_FROM_NAME => $obj->{'R_MEMBER'}->{'MEMBER_NAME'},
                                  LAST_FROM_ID   => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                  LAST_SENT      => time,
                                  LAST_MSG_ID    => $new_id,
                                  LAST_MSG_TITLE => $iB::IN{'msg_title'},
                                  SHOW_POPUP     => $show_popup,
                                }
                   );

    } else {
        $db->insert(  TABLE  => 'message_stats',
                      ID     =>  $obj->{'.to_member'}->{'MEMBER_ID'},
                      KEY    =>  $obj->{'.to_member'}->{'MEMBER_ID'},
                      VALUES => { MEMBER_ID          => $obj->{'.to_member'}->{'MEMBER_ID'},
                                  LAST_READ          => '',
                                  NEW_MESSAGES       => 1,
                                  LAST_FROM_NAME     => $obj->{'R_MEMBER'}->{'MEMBER_NAME'},
                                  LAST_FROM_ID       => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                  LAST_MSG_ID        => $new_id,
                                  LAST_MSG_TITLE     => $iB::IN{'msg_title'},
                                  LAST_SENT          => time,
                                  TOTAL_MESSAGES     => 1,
                                  VIRTUAL_DIR        => "in:Inbox|sent:Sent Items|",
                                  SHOW_POPUP         => $show_popup,
                                 }
                    );
    }
    
    # Are we adding this to our sent items folder?

    if ($iB::IN{'add_sent'}) {
    
        my $my_msg_stats = { };
        $my_msg_stats = $db->select( TABLE => 'message_stats',
                                     ID    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                     KEY   => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                   );

        if ($my_msg_stats->{'MEMBER_ID'}) {
            $my_msg_stats->{'TOTAL_MESSAGES'}++;
            $db->update( TABLE  => 'message_stats',
                         ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                         KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                         VALUES => { TOTAL_MESSAGES => $my_msg_stats->{'TOTAL_MESSAGES'} }
                       );
        } else {
            $db->insert( TABLE  => 'message_stats',
                         ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                         KEY    => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                         VALUES => { TOTAL_MESSAGES => $my_msg_stats->{'TOTAL_MESSAGES'} }
                       );
        }
   
        $db->insert( TABLE  => 'message_data',
                     ID     => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                     VALUES => { DATE              => time,
                                 READ_STATE        => 0,
                                 TITLE             => $Messenger::lang->{'saved_sent_msg'}.' '.$iB::IN{'msg_title'},
                                 MESSAGE           => $iB::IN{'Post'},
                                 MESSAGE_ICON      => $iB::IN{'iconid'},
                                 FROM_ID           => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                 FROM_NAME         => $obj->{'R_MEMBER'}->{'MEMBER_NAME'},
                                 REPLY             => '',
                                 REPLY_DATE        => '',
                                 VIRTUAL_DIR       => 'sent',
                                 MEMBER_ID         => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                 RECIPIENT_ID      => $obj->{'.to_member'}->{'MEMBER_ID'},
                                 RECIPIENT_NAME    => $obj->{'.to_member'}->{'MEMBER_NAME'}
                               }
                    );
    }
 
    $Messenger::lang->{'sent_text'} =~ s!<#FROM_MEMBER#>!$obj->{'R_MEMBER'}->{'MEMBER_NAME'}!;
    $Messenger::lang->{'sent_text'} =~ s!<#TO_MEMBER#>!$obj->{'.to_member'}->{'MEMBER_NAME'}!;
    $Messenger::lang->{'sent_text'} =~ s!<#MESSAGE_TITLE#>!$iB::IN{'msg_title'}!;

    $obj->{'.html'} .= MessengerView::sent_screen($obj->{'R_MEMBER'}, $obj->{'.to_member'}, $msg_stats);
    $obj->{'.html'} .= MessengerView::CP_end();

    $output->print_ikonboard( DB      => $db,
                              TITLE   => $Messenger::lang->{'t_welcome'},
                              NAV     => [qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00">$Messenger::lang->{'t_title'}</a>!],
                              OUTPUT  => $obj->{'.html'}
                            );
}


#+------------------------------------------------------------------------------------------------------

sub send_form {
    my ($obj, $db) = @_;

    require $iB::SKIN->{'DIR'} . '/PostView.pm' or $std->cgi_error($!);
    $Post::lang = $std->LoadLanguage('PostWords');

    my $contacts;

    my $address = $db->query( TABLE    => 'address_books',
                              WHERE    => "MEMBER_ID eq '$iB::MEMBER->{'MEMBER_ID'}'",
                              SORT_KEY => 'IN_MEMBER_NAME',
                            );

    if (scalar @{$address} > 0) {
        $contacts = qq~<select name='from_contact' class='forminput'><option value='-'>$Messenger::lang->{'other'}\n<option value='-'>----------\n~;
        for my $entry (@{$address}) {
            $contacts .= qq~<option value='$entry->{'IN_MEMBER_ID'}'>$entry->{'IN_MEMBER_NAME'}\n~;
        }
        $contacts .= qq~</select>\n~;
    } else {
        $contacts = $Messenger::lang->{'address_list_empty'};
    }


    $Messenger::lang->{'max_msg'}     =~ s!<#MAX_MSG_SIZE#>!$iB::INFO->{'MAX_MSG_SIZE'}!;
    $Messenger::lang->{'the_max_msg'} = $iB::INFO->{'MAX_MSG_SIZE'} * 1024;

    my ($name_to_enter, $old_message, $old_title);

    if ($iB::IN{'MID'}) {
        my $temp_mem = $mem->LoadMember( DB => $db, KEY => $iB::IN{'MID'}, METHOD => 'by id');
        $name_to_enter = $temp_mem->{'MEMBER_NAME'} if $temp_mem->{'MEMBER_ID'};
    }

    if ($iB::IN{'MSID'}) {
        my $temp = $db->select( TABLE   => 'message_data',
                                ID      => $obj->{'R_MEMBER'}->{'MEMBER_ID'},
                                KEY     => $iB::IN{'MSID'}
                              );
        $old_message = qq|[QUOTE]|. $temp->{'MESSAGE'} . qq|[/QUOTE]\n|;
        $old_message =~ s!<br>!\n!g;
        $old_title = 'Re:' . $temp->{'TITLE'};
        # Make sure we don't get loads of 'Re:' in the title
        $old_title =~ s!^(?:Re\:){1,}!Re:!g;
    }

    $obj->{'.html'} .= MessengerView::Send_form( 
                                                 {
                                                    CONTACTS => $contacts,
                                                    MEMBER   => $obj->{'R_MEMBER'},
                                                    N_ENTER  => $name_to_enter,
                                                    O_TITLE  => $old_title
                                                 }
                                                );
    $Post::lang->{'the_max_length'} = $iB::INFO->{'MAX_MSG_SIZE'} * 1024;
    $Post::lang->{'ib_state'}   = $iB::INFO->{'MSG_ALLOW_CODE'}  ? $Post::lang->{'ib_on'}   : $Post::lang->{'ib_off'};
    $Post::lang->{'html_state'} = $iB::INFO->{'MSG_ALLOW_HTML'}  ? $Post::lang->{'html_on'} : $Post::lang->{'html_off'};
    $obj->{'.html'} .= PostView::PostIcons() . PostView::postbox_buttons($old_message);
    $obj->{'.html'} .= MessengerView::send_form_footer();
    $obj->{'.html'} .= MessengerView::CP_end();

    my $smilies = qq~<tr align='center'>\n~;
    my $cnt = 0;
    my $show_table = 0;
    for my $e (split (/\|&\|/,$iB::INFO->{'EMOTICONS'}) ) {
        my ($type, $image, $p_inc) = split (/\|/,$e);
        next unless $type and $image;
        next unless $p_inc;

        $cnt++;
        $show_table++;
        $smilies .= qq~<td><a href="javascript:emoticon('$type')"><img src="$iB::INFO->{'EMOTICONS_URL'}/$image" alt="smilie" border="0"></a>&nbsp;</td>\n~;

        if ($cnt == $iB::INFO->{'EMO_PER_ROW'}) {
            $smilies .= qq~</tr>\n\n<tr align='center'>\n~;
            $cnt = 0;
        }
    }

    if ($cnt != $iB::INFO->{'EMO_PER_ROW'}) {
        $cnt++;
        for ($cnt .. $iB::INFO->{'EMO_PER_ROW'}) {
            $smilies .= qq~<td>&nbsp;</td>\n~;
        }
        $smilies .= qq~</tr>~;
    }

    my $table = PostView::smilie_table();
    if ($show_table) {
        $table =~ s:<!--THE SMILIES-->:$smilies:;
        $obj->{'.html'} =~ s:<!--SMILIE TABLE-->:$table:;
    }

    $output->print_ikonboard( DB         => $db,
                              TITLE      => $Messenger::lang->{'t_welcome'},
                              JAVASCRIPT => 1,
                              NAV        => [qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Msg;CODE=00">$Messenger::lang->{'t_title'}</a>!],
                              OUTPUT     => $obj->{'.html'}
                            );
}



sub Show_menu ($) {
    my ($obj, $db) = @_;
    my $Nav_tabs = { '00' => 'splash', '01' => 'in_box', '02' => 'contact', '07' => 'prefs', '04' => 'send'};
    my $Nav_color = { };
    for (qw[splash in_box contact prefs send]) { $Nav_color->{$_} = $iB::SKIN->{'USERNAV_OFF'} }
    $Nav_color->{ $Nav_tabs->{ $iB::IN{'CODE'} } } = $iB::SKIN->{'USERNAV_ON'};
    return MessengerView::Menu_bar($Nav_color);
}
   
#+------------------------------------------------------------------------------------------------------

sub Process {
    my ($obj, $db) = @_;
    $std->Error(LEVEL=>'1',MESSAGE=>'Wha.....?') unless (defined $iB::IN{'CODE'});

    $obj->SetSession($db);
    my $CodeNo = $std->CheckCodeNo($iB::IN{'CODE'});
    my %Mode = ( '00'     => \&Splash,
                 '01'     => \&msg_list,
                 '02'     => \&contact,
                 '03'     => \&view_msg,
                 '04'     => \&send,
                 '05'     => \&delete,

                 '06'     => \&multiact,

                 '07'     => \&prefs,
                 '08'     => \&do_prefs,
 
                 '09'     => \&add_member,
                 '10'     => \&del_member,
                 '11'     => \&edit_member,
                 '12'     => \&do_edit,
               );
    $Mode{$CodeNo} ? $Mode{$CodeNo}->($obj, $db) : MessengerError($obj,$db);
} 

#+------------------------------------------------------------------------------------------------------

sub SetSession {
    my ($obj, $db) = @_;

    # Display an "error" if we are not allowed to use the messenger
    unless ($iB::MEMBER_GROUP->{'USE_PM'}) {
        $std->Error( DB => $db, LEVEL => 1, MESSAGE => 'no_use_messenger' );
        return "0 but true";
    }
    require $iB::SKIN->{'DIR'} . '/MessengerView.pm' or $std->cgi_error($!);
    $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'no_guest_posting')  unless $obj->{'R_MEMBER'}->{'MEMBER_ID'};
    $obj->{'.html'} = $obj->Show_menu($db);
}

#+------------------------------------------------------------------------------------------------------

sub get_avatar {
    my ($obj, $m_avatar, $av_dims) = @_;
    return unless $iB::INFO->{'AVATARS'}
              and $m_avatar
              and $iB::MEMBER->{'VIEW_AVS'};

    return if $m_avatar eq 'noavatar';
    return '' if $m_avatar =~ m#\.swf#i and $iB::INFO->{'ALLOW_FLASH'} != 1;
    my ($d_a_width, $d_a_height) = split "x", $iB::INFO->{'DEF_AV_DIMS'};
    if ($m_avatar =~ m#\Ahttp\://#i) {
        if ($iB::INFO->{'AV_ALLOW_URL'}) {
            my ($width  , $height)   = split "x", $av_dims;
            my ($a_width, $a_height) = split "x", $iB::INFO->{'AV_DIMS'};
            $height ||= $a_height;
            $width  ||= $a_width;           
            return $m_avatar =~ m#\.swf\Z#i ? qq|<OBJECT CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" WIDTH=$width HEIGHT=$height><PARAM NAME=MOVIE VALUE=$m_avatar><PARAM NAME=PLAY VALUE=TRUE><PARAM NAME=LOOP VALUE=TRUE><PARAM NAME=QUALITY VALUE=HIGH><EMBED SRC=$m_avatar WIDTH=$width HEIGHT=$height PLAY=TRUE LOOP=TRUE QUALITY=HIGH></EMBED></OBJECT>|
                                            : qq|<img src='$m_avatar' border='0' width='$width' height='$height'>|;
        }
    }
    return qq|<img src='$iB::INFO->{'AVATARS_URL'}/$m_avatar' border='0' width='$d_a_width' height='$d_a_height'>| unless $m_avatar =~ m#\Ahttp\://#i;
}

sub do_member ($$) {
    my ($obj, $db, $member) = @_;

    # Get the member info from the relevant tables

    my $mem_title = $db->select( TABLE   => 'member_titles',
                                 KEY     => $member->{'MEMBER_LEVEL'},
                                 COLUMNS => ['ID', 'TITLE']
                               );

    my $mem_group = $db->select( TABLE   => 'mem_groups',
                                 KEY     => $member->{'MEMBER_GROUP'},
                                 COLUMNS => ['ID', 'TITLE', 'TEAM_ICON'],
                               );

    #Get the members Avatar
    $member->{'MEMBER_AVATAR'} = $obj->get_avatar($member->{'MEMBER_AVATAR'}, $member->{'AVATAR_DIMS'});

    #Sort out the member title
    $member->{'MEMBER_TITLE'} = $member->{'MEMBER_TITLE'} ? $member->{'MEMBER_TITLE'}
                                                          : $mem_title->{'TITLE'};

    unless( $mem_group->{'TEAM_ICON'} ) {
        $member->{'MEMBER_PIPS'} = $obj->{'title_table'}->{  $member->{'MEMBER_LEVEL'}  }->{'PIPS'};
        if (defined $member->{'MEMBER_PIPS'}) {
            if ($member->{'MEMBER_PIPS'} !~ /^\d+$/) {
                     $member->{'MEMBER_PIPS_IMG'} = qq!<img src="$iB::INFO->{'TEAM_ICON_URL'}/$member->{'MEMBER_PIPS'}" border='0'>!;
                } else {
                     $member->{'MEMBER_PIPS_IMG'} = qq!$iB::SKIN->{'A_STAR'}! x $member->{'MEMBER_PIPS'};
            }
        }
    } else {
        $member->{'MEMBER_PIPS_IMG'} = qq!<img src="$iB::INFO->{'TEAM_ICON_URL'}/$mem_group->{'TEAM_ICON'}" border='0'>!
    }

    $member->{'MEMBER_JOINED'} = $Messenger::lang->{'m_joined'}.' '.$std->get_date( TIME => $member->{'MEMBER_JOINED'}, METHOD => 'JOINED');
  

    if ($member->{'SIGNATURE'} and $iB::MEMBER->{'VIEW_SIGS'}) {
        $member->{'SIGNATURE'} = qq[<!--Signature--><br><br>--------------<br><span id='signature'>$member->{'SIGNATURE'}</span><!--E Signature-->];
    }

    $member->{'MEMBER_GROUP'} = $Messenger::lang->{'m_group'}.' '.$mem_group->{'TITLE'};
    $member->{'MEMBER_POSTS'} = $Messenger::lang->{'m_posts'}.' '.$member->{'MEMBER_POSTS'};

    $member->{'PROFILE_ICON'} = qq!<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Profile;CODE=03;MID=$member->{'MEMBER_ID'}">$iB::SKIN->{'P_PROFILE'}</a>&nbsp;!;

    $member->{'EMAIL_ICON'} = $obj->{'MEMBER'}->{'HIDE_EMAIL'} ? '' : qq[<a href="$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION;act=Mail;CODE=00;MID=$member->{'MEMBER_ID'}">$iB::SKIN->{'P_EMAIL'}</a>&nbsp;];

    $member->{'WEBSITE_ICON'} = ($member->{'WEBSITE'} and $member->{'WEBSITE'} =~ m#\Ahttp://.+?\S\Z#i)
                              ? (qq[<a href='$member->{'WEBSITE'}'>$iB::SKIN->{'P_WEBSITE'}</a>&nbsp;])
                              : ('');

    $member->{'ICQ_ICON'}
        = $obj->{'MEMBER'}->{'ICQNUMBER'} eq '' ? ''
                                                : qq[<a href="javascript:PopUp('$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION&act=ICQ&MID=$member->{'MEMBER_ID'}','Pager','450','330','0','1','1','1')">$iB::SKIN->{'P_ICQ'}</a>&nbsp;];
    $member->{'AOL_ICON'}
        = $obj->{'MEMBER'}->{'AOLNAME'}   eq '' ? ''
                                                : qq[<a href="javascript:PopUp('$iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?s=$iB::SESSION&act=AOL&MID=$member->{'MEMBER_ID'}','Pager','450','330','0','1','1','1')">$iB::SKIN->{'P_AOL'}</a>&nbsp;];
    return $member;
}


sub MessengerError  { my ($obj, $db) = @_; $std->Error( DB => $db, LEVEL=>'1',MESSAGE=>'incorrect_use') }


#+------------------------------------------------------------------------------------------------------
#+------------------------------------------------------------------------------------------------------

1;
