%#-- Begin HTML --#
<& '/widgets/wrappers/sharky/header.mc',
   title   => "$disp Profile",
   context => "Admin | Profile | $disp | $crumb"
&>
% if (ENABLE_WYSIWYG) {
%     # WYSIWYG code here, only used if textarea is in the page with wysiwyg on.
<& /widgets/wysiwyg/load.mc &>
% }
<form method="post" action="<% $r->uri %>" name="cont_profile" id="cont_profile" onsubmit="return confirmChanges('cont_profile')">
<%perl>;
my ($num_fields, $meta, $all, $num);

# Output the primary fields.
$m->comp(
    '/widgets/wrappers/sharky/table_top.mc',
    caption => "Properties",
    number  => ++$num
);

$m->comp(
    '/widgets/profile/displayFormElement.mc',
    objref   => $comp,
    readOnly => $no_edit || defined $id,
    key      => 'key_name'
);

$m->comp(
    '/widgets/profile/dumpRemainingFields.mc',
    objref     => $comp,
    readOnly   => $no_edit,
    fieldsUsed => $exclude
);

if (defined $id) {
    $m->comp('/widgets/profile/hidden.mc',
             value => $id,
             name  => 'element_type_id');
    $m->comp(
        '/widgets/profile/text.mc',
        disp => 'Content Type',
        value => $type,
        readOnly => 1,
    );
} else {
    # Output the Element Type Select list.
    $m->comp(
        '/widgets/profile/select.mc',
        options    => $biz_class_opts,
        disp       => 'Content Type',
        name       => 'biz_class_id',
        req       => 1,
        readOnly  => $no_edit,
        localize  => 1,
    );
    if (my $site_cx_id = $c->get_user_cx(get_user_id)) {
        $m->comp(
            '/widgets/profile/hidden.mc',
            value => $site_cx_id,
            name  => 'formBuilder|add_site_id_cb'
        );
    }
}

$m->comp('/widgets/wrappers/sharky/table_bottom.mc');

# Get the group's membership listed
$m->comp(
    '/widgets/grp_membership/grp_membership.mc',
    grp_class => 'Bric::Util::Grp::ElementType',
    obj       => $comp,
    formName  => 'cont_profile',
    no_edit   => $no_edit,
    widget    => $key_name,
    no_cb     => 1,
    num       => ++$num
);

