<& '/widgets/profile/hidden.mc',
    name    => 'container_prof|update_cb',
    value   => 1,
&>
% if (ENABLE_WYSIWYG) {
<& /widgets/wysiwyg/load.mc &>
%}
<%perl>;
# Show the story summary if needed.
$m->comp('/widgets/summary/summary.mc', asset => $asset, number => 1)
  if $show_summary;

# COUNT FOR REORDER JAVA SCRIPT
my $total = scalar @elements;
my $ord_vals = [ map { [ $_ - 1, $_ ] } 1..$total ];
my $x=0;

# Check if we should display elements.
if (@elements || @$elem_opts ) {
    $m->comp("/widgets/wrappers/sharky/table_top.mc",
             caption => $title,
             id      => 'containerprof',
             number  => $num++
            );
</%perl>

% if (scalar(@elements)) {
    <& '/widgets/profile/hidden.mc',
        name    => "$widget|edit_cb",
        value   => "",
    &>
% }

<table class="containerProf">
% if (scalar(@elements)) { # suppress labels if no results
<tr>
  <th><%$lang->maketext('Name')%></th>
  <th><%$lang->maketext('Content')%></th>
  <th class="position"><%$lang->maketext('Position')%></th>
  <th class="delete"><%$lang->maketext('Delete')%></th>
</tr>
% } # END if (scalar(@elements)) {

% # BEGIN FOREACH ELEMENTS
% my $no_hide; my $num = 0;
% foreach my $dt (@elements) {
% my $no_del;

% # START CONTENT ROWS
<tr>
% if ($dt->is_container) {
% # START IF CONTAINER

  <td class="name"><% $dt->get_name %>:</td>
  <td>
  <table>
<%perl>
# Find a suitable element to display
my($disp_buf, $value_buf);
foreach my $field ($dt->get_fields) {
#    next if $field->get_widget_type !~ /^text/;
    if (my $value = $field->get_value) {
        $disp_buf  = $field->get_name;
        $value_buf = substr($value, 0, 64);
        last;
    }
}
</%perl>
% if ($value_buf) {
    <tr>
      <td colspan="3"><b><% $disp_buf %>:</b> <% escape_html($value_buf) %></td>
    </tr>
% } # if ($value_buf)
    <tr>
      <td>
% my $at = $dt->get_element_type;
% if ($at->is_related_media || $at->is_related_story) {
      <table border=0 cellpadding=0 cellspacing=1>
      <tr>
    <td width=50 class=medHeader align="right">
      <span class=label><% $lang->maketext($at->is_related_media ? "URL" : "Title" )%>:</span>
    </td>
<%perl>
my $info = '';

if ($at->is_related_media) {
    my $rel = $dt->get_related_media;
    $info = $rel->get_uri if $rel;
} else {
    my $rel = $dt->get_related_story;
    $info = $rel->get_title if $rel;
}
</%perl>
    <td width=<% 578 - FIELD_INDENT - 125-50 %>>&nbsp;<% $info %>
    </td>
      </tr>
      <tr>
      <td colspan="2"><& '/widgets/profile/imageSubmit.mc',
         formName  => 'theForm',
         callback  => 'container_prof|edit_cb',
         image     => 'edit_lgreen',
         vspace    => 3,
         value     => $dt->get_id,
         useHidden => 0
      &></td>
      </tr>
      </table>
% } else {

    <& '/widgets/profile/imageSubmit.mc',
         formName  => 'theForm',
         callback  => 'container_prof|edit_cb',
         image     => 'edit_lgreen',
         vspace    => 3,
         value     => $dt->get_id,
         useHidden => 0
    &>
% }

</td>
% # START BULK EDIT SECTION
      <td align="center" valign="middle"><span class="label"> </span></td>
      <td><& '/widgets/profile/imageSubmit.mc',
         formName  => 'theForm',
         callback  => 'container_prof|bulk_edit_cb',
         image     => 'bulk_edit_lgreen',
         value     => $dt->get_id,
         useHidden => !$no_hide++
       &></td>
    </tr>
    </table>
  </td>
<%perl>;
} else {
    # START ELSE ( FIELD ELEMENT DISPLAY )
    my $at_obj = $dt->get_field_type;
    $no_del = $at_obj->get_required && $at_obj->is_active
        && $dt->get_object_order == 1;
    my $vals = { props => {
        type      => $at_obj->get_widget_type,
        disp      => $at_obj->get_name,
        length    => $at_obj->get_length,
        size      => $at_obj->get_length,
        cols      => $at_obj->get_cols,
        rows      => $at_obj->get_rows,
        maxlength => $at_obj->get_max_length,
        precision => $at_obj->get_precision,
        vals      => $at_obj->get_vals,
        multiple  => $at_obj->get_multiple,
    }};

    my $key =  $widget . '|' . $dt->get_id;

    # Get the value.
    if ($vals->{props}{type} eq 'checkbox') {
        $vals->{props}{chk} = $dt->get_value;
        $vals->{value} = 1;
    } else {
        $vals->{value} = $dt->get_value(ISO_8601_FORMAT) || $at_obj->get_default_val;
    }

    # Set the array of possible values, if necessary.
    if ( my $tmp = $vals->{props}{vals} ) {
        if ($vals->{props}{type} eq 'codeselect') {
            $vals->{props}{vals} = eval_codeselect($tmp, $dt);
        } else {
            my $val_prop;
            foreach my $line (split /\n/, $tmp) {
                # (c.f. comp/widgets/profile/displayAttrs.mc)
                my ($v, $l) = split /\s*(?<!\\),\s*/, $line;
                for ($v, $l) { s/\\,/,/g }
                push @$val_prop, [$v, $l];
            }
            $vals->{props}{vals} = $val_prop;
        }
    }
</%perl>
    <td class="name"><% $vals->{props}{disp} %>:</td>
    <td>
    <table>
    <tr>
% # This 100% is necessary to get the autosizing textareas to work in IE.
      <td width="100%">
    <& '/widgets/profile/displayFormElement.mc',
      key      => $key,
      vals     => $vals,
      useTable => 0,
      localize => 0
    &>
      </td>

%     if ($dt->is_autopopulated()) {
      <td>
        <& '/widgets/profile/hidden.mc',
            name    => "$widget|lock_val_cb",
            value   => $dt->get_id,
        &>
        &nbsp;Lock Val:
        <& '/widgets/profile/checkbox.mc',
            name    => "$widget|lock_val_" . $dt->get_id,
            checked => ($dt->is_locked ? 1 : 0),
        &>
        </td>
%     } else {
    <td>&nbsp;</td>
%     }
    </tr>
    </table>
    </td>
% # END FIELD AREA
% } # END ELSE (FIELD ELEMENT DISPLAY)

% # ORDER TABLE CELL
  <td class="position">

% my $f_key = "$widget|reorder_" . ($dt->is_container ? 'con' : 'dat') .
%   $dt->get_id;
<& /widgets/profile/displayFormElement.mc,
   key => $f_key,
   vals => {
       value => $num++,
       js    => 'onChange="reorder(this, \'theForm\')"',
       props => {
           type => 'select',
           vals => $ord_vals,
       },
   },
   useTable => 0
&>

  </td>

% # DELETE TABLE CELL
  <td class="delete">
%   if ($no_del) {
         &nbsp;
% } elsif ($dt->is_container) {
% # START IF CONTAINER
    <& '/widgets/profile/checkbox.mc',
        name => 'container_prof|delete_cont' . $dt->get_id,
        value => 1
    &>
% } else {
    <& '/widgets/profile/checkbox.mc',
        name => 'container_prof|delete_data' . $dt->get_id,
        value => 1
    &>
% }
   </td>
</tr>

% }
% # END FOREACH ELEMENTS

% if (scalar @elements) {
<tr>
  <td colspan="2"></td>
    <td class="position">
    <& '/widgets/profile/button.mc',
        disp      => $lang->maketext("Reorder"),
        widget    => 'container_prof',
        cb        => 'reorder_cb',
        button    => 'reorder_lgreen',
        useTable  => 0 &>
    </td>
    <td class="delete">
    <& '/widgets/profile/button.mc',
        disp      => $lang->maketext("Delete"),
        widget    => 'container_prof',
        cb        => 'delete_cb',
        button    => 'delete_red',
        useTable  => 0 &>
    </td>
</tr>
% }

% # DISPLAY IF NO ELEMENTS
% if (!$total)  {
<tr>
  <td colspan="4"><%$lang->maketext('No elements have been added.')%></td>
</tr>
% }

% # END ELEMENT DISPLAY
</table>

%# Begin element picker
<div class="actions">
    <& '/widgets/profile/imageSubmit.mc',
        formName => "theForm",
        callback => $widget ."|bulk_edit_this_cb",
        image    => "bulk_edit_lgreen",
        vspace   => 3,
        hspace   => 4,
        alt      => 'Bulk Edit',
    &>
% if (@$elem_opts) {
    <& '/widgets/profile/imageSubmit.mc',
        formName => "theForm",
        callback => $widget ."|add_element_cb",
        image    => "add_element_lgreen",
        alt      => 'Add Element',
    &>
    <& /widgets/profile/select.mc, name     => $widget.'|add_element',
                                   options  => $elem_opts,
                                   useTable => 0,
                                   multiple => 0,
                                   size     => 1,
    &>
% }
</div>
%# end data display


%$m->comp("/widgets/wrappers/sharky/table_bottom.mc");
%# end element display
% }

