<?_c
# This code was forked from the LiveJournal project owned and operated
# by Live Journal, Inc. The code has been modified and expanded by
# Dreamwidth Studios, LLC. These files were originally licensed under
# the terms of the license supplied by Live Journal, Inc, which can
# currently be found at:
#
# http://code.livejournal.org/trac/livejournal/browser/trunk/LICENSE-LiveJournal.txt
#
# In accordance with the original license, this code and all its
# modifications are provided under the GNU General Public License.
# A copy of that license can be found in the LICENSE file included as
# part of this distribution.
_c?>
<?page
body<=
<?_code
{
    use strict;
    use vars qw($title $body $head %GET %POST);
    use LJ::NotificationInbox;
    use LJ::Event;

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

    my $remote = LJ::get_remote()
        or return "<?needlogin?>";

    return $ML{'.error.not_ready'} unless $remote->can_use_esn;

    LJ::need_res(qw(
                  js/6alib/core.js
                  js/6alib/dom.js
                  js/6alib/view.js
                  js/6alib/datasource.js
                  js/6alib/checkallbutton.js
                  js/6alib/selectable_table.js
                  js/6alib/httpreq.js
                  js/6alib/hourglass.js
                  js/esn_inbox.js
                  stc/esn.css
                  stc/lj_base.css
                  ));

    my $formauth = LJ::form_auth();

    # get the user's inbox
    my $inbox = $remote->notification_inbox
        or return LJ::error_list( BML::ml('.error.couldnt_retrieve_inbox', { 'user' => $remote->{user} }) );

    # 2 instances of action buttons
    # map each to one variable
    my @buttons = qw{markRead markUnread delete markAllRead deleteAll};
    foreach my $button (@buttons) {
        for (my $i=1; $i<=2; $i++) {
            my $sfx_button = $button . "_" . $i;
            $GET{$button} = $GET{$sfx_button} if($GET{$sfx_button} && !$GET{$button});
            $POST{$button} = $POST{$sfx_button} if($POST{$sfx_button} && !$POST{$button});
        }
    }

    # Take a supplied filter but default it to undef unless it is valid
    my $view = $POST{view} || $GET{view} || undef;
    $view = undef if $view eq 'archive' && ! LJ::is_enabled('esn_archive');
    $view = undef if $view && !LJ::NotificationInbox->can("${view}_items");

    my $itemid = $view eq "singleentry" ? int( $POST{itemid} || $GET{itemid} || 0 ) : 0;

    # Bolds the selected View/Folder
    my $selected_folder = $view || 'all';
    $selected_folder = "entrycomment" if $selected_folder eq "singleentry";

    $selected_folder = qq(
        <style>
            .filterlink_$view {display: none;}
            .entry-tags {text-align: right; font-style: italic;}
        </style>
        );
    $head = $selected_folder;

    # get events sitting in inbox
    my @notifications = $inbox->items;

    my @errors;

    if (LJ::did_post()) {

        # operate on notices by default but switch if view parameter specified
        my $nitems = \@notifications;
        my $name = "all";
        if ($view) {
            my @items = eval "\$inbox->${name}_items";
            push @items, $inbox->usermsg_sent_items;
            $nitems = \@items;
        }

        if ($POST{markAllRead}) {
            $inbox->mark_all_read( $view, itemid => $itemid );
        } elsif ($POST{deleteAll}) {
            $inbox->delete_all( $view, itemid => $itemid );
        } else {
            # go through each item and see if it's checked
            foreach my $item (@$nitems) {
                my $qid = eval { $item->qid } or next;
                my $checked = $POST{"${name}_Check-$qid"};
                next unless $checked;

                if ($POST{markRead}) {
                    $item->mark_read;
                } elsif ($POST{markUnread}) {
                    $item->mark_unread;
                } elsif ($POST{delete}) {
                    $item->delete;
                }
            }

            # reload inbox after making changes
            @$nitems = eval "\$inbox->${name}_items";
        }
    }

    # Allow bookmarking to work without Javascript
    # or before JS events are bound
    if ($GET{bookmark_off} && $GET{bookmark_off} =~ /^\d+$/) {
        push @errors, $ML{'.error.max_bookmarks'}
            unless $inbox->add_bookmark($GET{bookmark_off});
    }
    if ($GET{bookmark_on} && $GET{bookmark_on} =~ /^\d+$/) {
        $inbox->remove_bookmark($GET{bookmark_on});
    }

    # Pagination
    my $page = int($POST{page} || $GET{page});

    $body .= LJ::error_list(@errors) if (@errors);

    my $viewarg = $view  ? "&view=$view" : "";
    my $itemidarg = $itemid ? "&itemid=$itemid" : "";

    # Inbox Nav
    $body .= qq{
        <table summary='' id="table_inbox" style="width: 100%"><tr><td id="table_inbox_folders" valign="top" style="padding-right: 12px">};
    $body .= LJ::Widget::InboxFolderNav->render( 'page' => 1, 'view' => $view );

    $body .= qq{
        </td>
        <td width="1" height="100%" style="border-left: 1px solid #ccc"><img src="$LJ::IMGPREFIX/spacer.gif" alt="" /></td>
        <td id="table_inbox_messages" valign="top" style="padding-left: 10px; width: 100%;">
            <div class="inbox_newitems pkg">
                <span class="esnlinks" style="float: left"><a href="$LJ::SITEROOT/inbox/?page=$page$viewarg$itemidarg" id="RefreshLink"><?_ml inbox.refresh _ml?></a> |
                    <a href="$LJ::SITEROOT/manage/settings/?cat=notifications"><?_ml inbox.manage_settings _ml?></a></span>
            </div>

    };

    # Filter by view if specified
    my @all_items;
    if ($view) {
        if ( $view eq "singleentry" ) {
            @all_items = eval "\$inbox->${view}_items( $itemid )";
        } else {
            @all_items = eval "\$inbox->${view}_items";
        }
    } else {
        @all_items = $inbox->all_items;
    }

    my $itemcount = scalar @all_items;

    $body .= LJ::error_list( $@ ) if $@;

    # Pagination
    $page = int($POST{page} || $GET{page});
    
    $body .= LJ::Widget::InboxFolder->render(
                     folder  => "all",
                     reply_btn => 1,
                     expand    => $GET{expand},
                     inbox     => $inbox,
                     page      => $page,
                     view      => $view,
                     mode      => $GET{mode},
                     items     => \@all_items,
                     itemid    => $itemid,
              );

    # Repeat refresh/manage links if we have more than a few items (15 max per page)
    $body .= qq{
            <div class="inbox_newitems pkg">
                <span class="esnlinks" style="float: left"><a href="$LJ::SITEROOT/inbox/?page=$page$viewarg$itemidarg"><?_ml inbox.refresh _ml?></a> |
                    <a href="$LJ::SITEROOT/manage/settings/?cat=notifications"><?_ml inbox.manage_settings _ml?></a></span>
            </div>
    } if $itemcount > 10;

    $body .= qq{
        </td></tr></table>
    };

    # send the i18n variables to the js page context
    $body .= "<script type='text/javascript'>\n";
    $body .= "expanded = '$ML{'widget.inbox.notification.expanded'}';\n";
    $body .= "collapsed = '$ML{'widget.inbox.notification.collapsed'}';\n";
    $body .= "add_bookmark = '$ML{'widget.inbox.notification.add_bookmark'}';\n";
    $body .= "rem_bookmark = '$ML{'widget.inbox.notification.rem_bookmark'}';\n";
    $body .="</script>\n"; $body .= "</p>\n";


    return $body;
}
 _code?>
