<?_code

 $title = $ML{'.title'};
 $body = "";

 LJ::set_active_crumb('friendsfilter');
 
 if ($FORM{'mode'} eq "view") 
 {
     my $user = lc($FORM{'user'});
     my $filter = 0;
     foreach my $k (keys %FORM) {
         next unless ($k =~ /^bit_(\d+)$/);
         my $bit = $1;
         next if ($bit < 1 || $bit > 30);
         $filter |= (1 << $bit);
     }
     my $extra = "?filter=$filter";

     return BML::redirect("$LJ::SITEROOT/users/$user/friends${extra}");
 }

 my $remote = LJ::get_remote();

 unless ($remote) { $body .= "<?needlogin?>"; return; }

 my %res;
 # FIXME: make this use LJ::Protocol::do_request 
 LJ::do_request({ 'mode' => 'getfriendgroups',
                  'ver'  => $LJ::PROTOCOL_VER,
                  'user' => $remote->{'user'}, },
                \%res, { 'noauth' => 1, 'userid' => $remote->{'userid'} });
 
 
 unless ($res{'frgrp_maxnum'}) {
     $body = "<?h1 $ML{'.error.nogroups.header'} h1?><?p $ML{'.error.nogroups'} p?>";
     return;
 }

 my %group;
 foreach $k (keys %res) {
     if ($k =~ /^frgrp_(\d+)_name/) {
         $group{$1}->{'name'} = $res{$k};
     } 
     elsif ($k =~ /^frgrp_(\d+)_sortorder/) {
         $group{$1}->{'sortorder'} = $res{$k};
     } 
 }
 
 $body .= "<?h1 $ML{'.select.header'} h1?><?p $ML{'.select'} p?>";
 $body .= "<form method='post' style='display: inline' action='filter.bml'>\n";
 $body .= LJ::html_hidden("user", $remote->{'user'},
                          "mode", "view");
 $body .= "<div style='margin-left: 30px'>";
 
 foreach my $g (sort { $group{$a}->{'sortorder'} <=> $group{$b}->{'sortorder'} } keys %group)
 {
     my $url = "$LJ::SITEROOT/users/$remote->{'user'}/friends/" . LJ::eurl($group{$g}->{'name'});
     $body .= "<input type='checkbox' value='1' name=\"bit_$g\" /> <a href=\"$url\">" . LJ::ehtml($group{$g}->{'name'}) . "</a><br />\n";
 }

 $body .= "<input type='submit' value=\"$ML{'.submit'}\"> <input type='reset' value=\"$ML{'.reset'}\"></div>";
 $body .= "<?p " . BML::ml('.editgroups', { 'link' => "<a href='editgroups.bml'>$ML{'/friends/editgroups.bml.title'}</a>" }) . " p?>";
 $body .= "</form>";

 return;

_code?><?page
title=><?_code return $title; _code?>
body=><?_code return $body; _code?>
page?><?_c <LJDEP>
link: htdocs/users, htdocs/friends/editgroups.bml
post: htdocs/friends/filter.bml
</LJDEP> _c?>