%### Start Related Story Section ###
% if ($is_related_story) {
<& /widgets/wrappers/sharky/table_top.mc,
       caption => 'Related Story',
     number => $num++
&>

% $related_summary->($element, 'story', $widget, $asset);

<& /widgets/wrappers/sharky/table_bottom.mc &>

% }

%### End Related Story Section ###


%### Start Related Media Section ###
% if ($is_related_media) {

<& /widgets/wrappers/sharky/table_top.mc,
       caption => 'Related Media  ',
     number => $num++
&>

% $related_summary->($element, 'media', $widget, $asset);

<& /widgets/wrappers/sharky/table_bottom.mc &>

% }
%### End Related Media Section ###

% if ($show_summary) {
<div class="buttonBar">
    <div class="delete">
        <& '/widgets/profile/checkbox.mc',
            name    => "$widget|delete",
            id      => $widget . "delete",
            value   => "Delete",
            disp    => $lang->maketext('Delete this Profile'),
            label_after => 1,
            useTable    => 0,
        &>
    </div>
    <div class="buttons">
        <div class="save">
            <& "/widgets/buttons/submit.mc",
                disp      => 'Save',
                widget    => $widget,
                cb        => 'save_and_up_cb',
                button    => 'save_red',
                useTable  => 0
            &>
            <& "/widgets/buttons/submit.mc",
                disp      => 'Save and Stay',
                widget    => $widget,
                cb        => 'save_and_stay_cb',
                button    => 'save_and_stay_lgreen',
                useTable  => 0
            &>
        </div>
        <div class="cancel">
            <& "/widgets/buttons/submit.mc",
                disp      => 'Cancel',
                widget    => $widget,
                cb        => 'up_cb',
                button    => 'cancel_red',
                useTable  => 0
            &>
        </div>
    </div>
</div>
% }
%# this script creates an array with the names
%# of select boxes that need ordering
<script type="text/javascript">
<%perl>;
$m->out("var selectOrderNames = new Array(" );