<=body
title=><?_code return $title; _code?>
head<=

<?_code return $head; _code?>

<script>
LJ_cmtinfo = {};
LJ_cmtinfo['disableInlineDelete'] = 1;
var pageNum;
var cur_folder = '<?_code return $POST{view} || $GET{view} || undef; _code?>';
var itemid = <?_code return int( $POST{itemid} || $GET{itemid} || 0 ) _code?>;

document.addEventListener("DOMContentLoaded", setup, cur_folder);

var tableview;
var checkallButton;
/* Can have multiple tables or folders displayed on the same page */
var folders = ['all'];

function setup (e) {
    if (! Site.has_remote) return;

    for (var i=0; i<folders.length; i++) {
        var name = folders[i];
        tableview = new View();

        tableview.init({ "view": $(name + "_Table"), "selectedClass": "selected" });

        // 2 instances of action buttons
        for (var i=1; i<=2; i++) {
            checkallButton = new CheckallButton();
            checkallButton.init({
                  "class": "InboxItem_Check",
                  "button": $(name + "_CheckAll_" + i),
                  "parent": tableview.getView()
            });
            if( checkallButton.button )
                checkallButton.button.checked = false;
        }
    }

// 2 instances of action buttons
for (var i=1; i<=2; i++) {
    if( $("Page_Prev_"+i) )
        DOM.addEventListener($("Page_Prev_"+i), "click", Page_Prev);
    if( $("Page_Next_"+i) )
        DOM.addEventListener($("Page_Next_"+i), "click", Page_Next);
}

if ($("pageNum")) pageNum = parseInt($("pageNum").value, 10);
}

function xtra_args () {
    var args = '';
    var view = $("inbox_view").value;
    if (view) args += "&view=" + view;
    if (itemid) args += "&itemid="+itemid;
    return args;
}

function Page_Prev (e) {
    if (pageNum) {
        var args = xtra_args();
        window.location.href = "<?siteroot?>/inbox/?page=" + (pageNum - 1) + args;
    }
}

function Page_Next (e) {
    if (pageNum) {
        var args = xtra_args();
        window.location.href = "<?siteroot?>/inbox/?page=" + (pageNum + 1) + args;
    }
}

</script>

<=head

bodyopts=><?_code return "id='page_inbox' class='self_wrap'" _code?>
page?>