if (defined $id) {
    if ($comp->is_top_level) {
        my @elem_sites = $comp->get_sites;
        if (!@$sites || @elem_sites > 1 || @$sites > 1) {
            my $site_sub = sub {
                my $siteid = $_[0]->get_id;
                if ($_[1] eq 'primary') {
                    $m->scomp(
                        '/widgets/select_object/select_object.mc',
                        object     => 'output_channel',
                        field      => 'name',
                        constrain  => { site_id => $siteid, active => 1 },
                        no_persist => 1,
                        name       => "primary_oc_site_$siteid",
                        useTable   => 0,
                        selected   => $comp->get_primary_oc_id($siteid) || '',
                    );
                }
            };

            $m->comp(
                '/widgets/wrappers/sharky/table_top.mc',
                caption => 'Sites',
                number => ++$num,
            );
            $m->comp(
                '/widgets/listManager/listManager.mc',
                object         => 'site',
                userSort       => 0,
                def_sort_field => 'name',
                objs           => scalar $comp->get_sites,
                addition       => undef,
                fields         => [qw(name description primary)],
                field_titles   => { primary => 'Primary Output Channel'},
                field_values   => $site_sub,
                profile        => undef,
                select         => $sel_sub,
            );

            my %sites = map { $_->get_id => 1 } @elem_sites;
            my @available_sites = grep {
                !$sites{$_->get_id} && chk_authz($_, EDIT, 1)
            } Bric::Biz::Site->list({
                active            => 1,
                output_channel_id => 'not null',
            });

            if (@available_sites) {
                $m->print(qq{<div class="actions">\n});
                $m->comp(
                    '/widgets/select_object/select_object.mc',
                    object     => 'site',
                    field      => 'name',
                    objs       => \@available_sites,
                    no_persist => 1,
                    name       => 'formBuilder|add_site_id_cb',
                    default    => ['' => 'Add Site'],
                    js         => "onChange='submit()'",
                    useTable   => 0,
                );
                $m->print("</div>\n");
            }
            $m->comp('/widgets/wrappers/sharky/table_bottom.mc');
        }

        # Manage Output Channels.
        my %got_ocs = map { $_->get_id => 1 } $comp->get_output_channels;
        my @available_ocs;
        foreach my $site ($comp->get_sites) {
            push @available_ocs, grep {!$got_ocs{$_->get_id}}
                Bric::Biz::OutputChannel->list({
                    site_id => $site->get_id,
                    active  => 1
                });
        }

        if (scalar keys %got_ocs > 1 || @available_ocs) {
            my %field_subs = (
                enabled => sub {
                    my $ocid = $_[0]->get_id;
                    return 'Yes'
                        if $comp->get_primary_oc_id($_[0]->get_site_id) == $ocid;
                    $m->scomp(
                        '/widgets/profile/checkbox.mc',
                        name     => 'enabled',
                        value    => $ocid,
                        checked  => $_[0]->is_enabled,
                        useTable => 0
                    );
                },
            );
            my $oc_sub = sub {
                my $code = $field_subs{$_[1]} or return;
                $code->(shift);
            };

            my %poc_ids = map { $comp->get_primary_oc_id($_->get_id) => 1 }
                $comp->get_sites;

            my $oc_sel_sub = sub {
                return if $poc_ids{$_[0]->get_id};
                return ['Delete', 'rem_oc'];
            };

            $m->comp(
                '/widgets/wrappers/sharky/table_top.mc',
                caption => 'Output Channels',
                number  => ++$num,
            );

            my $field_titles = { enabled => 'Enabled' };
            my $fields       = [qw(name description site enabled)];
            if (@elem_sites == 1 && @$sites <= 1) {
                push @$fields, 'primary';
                $field_titles->{primary} = 'Primary';
                my $site_id = $elem_sites[0]->get_id;
                my $prim_id = $comp->get_primary_oc_id($site_id);
                $field_subs{primary} = sub {
                    my $oc_id = shift->get_id;
                    $m->scomp(
                        '/widgets/profile/radio.mc',
                        name     => "primary_oc_site_$site_id",
                        value    => $oc_id,
                        checked  => $oc_id == $prim_id,
                        useTable => 0
                    );
                };
            }

            $m->comp(
                '/widgets/listManager/listManager.mc',
                object         => 'output_channel',
                userSort       => 0,
                def_sort_field => 'name',
                objs           => scalar $comp->get_output_channels,
                addition       => undef,
                fields         => $fields,
                field_titles   => $field_titles,
                field_values   => $oc_sub,
                profile        => undef,
                select         => $oc_sel_sub,
            );

            if (@available_ocs) {
                $m->print(qq{<div class="actions">\n});
                $m->comp(
                    '/widgets/select_object/select_object.mc',
                    object     => 'output_channel',
                    objs       => \@available_ocs,
                    field      => 'name',
                    no_persist => 1,
                    getter     => $oc_name_getter,
                    name       => 'formBuilder|add_oc_id_cb',
                    default    => ['' => 'Add Output Channel'],
                    js         => "onChange='submit()'",
                    useTable   => 0,
                );
                $m->print("</div>\n");
            }
            $m->comp('/widgets/wrappers/sharky/table_bottom.mc');
        }
    }

    # display elements contained by this asset type
    my $i;
    my $label = $no_edit ? 'View' : 'Edit';
    # Output the actions.
    my $containers = $comp->get_containers;

    $m->comp(
        '/widgets/wrappers/sharky/table_top.mc',
        caption => 'Existing Subelement Types',
        number  => ++$num,
    );

    unless($no_edit) {
        $m->print(qq{<div style="padding: 5px;">});
        $m->comp(
            '/widgets/profile/imageSubmit.mc',
            formName => "cont_profile",
            callback => "formBuilder|addElementType_cb",
            alt      => 'Add Element Type',
            image    => "add_sub_element_lgreen",
        );
        $m->print(qq{</div>});
    }

    $m->comp(
        '/widgets/listManager/listManager.mc',
        object         => 'element_type',
        objs           => $containers,
        addition       => undef,
        fields         => [qw(name biz_class_id description)],
        profile        => undef,
        select         => $no_del ? undef : ['Delete', 'element_type|delete_sub'],
        alter     => {
            biz_class_id => sub {
                return 'Subelement' unless $_[1]->get_top_level;
                return get_disp_name($_[0]);
            },
        },
    );

    $m->comp('/widgets/wrappers/sharky/table_bottom.mc');
}

        # display existing attributes for this asset type
        if (defined $id) {
            $m->comp(
                '/widgets/wrappers/sharky/table_top.mc',
                caption => "Custom Fields",
                number  => ++$num,
            );

            # mangle the attrs and meta to match the existing display code.
            my $all_data = $comp->get_field_types;
            if (@$all_data) {
                my @attrs;
                for my $field_type (@$all_data) {
                    my $attr = {
                        value => $field_type->get_default_val,
                        id    => $field_type->get_id,
                        name  => $field_type->get_key_name,
                        meta  => {
                            disp => { value => $field_type->get_name },
                            map {
                                $_->{name} => {
                                    value => $_->{get_meth}->($field_type),
                                }
                            } grep { $_->{get_meth} }  $field_type->my_meths(1)
                        },
                    };

                    # Set up the widget to be used.
                    $attr->{meta}{type}{value}
                        = $attr->{meta}{widget_type}{value} eq 'pulldown'
                            ? 'select' : $attr->{meta}{widget_type}{value};
                    push @attrs, $attr;
                }

                $num_fields = @attrs;
                $m->comp("/widgets/profile/displayAttrs.mc",
                         form_name   => 'cont_profile',
                         attr        => \@attrs,
                         readOnly    => $no_edit,
                         useEdit     => !$no_edit,
                         usePosition => !$no_edit,
                         useDelete   => !$no_edit
                );
            } else {
                $m->print(
                    qq{<div style="padding: 5px;">},
                    $lang->maketext("No fields defined"),
                    "</div>"
                );
            }

    # Close the table.
    $m->comp("/widgets/wrappers/sharky/table_bottom.mc");
}

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