my $txt = '';
foreach my $dt (@elements) {
    if ($dt->is_container) {
           $txt .= '"container_prof|reorder_con' . $dt->get_id() . '", ';
    } else {
        $txt .= '"container_prof|reorder_dat' . $dt->get_id() . '", ';
    }
}
$m->out( substr($txt, 0, length($txt) - 2 ) );
$m->out(")\n\n");
$m->out("</script>");

return $num;

</%perl>
<%args>
$widget
$num          => undef
$title        => undef
$show_summary => undef
</%args>
<%init>;
# the element object
my $element = get_state_data($widget, 'element');

$title ||= $element->get_name;
my $start = get_state_data($widget, 'start');

# the contained elements
my @elements = $element->get_elements();

# Get the list of fields and subelements that can be added.
my $elem_opts = [
    map  { $_->[1] }
    sort { $a->[0] cmp $b->[0] }
    map  {
        my $key = $_->can('get_sites') ? 'cont_' : 'data_';
        [ lc $_->get_name => [ $key . $_->get_id => $_->get_name ] ]
    }
        $element->get_possible_field_types,
        grep { chk_authz($_, READ, 1) } $element->get_possible_containers
];

my $at_id = $element->get_element_type_id;
my $at = Bric::Biz::ElementType->lookup({'id' => $at_id});

# Uncomment this when the related_element flag is in at_type.
my $is_related_story = $at->is_related_story ? 1 : 0;
my $is_related_media = $at->is_related_media ? 1 : 0;

# Nab the story from the story_prof widget.
my $type  = $element->get_object_type;
my $asset = get_state_data($type.'_prof', $type);
</%init>
<%once>;
my $related_summary = sub {
  my ($element, $type, $widget, $asset) = @_;
  my $rel = $type eq 'story' ? $element->get_related_story
                             : $element->get_related_media;

  my $button = $m->scomp(
      '/widgets/profile/button.mc',
      widget   => $widget,
      cb       => "pick_related_".$type."_cb",
      button   => "edit_lgreen",
      useTable => 0
  );

  if ($rel) {
      add_msg('Related [_1] "[_2]" is not active. Please relate another [_1].',
              $type, $rel->get_title)
        unless $rel->is_active;

      add_msg('Related [_1] "[_2]" is not active. Please relate another [_1].',
              $type, $rel->get_title)
        unless $rel->is_active;

      my $thumb = '';
      if (USE_THUMBNAILS && $type ne 'story') {
          if ($thumb =  $rel->thumbnail_uri) {
              $thumb = $m->comp(
                  '/widgets/profile/preview_link.mc',
                  doc   => $rel,
                  value => qq{<img src="$thumb" style="border: 0" />&nbsp;},
                  type  => $type,
              );
          }
      }
      # The summary info
      $m->comp('/widgets/summary/summary.mc',
                asset  => $rel,
                type   => $type,
                header => 'Currently Related '.ucfirst($type),
                frame  => 0,
                button => $thumb . $button );
  } else {
      $m->out('<div class="noneFound">',
              $lang->maketext('No related [_1]'. ucfirst($type)),
              qq{<div class="button">$button</div>},
              '</div>');
      if (RELATED_MEDIA_UPLOAD && $type eq 'media') {
          # Give 'em an upload form.
          if (my $uploader = $m->scomp(
                  '/widgets/profile/media_upload.mc',
                  widget      => $widget,
                  file_widget => 'container_prof',
                  formName    => "theForm",
                  site_id     => $asset->get_site_id,
          )) {
              $m->out(qq{<div class="uploader">$uploader</div>\n});
          }
      }
  }
};
</%once>
