###############################################################################
# MyCenter.pl                                                                 #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2.1                                                  #
# Packaged:       March 5, 2008                                               #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2008 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

$mycenterplver = 'YaBB 2.2.1 $Revision: 1.123.2.11 $';
if ($action eq 'detailedversion') { return 1; }

&LoadLanguage('InstantMessage');
&LoadLanguage('MyCenter');
require "$templatesdir/$usemycenter/MyCenter.template";
if (-e "$vardir/gmodsettings.txt" && $iamgmod) { require "$vardir/gmodsettings.txt"; }
$mycenter_txt{'welcometxt'} =~ s/USERLABEL/${$uid.$username}{'realname'}/g;

$showIM = '';
$IM_home = '';
$IM_box = '';
$showProfile = '';
$PMfileToOpen = '';
$sendBMess = '';
$isBMess = '';
$showFavorites = '';
$showNotifications = '';

if (!$yyjavascript) { $yyjavascript = ''; }

	$yyjavascript .= qq~
function Avatars ()	{
	var userpic_width = $userpic_width;
	var userpic_height = $userpic_height;
	function ResizeAvatars(){
		if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4 && navigator.userAgent.indexOf("Opera") < 0) {
		for(var i=0; imgEle=document.getElementsByName('avatar')[i];i++) {
			if (userpic_width == 0) { tmpuserpic_width = imgEle.width; } else {tmpuserpic_width = userpic_width;}
			if (userpic_height == 0) { tmpuserpic_height = imgEle.height; } else {tmpuserpic_height = userpic_height;}
			var ratio = imgEle.width / imgEle.height;
			for(z=0;z<2;z++) {
				if (imgEle.width > tmpuserpic_width) { imgEle.width = tmpuserpic_width; imgEle.height = parseInt(imgEle.width / ratio); }
				if (imgEle.height > tmpuserpic_height) { imgEle.height = tmpuserpic_height; imgEle.width = parseInt(imgEle.height * ratio); }
			}
		}
		}
	}
	document.onload = ResizeAvatars();
}
~;

##  here begins the user centre, from the old IMIndex
sub mycenter	{
	if ($iamguest) { &fatal_error('im_members_only'); }
	# navigation links
	$IM_home = qq~<a href="$scripturl" class="nav">$mbname</a>~;
	$yynavigation = qq~&rsaquo; $img_txt{'mycenter'}~;
	$IM_box = '';
	my $PMfileToOpen = '';
	$PMmessageProcessed = '';
	my @otherStoreFolders = ();
	my $otherStoreSelect = '';
	$replyguest = $INFO{'replyguest'} || $FORM{'replyguest'};
	## select view by action
	if ($action =~ /^im/ || $action eq 'deletemultimessages' || $action eq 'pmsearch') { $view = 'pm'; }
	elsif ($action eq 'mycenter') { $view = 'mycenter'; }
	elsif ($action eq 'shownotify' || $action=~ /^notify/ || $action eq 'boardnotify2') { $view = 'notify'; $yyimbox = $img_txt{'418'}; }
	elsif ($action eq 'myusersrecentposts') { $view = 'recentposts'; }
	elsif ($action eq 'favorites') { $view = 'favorites'; $yyimbox = $img_txt{'70'}; }
	elsif ($action =~ /^my/ && $action ne 'myusersrecentposts') { $view = 'profile'; }
	## viewing PMs
	if ($view eq 'pm') { # pm views
		## viewing a message box
		require "$sourcedir/InstantMessage.pl";
		if ($action eq 'im' || $action eq 'imoutbox' || $action eq 'imstorage') {
			my $foundextra = 0;
			foreach my $storefolder (split(/\|/, ${$username}{'PMfolders'}))	{
				if(($action eq 'im' && $storefolder ne 'out') || ($action eq 'imoutbox' && $storefolder ne 'in') || ($action eq 'imstorage' && $storefolder ne $INFO{'viewfolder'})) {
					push (@otherStoreFolders, $storefolder);
					$foundextra = 1;
				}
			}
			if ($foundextra > 0)	{
				$otherStoreSelect = qq~ $inmes_txt{'storein'} <select name="tostorefolder" id="tostorefolder">~;
				foreach my $otherFolder (@otherStoreFolders) {
					my $otherFolderName = $otherFolder;
					if ($otherFolder eq 'in') { $otherFolderName = $im_folders_txt{'in'}; }
					elsif ($otherFolder eq 'out') { $otherFolderName = $im_folders_txt{'out'}; }
					$otherStoreSelect .= qq~<option value="$otherFolder">$otherFolderName</option>~;
				}
				$otherStoreSelect .= qq~</select>~;
			}
		}
		## inbox
		if ($action eq 'im' || ($action eq 'imshow' && $INFO{'caller'} == 1)) {
			$yyimbox = $inmes_txt{'inbox'};
			$status = $inmes_imtxt{'status'};
			$senderinfo = $inmes_txt{'318'};
			$callerid = 1;
			$boxtxt = $inmes_txt{'316'};
			$movebutton  = qq~<input type="submit" name="imaction" value="$inmes_imtxt{'store'}" class="button" />$otherStoreSelect $inmes_txt{'storeor'}~;
			$IM_box = $inmes_txt{'inbox'};
			if($INFO{'focus'} eq 'bmess' || $INFO{'bmess'} eq 'yes') { $IM_box = $inmes_txt{'broadcast'}; $callerid = 5; }
			$PMfileToOpen = 'msg';
			}
		##  draft box
		elsif ($action eq 'imdraft') {
			$yyimbox = $inmes_txt{'draft'};
			$status = $inmes_imtxt{'status'};
			$senderinfo = $inmes_txt{'324'};
			$callerid = 4;
			$boxtxt = $inmes_txt{'draft'};
			$movebutton = '';
			$IM_box = $inmes_txt{'draft'};
			$PMfileToOpen = 'imdraft';
			}
		## outbox
		elsif ($action eq 'imoutbox' || ($action eq 'imshow' && $INFO{'caller'} == 2)) {
			$yyimbox = $inmes_txt{'773'};
			$status = $inmes_imtxt{'status'};
			$senderinfo = $inmes_txt{'324'};
			$callerid = 2;
			$boxtxt = $inmes_txt{'outbox'};
			$movebutton  = qq~<input type="submit" name="imaction" value="$inmes_imtxt{'store'}" class="button" />$otherStoreSelect $inmes_txt{'storeor'}~;
			$IM_box = $inmes_txt{'outbox'};
			$PMfileToOpen = 'outbox';
			}
		# store
		elsif ($action eq 'imstorage' || ($action eq 'imshow' && $INFO{'caller'} == 3)) {
			$yyimbox = $inmes_txt{'774'};
			$status = '';
			$senderinfo = $inmes_txt{'318'};
			if ($INFO{'viewfolder'} eq 'out') { $senderinfo = $inmes_txt{'324'}; }
			elsif ($INFO{'viewfolder'} ne 'in') { $senderinfo = qq~$inmes_txt{'318'} / $inmes_txt{'324'}~; }
			$callerid = 3;
			$boxtxt = $inmes_txt{'storage'};
			$movebutton  = qq~<input type="submit" name="imaction" value="$inmes_imtxt{'store'}" class="button" />$otherStoreSelect $inmes_txt{'storeor'}~;
			$IM_box = $inmes_txt{'storage'};
			if ($INFO{'viewfolder'} eq 'in' || $INFO{'viewfolder'} eq 'out') { $IM_box .= qq~ &rsaquo; $im_folders_txt{"$INFO{'viewfolder'}"}~; }
			elsif ($INFO{'viewfolder'}) { $IM_box .= qq~ &rsaquo; $INFO{'viewfolder'}~; }
			$PMfileToOpen = 'imstore';
			}
		## sending a message / previewing
		elsif ($action eq 'imsend' || ($action eq 'imsend2' && $FORM{'previewim'})) {
			$IM_box = $inmes_txt{'148'};
			if ($INFO{'forward'} == 1) { $IM_box = $inmes_txt{'forward'}; }
			if ($INFO{'reply'} == 1) { $IM_box = $inmes_txt{'replymess'}; }
			&IMPost;
			&buildIMsend;
			&doshowims;
			}
		## posting the message or draft
		elsif ($action eq 'imsend2' || $FORM{'draft'})	{
			$IM_box = $inmes_txt{'148'};
			if($INFO{'forward'} == 1) { $IM_box = $inmes_txt{'forward'}; }
			if($INFO{'reply'} == 1) { $IM_box = $inmes_txt{'replymess'}; }
			&IMsendMessage;
		}
		elsif ($action eq 'imshow' && $INFO{'caller'} == 5)	{
			$yyimbox = $inmes_txt{'broadcast'};
			$status = $inmes_imtxt{'status'};
			$senderinfo = $inmes_txt{'318'};
			$callerid = 5;
			$boxtxt = $inmes_txt{'316'};
			$movebutton = qq~<input type="submit" name="imaction" value="$inmes_imtxt{'store'}" class="button" />$otherStoreSelect $inmes_txt{'storeor'}~;
			$IM_box = $inmes_txt{'broadcast'};
			$PMfileToOpen = 'msg';
			}
	}
	## viewing front page
	elsif ($action eq "mycenter")	{
		$yyimbox = "$inmes_txt{'mycenter'}";
	}

	$mctitle = $yyimbox;

	## draw the container
	&drawPMbox($PMfileToOpen);

	## set template up
	$mycenter_template =~ s/({|<)yabb mcviewmenu(}|>)/$MCViewMenu/g;
	$mycenter_template =~ s/({|<)yabb mcmenu(}|>)/$yymcmenu/g;
	$mycenter_template =~ s/({|<)yabb mcpmmenu(}|>)/$MCPmMenu/g;
	$mycenter_template =~ s/({|<)yabb mcprofmenu(}|>)/$MCProfMenu/g;
	$mycenter_template =~ s/({|<)yabb mcpostsmenu(}|>)/$MCPostsMenu/g;
	$mycenter_template =~ s/({|<)yabb mcglobformstart(}|>)/$MCGlobalFormStart/g;
	$mycenter_template =~ s/({|<)yabb mcextrasmilies(}|>)/$MCExtraSmilies/g;
	$mycenter_template =~ s/({|<)yabb mccontent(}|>)/$MCContent/g;
	$mycenter_template =~ s/({|<)yabb mctitle(}|>)/$mctitle/g;
	$mycenter_template =~ s/({|<)yabb selecthtml(}|>)/$selecthtml/g;
	$mycenter_template =~ s/({|<)yabb forumjump(}|>)//g;

	## end new style box
	$yymain .= qq~$mycenter_template~;
	&template;
	if ($action eq 'imsend2' && !$FORM{'previewim'}) {
		$yySetLocation = qq~$scripturl?action=imoutbox~;
		&redirectexit;
	} else { 
		exit;
	}
}


sub AddFolder	{
	if ($iamguest) { &fatal_error("im_members_only"); }
	my $storefolders = ${$username}{'PMfolders'};
	my @currStoreFolders = split(/\|/, ${$username}{'PMfolders'});
	my $x = 0;
	my $newStoreFolders = "in|out";
	
	my $newFolderName = $FORM{'newfolder'};
	chomp $newFolderName;

	nxtfdr: foreach my $currStoreFolder (@currStoreFolders) {
		if ($FORM{'newfolder'})	{
			if ($newFolderName !~ /^[\s0-9A-Za-z-_]+$/) { &fatal_error('invalid_character', $inmes_txt{'foldererror'}); }
			if($FORM{'newfolder'} eq $currStoreFolder)	{ &fatal_error('im_folder_exists'); }
		}
		elsif ($FORM{'delfolders'})	{
			if ($currStoreFolder eq 'in' || $currStoreFolder eq 'out') { $x++; next nxtfdr; }
			if ($FORM{"delfolder$x"} ne 'del') { $newStoreFolders .= qq~|$currStoreFolder~; }
		}
		$x++;
	}
	if ($FORM{'newfolder'}) { ${$username}{'PMfolders'} = qq~$storefolders|$FORM{'newfolder'}~; }
	elsif ($FORM{'delfolders'})	{ ${$username}{'PMfolders'} = $newStoreFolders; }
	&buildIMS($username, 'update');
	$yySetLocation = qq~$scripturl?action=mycenter~;
	&redirectexit;
}


sub CallBackRec	{
	my $receiver = $_[0];
	my $rid = $_[1];

	fopen(RECMSG, "$memberdir/$receiver.msg");
	@rims = <RECMSG>;
	fclose(RECMSG);
	$nodel = 0;
	fopen(REVMSG, ">$memberdir/$receiver.msg");
	## run through and drop the message line
	foreach $line (@rims) {
		chomp($line);
		($rmessageid,undef, undef, undef, undef, undef, undef, undef, undef, undef, undef, undef, $flags, undef) = split(/\|/, $line, 14);
		chomp($rmessageid);
		if ($rmessageid != $rid ) { print REVMSG "$line\n"; }
		elsif (($rmessageid == $rid) && !$flags =~ /u/i ) { print REVMSG "$line\n"; $nodel = 1;}
	}
	fclose(REVMSG);
	return $nodel;
}


##  call an unopened message back
sub CallBack {
	
	# set variables from GET - localised
	$nodel = 0;
	my $receiver = $INFO{'receiver'} || $_[0];

	## open rec's inbox
	if($receiver && $receiver !~ /,/) {
		my $receiver = &decloak($receiver);
		&CallBackRec($receiver,$INFO{'rid'});
	}
	elsif($INFO{'receiver'}) {
		foreach my $rec (split(/\,/, $receiver)) {
			$rec = &decloak($rec);
			&UserCheck($rec, "im_notify");
			if (!$usercheck{'im_notify'}) { &CallBackRec($rec,$INFO{'rid'}); }
		}
	}

	if ($nodel == 1) { &fatal_error("im_deleted"); }

	$yySetLocation = qq~$scripturl?action=imoutbox~;
	&redirectexit;
}

## lookup specific flag in PM
sub checkMessageFlag	{
	## look for $user.$pmFile, find $id message and check for $messageFlag
	my ($user, $id, $pmFile, $messageFlag) = @_;
	my $messageFoundFlag = 0;
	if (-e "$memberdir/$user.$pmFile")	{
		fopen ("USERMSG", "$memberdir/$user.$pmFile");
		my @userMessages = <USERMSG>;
		fclose ("USERMSG");
		chomp @usermessages;
		foreach my $userMessage (@userMessages)	{
			my($uMessageId, undef, undef, undef, undef, undef, undef, undef, undef, undef , undef, undef, $uMessageFlags, undef) = split(/\|/, $userMessage,  14);
			if($uMessageId eq $id)	{
				if($uMessageFlags =~ /$messageFlag/i)	{
					$messageFoundFlag = 1; last;}
			}
		}
	}
	return $messageFoundFlag;

}