if (!$no_edit && defined $id) {
    # Output the formBuilder.
    $m->comp(
        '/widgets/formBuilder/formBuilder.mc',
        numFields     => 0,
        widget        => 1,
        stay          => 1,
        formName      => 'cont_profile',
        numFields     => $num_fields,
        num           => ++$num,
        caption       => 'Add New Field',
        useRequired   => 1,
        useQuantifier => 1
    );
} else {
    # Add the buttons.
    $m->comp(
        '/widgets/profile/hidden.mc',
        name  => 'isNew',
        value => 1,
    ) unless defined $id;
    $m->comp(
        '/widgets/profile/formButtons.mc',
        type => $key_name,
        val => 'next_dkgreen',
        section => $section,
        no_del => 1,
        no_save => $no_edit,
        widget  => "formBuilder",
    );
}
</%perl>
</form>
<& '/widgets/wrappers/sharky/footer.mc', param => \%ARGS &>
<%once>;
my $class    = 'Bric::Biz::ElementType';
my $key_name = 'element_type';
my $section  = 'admin';
my $disp     = get_disp_name('element_type'); # HACK!

my $sel_sub  = sub {
    return unless chk_authz($_[0], EDIT, 1);
    return ['Delete', 'rem_site'];
};

my $ng = Bric::Biz::OutputChannel->my_meths->{name}{get_meth};
my $sg = Bric::Biz::OutputChannel->my_meths->{site}{get_meth};

my $oc_name_getter = sub {
    my $o = shift;
    return $ng->($o) . ' (' . $sg->($o) . ')';
};

my $biz_class_opts = [
    [ 0 => 'Subelement'],
    map { [ get_class_info(lc $_)->get_id => $_ ] }
    qw(Story Image Audio Video Media)
];
$biz_class_opts->[-1][1] = 'Other Media';
</%once>
<%args>
$id => undef
</%args>
<%init>;
# Do any redirects first.
do_queued_redirect();

$id = $ARGS{element_type_id} unless defined $id;
# Instantiate an object.
my $comp = $ARGS{obj} ? $ARGS{obj} : defined $id ? $class->lookup({ id => $id})
  : $class->new;

$id ||= $comp->get_id;

# Check authorization.
chk_authz($comp, $id ? READ : CREATE);
my $no_edit = !chk_authz($comp, ($id ? EDIT : CREATE), 1);
my $no_del = !$id || $no_edit;

# Get the name for the breadcrumb trail.
my $crumb = $comp->get_name;
$crumb = $crumb ? "&quot;$crumb&quot;" : 'New';

# Figure out its type.
my $exclude = { map { $_ => 1 } qw(
    active
    media
    top_level
    biz_class_id
    key_name
) };
my $type = 'Subelement';
if (defined $id) {
    if ($comp->is_top_level) {
        $exclude->{paginated} = 1;
        $type = get_disp_name($comp->get_biz_class_id);
        $type = 'Other Media' if $type eq 'Media';
    } else {
        $exclude->{fixed_uri} = 1;
    }
} else {
    @{$exclude}{qw(paginated fixed_uri related_story related_media)}
        = (1, 1, 1, 1);
}

my $sites = $c->get('__SITES__');

unless ($sites) {
    $sites = Bric::Biz::Site->list({ active => 1 });
    $c->set('__SITES__', $sites);
}

$sites = [grep { chk_authz($_, EDIT, 1) } @$sites];
</%init>
<%doc>
###############################################################################

=head1 NAME

/admin/profile/element_type/dhandler - Container profile interface

=head1 VERSION

$LastChangedRevision$

=head1 DATE

$LastChangedDate$

=head1 DESCRIPTION

Displays the profile for containers.

</%doc>
