<?page
title=>Theme Previews
body<=
<?_code
{
    use strict;
    use vars qw(%GET %POST);

    LJ::set_active_crumb('themes');

    my $ret;
    my $dbr = LJ::get_db_reader();

    my $remote = LJ::get_remote();

    return "<?h1 Login Required h1?><?p Before you customize your journal, you must first <a href='/login.bml?ret=1'>login</a>. p?>"
        unless $remote;

    my @journals = ($remote->{'user'});
    push @journals, LJ::get_shared_journals($remote);
    my $journal = $GET{'journal'} || $remote->{'user'};
    unless (grep { $_ eq $journal } @journals) {  return BML::redirect("/customize/");  }

    $ret .= "<p>[&lt;&lt; <a href='/customize/?journal=$journal'>Back</a>]</p>";

    my $u = $remote;
    $u = LJ::load_user($journal) unless $journal eq $remote->{'user'};
    my $userid = $u->{'userid'};

    LJ::load_user_props($u, "stylesys", "s2_style");
    $u->{'stylesys'} ||= 1;
    my $pub = LJ::S2::get_public_layers();
    my $userlay = {};   # TODO: add API call to fetch these
    my %style = LJ::S2::get_style($u->{'s2_style'});

    return "S2 required" unless $u->{'stylesys'} == 2 && $style{'layout'};

    # get themes for this layer
    my @themes = LJ::S2::get_layout_themes([$pub, $userlay], $style{'layout'});

    # make the context, without the theme
    my @layers;
    foreach (qw(core i18nc layout i18n)) {
        push @layers, $style{$_} if $style{$_};
    }
    LJ::S2::load_layers(@layers, map { $_->{'s2lid'} } @themes);
    
    my $cleaner = new HTMLCleaner ('output' => sub { $ret .= $_[0]; });
    my $out_straight = sub { $ret .= $_[0]; };
    my $out_clean = sub { $cleaner->parse($_[0]); };

    $LJ::S2::CURR_PAGE = undef;

    foreach my $t (0, @themes) {
        my $id = ref $t ? $t->{'s2lid'} : 0;
        my $name = ref $t ? LJ::eall($t->{'name'}) : "Layout Default";
        my $ctx = S2::make_context(@layers, $id);
        LJ::S2::escape_context_props($ctx);
        LJ::S2::populate_system_props($ctx);

        S2::set_output(sub {});  # printing suppressed
        S2::set_output_safe(sub {}); 
        eval { S2::run_code($ctx, "prop_init()"); };
        S2::set_output($out_straight);
        S2::set_output_safe($out_straight);
        $ret .= "<?h1 $name h1?>";
        $ret .= "<div>";
        eval { S2::run_code($ctx, "print_theme_preview()"); };
        $ret .= "</div>";

    }
    $cleaner->eof if $cleaner;  # flush any remaining text/tag not yet spit out

    return $ret;

}
_code?>
<=body
page?>