## lookup specific flag in PM, amend as required
sub updateMessageFlag	{
	## look for $user.$pmFile, find $id message and check for $messageFlag. change to $newMessageFlag
	my ($user, $id, $pmFile, $messageFlag, $newMessageFlag) = @_;
	## if the old and new flags are eq, no point trying to do anything!
	if($messageFlag eq $newMessageFlag) {return 0;}
	my $messageFoundFlag = 0;
	if (-e "$memberdir/$user.$pmFile")	{
		fopen ("USERFILE", "+<$memberdir/$user.$pmFile");
		@userFile = <USERFILE>;
		seek USERFILE, 0, 0;
		chomp @userFile;
		foreach my $userMessage (@userFile)	{
			my($uMessageId, $uFrom, $uToUser, $uTocc, $uTobcc, $uSubject, $uDate, $uMessage, $uPid, $uReply , $uip, $uStatus, $uMessageFlags, $uStorefolder, $uAttach) = split(/\|/, $userMessage );
			if($uMessageId eq $id)	{
				if($uMessageFlags =~ /$messageFlag/)	{
					$messageFoundFlag = 1;#}
					$uMessageFlags =~ s/$messageFlag/$newMessageFlag/;
					$userMessage	 = "$uMessageId|$uFrom|$uToUser|$uTocc|$uTobcc|$uSubject|$uDate|$uMessage|$uPid|$uReply |$uip|$uStatus|$uMessageFlags|$uStorefolder|$uAttach";
				}
			}
			print USERFILE  "$userMessage\n";
		}
		fclose("USERFILE");

	}
	return $messageFoundFlag;
}


## lookup value in pm file
sub checkIMS {
	my $user = $_[0];
	my $id = $_[1];
	my $checkfor = $_[2];

	## has the message been opened by the receiver? 1 = yes 0 = no
	if ($checkfor eq 'messageopened') {
		my $messageFoundFlag = &checkMessageFlag($user, $id, 'msg', 'u');
		if ($messageFoundFlag == 1) { return 0; }
		else	{$messageFoundFlag = &checkMessageFlag($user, $id, 'imstore', 'u'); }
		if ($messageFoundFlag == 1) { return 0; }
		else	{ return 1; }
	}

	## has the message been replied to? 1 = yes 0 = no
	if ($checkfor eq 'messagereplied') {
		## check in msg and imstore
		my $messageFoundFlag = &checkMessageFlag($user, $id, 'msg', 'r');
		if ($messageFoundFlag == 1) { return 1; }
		else	{$messageFoundFlag = &checkMessageFlag($user, $id, 'imstore', 'r'); }
		if ($messageFoundFlag == 1) { return 1; }
		else	{ return 0; }
	}
}


## update IMS for user - &updateIMS([user],[PM msgid],[target/action])
sub updateIMS {
	## user to update, messageid affected, purpose of call
	## call  can be: 'messagein'/'messageout/imstorein/imstoreout - adding message to spec'd section
	##    #reply'/read/ - switch flag
	# these are the local variables for rewriting the ims file
	# only used as needed, but need to be declared here
	my $user = $_[0];
	my $id = $_[1];
	my $target = $_[2];
	$numToProc = $_[3];
	my $adjuster = 1;
	if ($numToProc) { $adjuster = $numToProc; }
	# load the ims file so all values are availble
	## just on the chance that user is new , check and build if needed
	&buildIMS($user, 'load');

	## new msg received - add to the inbox lists and increment the counts
	if ($target eq 'messagein')	{  ## works2
		# read the lines into temp variables
		${$user}{'PMmnum'}++;
		${$user}{'PMimnewcount'}++;
	}
	# message sent - add to the outbox list and increment count

	if ($target eq 'messageout') {  ## works2
		${$user}{'PMmoutnum'}++;
	}
	# message moved to imstore, from msg - add to store(in) and increment store, decrease inbox

	if ($target eq 'imstorein') {
		${$user}{'PMstorenum'} = ${$user}{'PMstorenum'} + $adjuster;
		${$user}{'PMmnum'} = ${$user}{'PMmnum'} - $adjuster;
	}
	# message moved to imstore, from outbox - add to store(in) and increment
	if ($target eq 'imstoreout') {
		${$user}{'PMstorenum'} = ${$user}{'PMstorenum'} + $adjuster;
	}
	if ($target eq 'imstoreinnew')	{
		${$user}{'PMimnewcount'} = ${$user}{'PMimnewcount'} - $adjuster;
	}

	## reading msg in inbox - newcount -1, remove from unread list
	if ($target eq 'inread')	{  ## works
		my $messageRead = &updateMessageFlag($user, $id, 'msg', 'u', '');
		if ($messageRead)	{
			${$user}{'PMimnewcount'} = ${$user}{'PMimnewcount'} - 1;
		}
	}
	if ($target eq 'bmread')	{  ## works
		my $messageRead = &updateMessageFlag($user, $id, 'msg', 'u', '');
		if ($messageRead)	{
			${$user}{'PMimnewcount'} = ${$user}{'PMimnewcount'} - 1;
		}
	}
	# all inbox read - clear unread list and count
	if ($target eq 'inreadall')	{
		${$user}{'PMimnewcount'} = 0;
	}

	if ($target eq 'deletemsg') {
		my $currcount = ${$user}{'PMmnum'};
		my $currnewcount = ${$user}{'PMimnewcount'};
		${$user}{'PMmnum'} = ${$user}{'PMmnum'} - $adjuster;
		my $msgRead = &checkIMS($user, $id, 'messageopened');
		# if the message is unread...
		if (!$msgRead)	{
			${$user}{'PMimnewcount'} = ${$user}{'PMimnewcount'} - 1;
		}
	}
	##  delete message - outbox

	if ($target eq 'deleteout') {
		# read in outcurrent list
		${$user}{'PMmoutnum'} = ${$user}{'PMmoutnum'} - $adjuster;
	}
	##  delete message - store
	if ($target eq 'deletestore') {
		${$user}{'PMstorenum'} = ${$user}{'PMstorenum'} - $adjuster;
	}
	## callback message - take off imnewcount, mnum
	if ($target eq 'callback') {
		${$user}{'PMmnum'}--;
		${$user}{'PMimnewcount'}--;
	}
	if ($target eq 'draftadd')	{
		${$user}{'PMdraftnum'}++;
	}

	## if amending content
	## zap the ims file and rebuild it with the new values
	&buildIMS($user, 'update');
}


## delete IMs
sub Del_Some_IM {
	&LoadLanguage('InstantMessage');
	if ($iamguest) { &fatal_error('im_members_only'); }

	my $fileToOpen = "$username.msg";
	if ($INFO{'caller'} == 2) { $fileToOpen = "$username.outbox"; }
	elsif ($INFO{'caller'} == 3) { $fileToOpen = "$username.imstore"; }
	elsif ($INFO{'caller'} == 4) { $fileToOpen = "$username.imdraft"; }
	elsif ($INFO{'caller'} == 5) { $fileToOpen = "broadcast.messages"; }

	fopen(USRFILE, "<$memberdir/$fileToOpen");
	@messages = <USRFILE>;
	fclose(USRFILE);

	## deleting
	if ($FORM{'imaction'} eq $inmes_txt{'remove'} || $INFO{'action'} eq $inmes_txt{'remove'}) {
		fopen(UFILE, ">$memberdir/$fileToOpen");
		seek UFILE, 0, 0;
		my $b = 0;
		for (my $a = 0; $a < @messages; $a++) {
			if ($FORM{"message$a"} != 1) { print UFILE "$messages[$a]";}
			else {
				$b++;
			}
		}
		fclose(UFILE);
	}
	##  store
	elsif ($FORM{'imaction'} eq $inmes_imtxt{'store'} || $INFO{'imaction'} eq $inmes_imtxt{'store'}) {
		my (@messages, $a, $musername, $msub, $mdate, $mmessage, $messageid, $mip, $checkmess);
		$source = $INFO{'caller'} == 1 ? 'in' : 'out';
		fopen(URNFILE, "$memberdir/$fileToOpen");
		my @messages = <URNFILE>;
		fclose(URNFILE);
		fopen(trANSFER, ">>$memberdir/$username.imstore", 1);
		my $a = 0;
		my $newStoreFolder = '';
		if ($FORM{'tostorefolder'}) {
			$newStoreFolder = $FORM{'tostorefolder'};
			$imstorefolder = $newStoreFolder;
		}
		else	{
			if ($INFO{'caller'} == 1)	{ $newStoreFolder = 'in'; }
			elsif ($INFO{'caller'} == 2) { $newStoreFolder = 'out'; }
		}
		my $movecount = 0;
		my $newcount = 0;
		my $a = 0;
		if ($INFO{'caller'} != 3) { fopen(URNFILE, ">$memberdir/$fileToOpen"); }
		foreach my $mess (@messages) {
			if (!$FORM{"message$a"}) {
				## leave it where it was - only do this on in/out boxes
				if ($INFO{'caller'} != 3) { print URNFILE "$mess"; }
				## for storebox, just put the lne back as it was
			} else {
				chomp $mess;  #ages[$a];
				my ($imessageid, $imusername, $imusernameto, $imusernametocc, $imusernametobcc, $imsub, $imdate, $mmessage, $ipmessageid, $mip, $imreply, $imstatus, $imflags, undef, $imattachment) = split(/\|/, $mess);  #ages[$a]);
				if ($INFO{'caller'} != 3) {
					print trANSFER "$imessageid|$imusername|$imusernameto|$imusernametocc|$imusernametobcc|$imsub|$imdate|$mmessage|$ipmessageid|$mip|$imreply|$imstatus|$imflags|$imstorefolder|$imattachment\n";
				} else {
					## if moving within the store, just update the list member and then print the whole file back
					$messages[$a] = "$imessageid|$imusername|$imusernameto|$imusernametocc|$imusernametobcc|$imsub|$imdate|$mmessage|$ipmessageid|$mip|$imreply|$imstatus|$imflags|$imstorefolder|$imattachment\n";
				}
				# send to store with in
				$movecount++;
				if ($imflags =~ /u/)	{ $newcount++; }
				# send to store with out
			}
			$a++;
		}
		fclose(trANSFER);
		fclose(URNFILE);

		if ($INFO{'caller'} == 3)	{
			fopen(trANSFER, ">$memberdir/$fileToOpen");
			print trANSFER @messages;
			fclose(trANSFER);
		}

		if ($movecount > 0) { &updateIMS($username, $imessageid, 'imstorein', $movecount); }
		if ($newcount > 0) { &updateIMS($username, $imessageid, 'imstoreinnew', $newcount); }
	}

	my $redirect = 'im';
	my $redirectview = '';
	if ($INFO{'caller'} == 2)	{ $redirect = 'imoutbox'; }
	elsif ($INFO{'caller'} == 3) { $redirect = 'imstorage'; $redirectview = ";viewfolder=$INFO{'viewfolder'}"; }
	elsif ($INFO{'caller'} == 4) { $redirect = 'imdraft'; }
	elsif ($INFO{'caller'} == 5) { $redirectview = ';focus=bmess'; }
	$yySetLocation = qq~$scripturl?action=$redirect$redirectview~;
	&redirectexit;
}

## if the user is valid..
sub LoadValidUserDisplay	{
	$muser = $_[0];
	if ($muser ne 'Guest' && !$yyUDLoaded{$muser} && -e ("$memberdir/$muser.vars")) {
		$sm = 1;
		&LoadUserDisplay($muser);
	}
}

## create either a full link or just a name for the IM display
sub CreateUserDisplayLine	{
	$usrname = $_[0];
	my $usernamelink;

	$sendPM = '';
	$sendEmail = '';
	$membAdInfo = '';

	if ($yyUDLoaded{$usrname}) {
		unless ($INFO{'caller'} == 2 && ($mstatus =~ /b/ || $mtousers =~ /,/ || $mccusers || $mbccusers)) {
			$text = ${$uid.$usrname}{'usertext'};
			$signature = ${$uid.$usrname}{'signature'};
			if ($INFO{'caller'} == 2 || $INFO{'caller'} == 3) { $signature = ''; }
			unless($INFO{'caller'} == 5 && $mstatus eq 'g') { &userOnLineStatus($usrname); }
		
			if (!$iamguest) {
				# Allow instant message sending if current user is a member.
				$sendPM = qq~$menusep<a href="$scripturl?action=imsend;to=$useraccount{$usrname}">$img{'message_sm'}</a>~;
			}
			if (${$uid.$usrname}{'hidemail'} ne 'checked' || $iamadmin || $iamgmod || $allow_hide_email ne 1) {
				$sendEmail = qq~$menusep<a href="mailto:${$uid.$usrname}{'email'}">$img{'email_sm'}</a>~;
			}
			
			$wwwlink = ${$uid.$usrname}{'weburl'} ? qq~$menusep${$uid.$usrname}{'weburl'}~ : '';
			$aimad = ${$uid.$usrname}{'aim'} ? qq~$menusep${$uid.$usrname}{'aim'}~ : '';
			$icqad = ${$uid.$usrname}{'icq'} ? qq~$menusep${$uid.$usrname}{'icq'}~ : '';
			$yimad = ${$uid.$usrname}{'yim'} ? qq~$menusep${$uid.$usrname}{'yim'}~ : '';
			$msnad = ${$uid.$usrname}{'msn'} ? qq~$menusep${$uid.$usrname}{'msn'}~ : '';
			$gtalkad = ${$uid.$usrname}{'gtalk'} ? qq~$menusep${$uid.$usrname}{'gtalk'}~ : '';
			$skypead = ${$uid.$usrname}{'skype'} ? qq~$menusep${$uid.$usrname}{'skype'}~ : '';
			
			$membAdInfo = $profbutton . $wwwlink . $msnad . $gtalkad . $icqad . $yimad . $aimad . $skypead;
		}
		$usernamelink = $link{$usrname};
		if ($musername eq $username) {
			$imOpened = &checkIMS($usrname, $messageid, 'messageopened');
			&UserCheck($usrname, 'im_notify');
			if (!$imOpened && !$usercheck{'im_notify'}) { $usernamelink .= qq~ <span class="small">(<a href="$scripturl?action=imcb;rid=$messageid;receiver=$useraccount{$usrname}" onclick="return confirm('$inmes_imtxt{'73'}')">$inmes_imtxt{'83'}</a>)</span>~; }
		}
	} else {
		$usernamelink = qq~<b>$usrname</b>~;
	}
	return $usernamelink;

}

##  posting the IM
sub IMPost {
	if (($INFO{'bmess'} || $FORM{'isBMess'}) eq 'yes') { $sendBMess = 1; }
	##  if user isn't a FA/gmod and has a postcount below the threshold.....
	if (!$iamadmin && !$iamgmod && !$staff && ${$uid.$username}{'postcount'} < $numposts) {
		&fatal_error('im_low_postcount');
	}
	##  guests not allowed.....
	if ($iamguest) { &fatal_error('im_members_only'); }
	my ($mdate, $mip, $mmessage);
	##  if the IM has a number assigned already, open the right IM file
	if ($INFO{'id'} ne '' && !$replyguest) {
		
		if ($INFO{'caller'} < 5) { &updateIMS($username, $INFO{'id'}, 'inread'); }
		else { &updateIMS($username, $INFO{'id'}, 'bmread'); }
		
		my $pmFileType = "$username.msg";
		if ($INFO{'caller'} == 2) { $pmFileType = "$username.outbox"; }
		elsif ($INFO{'caller'} == 3) { $pmFileType = "$username.imstore"; }
		elsif ($INFO{'caller'} == 4) { $pmFileType = "$username.imdraft"; }
		elsif ($INFO{'caller'} == 5) { $pmFileType = "broadcast.messages"; }
		fopen(FILE, "$memberdir/$pmFileType");
		@messages = <FILE>;
		fclose(FILE);
		## split content of IM file up
		foreach my $checkTheMessage (@messages)	{
			($qmessageid, $mfrom, $mto, $mtocc, $mtobcc, $msubject, $mdate, $message, $mparid, $mreplyno, $mip, $mstatus, $mflags, $mstore, $mattach) = split(/\|/, $checkTheMessage);
			if ($qmessageid == $INFO{'id'}) { last; }
		}
		## remove 're:' from subject (why?)
		$msubject =~ s/Re: //g;
		## if replying/quoting, up the reply# by 1
		if ($INFO{'quote'} || $INFO{'reply'}) { $mreplyno++; $INFO{'status'} = $mstatus; }
		##  if quote
		if ($INFO{'reply'}) { $message = ''; }
		if ($INFO{'quote'}) {
			# swap out brs and spaces
			$message =~ s~<br />~\n~g;
			$message =~ s~<br>~\n~ig;
			$message =~ s/ \&nbsp; \&nbsp; \&nbsp;/\t/ig;
			if (!$nestedquotes) {
				$message =~ s~\n{0,1}\[quote([^\]]*)\](.*?)\[/quote\]\n{0,1}~\n~isg;
				$message =~ s~\n*\[/*quote([^\]]*)\]\n*~~ig;
			}
			if ($mfrom ne "" && $do_scramble_id) { $cloakedAuthor = &cloak($mfrom); }
			else { $cloakedAuthor = $mfrom; }
			$quotestart = int($quotemsg / $maxmessagedisplay) * $maxmessagedisplay;
			if ($INFO{'forward'} || $INFO{'quote'}) {
				$message    = qq~[quote author=$cloakedAuthor link=impost date=$mdate\]$message\[/quote\]\n~;
			}
			if ($message =~ /\#nosmileys/isg) { $message =~ s/\#nosmileys//isg; $nscheck = "checked"; }
		}
		if ($INFO{'reply'} || $INFO{'forward'} || $INFO{'quote'}) { $msubject = "Re: $msubject"; }
	} elsif ($replyguest) {
		fopen(FILE, "$memberdir/broadcast.messages");
		my @messages = <FILE>;
		fclose(FILE);
		## split content of IM file up
		foreach my $checkTheMessage (@messages){
			($qmessageid, $mfrom, $mto, $mtocc, $mtobcc, $msubject, $mdate, $message, $mparid, $mreplyno, $mip, $mstatus, $mflags, $mstore, $mattach) = split(/\|/, $checkTheMessage);
			if ($qmessageid == $INFO{'id'}) { last; }
		}
		($guestName, $guestEmail) = split(/\ /, $mfrom);
		$guestName =~ s/%20/ /g;
		$message =~ s~<br />~\n~g;
		$message =~ s~<br>~\n~ig;
		$message =~ s/ \&nbsp; \&nbsp; \&nbsp;/\t/ig;
		$message =~ s~\[b\](.*?)\[/b\]~*$1*~isg;
		$message =~ s~\[i\](.*?)\[/i\]~/$1/~isg;
		$message =~ s~\[u\](.*?)\[/u\]~_$1_~isg;
		$message =~ s~\[.*?\]~~g;
		my $sendtouser = ${$uid.$username}{'realname'};
		my $mdate = &timeformat($mdate, 1);
		require "$sourcedir/Mailer.pl";
		&LoadLanguage('Email');
		#sender email date subject message
		$message = &template_email($replyguestmail, {'sender' => $guestName, 'email' => $guestEmail, 'sendto' => $sendtouser, 'date' => $mdate, 'subject' => $msubject, 'message' => $message});
		$msubject = qq~Re: $msubject~;
	}

	$submittxt = $inmes_txt{'sendmess'};
	if ($INFO{'forward'} == 1) { $submittxt = $inmes_txt{'forward'}; }
	$destination = 'imsend2';
	$waction = 'imsend';
	$is_preview = 0;
	$post = 'imsend';
	$previewtxt = $inmes_txt{'507'};
	$preview = 'previewim';
	$icon = 'xx';
	$draft = 'draft';
	$mctitle = $inmes_txt{'sendmess'};
	if ($sendBMess) { $mctitle = $inmes_txt{'sendbroadmess'}; }
}


sub IMRemove {
	if ($iamguest) { &fatal_error("im_members_only"); }
	# switched 'search for ' ID to variable
	my (@messages, $a, $musername, $msub, $mdate, $mmessage, $messageid, $mip,$delfrom);
	my $remMessage = $INFO{'id'};

	if ($INFO{'caller'} == 1) {
		$redirect = 'im';
		$delfrom = 'msg';
		fopen(REMFILE, "+<$memberdir/$username.msg");
	}
	elsif ($INFO{'caller'} == 2) {
		$redirect = 'imoutbox';
		$delfrom = 'out';
		fopen(REMFILE, "+<$memberdir/$username.outbox");
	}
	elsif ($INFO{'caller'} == 3) {
		$redirect = 'imstorage';
		$delfrom = 'store';
		fopen(REMFILE, "+<$memberdir/$username.imstore");
	}
     elsif ($INFO{'caller'} == 4) {
     	$redirect = 'imdraft';
		$delfrom = 'drafts';
     	fopen(REMFILE, "+<$memberdir/$username.imdraft");
     }
     elsif ($INFO{'caller'} == 5) {
     	$redirect = 'im;focus=bmess';
		$delfrom = '';
     	fopen(REMFILE, "+<$memberdir/broadcast.messages");
     }
	seek REMFILE, 0, 0;
	@messages = <REMFILE>;
	seek REMFILE, 0, 0;
	truncate REMFILE, 0;
	for ($a = 0; $a < @messages; $a++) {
		chomp $messages[$a];
		# ONLY delete MSG with correct ID
		my ($imessageid, $imusername, $imusernameto, $imusernametocc, $imusernametobcc, $imsub, $imdate, $mmessage, $ipmessageid, $mip) = split(/\|/, $messages[$a]);
		# If Message-ID is < 100, user has used the old IM before
		if ($imessageid < 100) {
			if ($a ne $remMessage) { print REMFILE "$messages[$a]\n"; }
		} else {
			if ($imessageid ne $remMessage) { print REMFILE "$messages[$a]\n"; }
		}
	}
	fclose(REMFILE);
	&updateIMS($username, $remMessage, "delete$delfrom");
	$yySetLocation = qq~$scripturl?action=$redirect~;
	&redirectexit;
}

sub MarkAll {
	fopen(FILE, "+<$memberdir/$username.msg");
	seek FILE, 0, 0;
	@messages = <FILE>;
	seek FILE, 0, 0;
	truncate FILE, 0;
	for ($a = 0; $a < @messages; $a++) {
		chomp $messages[$a];
		($imessageid, $imusername, $imusernameto, $imusernametocc, $imusernametobcc, $imsub, $imdate, $mmessage, $imessagepid, $imreply, $mip, $imstatus, $imflags, $imstore, $imattach) = split(/\|/, $messages[$a]);
		if($imflags =~ /u/)	{
			$imflags  =~ s/u//;
			print FILE "$imessageid|$imusername|$imusernameto|$imusernametocc|$imusernametobcc|$imsub|$imdate|$mmessage|$imessagepid|$imreply|$mip|$imstatus|$imflags|$imstore|$imattach\n"; }
		else { print FILE "$messages[$a]\n"; }
	}
	fclose(FILE);
	${$username}{'PMimnewcount'} = 0;
	&buildIMS($username, 'update');
	$yySetLocation = qq~$scripturl?action=im~;
	&redirectexit;
}

## page index for PM
sub PmPageindex {
	my ($msindx, $trindx, $mbindx, undef) = split(/\|/, ${$uid.$username}{'pageindex'});
	if ($INFO{'action'} eq 'pmpagedrop') { ${$uid.$username}{'pageindex'} = qq~$msindx|$trindx|$mbindx|1~; }
	if ($INFO{'action'} eq 'pmpagetext') { ${$uid.$username}{'pageindex'} = qq~$msindx|$trindx|$mbindx|0~; }
	&UserAccount($username, 'update');
	if ($INFO{'pmaction'} =~ /\//)	{
		my ($act, $val) = split(/\//, $INFO{'pmaction'});
		$INFO{'pmaction'} = $act . ';start=' . $val;
	}
	if ($INFO{'focus'} eq 'bmess') { $bmesslink = qq~;focus=bmess~;}
	$yySetLocation = qq~$scripturl?action=$INFO{'pmaction'}$bmesslink;start=$INFO{'start'}~;
	&redirectexit;
}

## draw the whole block , with the menu, and the various PM views.
sub drawPMbox {
	&LoadLanguage('InstantMessage');
	&LoadLanguage('Profile');
	$PMfileToOpen = $_[0];
	@dimmessages;
	@bmessages;
	if ($view eq 'pm' && ($PM_level  == 1 || $PM_level  == 2 && ($iamadmin || $iamgmod || $iammod) || $PM_level  == 3 && ($iamadmin || $iamgmod) )) {
		($qmessageid, $mfrom, $mto, $mtocc, $mtobcc, $msubject, $mdate, $message, $mparid, $mreplyno, $mip, $mstatus, $mflags, $mstore, $mattach);

		if (!$INFO{'focus'})	{
			if ($callerid < 5) {
				fopen(NFILE, "$memberdir/$username.$PMfileToOpen");
				@dimmessages = <NFILE>;
			} else {
				fopen(NFILE, "$memberdir/broadcast.messages");
				@bmessages = <NFILE>;
			}
			fclose(NFILE);
		}
		elsif ($INFO{'focus'} eq 'bmess' && $PMenableBm_level > 0)	{
			fopen(BFILE, "$memberdir/broadcast.messages");
			@bmessages = <BFILE>;
			fclose(BFILE);
		}
		$stkmess = 0;
		if (@bmessages > 0) {
			foreach my $checkbcm (@bmessages) {
				$icanview = 0;
				my (undef, $mfrom, $mto, undef, undef, undef, undef, undef, undef, undef, undef, $messStatus, undef) = split (/\|/, $checkbcm);
				if ($mfrom eq $username) { $icanview = 1; }
				else { &BroadMessageView($mto); }
				if ($icanview != 0) {
					if ($messStatus =~ /g/ || $messStatus =~ /a/) {
						push (@stkbmessages, $checkbcm);
						$stkmess++;
					} else {
						push (@tmpbmessages, $checkbcm);
					}
				}
			}
			undef @bmessages;
		}
		@stkbmessages = sort {$b <=> $a} @stkbmessages;
		@tmpbmessages = sort {$b <=> $a} @tmpbmessages;
		push (@dimmessages, @stkbmessages);
		push (@dimmessages, @tmpbmessages);
		undef @stkbmessages;
		undef @tmpbmessages;
	}

	$yyjavascript .= qq~
		function changeBox(cbox) {
			box = eval(cbox);
			box.checked = !box.checked;
		}
	~;

	##  new style box ####
	## start with forum > my messages > inbox
	$yymain .= qq~
<script language="JavaScript1.2" src="$postjspath" type="text/javascript"></script>
<script language="JavaScript1.2" type="text/javascript">
<!--
var postas = '$post';
var namefield = '$realname';
var mailfield = '$realemail';
function checkForm(theForm) {
	if (navigator.appName == "Microsoft Internet Explorer" && document.getElementById('iecopy').checked == true) { theForm.message.createTextRange().execCommand("Copy"); }
	if (theForm.subject.value == "") { alert("$post_txt{'77'}"); theForm.subject.focus(); return false }
	if (postas == "imsend") { if (theForm.toshow.value == "") { alert("$post_txt{'752'}"); theForm.toshow.focus(); return false } }
	else {
		if (namefield == "") {
			if (theForm.name.value == "" || theForm.name.value == "_" || theForm.name.value == " ") { alert("$post_txt{'75'}"); theForm.name.focus(); return false }
			if (theForm.name.value.length > 25)  { alert("$post_txt{'568'}"); theForm.name.focus(); return false }
		}
		if (mailfield == "") {
			if (theForm.email.value == "") { alert("$post_txt{'76'}"); theForm.email.focus(); return false }
			if (! checkMailaddr(theForm.email.value)) { alert("$post_txt{'500'}"); theForm.email.focus(); return false }
		}
	}
	if (theForm.message.value == "") { alert("$post_txt{'78'}"); theForm.message.focus(); return false }
	return true
}
function NewWindow(mypage, myname, w, h, scroll) {
	var new_win;
	new_win = window.open (mypage, myname, 'status=yes,height='+h+',width='+w+',top=100,left=100,scrollbars=yes');
	new_win.window.focus();
}

// copy user
function copyUser (oElement) {
	var indexToCopyId = oElement.options.selectedIndex;
	var indexToCopy = oElement.options[indexToCopyId];
	var username = indexToCopy.text;
	var userid = indexToCopy.value;
	insert_user ('toshow',username,userid);
}

// insert user name to list
function insert_user (oElement,username,userid) {
	var exists = false;
	var oDoc = window.document;
	var oList = oDoc.getElementById('toshow').options;
	for (var i = 0; i < oList.length; i++) {
		if (oList[i].text == username) {
			exists = true;
			alert("$usersel_txt{'memfound'}");
		}
	}
	if (!exists) {
		if (oList.length == 1 && oList[0].value == '0' ) {
			oList[0].value = userid;
			oList[0].text = username;
		} else {
			var newOption = oDoc.createElement("option");
			oDoc.getElementById(oElement).appendChild(newOption);
			newOption.text = username;
			newOption.value = userid;
		}
	}
}
//-->
</script>
	~;

	if ($action =~ /^im/ && (!@dimmessages && $INFO{'focus'} ne 'bmess') && ($PM_level == 1 || $PM_level == 2 && ($iamadmin || $iamgmod || $iammod) || $PM_level == 3 && ($iamadmin || $iamgmod))) {
		if (!@dimmessages) {
			if ($action eq 'im') { unlink("$memberdir/$username.msg"); }
			elsif ($action eq 'imoutbox')  { unlink("$memberdir/$username.outbox"); }
			elsif ($action eq 'imstorage') { unlink("$memberdir/$username.imstore"); }
			elsif ($action eq 'imdraft') { unlink("$memberdir/$username.imdraft"); }
		}
	}

	&LoadCensorList;

	# Fix moderator showing in info
	$sender = 'im';
	$acount = 0;
	## set browser title
	$yytitle = $mycenter_txt{'welcometxt'};

	## start new container - left side is menu, right side is content
	my ($display_prof, $display_posts, $display_pm, $tabPMHighlighted, $tabProfHighlighted, $tabNotifyHighlighted);

	if ($mycenter_template =~ /({|<)yabb mcmenu(}|>)/g) {
		require "$sourcedir/TabMenu.pl";
		&mcMenu;
		$newtemplate = 1;
	}
	
	if ($view eq 'profile' || ($view eq 'mycenter' && ($PM_level == 0 || ($PM_level == 2 && !$iamadmin && !$iamgmod && !$iammod ) || ($PM_level == 3 && !$iamadmin && !$iamgmod)))) {
		$display_prof = 'inline';
		$tabProfHighlighted = 'windowbg2';
	} else {
		$display_prof = 'none';
		$tabProfHighlighted = 'windowbg';
	}
	
	if ($view eq 'notify' || $view eq 'favorites' || $view eq 'recentposts') {
		$display_posts = 'inline';
		$tabNotifyHighlighted = 'windowbg2';
	} else {
		$display_posts = 'none';
		$tabNotifyHighlighted = 'windowbg';
	}
	
	if ($view eq 'pm' || ($view eq 'mycenter' && ($PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod)) || ($PM_level == 3 && ($iamadmin || $iamgmod))))) {
		$display_pm = 'inline';
		$tabPMHighlighted = 'windowbg2';
	} else {
		$display_pm = 'none';
		$tabPMHighlighted = 'windowbg';
	}

	my $tabWidth = '33%';
	if ($PM_level == 0 || ($PM_level == 2 && !$iamadmin && !$iamgmod && !$iammod ) || ($PM_level == 3 && !$iamadmin && !$iamgmod)) { $tabWidth = '50%'; }
	$MCViewMenu = '';
	$MCPmMenu = '';
	$MCProfMenu = '';
	$MCPostsMenu = '';
	$MCGlobalFormStart = '';
	$MCExtraSmilies = '';
	$MCContent = '';

	if ($newtemplate) {
		$MCViewMenu .= qq~
		<script language="JavaScript1.2" type="text/javascript">
		<!--
		function changeToTab(tab) {
		~;
		if ($PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod)) || ($PM_level == 3 && ($iamadmin || $iamgmod))   )	{
			$MCViewMenu .= qq~
				document.getElementById('cont_pm').style.display = 'none';
				document.getElementById('menu_pm').className = '';
			~;
		}
		$MCViewMenu .= qq~
				document.getElementById('cont_prof').style.display = 'none';
				document.getElementById('menu_prof').className = '';
				document.getElementById('cont_posts').style.display = 'none';
				document.getElementById('menu_posts').className = '';
				document.getElementById('cont_' + tab).style.display = 'inline';
				document.getElementById('menu_' + tab).className = 'selected';
		}
		//-->
		</script>
		~;
	} else {
		$MCViewMenu .= qq~
		<script language="JavaScript1.2" type="text/javascript">
		<!--
		function changeToTab(tab) {
		~;
		if ($PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod)) || ($PM_level == 3 && ($iamadmin || $iamgmod))   )	{
			$MCViewMenu .= qq~
				document.getElementById('cont_pm').style.display = 'none';
				document.getElementById('menu_pm').className = 'windowbg';
			~;
		}
		$MCViewMenu .= qq~
				document.getElementById('cont_prof').style.display = 'none';
				document.getElementById('menu_prof').className = 'windowbg';
				document.getElementById('cont_posts').style.display = 'none';
				document.getElementById('menu_posts').className = 'windowbg';
				document.getElementById('cont_' + tab).style.display = 'inline';
				document.getElementById('menu_' + tab).className = 'windowbg2';
		}
		//-->
		</script>
		~;
		$MCViewMenu .= qq~
		<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center" >
		<tr>
		~;
		if ($PM_level == 0 || ($PM_level == 2 && !$iamadmin && !$iamgmod && !$iammod ) || ($PM_level == 3 && !$iamadmin && !$iamgmod)) {
			$display_prof = 'inline';
			$tabProfHighlighted = 'windowbg2';
		}
		if ($PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod)) || ($PM_level == 3 && ($iamadmin || $iamgmod))   )	{
			$MCViewMenu .= qq~
				<td width="$tabWidth" align="center" valign="middle" class="$tabPMHighlighted" id="menu_pm"><a href="javascript:void(0);" onclick="changeToTab('pm'); return false;">$mc_menus{'messages'}</a></td>~;
		}
		$MCViewMenu .= qq~
			<td width="$tabWidth" align="center" valign="middle" class="$tabProfHighlighted" id="menu_prof"><a href="javascript:void(0);" onclick="changeToTab('prof'); return false;">$mc_menus{'profile'}</a></td>
			<td width="$tabWidth" align="center" valign="middle" class="$tabNotifyHighlighted" id="menu_posts"><a href="javascript:void(0);" onclick="changeToTab('posts'); return false;">$mc_menus{'posts'}</a></td>
		</tr>
		</table>
		~;
	}

## start PM div
	if ($PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod)) || ($PM_level == 3 && ($iamadmin || $iamgmod))) {
		$MCPmMenu = qq~
	<div id="cont_pm" style="display: $display_pm">
		<table id="pms" width="100%" align="center" class="windowbg2" cellpadding="1">
		~;

		if (($PMenableBm_level == 1 && ($iamadmin || $iamgmod || $iammod)) || ($PMenableBm_level == 2 && ($iamadmin || $iamgmod)) || ($PMenableBm_level == 3 && $iamadmin)) {
			$MCPmMenu .= qq~
			<tr>
				<td style="text-align: left;" colspan="3">
					<span class="nav"><b><a href="$scripturl?action=imsend;bmess=yes">$img{'sendbmess'}</a></b></span>
				</td>
			</tr>~;
		}

		my $inboxNewCount = qq~, ${$username}{'PMimnewcount'} $inmes_txt{'new'}~;
		if (${$username}{'PMimnewcount'} == 0) { $inboxNewCount = ''; }

		$MCPmMenu .= qq~
		 	<tr>
		 		<td style="text-align: left;" colspan="3"><span class="nav"><b><a href="$scripturl?action=imsend">$img{'im_send'}</a></b></span></td>
			</tr>
			<tr>
				<td width="15%" class="windowbg2"><img src="$imagesdir/im_inbox.gif" alt="$inmes_txt{'inbox'}" border="0" /></td>
				<td width="60%" class="windowbg2"><span class="nav"><b><a href="$scripturl?action=im">$inmes_txt{'inbox'}</a></b></span></td>
				<td width="25%" class="windowbg2"><span class="nav">${$username}{'PMmnum'}$inboxNewCount</span></td>
			</tr>~;

		if ($PMenableBm_level > 0 || ($PMenableGuestButton == 1 && ($iamadmin || $iamgmod))) {
			$MCPmMenu .= qq~
			<tr>
				<td width="15%" class="windowbg2"><img src="$imagesdir/im_inbox.gif" alt="$inmes_txt{'broadcast'}" border="0" /></td>
				<td width="60%" class="windowbg2"><span class="nav"><b><a href="$scripturl?action=im;focus=bmess">$inmes_txt{'broadcast'}</a></b></span></td>
				<td width="25%" class="windowbg2"><span class="nav">${$username}{'PMbcCount'}</span></td>
			</tr>~;
		}

		$MCPmMenu .= qq~
			<tr>
				<td width="15%" class="windowbg2"><img src="$imagesdir/im_outbox.gif" alt="$inmes_txt{'draft'}" border="0" /></td>
				<td width="60%" class="windowbg2"><span class="nav"><b><a href="$scripturl?action=imdraft">$inmes_txt{'draft'}</a></b></span>	</td>
				<td width="25%" class="windowbg2"><span class="nav">${$username}{'PMdraftnum'}</span></td>
			</tr>
			<tr>
				<td width="15%" class="windowbg2"><img src="$imagesdir/im_outbox.gif" alt="$inmes_txt{'outbox'}" border="0" /></td>
				<td width="60%" class="windowbg2"><span class="nav"><b><a href="$scripturl?action=imoutbox">$inmes_txt{'outbox'}</a></b></span>	</td>
				<td width="25%" class="windowbg2"><span class="nav">${$username}{'PMmoutnum'}</span></td>
			</tr>
			<tr>
				<td colspan="3"><hr width="100%" class="hr" /></td>
			</tr>
			<tr>
				<td width="15%" class="windowbg2"><img src="$imagesdir/imstore.gif" alt="$inmes_txt{'storage'}" border="0" /></td>
				<td width="60%" class="windowbg2"><span class="small">$inmes_txt{'storage'}</span></td>
				<td width="25%" class="windowbg2"><span class="nav">${$username}{'PMstorenum'}</span></td>
			</tr>
			<tr>
				<td width="15%" class="windowbg2">&nbsp;</td>
				<td width="60%" class="windowbg2"><span class="nav">&nbsp; &nbsp;<b><a href="$scripturl?action=imstorage;viewfolder=in">$im_folders_txt{'in'}</a></b></span></td>
				<td width="25%" class="windowbg2"><span class="nav">~; $MCPmMenu .= $folderCount[0] || 0; $MCPmMenu .= qq~</span></td>
			</tr>
			<tr>
				<td width="15%" class="windowbg2">&nbsp;	</td>
				<td width="60%" class="windowbg2"><span class="nav">&nbsp; &nbsp;<b><a href="$scripturl?action=imstorage;viewfolder=out">$im_folders_txt{'out'}</a></b> </span></td>
				<td width="25%" class="windowbg2"><span class="nav">~; $MCPmMenu .= $folderCount[1] || 0; $MCPmMenu .= qq~</span></td>
			</tr>
		~;

		## if there are some folders to show under storage
		## split the list down and show it with link to each folder
		if ($enable_storefolders > 0) {
			my $storeFoldersTotal = 0;
			my $DelAdFolder = 0;
			if (${$username}{'PMfolders'}) {
				my $x = 2;
				foreach my $storefolder (split(/\|/, ${$username}{'PMfolders'})) {
					if ($storefolder ne 'in' && $storefolder ne 'out') {
						$storeFoldersTotal++;
						$MCPmMenuTemp .= qq~
						<tr>
							<td width="15%" class="windowbg2">~;
						if ($storeFoldersTotal > 0 && $folderCount[$x] == 0) {
							$DelAdFolder = 1;
							$MCPmMenuTemp .= qq~
								<input type="checkbox" name="delfolder$x" id="delfolder$x" value="del" />~;
						} else {
							$MCPmMenuTemp .= qq~&nbsp;~;
						}

						$MCPmMenuTemp .= qq~
							</td>
							<td width="60%" class="windowbg2"><span class="nav">&nbsp; &nbsp;<b><a href="$scripturl?action=imstorage;viewfolder=$storefolder">$storefolder</a></b></span></td>
							<td width="25%" class="windowbg2"><span class="nav">~; $MCPmMenuTemp .= $folderCount[$x] || 0; $MCPmMenuTemp .= qq~</span></td>
						</tr>~;
					$x++;
					}
				}

				if ($DelAdFolder)	{
					$MCPmMenuTemp .= qq~
						<tr>
							<td class="windowbg2" cellspacing="1" colspan="3">
							<input type="submit" name="imaction" id="imaction" value="$inmes_txt{'delete'}" class="button" />
							<input type="hidden" name="delfolders" id="delfolders" value="yes" />
							</td>
						</tr>
					~;
				}
			}

			if ($storeFoldersTotal) {
				$MCPmMenu .= qq~
					<tr>
						<td class="windowbg2" cellspacing="1" colspan="3">
						<form action="$scripturl?action=delpmfolder" method="post" name="pmfolder" id="pmfolder" enctype="application/x-www-form-urlencoded" style="display:inline;"  onsubmit="return submitproc()">
						$MCPmMenuTemp
						</form>
						</td>
					</tr>
				~;
			}

			$MCPmMenu .= qq~
			<tr>
				<td colspan="3"><hr width="100%" class="hr" /></td>
			</tr>
			<tr>
				<td colspan="3"><span class="nav"><b><a href="$scripturl?action=markims">$inmes_txt{'764'}</a></b></span><br /></td>
			</tr>~;

			## this allows user to add a new folder on the fly
			if ($storeFoldersTotal < $enable_storefolders ) {
				$MCPmMenu .= qq~
			<tr>
				<td colspan="3">
				<hr width="100%" class="hr" />
					<form action="$scripturl?action=newpmfolder" method="post" name="pmfolder" id="pmfolder" enctype="application/x-www-form-urlencoded" style="display:inline;"  onsubmit="return submitproc()">
					$inmes_imtxt{'newstorefolder'}
					&nbsp; <input type="text" name="newfolder" id="newfolder" size="15" value="$mc_folders{'foldername'}" onclick="this.value='';" />
					<input type="submit" name="imaction" id="imaction" value="$inmes_txt{'addfolder'}" class="button" /> 
					</form>
				</td>
			</tr>~;
			}
		}

		unless ($enable_PMsearch == 0) {
			$MCPmMenu .= qq~
			<tr>
				<td colspan="3">
				<hr width="100%" class="hr" />
				<script language="JavaScript1.2" src="$ubbcjspath" type="text/javascript"></script>
				$pm_search{'desc'}<br />
				<form action="$scripturl?action=pmsearch" method="post" onsubmit="return submitproc()" style="display: inline">
				<input type="hidden" name="searchtype" value="allwords" id="searchtype" />
				<input type="hidden" name="subfield" value="on" id="subfield" />
				<input type="hidden" name="msgfield" value="on" id="msgfield" />
				<input type="hidden" name="numberreturned" value="$enable_PMsearch" id="numberreturned" />
				<input type="hidden" name="oneperthread" value="1" id="oneperthread" />
				<input type="hidden" name="action" value="dosearch" id="action" />
			~;
			if ($view ne 'pm') {
				$MCPmMenu .= qq~<input type="hidden" name="pmbox" id="pmbox" value="!all" checked="checked" />~;
			}
			if ($view eq 'pm') {
				$MCPmMenu .= qq~<input type="radio" name="pmbox" id="pmbox" value="!all" checked="checked" /> $pm_search{'all'} ~;
			}
			if ($view eq 'pm' && $action ne 'pmsearch') {
				$MCPmMenu .= qq~<input type="radio" name="pmbox" id="pmbox" value="$callerid" /> $pm_search{'justthis'} ~;
			}
			if ($view eq 'pm') { $MCPmMenu .= qq~<br />~; }
			$MCPmMenu .= qq~
				<input type="text" name="search" size="16" style="font-size: 11px; vertical-align: middle;" />
				<input type="image" src="$imagesdir/search.gif" style="border: 0; background-color: transparent; margin-right: 5px; vertical-align: middle;" />
				</form>
				</td>
			</tr>
			~;
		}

		$MCPmMenu .= qq~
		</table>
	</div>
		~;
	}
## end PM div

## start Profile div
	$MCProfMenu = qq~
	<div id="cont_prof" style="display: $display_prof">
	<table id="prof"  width="100%" align="center" class="windowbg2" cellpadding="4">
		<tr>
			<td style="text-align: left;">~;

	## links for profile pages. SID is now cloaked and controls whether or not
	## the action goes to authenticate or straight to the page.
	## The trick is to use $page to pass the intended page through and switch over on
	## positive id.
	if ($page && $page ne $action)  { $action = $page; }
	my $profileLink;
	my $sid = $INFO{'sid'};
	my $thisLink = '';
	my $sidLink = '';
	if (!$sid) {$sid = $FORM{'sid'}; }
	if ($sid) { $sidLink = ";sid=$sid"; }

	if (!$sid) { $profileLink = 'action=profileCheck;page='; }
	else	{$profileLink = 'action=';}
	$thisLink = 'action=myviewprofile;username=' . $useraccount{$username};
	$MCProfMenu .= qq~
        <span class="nav"><b><a href="$scripturl?$thisLink">$inmes_txt{'viewprofile'}</a></b></span><br /><br />~;

	$thisLink = $profileLink . 'myprofile;username=' . $useraccount{$username} . $sidLink;
	$MCProfMenu .= qq~
        <span class="nav"><b><a href="$scripturl?$thisLink">$profile_txt{'79'}</a></b></span><br />~;

	$thisLink = $profileLink . 'myprofileContacts;username=' . $useraccount{$username} . $sidLink;
	$MCProfMenu .= qq~
        <span class="nav"><b><a href="$scripturl?$thisLink">$profile_txt{'819'}</a></b></span><br />~;

	$thisLink = $profileLink . 'myprofileOptions;username=' . $useraccount{$username} . $sidLink;
	$MCProfMenu .= qq~
        <span class="nav"><b><a href="$scripturl?$thisLink">$profile_txt{'818'}</a></b></span><br />~;

	if ($buddyListEnabled) {
		$thisLink = $profileLink . 'myprofileBuddy;username=' . $useraccount{$username} . $sidLink;
		$MCProfMenu .= qq~
        	<span class="nav"><b><a href="$scripturl?$thisLink">$profile_buddy_list{'buddylist'}</a></b></span><br />~;
	}

	if ($PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod)) || ($PM_level == 3 && ($iamadmin || $iamgmod))) {
		$thisLink = $profileLink . 'myprofileIM;username=' . $useraccount{$username} . $sidLink;
		$MCProfMenu .= qq~
		<span class="nav"><b><a href="$scripturl?$thisLink">$inmes_txt{'765'}</a></b></span>
		<br />
		~;
	}

    if ($iamadmin || ($iamgmod && $allow_gmod_profile && $gmod_access2{'profileAdmin'} eq 'on')) {
		$thisLink = $profileLink . 'myprofileAdmin;username=' . $useraccount{$username} . $sidLink;
		$MCProfMenu .= qq~
			<span class="nav"><b><a href="$scripturl?$thisLink">$profile_txt{'820'}</a></b></span>
			<br />
		~;
	}

	$MCProfMenu .= qq~
		</td></tr>
	</table>
	</div>
    ~;
## end Profile div

## start Posts div
    $MCPostsMenu = qq~
    <div id="cont_posts" style="display: $display_posts">
	<table id="posts" width="100%" align="center" class="windowbg2" cellpadding="4">
		<tr><td class="windowbg2">
			<span class="nav"><b><a href="$scripturl?action=shownotify">$inmes_txt{'viewnotify'}</a></b></span><br />
			<span class="nav"><b><a href="$scripturl?action=favorites">$inmes_txt{'viewfavs'}</a></b></span><br />
    ~;
    if (${$uid.$username}{'postcount'} > 0 && $maxrecentdisplay > 0) {
		$MCPostsMenu .= qq~
		<br /><br />
		<form action="$scripturl?action=myusersrecentposts;username=$useraccount{$username}" method="post" style="display: inline;">
		<span class="small">$inmes_txt{'viewrecentposts'} <select name="viewscount" size="1">
		<option value="5" selected="selected">5</option>
		<option value="10">10</option>
		<option value="15">15</option>
		<option value="$maxrecentdisplay">$maxrecentdisplay</option>
		</select> $inmes_txt{'viewrecentposts2'}
		<input type="submit" value="$inmes_txt{'goviewrecent'}" class="button" /></span>
		</form>
	~;
	}
	$MCPostsMenu .= qq~
		</td></tr>
	</table>
	</div>
	~;
## end Posts div

	if ($view eq 'pm' && $action ne 'imsend' && $action ne 'imsend2') {
		my $imstoreFolder;
		if ($action eq 'imstorage') { $imstoreFolder = ";viewfolder=$INFO{'viewfolder'}"; }
		$MCGlobalFormStart = qq~
		<form action="$scripturl?action=deletemultimessages;caller=$callerid$imstoreFolder" method="post" name="searchform" enctype="application/x-www-form-urlencoded">
		~;
	}

if (!$replyguest) {

	if ($view eq 'pm' && ($action eq 'imsend' || $action eq 'imsend2')) {
		$thecurboard = qq~action=$destination~;
		$MCGlobalFormStart .= qq~<form action="$scripturl?$thecurboard" method="post" name="postmodify" id="postmodify" enctype="application/x-www-form-urlencoded" onsubmit="~;
		if (!${$uid.$toshow}{'realname'}) { $MCGlobalFormStart .= qq~selectNames(); ~; }
		$MCGlobalFormStart .= qq~if(!checkForm(this)) { return false; } else { return submitproc(); }">~;

    ## add smilies box
	## smilies
		$MCPmMenu .= qq~
		<script language="JavaScript1.2" src="$ubbcjspath" type="text/javascript"></script>
		<script language="JavaScript1.2" type="text/javascript">
		<!--
		~;

		if ($smiliestyle == 1) { $smiliewinlink = qq~$scripturl?action=smilieput~; }
		else { $smiliewinlink = qq~$scripturl?action=smilieindex~; }
		
		$MCPmMenu .= qq~
		function smiliewin() {
			window.open("$smiliewinlink", 'list', 'width=$winwidth, height=$winheight, scrollbars=yes');
		}
		//-->
		</script>
		~;

		if ($showadded == 2 || $showsmdir == 2) {
			$MCExtraSmilies .= qq~
			<br />
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			function Smiliextra() {
				AddTxt=smiliecode[document.postmodify.smiliextra_list.value];
				AddText(AddTxt);
			}
			~;
			$smilieslist = '';
			$smilie_url_array = '';
			$smilie_code_array = '';
			$i = 0;
			if ($showadded == 2) {
				while ($SmilieURL[$i]) {
					$smilieslist .= qq~	document.write('<option value="$i">$SmilieDescription[$i]</option>');\n~;
					if ($SmilieURL[$i] =~ /\//i) { $tmpurl = $SmilieURL[$i]; }
					else { $tmpurl = qq~$defaultimagesdir/$SmilieURL[$i]~; }
					$smilie_url_array .= qq~"$tmpurl", ~;
					$tmpcode = $SmilieCode[$i];
					$tmpcode =~ s/\&quot;/"+'"'+"/g;    # "'
					&FromHTML($tmpcode);
					$tmpcode =~ s/&#36;/\$/g;
					$tmpcode =~ s/&#64;/\@/g;
					$smilie_code_array .= qq~" $tmpcode", ~;
					$i++;
				}
			}
			if ($showsmdir == 2) {
				opendir(DIR, "$smiliesdir");
				@contents = readdir(DIR);
				closedir(DIR);
				foreach $line (sort { uc($a) cmp uc($b) } @contents) {
					($name, $extension) = split(/\./, $line);
					if ($extension =~ /gif/i || $extension =~ /jpg/i || $extension =~ /jpeg/i || $extension =~ /png/i) {
						if ($line !~ /banner/i) {
							$smilieslist .= qq~	document.write('<option value="$i">$name</option>');\n~;
							$smilie_url_array .= qq~"$smiliesurl/$line", ~;
							$smilie_code_array .= qq~" [smiley=$line]", ~;
							$i++;
						}
					}
				}
			}
			$smilie_url_array  .= qq~""~;
			$smilie_code_array .= qq~""~;

			$MCExtraSmilies .= qq~
			smilieurl = new Array($smilie_url_array);
			smiliecode = new Array($smilie_code_array);
			if ((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4)) {
				document.write('<table class="bordercolor" height="90" width="120" border="0" cellpadding="2" cellspacing="1" align="center"><tr>');
				document.write('<td height="15" align="center" valign="middle" class="titlebg"><span class="small"><b>$post_smiltxt{'1'}</b></span></td>');
				document.write('</tr><tr>');
				document.write('<td height="20" align="center" valign="top" class="windowbg2"><select name="smiliextra_list" onchange="document.images.smiliextra_image.src= smilieurl[document.postmodify.smiliextra_list.value]" style="width:114px; font-size:7pt;">');
				$smilieslist
				document.write('</select></td>');
				document.write('</tr><tr>');
				document.write('<td height="70" align="center" valign="middle" class="windowbg2"><img name="smiliextra_image" src="'+smilieurl[0]+'" alt="" border="0" onclick="javascript: Smiliextra();" style="cursor: pointer;"></td>');
				document.write('</tr><tr>');
				document.write('<td height="15" align="center" valign="middle" class="windowbg2"><span class="small"><a href="javascript: smiliewin();">$post_smiltxt{'17'}</a></span></td>');
				document.write('</tr></table>');
			}
			//-->
			</script>
			<br />
			~;
		}
	}

} else {
	$thecurboard = qq~action=$destination~;
	$MCGlobalFormStart .= qq~<form action="$scripturl?$thecurboard" method="post" name="postmodify" id="postmodify" enctype="application/x-www-form-urlencoded">~;
}

   ###################################################
   ########  right side container starts here
   ###################################################
	if ($view eq 'mycenter') {
		if (!$yyUDLoaded{$username} && -e ("$memberdir/$username.vars")) {
			&LoadUserDisplay($username);
		}
		if (${$uid.$username}{'regtime'}) {
			$registrationdate = ${$uid.$username}{'regtime'};
		} else {
			$registrationdate = int(time);
		}
		my ($aimad, $yimad, $msnad, $gtalkad, $skypead, $icqad, $signature_hr);

		# user is current / admin / gmod
		$usernamelink = ${$uid.$username}{'realname'};
		if($color)	{$usernamelink= qq~<span style="color:$color; font-weight: bold; ">${$uid.$username}{'realname'}</span>~;}
		$star        = $memberstar{$username};
		$memberinfo  = "$memberinfo{$username}$addmembergroup{$username}";
		$memberinfo =~ s~\n~~g;
		&usersOnline;
		$userOnline = &userOnLineStatus($username);

	#################################

		$template_userpic = ${$uid.$username}{'userpic'};
		$template_usertext = ${$uid.$username}{'usertext'};
		$template_gender = ${$uid.$username}{'gender'};
		$template_postinfo = qq~$mycenter_txt{'posts'}: ${$uid.$username}{'postcount'}<br />~;
		$userlocation = ${$uid.$username}{'location'};
		&ToChars($userlocation);

		if ($showuserpic && $allowpics) {
			if (${$uid.$username}{'userownpic'}) {
				$avstyle = "";
				if ($ENV{'HTTP_USER_AGENT'} !=~ /MSIE/g || $ENV{'HTTP_USER_AGENT'} =~ /Opera/) {
					if ($userpic_width > 0 || $userpic_height > 0) {
						$avstyle = qq~ style="~;
						if ($userpic_width > 0)  { $avstyle .= qq~max-width: $userpic_width\px\; ~; }
						if ($userpic_height > 0) { $avstyle .= qq~max-height: $userpic_height\px\;~; }

						# Limit avatar widths/heights for safari - since Safari contains a bug
						# regarding max-width, and height when only one is present.
						# http://bugzilla.opendarwin.org/show_bug.cgi?id=5146
						if (($userpic_height == 0 && $userpic_width > 0)  && $ENV{'HTTP_USER_AGENT'} =~ /Safari/) { $avstyle .= qq~max-height: $userpic_width\px\;~; }
						if (($userpic_width == 0  && $userpic_height > 0) && $ENV{'HTTP_USER_AGENT'} =~ /Safari/) { $avstyle .= qq~max-width: $userpic_height\px\;~; }

						$avstyle .= qq~"~;
					}
					$avatar = qq~<img src="$template_userpic" alt="" border="0"$avstyle/><br />~;
				} else {
					$avatar = qq~
			<script language="JavaScript1.2" type="text/javascript">
			<!-- //
				var userpic_width = $userpic_width;
				var userpic_height = $userpic_height;
				imgEle = new Image();
				imgEle.src = "$template_userpic";

				if(imgEle.width) {
					if (userpic_width == 0) { tmpuserpic_width = imgEle.width; } else {tmpuserpic_width = userpic_width;}
					if (userpic_height == 0) { tmpuserpic_height = imgEle.height; } else {tmpuserpic_height = userpic_height;}
					var ratio = imgEle.width / imgEle.height;
					for(z=0;z<2;z++) {
						if (imgEle.width > tmpuserpic_width) { imgEle.width = tmpuserpic_width; imgEle.height = parseInt(imgEle.width / ratio); }
						if (imgEle.height > tmpuserpic_height) { imgEle.height = tmpuserpic_height; imgEle.width = parseInt(imgEle.height * ratio); }
					}
					document.write('<img src=" ' + imgEle.src + ' " width=" ' +imgEle.width + ' " height=" ' + imgEle.height + ' " alt="" border="0" /><br />');
				}
				else {
					if (userpic_width == 0) { tmpuserpic_width = 65; } else {tmpuserpic_width = userpic_width;}
					document.write('<img src="$template_userpic" width=" ' + tmpuserpic_width + ' " alt="" border="0" /><br />');
				}
			// -->
			</script>
			<noscript>
			~;

					if ($userpic_width > 0 || $userpic_height > 0) {
						$avstyle = qq~ style="~;
						if ($userpic_width > 0) { $avstyle .= qq~width: $userpic_width\px\;~; }
						$avstyle .= qq~"~;
					}
					$avatar .= qq~<img src="$template_userpic" alt="" border="0"$avstyle /><br />
			</noscript>
			~;
				}
			} else {
				$avatar = qq~<img src="$template_userpic" alt="" border="0" /><br />~;
			}
		} else {
			$avatar = $template_userpic;
		}

		$mctitle = $mycenter_txt{'welcometxt'} ;
		#################################
		$myprofileblock =~ s/({|<)yabb userlink(}|>)/$usernamelink/g;
		$myprofileblock =~ s/({|<)yabb memberinfo(}|>)/$memberinfo/g;
		$myprofileblock =~ s/({|<)yabb stars(}|>)/$star/g;
		$myprofileblock =~ s/({|<)yabb useronline(}|>)/$userOnline/g;
		$myprofileblock =~ s/({|<)yabb userpic(}|>)/$avatar/g;
		$myprofileblock =~ s/({|<)yabb usertext(}|>)/$template_usertext/g;
		$myprofileblock =~ s/({|<)yabb postinfo(}|>)/$template_postinfo/g;
		$myprofileblock =~ s/({|<)yabb gender(}|>)/$template_gender/g;
		$myprofileblock =~ s/({|<)yabb location(}|>)/$userlocation/g;
		################################
		$myprofileblock =~ s/({|<)yabb .+?(}|>)//g;
		
		if ($buddyListEnabled) {
			$buddiesCurrentStatus;
			if (${$uid.$username}{'buddylist'})	{
				&LoadBuddyList;
				$buddiesCurrentStatus = qq~$mycenter_txt{'buddylisttitle'}:<br />$buddiesCurrentStatus~;
			} else { 
				$buddiesCurrentStatus = $mycenter_txt{'buddylistnone'};
			}
		} else {
			$buddiesCurrentStatus = qq~<br />~;
		}

		$MCContent .= qq~
		<table width="100%" border="0" cellspacing="1" cellpadding="5" align="right">
				<tr>
					<td width="33%" class="windowbg2" valign="top">
						$myprofileblock
					</td>
					<td width="67%" class="windowbg2" valign="top">
						$buddiesCurrentStatus
					</td>
				</tr>
				<tr>
					<td colspan="2" class="windowbg">
						$mycenter_txt{'currentsettings'}
					</td>
				</tr>
				<tr>
					<td class="windowbg2">
						$mycenter_txt{'onoffstatus'}<br />
					</td>
					<td class="windowbg2">
		~;

		my $onOffStatus = $mycenter_txt{'onoffstatuson'};
		if (${$uid.$username}{'offlinestatus'} eq 'away') { $onOffStatus = $mycenter_txt{'onoffstatusaway'}; }
		my $notifyType = '';
		my $stealthstatus = '';

		if ($PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod ) || ($PM_level == 3 && ($iamadmin || $iamgmod)))) {
			$notifyType = $mycenter_txt{'notifytypeemail'};
			if (${$uid.$username}{'onlinealert'} eq 'on') { $notifyType = $mycenter_txt{'notifytypepm'}; }
			$notifyType = qq~
				<tr>
					<td class="windowbg2">$mycenter_txt{'notify'}</td>
					<td class="windowbg2">\'$notifyType\'</td>
				</tr>~;
		}

  		if (($iamadmin || $iamgmod) && $enable_MCstatusStealth) {
  			$stealthstatus = $mycenter_txt{'stealth_off'};
  			if (${$uid.$username}{'stealth'} eq 'checked') { $stealthstatus = $mycenter_txt{'stealth_on'}; }
			$stealthstatus = qq~
				<tr>
					<td class="windowbg2">$mycenter_txt{'stealth'}</td>
					<td class="windowbg2">\'$stealthstatus\'</td>
				</tr>~;
  		}

		$MCContent .= qq~\'$onOffStatus\'</td>
				</tr>
		$stealthstatus
		$notifyType
			</table>
	~;	
	}

	 ############## sending pm #######################
	elsif ($view eq 'pm' && ($action eq 'imsend' || $action eq 'imsend2')) {
		my $sendTitle = $inmes_txt{'sendmess'};
		if ($sendBMess) { $sendTitle = $inmes_txt{'sendbroadmess'}; }
		$MCContent .= qq~
		<table width="100%" border="0" cellspacing="0" cellpadding="5">
			$imsend</form>
			$PMmessageProcessed
		</table>
		<br />~;
	}
		
	# inbox/outbox/ storage/draft  viewing
	elsif ($view eq 'pm' && ($action eq 'im' || $action eq 'imoutbox' || $action eq 'imstorage' || $action eq 'imdraft')) {
		&drawPMView;
	}
	elsif ($view eq 'pm' && $action eq 'imshow') {
		$showIM = '';
		if ($INFO{'id'} eq 'all') {
			foreach (@dimmessages) {
				$showmessid = (split /\|/, $_)[0];
				$showIM .= &DoShowIM($showmessid);
				if ($INFO{'caller'} == 5 && $showmessid > ${$username}{'PMbcLastRead'}) { 
					${$username}{'PMbcLastRead'} = $showmessid;
					&buildIMS($username, 'update');
				}
			}
		} else { 
			$showIM = &DoShowIM($INFO{'id'});
			if ($INFO{'caller'} == 5 && $INFO{'id'} > ${$username}{'PMbcLastRead'}) {
				${$username}{'PMbcLastRead'} = $INFO{'id'};
				&buildIMS($username, 'update');
			}
		}

		$MCContent .= qq~
			$showIM
		<br />
		~;
	}
	elsif ($view eq 'pm' && $action eq 'pmsearch') {
		&spam_protection;
		$yysearchmain = '';
		require "$sourcedir/Search.pl";
		&pmsearch;
		$MCContent .= qq~
			$yysearchmain
		<br />
		~;
	}
	elsif ($view eq 'profile') {
		## if user has had to go via id check, this restores their intended page
		$page = $INFO{'page'};
		if($page && $action ne $page) { $action = $page; }
		require "$sourcedir/Profile.pl";
		if ($action eq 'myprofileIM') { &ModifyProfileIM; }
		elsif ($action eq 'myprofileIM2') { &ModifyProfileIM2; }
		elsif ($action eq 'myprofile') { &ModifyProfile; }
		elsif ($action eq 'myprofile2') { &ModifyProfile2; }
		elsif ($action eq 'myprofileContacts') { &ModifyProfileContacts; }
		elsif ($action eq 'myprofileContacts2') { &ModifyProfileContacts2; }
		elsif ($action eq 'myprofileOptions') { &ModifyProfileOptions; }
		elsif ($action eq 'myprofileOptions2') { &ModifyProfileOptions2; }
		elsif ($action eq 'myprofileBuddy') { &ModifyProfileBuddy; }
		elsif ($action eq 'myprofileBuddy2') { &ModifyProfileBuddy2; }
		elsif ($action eq 'myviewprofile') { &ViewProfile; }
		elsif ($action eq 'myprofileAdmin')	{ &ModifyProfileAdmin; }
		elsif ($action eq 'myprofileAdmin2') { &ModifyProfileAdmin2; }
		$MCContent .= qq~
			$showProfile
		<br />
		~;
	}
	elsif ($view eq 'notify') {
		require "$sourcedir/Notify.pl";
		if ($action eq 'shownotify') { &ShowNotifications; }
		elsif ($action eq 'boardnotify2') { &BoardNotify2; &ShowNotifications; }
		elsif ($action eq 'notify4') { &Notify4; }
		$MCContent .= $showNotifications;
		$MCContent .= qq~
		<br />
		~;
	}
	elsif ($view eq 'recentposts') {
		require "$sourcedir/Profile.pl";
		&usersrecentposts;
		$MCContent .= $showProfile;
		$MCContent .= qq~
		<br />
		~;
	}
	elsif ($view eq 'favorites'){
		require "$sourcedir/Favorites.pl";
		&Favorites;
		$MCContent .= $showFavorites;
		$MCContent .= qq~
		<br />
		~;
	}
}

sub drawPMView	{
		## column headers
		## note - if broadcast messages not enabled but guest pm is, admin/gmod still
		##  see the broadcast split
		if (($enable_PMcontrols && ${$uid.$username}{'pmviewMess'} eq "on") || (!$enable_PMcontrols && !$enable_PMviewMess) )	{
			if (!$yyYaBBCloaded) { require "$sourcedir/YaBBC.pl"; }
		}
		if ($INFO{'sort'} ne 'gpdate' && $INFO{'sort'} ne 'thread') { &pageLinksList; }
		my $dateColhead = "$inmes_txt{'317'}";
		if ($action eq 'imdraft') { $dateColhead = $inmes_txt{'datesave'}; }

		$mctitle = $IM_box;
		$MCContent .= qq~
		<table border="0" width="100%" cellspacing="1" cellpadding="3" class="bordercolor">
		~;

		if ($#dimmessages >= $maxmessagedisplay || $INFO{'start'} =~ /all/) {
			$MCContent .= qq~
		  	<tr><td colspan="3" class="titlebg">$pageindex1$pageindexjs</td></tr>
			~;
		}

		if ($INFO{'viewfolder'} ne '') { $vfolder = qq~;viewfolder=$INFO{'viewfolder'}~; }
		if ($INFO{'focus'} eq 'bmess') { $vbmess = qq~;focus=bmess~; }
		if ($INFO{'sort'} ne 'gpdate') { $sbgpdate = qq~;sort=gpdate~; }

		unless ($action eq 'imstorage' && $INFO{'viewfolder'} eq '') {
			$MCContent .= qq~
			<tr>
				<td class="titlebg"  width="65%"><b>$inmes_txt{'70'}</b></td>
				<td class="titlebg"  width="15%"><b>$senderinfo</b></td>
				<td class="titlebg"  width="20%"><b><a href="$scripturl?action=$action$sbgpdate$vfolder$vbmess">$dateColhead</a></b></td>
			</tr>
			~;
		}

		## if no messages found in file, say so
		my $storeContentFound = 0;
		if ($INFO{'viewfolder'} && @dimmessages) {
			foreach my $checkPost (@dimmessages)	{
				my $thisStorefolder= (split /\|/, $checkPost)[13];
				if ($thisStorefolder eq $INFO{'viewfolder'}) { $storeContentFound = 1; last; }
			}
		}

		if (!@dimmessages || ($storeContentFound == 0 && $INFO{'viewfolder'})) {
			## drop in the 'no messages' text
			$MCContent .= qq~
	  <tr>
	    <td class="windowbg" colspan="6" height="21">$inmes_txt{'151'}</td>
	  </tr></table>
	   <br clear="all" /><br />
		~;
		} else {
			## set colours for display
			$acount++;
			my $sortBy = $INFO{'sort'};
			my $maxcounter = $maxmessagedisplay;
			## if on last page, adjust the maxcounter down
			if ((($#dimmessages + 1) - $start) < $maxmessagedisplay || $sortBy eq 'gpdate') { $maxcounter = @dimmessages; }
			else { $maxcounter = ($start + $maxmessagedisplay); }
			$#messages = $counter - 1;
			if (!$start) { $start = 0; }
			$counter = $start;
			if(!$counter) { $counter = 0; }
			my $viewBMess;
			my $groupByDate = 0;
			my $dateSpan = 0;
			my $latestPM = 0;
			if ($INFO{'focus'} eq 'bmess') { $viewBMess = 1; }
			if ($sortBy eq 'gpdate') {
				my $topMDate = (split /\|/, $dimmessages[0])[6];
				my $oldestDate = (split /\|/, $dimmessages[$#dimmessages])[6];
				$groupByDate = 1;
				## work out the span of days - today less oldest message, in days
				$dateSpan = int(($date - $oldestDate) / 86400); # in days
				$latestPM = (($date - $topMDate) / 3600); # in hours
			}
			## if sort is grouped, extra block is added per group
			## pull date of newest pm

			my $latestDateSet = 0;
			my $lastWeekSet = 0;
			my $twoWeeksSet = 0;
			my $threeWeeksSet = 0;
			my $monthSet = 0;
			my $gtMonthSet = 0;
			my $useMeFirst = "";
			my $uselegend = "";

			# work out the newest pm date soa s to put the right first block in
			if ($dateSpan > 31)	{ $gtMonthSet = 1; $useMeFirst = "o"; $uselegend = 'older'; }
			if ($dateSpan > 21 && ($latestPM / 24) < 32 ) { $monthSet = 1; $useMeFirst = "m"; $uselegend = 'fourweeks';}
			if ($dateSpan > 14 && ($latestPM / 24) < 22 ) { $threeWeeksSet = 1; $useMeFirst = "3"; $uselegend = 'threeweeks';}
			if ($dateSpan > 7  && ($latestPM / 24) < 15 ) { $twoWeeksSet = 1; $useMeFirst = "2"; $uselegend = 'twoweeks';}
			if ($dateSpan > 1 && ($latestPM / 24) < 8 ) { $lastWeekSet = 1; $useMeFirst = "1"; $uselegend = 'oneweek';}
			if ($latestPM < 24) { $latestDateSet = 1; $useMeFirst = "l"; $uselegend = 'latest'; }

			if ($sortBy eq 'gpdate') {
				$MCContent .= qq~
				<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{$uselegend}</span>	</td>
				</tr>
				~;
				$counterCheck = $start; 
			}
			if ($viewBMess){ $stkDateSet = 1; }

			for ($counter = $start; $counter < $maxcounter; $counter++) {
	#####################################  top of messages list ###############
	## $messageid, $musername, $musernameto, $musernamecc, $musernamebcc
				chomp $dimmessages[$counter];
				my ($messageid, $musername, $musernameto, $musernamecc, $musernamebcc, $msub, $mdate, $immessage, $mpmessageid, $mreplyno, $mips, $messageStatus, $messageFlags, $storeFolder, $messageAttachment) = split(/\|/, $dimmessages[$counter]);
				## if we are viewing  one of the storage folders, filter out the
				##  PMs that don't match
				if($action eq 'imstorage' && $INFO{'viewfolder'} ne $storeFolder) { next; }
				## set the status icon
				my $messIconName = 'standard';
				if ($messageStatus =~ /c/) { $messIconName = 'confidential'; }
				elsif ($messageStatus =~ /u/) { $messIconName = 'urgent'; }
				elsif ($messageStatus =~ /a/) { $messIconName = 'alertmod'; }
				elsif ($messageStatus =~ /gr/) { $messIconName = 'guestpmreply'; }
				elsif ($messageStatus =~ /g/) { $messIconName = 'guestpm'; }
				my $messIcon = qq~<img src="$imagesdir/$messIconName.gif" name="icons" border="0" hspace="15" alt="$im_message_status{$messIconName}" style="vertical-align: middle;" />~;

				my ($hasMultiRecs,$multiRecs);
				if ($musernameto =~ /,/ || $musernamecc || $musernamebcc ) { $hasMultiRecs = 1; }

				## if store, set the from/to

				# check for multiple recs (outbox/store/draft only)
				## and build the to/rec string for individual callback
				my %usersRec;
				my $usernameto = '';
				if ($action eq 'imoutbox' || $action eq 'imstorage' || $action eq 'imdraft') {
					if ($hasMultiRecs) {
						my $switchComma = 0;
						$usernameto = '';
						if ($messageStatus !~ /b/) {
							## check each to see if they read the message
							foreach my $muser (split(/\,/, $musernameto)) {
								$userToMessRead = &checkIMS($muser, $messageid, 'messageopened');
								%usersRec = {%usersRec , $muser => $userToMessRead};
								if (!$yyUDLoaded{$muser}) { &LoadUser($muser); }
								if ($usernameto && $switchComma == 0)	{ $usernameto .= qq~ ...~; $switchComma = 1; }
								elsif (!$usernameto) {
									$usernameto = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$muser}">${$uid.$muser}{'realname'}</a>~;
								}
							}
							if ($musernamecc)	{
							## check each to see if they read the message
								foreach my $muser (split(/\,/, $musernamecc))	{
									$userToMessRead = &checkIMS($muser, $messageid, 'messageopened');
									%usersRec = {%usersRec , $muser => $userToMessRead};
									if (!$yyUDLoaded{$muser}) { &LoadUser($muser); }
									if ($usernameto && $switchComma == 0)	{ $usernameto .= qq~ ...~; $switchComma = 1; }
								}
							}
							if ($musernamebcc)	{
								## check each to see if they read the message
								foreach my $muser (split(/\,/, $musernamebcc))	{
									$userToMessRead = &checkIMS($muser, $messageid, 'messageopened');
									%usersRec = {%usersRec , $muser => $userToMessRead};
									if (!$yyUDLoaded{$muser}) { &LoadUser($muser); }
									if($usernameto && $switchComma == 0)	{$usernameto .= qq~ ...~; $switchComma = 1; }
								}
							}
						} else {
							foreach my $muser (split(/\,/, $musernameto)) {
								if ($muser eq 'all') { $usernameto = $inmes_txt{'bmallmembers'}; }
								elsif ($muser eq 'mods') { $usernameto = $inmes_txt{'bmmods'}; }
								elsif ($muser eq 'gmods') { $usernameto = $inmes_txt{'bmgmods'}; }
								else {
									my $title = (split /\|/, $NoPost{$muser})[0];
									$usernameto = $title;
								}
								if ($usernameto && $switchComma == 0)	 { $usernameto .= qq~ ...~; $switchComma = 1; last; }
							}
						}
					}
					else	{
						if ($messageStatus !~ /b/) {
							$userToMessRead = &checkIMS($musernameto, $messageid, 'messageopened');
							if (!$yyUDLoaded{$musernameto}) { &LoadUser($musernameto); }
							$usernameto = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$musernameto}">${$uid.$musernameto}{'realname'}</a>~;
						} else {
							if ($musernameto eq 'all') { $usernameto = $inmes_txt{'bmallmembers'}; }
							elsif ($musernameto eq 'mods') { $usernameto = $inmes_txt{'bmmods'}; }
							elsif ($musernameto eq 'gmods') { $usernameto = $inmes_txt{'bmgmods'}; }
							else {
								my $title = (split /\|/, $NoPost{$musernameto})[0];
								$usernameto = $title;
							}
						}
					}
				}
				## done multi
				## kill if not needed
				if (!$hasMultiRecs) { undef %usersRec; }

				## time to output name
				# for multi recs, have to split it down and test per user
				## happens for any message sent with cc or bcc
				my $checkz = 0;
				my $allChecked = 0;

				$msub = &Censor($msub);
				&ToChars($msub);
				$mydate = &timeformat($mdate);
				## start of message row 1
				## for inbox or store, check from
				my ($fromToName, $messageIcon, $callBack, $messageAction);
				if ($action ne 'imstorage' && $action ne 'imdraft' && !$viewBMess) {
					## detect multi-rec
					my ($imnew, $imRepliedTo, $imOpened);
					## outbox - has the recp opened the message? (allow for multi)
					if ($action eq 'imoutbox' && !$hasMultiRecs ) {
						$imOpened = &checkIMS($musernameto, $messageid, 'messageopened');
					}
					elsif ($action eq 'im') { ## inbox - has user opened ?
						$imOpened = &checkIMS($username, $messageid, 'messageopened');
					}
					if ($action eq 'im') { $imRepliedTo = &checkIMS($user, $messageid, 'messagereplied'); }

					## viewing inbox
					if ($action eq 'im') {
						## not opened
						if (!$imOpened && !$hasMultiRecs) {
							$messageIcon = qq~<img src="$imagesdir/imclose.gif" border="0" alt="$inmes_imtxt{'innotread'}" style="vertical-align: middle;" />~;
						}
						## replied to
						elsif ($imRepliedTo && !$hasMultiRecs) {
							$messageIcon = qq~<img src="$imagesdir/answered.gif" border="0" alt="$inmes_imtxt{'08'}" style="vertical-align: middle;" />~;
						}
						## opened
						elsif ($imOpened && !$hasMultiRecs) {
							$messageIcon = qq~<img src="$imagesdir/imopen.gif" border="0" alt="$inmes_imtxt{'inread'}" style="vertical-align: middle;" />~;
						}
						## not opened multi
						elsif (!$imOpened && $hasMultiRecs) {
							$messageIcon = qq~<img src="$imagesdir/imclose2.gif" border="0" alt="$inmes_imtxt{'inread'}" style="vertical-align: middle;" />~;
						}
						## opened multi
						elsif ($imOpened && $hasMultiRecs) {
							$messageIcon = qq~<img src="$imagesdir/imopen2.gif" border="0" alt="$inmes_imtxt{'inread'}" style="vertical-align: middle;" />~;
						}
					}

					##  outbox
					elsif ($action eq 'imoutbox') {

						## not opened
						if (!$imOpened && !$hasMultiRecs) {
	                           &UserCheck($musernameto, 'im_notify');
							if(!$usercheck{'im_notify'}) {
								$messageIcon = qq~<a href="$scripturl?action=imcb;rid=$messageid;receiver=$useraccount{$musernameto}" onclick="return confirm('$inmes_imtxt{'73'}')"><img src="$imagesdir/imclose.gif" border="0" alt="$inmes_imtxt{'outnotread'}" style="vertical-align: middle;" /></a>~;
								$callBack = qq~<span class="small"><a href="$scripturl?action=imcb;rid=$messageid;receiver=$useraccount{$musernameto}" onclick="return confirm('$inmes_imtxt{'73'}')">$inmes_imtxt{'83'}</a> | </span>~;
							} else {
								$messageIcon = qq~<img src="$imagesdir/imclose.gif" border="0" alt="$inmes_imtxt{'outnotread'}" style="vertical-align: middle;" />~;
							}
						}
						## opened
						elsif ($imOpened && !$hasMultiRecs) {
							$messageIcon = qq~<img src="$imagesdir/imopen.gif" border="0" alt="$inmes_imtxt{'outread'}" style="vertical-align: middle;" />~;
						}

						## for multi rec, and none opened
						if ($hasMultiRecs) {
							$countrecepients = 0;
							$countread = 0;
							foreach my $recname (split(/\,/, $musernameto)) {
								$countrecepients++;
								$imOpened = &checkIMS($recname, $messageid, 'messageopened');
								if ($imOpened) { $oneRead = 1; $countread++; }
							}
							if ($musernamecc) {
								foreach my $recname (split(/\,/, $musernamecc)) {
									$countrecepients++;
									$imOpened = &checkIMS($recname, $messageid, 'messageopened');
									if ($imOpened) { $oneRead = 1; $countread++; }
								}
							}
							if ($musernamebcc) {
								foreach my $recname (split(/\,/, $musernamebcc)) {
									$countrecepients++;
									$imOpened = &checkIMS($recname, $messageid, 'messageopened');
									if ($imOpened) { $oneRead = 1; $countread++; }
								}
							}
							if (!$oneRead) {
								$messageIcon = qq~<img src="$imagesdir/imclose2.gif" border="0" alt="$inmes_imtxt{'outmultinotread'}" style="vertical-align: middle;" />~;
								$callBack = qq~<span class="small"><a href="$scripturl?action=imshow;id=$messageid;caller=2">$inmes_imtxt{'multicallback'}</a> | </span>~;
							} elsif($countrecepients == $countread) {
								$messageIcon = qq~<img src="$imagesdir/imopen2.gif" border="0" alt="$inmes_imtxt{'outmultiread'}" style="vertical-align: middle;" />~;
							} elsif($countrecepients != $countread) {
								$messageIcon = qq~<img src="$imagesdir/imopen3.gif" border="0" alt="$inmes_imtxt{'outmultisomeread'}" style="vertical-align: middle;" />~;
								$callBack = qq~<span class="small"><a href="$scripturl?action=imshow;id=$messageid;caller=2">$inmes_imtxt{'multicallback'}</a> | </span>~;
							}
						}

					}
				}

				## switch action if opening a draft - want this sending to the 'send' screen
				my $actString = 'imshow';
				if ($action eq 'imdraft') { $actString = 'imsend'; }

				## if grouping, check bar here
				if ($stkmess && $sortBy ne 'gpdate' && $normDateSet && $viewBMess) {
					## sticky messages
					$normDateSet = 0;
					$MCContent .= qq~
				<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{'standart'}</span></td>
				</tr>
					~;
				}

				if ($stkmess && $sortBy ne 'gpdate' && $stkDateSet && $viewBMess && ($messageStatus =~ /g/ || $messageStatus =~ /a/)) {
					## sticky messages
					$stkDateSet = 0;
					$MCContent .= qq~
				<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{'important'}</span></td>
				</tr>
					~;
				}

				if ($sortBy eq 'gpdate' && ($latestDateSet && ($date - $mdate)/86400  > 1 ) && $counter > $counterCheck) {
					## 24 hours
					$latestDateSet = 0;
					if ($lastWeekSet) {
						$counterCheck = $counter;
						$uselegend = 'oneweek';
				$MCContent .= qq~
				<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{$uselegend}</span></td>
				</tr>
				~;
					}
				}

				if ($sortBy eq 'gpdate' && ($lastWeekSet && ($date - $mdate)/86400  > 7 ) && $counter > $counterCheck) {
					$lastWeekSet = 0;
					if ($twoWeeksSet) {
						$counterCheck = $counter;
						$uselegend = 'twoweeks';
				$MCContent .= qq~
				<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{$uselegend}</span></td>
				</tr>
				~;
					}
				}

				if ($sortBy eq 'gpdate' &&  ($twoWeeksSet && ($date - $mdate)/86400  > 14 )  && $counter > $counterCheck) {
					$twoWeeksSet = 0;
					if ($threeWeeksSet) {
						$counterCheck = $counter;
						$uselegend = 'threeweeks';
				$MCContent .= qq~
				<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{$uselegend}</span></td>
				</tr>
				~;
					}
				}

				if ($sortBy eq 'gpdate' && ($threeWeeksSet && ($date - $mdate)/86400  > 21  )  && $counter > $counterCheck) {
					$threeWeeksSet = 0;
					if ($monthSet)	{
						$counterCheck = $counter;
						$uselegend = 'fourweeks';
				$MCContent .= qq~<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{$uselegend}</span></td>
				</tr>
				~;
					}
				}

				if ($sortBy eq 'gpdate' && ($monthSet && ($date - $mdate)/86400  > 31  ) && $counter > $counterCheck) {
					$monthSet = 0;
					if ($gtMonthSet)	{
						$uselegend = 'older';
				$MCContent .= qq~
				<tr>
					<td class="titlebg"  width="100%" colspan="3"><span class="imgtitlebg">$im_sorted{$uselegend}</span></td>
				</tr>
				~;
					}
				}

				my $BCnew;
				if ($action eq 'im' && $viewBMess && ${$username}{'PMbcLastRead'} < $messageid && $username ne $musername) {
					$BCnew = qq~&nbsp;<img src="$imagesdir/new.gif" alt="" border="0" style="vertical-align: middle;" />~;
				}

				$MCContent .= qq~
		  <tr>
		    <td class="windowbg" align="left">$BCnew$messageIcon$messIcon<a href="$scripturl?action=$actString;caller=$callerid;id=$messageid">$msub</a></td>~;

				if ($action eq 'im') {
					if ($messageStatus eq 'g') {
						my ($guestName, $guestEmail) = split(/\ /, $musername);
						$guestName =~ s/%20/ /g;
						$usernameto = qq~$guestName<br />(<a href="mailto:$guestEmail">$guestEmail</a>)~;
					} else {
						&LoadUser($musername);
						$usernameto = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$musername}">${$uid.$musername}{'realname'}</a>~;
					}
					$MCContent .= qq~
					<td class="windowbg">$usernameto</td>~; #[inbox broadcast]
				}
				elsif ($action eq 'imoutbox') {
					if ($messageStatus eq 'gr') {
						my ($guestName, $guestEmail) = split(/\ /, $musernameto);
						$guestName =~ s/%20/ /g;
						$usernameto = qq~$guestName<br />(<a href="mailto:$guestEmail">$guestEmail</a>)~;
					}
					$MCContent .= qq~
				    <td class="windowbg">$usernameto</td>~; #[outbox]
				}
				elsif ($action eq 'imdraft') {
					if ($musernameto !~ /,/) { 
						&LoadUserDisplay($musernameto);
						if (!$yyUDLoaded{$musernameto}) { &LoadUser($musernameto); }
						$musernameto = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$musernameto}">${$uid.$musernameto}{'realname'}</a>~;
					}
					elsif ($musernameto =~ /,/) { $musernameto = qq~ \.\.\.~; }
					elsif ($musernamecc || $musernamecc =~ /,/ ) { $musernameto .= qq~ \.\.\.~; }
					elsif ($musernamebcc || $musernamebcc =~ /,/ ) { $musernameto .= qq~ \.\.\.~; }
					$MCContent .= qq~
				    <td class="windowbg">$musernameto</td>~; #[DRAFT]
				}
				elsif ($action eq 'imstorage') {
				   	if ($INFO{'viewfolder'} eq 'in' && $musername ne '') {
				   		if (!$yyUDLoaded{$musername})	{ &LoadUser($musername); }	# is to user
				    		$usernameto = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$musername}">${$uid.$musername}{'realname'}</a>~;
						$MCContent .= qq~
					<td class="windowbg">$usernameto</td>~; #[store IN]
					} elsif ($INFO{'viewfolder'} eq 'out') {
						if ($messageStatus eq 'gr') {
							my ($guestName, $guestEmail) = split(/\ /, $musernameto);
							$guestName =~ s/%20/ /g;
							$usernameto = qq~$guestName<br />(<a href="mailto:$guestEmail">$guestEmail</a>)~;
						}
				    		$MCContent .= qq~
					<td class="windowbg">$usernameto</td>~; #[store OUT]
				    	} else {
				   		if (!$yyUDLoaded{$musername})	{ &LoadUser($musername); }	# is to user
				    		$usernamefrom = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$musername}">${$uid.$musername}{'realname'}</a>~;
						if ($messageStatus eq 'gr') {
							my ($guestName, $guestEmail) = split(/\ /, $musernameto);
							$guestName =~ s/%20/ /g;
							$usernameto = qq~$guestName<br />(<a href="mailto:$guestEmail">$guestEmail</a>)~;
						}
				    		$MCContent .= qq~
					<td class="windowbg">$usernamefrom / $usernameto</td>~; #[store OTHER]
					}
				}
				$MCContent .= qq~
			<td class="windowbg">$mydate</td>
			    ~;

				undef $quotecount;
				undef $codecount;
				$quoteimg = '';
				$codeimg = '';

				if ($immessage =~ /\[quote(.*?)\]/isg) {
					$quoteimg = qq~<img src=$imagesdir\/quote.gif alt="$inmes_imtxt{'69'}" \/>&nbsp;~;
					$immessage =~ s/\[quote(.*?)\](.+?)\[\/quote\]//ig;
				}
				if ($immessage =~ /\[code\]/isg) {
					$codeimg = qq~<img src=$imagesdir\/code1.gif alt="$inmes_imtxt{'84'}" \/>&nbsp;~;
					$immessage =~ s/\[code\](.+?)\[\/code\]//ig;
				}
				$immessage =~ s~<br />~&nbsp;~g;
				$immessage =~ s~&nbsp;&nbsp;~ ~g;
				&ToChars($immessage);
				$immessage =~ s~\[.*?\]~~g;
				&FromChars($immessage);
				$convertstr = $immessage;
				$convertcut = 100;
				&CountChars;
				my $immessage = $convertstr;
				&ToChars($immessage);
				if ($cliped) { $immessage .= "..."; }
				$immessage = qq~$quoteimg$codeimg $immessage~;
				$immessage = &Censor($immessage);

				if ($UseMenuType != 1) { $sepa = '&nbsp;|&nbsp;'; }
				else { $sepa = $menusep; }
				## inline list for msg
				my ($actionsMenu, $actionsMenuselect, $storefolderView);
				## build actionsMenu for output
				if ($action eq 'im' && !$viewBMess) { $actionsMenu = qq~<a href="$scripturl?action=imsend;caller=$callerid;quote=1;to=$useraccount{$musername};id=$messageid">$inmes_txt{'145'}</a>$sepa<a href="$scripturl?action=imsend;caller=$callerid;reply=1;to=$useraccount{$musername};id=$messageid">$inmes_txt{'146'}</a>$sepa<a href="$scripturl?action=imsend;caller=$callerid;forward=1;quote=1;id=$messageid">$inmes_txt{'147'}</a>$sepa<a href="$scripturl?action=imremove;caller=$callerid;id=$messageid" onclick="return confirm('$inmes_txt{'770'}')">$inmes_txt{'remove'}</a>~; }
				## broadcast messages can only be quoted on!
				elsif ($action eq 'im' && $viewBMess) {
					if ($messageStatus eq 'g') {
						$actionsMenu = qq~<a href="$scripturl?action=imsend;caller=$callerid;quote=1;replyguest=1;id=$messageid">$inmes_txt{'146'}</a>~;
					} else {
						$actionsMenu = qq~<a href="$scripturl?action=imsend;caller=$callerid;quote=1;id=$messageid">$inmes_txt{'145'}</a>$sepa<a href="$scripturl?action=imsend;caller=$callerid;reply=1;to=$useraccount{$musername};id=$messageid">$inmes_txt{'146'}</a>~;
					}
					if ($iamadmin || $username eq $musername) { $actionsMenu .= qq~$sepa<a href="$scripturl?action=imremove;caller=$callerid;id=$messageid" onclick="return confirm('$inmes_txt{'770'}')">$inmes_txt{'remove'}</a>~; $deleteButton = 1; }
				}
				## for others
				elsif ($action eq 'imdraft') { $actionsMenu = qq~<a href="$scripturl?action=imremove;caller=$callerid;id=$messageid" onclick="return confirm('$inmes_txt{'770'}')">$inmes_txt{'remove'}</a>~; }
				elsif ($action eq 'imoutbox') { $actionsMenu = qq~$callBack<a href="$scripturl?action=imremove;caller=$callerid;id=$messageid" onclick="return confirm('$inmes_txt{'770'}')">$inmes_txt{'remove'}</a>~; }
				else {
					if ($action eq 'imstorage') { $storefolderView = ";viewfolder=$INFO{'viewfolder'}"; }
					if ($messageStatus =~ /gr/) {
						$actionsMenu = qq~<a href="$scripturl?action=imremove;caller=$callerid;id=$messageid$storefolderView" onclick="return confirm('$inmes_txt{'770'}')">$inmes_txt{'remove'}</a>~;
					} else {
						$actionsMenu = qq~$callBack<a href="$scripturl?action=imsend;caller=$callerid;quote=1;to=$useraccount{$musername};id=$messageid">$inmes_txt{'145'}</a>$sepa<a href="$scripturl?action=imsend;caller=$callerid;reply=1;to=$useraccount{$musername};id=$messageid">$inmes_txt{'146'}</a>$sepa<a href="$scripturl?action=imsend;caller=$callerid;forward=1;id=$messageid">$inmes_txt{'147'}</a>$sepa<a href="$scripturl?action=imremove;caller=$callerid;id=$messageid$storefolderView" onclick="return confirm('$inmes_txt{'770'}')">$inmes_txt{'remove'}</a>~;
					}
				}
				if (!$viewBMess || ($viewBMess && ($iamadmin || $username eq $musername))) {
					$actionsMenuselect = qq~<input type="checkbox" name="message$counter" class="windowbg" value="1" style="cursor: hand;" /> $inmes_txt{'delete'}~;
					if ($action ne 'imdraft' && !$viewBMess) { $actionsMenuselect .= qq~/$inmes_imtxt{'store'}~; }
				}
				$MCContent .= qq~
			</tr>
			<tr><td colspan="3" height="21" class="windowbg2">
		  		~;

		  		if (($enable_PMcontrols && ${$uid.$username}{'pmviewMess'} eq 'on') || (!$enable_PMcontrols && !$enable_PMviewMess) )	{
		  			if ($immessage =~ /\#nosmileys/isg || $ns =~ "NS") { $immessage =~ s/\#nosmileys//isg; }
					else {$message = $immessage; &MakeSmileys; $immessage = $message; }
		  			$MCContent .= qq~
		$immessage<br /><br />
		<hr width="100%" class="hr" />
				~;	
				}
				$MCContent .= qq~
				<div style="float: left; text-align: left; width: 65%;"><span class="small">$actionsMenu</span></div>
				<div style="float: right; text-align: right; width: 35%;"><span class="small">$actionsMenuselect</span></div>
			</td></tr>
			~;
			$acount++;
			if ($acount == $stkmess +1) { $normDateSet = 1; }
			} # end of message loop ##################################

			## limiter bar
			if ($enable_imlimit == 1 && !$viewBMess) {
				my $impercent = 0;
				my $imbar = 0;
				my $imrest = 0;
				my $messageCounter = @dimmessages;
				if ($action eq 'im' && !$viewBMess) {
					if ($messageCounter != 0 && $numibox != 0) {
						$impercent = int(100 / $numibox * $messageCounter);
						$imbar = int(200 / $numibox * $messageCounter);
					}

					$intext = qq~($inmes_imtxt{'13'} $messageCounter $inmes_imtxt{'01'} $numibox $inmes_imtxt{'19'} $inmes_txt{'inbox'} $inmes_txt{'folder'})~;
				}

				elsif ($action eq 'imoutbox') {
					if ($messageCounter != 0 && $numobox != 0) {
						$impercent = int(100 / $numobox * $messageCounter);
						$imbar = int(200 / $numobox * $messageCounter);
					}
					$intext = qq~($inmes_imtxt{'13'} $messageCounter $inmes_imtxt{'01'} $numobox $inmes_imtxt{'19'} $inmes_txt{'outbox'} $inmes_txt{'folder'})~;
				}

				elsif ($action eq 'imdraft') {
					if ($messageCounter != 0 && $numdraft != 0) {
						$impercent = int(100 / $numdraft * $messageCounter);
						$imbar = int(200 / $numdraft * $messageCounter);
					}
					$intext = qq~($inmes_imtxt{'13'} $messageCounter $inmes_imtxt{'01'} $numdraft $inmes_imtxt{'19'} $inmes_txt{'draft'} $inmes_txt{'folder'})~;
				}
				elsif ($action eq 'imstorage') {
					if ($messageCounter != 0 && $numstore != 0) {
						$impercent = int(100 / $numstore * $messageCounter);
						$imbar = int(200 / $numstore * $messageCounter);
					}
					$intext = qq~($inmes_imtxt{'13'} $messageCounter $inmes_imtxt{'01'} $numstore $inmes_imtxt{'19'} $inmes_txt{'storage'} $inmes_txt{'folder'})~;
				}
				$imrest = 200 - $imbar;
				if ($imbar > 200) { $imbar  = 200; }
				if ($imrest <= 0) { $dorest = ''; }
				else { $dorest = qq~<img src="$imagesdir/usageempty.gif" height="8" width="$imrest" align="middle" alt="" />~; }
				$imbargfx = qq~$inmes_imtxt{'67'}:&nbsp;<img src="$imagesdir/usage.gif" align="middle" alt="" /><img src="$imagesdir/usagebar.gif" height="8" width="$imbar" align="middle" alt="" />$dorest<img src="$imagesdir/usage.gif" align="middle" alt="" />&nbsp;$impercent&nbsp;%&nbsp;<br />~;
			} else {
				$intext = qq~&nbsp;~;
				$imbargfx = qq~&nbsp;~;
			}
			unless ($action eq 'imstorage' && $INFO{'viewfolder'} eq '') { 
				$removeButton = qq~<input type="submit" name="imaction" value="$inmes_txt{'remove'}" class="button" onclick="return confirm('$inmes_txt{'delmultipms'}');" />~;
				$inmes_txt{'777'} =~ s/REMOVE/$removeButton/;
				$removeButton = $inmes_txt{'777'};
			}
			if (@dimmessages) {
				$MCContent .= qq~
				<tr>
					<td class="titlebg" colspan="3" align="right" height="21" >
				~;
				if (!$viewBMess) {
					$MCContent .= qq~
					<span  class="small"><b>$imbargfx&nbsp;$intext<br /><br /></b></span>~;
					unless ($action eq 'imstorage' && $INFO{'viewfolder'} eq '') { $MCContent .= $movebutton; }
				}
				if (!$viewBMess || ($viewBMess && ($iamadmin|| $deleteButton))) {
					$MCContent .= qq~ $removeButton~;
				}
				$MCContent .= qq~
					</td>
				</tr>
				~;
			}

		if (@dimmessages && (!$viewBMess || ($viewBMess && ($iamadmin || $deleteButton)))) {
			unless ($action eq 'imstorage' && $INFO{'viewfolder'} eq '') {
				$MCContent .= qq~
				<tr>
					<td class="windowbg" colspan="3" align="right">
					<div style="float: right;">
						<i>$inmes_txt{'737'}</i>&nbsp;<input type="checkbox" onclick="if (this.checked) checkAll(); else uncheckAll();" />
					</div>
					<br />
					<script language="JavaScript1.2" type="text/javascript">
					<!--
					function checkAll() {
						for (var i = 0; i < document.searchform.elements.length; i++) {
							document.searchform.elements[i].checked = true;
						}
					}
					function uncheckAll() {
						for (var i = 0; i < document.searchform.elements.length; i++) {
						document.searchform.elements[i].checked = false;
						}
					}
					// -->
					</script>
			 		~;
				$MCContent .= qq~
					</td>
				</tr>
				~;
			}
		}
		$MCContent .= qq~
		</table>
		</form>
		~;
	}
}


## load user's buddylist and show status of said members
sub LoadBuddyList {

	# Load background color list.
	my @cssvalues = ('windowbg2', 'windowbg');
	my $cssnum = scalar @cssvalues;
	my $counter = 0;

	my @buddies = split('\|',${$uid.$username}{'buddylist'}) ;
	chomp @buddies;
	$buddiesCurrentStatus = qq~
		<table cellspacing="1" cellpadding="1" width="100%" align="center" border="0">
		<tr class="catbg"><td align="center">$profile_txt{'68a'}</td><td align="center">$profile_txt{'68b'}</td><td align="center"><img src="$imagesdir/imclose.gif" border="0" alt="$profile_txt{'69a'}" /></td><td align="center"><img src="$imagesdir/email.gif" border="0" alt="$profile_txt{'69'}" /></td><td align="center"><img src="$imagesdir/www.gif" border="0" alt="$profile_txt{'96'}" /></td></tr>
	~;
	if (!@logentries) { &usersOnline; }
	foreach my $buddyname (@buddies)	{
		$css = $cssvalues[($counter % $cssnum)];
		my ($buddyrealname);
		my ($online, $buddyemail, $buddypm, $buddywww) = '&nbsp;';
		if (-e "$memberdir/$buddyname.vars") {
			&LoadUser($buddyname);
			$online = &userOnLineStatus($buddyname);
			$buddyrealname = ${$uid.$buddyname}{'realname'};
			$usernamelink = $link{$buddyname};
		if (${$uid.$buddyname}{'hidemail'} eq "checked" && !$iamadmin && $allow_hide_email eq 1) {
			$buddyemail = qq~<img src="$imagesdir/lockmail.gif" alt="Hidden Email" />~;
		} else {
			$buddyemail = qq~<a href="$scripturl?action=mailto;username=$useraccount{$buddyname}" target="_blank"><img src="$imagesdir/email.gif" border="0" alt="$profile_txt{'889'} ${$uid.$buddyname}{'email'}" /></a>~;
		}
		$buddypm = qq~<a href="$scripturl?action=imsend;to=$useraccount{$buddyname}"><img src="$imagesdir/imclose.gif" border="0" alt="$profile_txt{'688'} $buddyrealname" /></a>~;
		if (${$uid.$buddyname}{'weburl'}) { $buddywww = qq~<a href="${$uid.$buddyname}{'weburl'}" target="_blank"><img src="$imagesdir/www.gif" border="0" alt="${$uid.$buddyname}{'webtitle'}" /></a>~; }
		} else {
			$usernamelink = qq~<b>$buddyname</b> ($maintxt{'470a'})~;
		}
		$buddiesCurrentStatus .= qq~<tr class="$css"><td align="left">$usernamelink</td><td align="center">$online</td><td align="center">$buddypm</td><td align="center">$buddyemail</td><td align="center">$buddywww</td></tr>~;
		$counter++;
	}
	$buddiesCurrentStatus .= "</table>";
	return $buddiesCurrentStatus;
}

1;