%#-- Begin HTML --#
<script type="text/javascript">
function contribJump(obj) {
    window.location.href = "/admin/profile/contrib/edit/<% $id %>/"
                           + obj[obj.selectedIndex].value;
}
</script>
% 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="contrib_profile" onsubmit="if(uniqueRole(this.subsys)) { return confirmChanges(this) } else { return false }">

<%perl>;
$m->comp('/widgets/profile/hidden.mc',
	 value => $id,
	 name => 'contrib_id') if defined $id;

# display person object fields
&$defaultFields($contrib, $no_edit);

# have the user select a group and role
if ($mode eq "new") {
    $m->comp('/widgets/profile/hidden.mc',
	     value => $mode,
	     name => 'mode');

    # choose group
    &$showGroups($no_edit);
    &$stepOneOfTwo($type, $section);

} elsif ( $mode eq "edit" ) {
    if ($curSubsys || scalar(@subsys) <= 1) {
	# show full edit screen if role is well defined.
	$m->comp('/widgets/profile/hidden.mc',
		 value => $mode,
		 name => 'mode');

	&$showAttrs($contrib, $id, $curSubsys, $extending, $no_edit, \%ARGS);

	# show drop down of other subsys, if any
	if (scalar(@subsys)) {
	    $m->comp("/widgets/wrappers/sharky/table_top.mc",
		     caption => "Switch Roles",
		     number  => 4);

	    my $opts;
	    foreach my $s (@subsys) {
		$opts->{$s} = ($s eq "_MEMBER_SUBSYS") ? "Default" : $s;
	    }

	    $m->comp("/widgets/profile/select.mc",
		     options => $opts,
		     disp   => "Contributor Roles",
		     name   => "cont_roles",
		     value  => $curSubsys,
 		     js     => " onChange='contribJump(this)'");

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

	}

	# Display the form buttons.
	$m->comp('/widgets/profile/formButtons.mc',
		 type    => $type,
                 widget  => $type,
		 section => $section,
		 no_del  => $no_del,
		 no_save => $no_edit,
		 return  => '/admin/manager/contrib'
		);

    } else {
	# show all roles for this member so the user can choose one
	$m->comp('/widgets/profile/hidden.mc', value => 'preEdit', name => 'mode');

	$m->comp("/widgets/wrappers/sharky/table_top.mc",
		 caption => "Roles",
		 number  => 2);

	my $roleOpts;
	foreach my $sys (@subsys) {
	    $roleOpts->{$sys} =($sys ne '_MEMBER_SUBSYS') ?  $sys : "Default";
	}

	$m->comp("/widgets/profile/select.mc",
		 disp    => 'Select Role',
		 options => $roleOpts,
		 name    => 'subsys');

	$m->comp("/widgets/wrappers/sharky/table_bottom.mc");
	&$stepOneOfTwo($type, $section);
    }

} elsif ( $mode eq "extend" ) {

    $m->comp('/widgets/profile/hidden.mc',
	     value => $mode,
	     name => 'mode');

    $m->comp("/widgets/wrappers/sharky/table_top.mc",
	     caption => "Roles",
	     number  => 2);

    # Display a read-only list of existing roles, if more than one.
    if (@subsys > 1) {
	$m->out("<table width=570><tr><td width=130 align=right>");
        $m->out("<span class=label>".$lang->maketext('Existing roles').":</span></td><td width=440>\n");
	foreach my $ss (@subsys) {
	    $m->out ( "$ss<br />\n") if $ss ne '_MEMBER_SUBSYS';
	}
	$m->out("</ul>\n");
	$m->out("</td></tr></table>");
    }

    # Send the roles to javascript so we can check before submitting
    $m->out('<script language="javascript">' . "\n");
    $m->out("var checkUnique = true\n");
    $m->out("var roles = new Array(");

    my $var = '';
    foreach my $ss (@subsys) {
	$var .= "'$ss', " if $ss ne '_MEMBER_SUBSYS';
    }

    $m->out(substr($var, 0, -2) . ");\n</script>\n");

    # text box for new role name
    $m->comp("/widgets/profile/text.mc",
	     disp    => 'New Role Name',
	     name    => 'subsys',
	     useTable => 1);

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

    &$stepOneOfTwo($type, $section);
}
</%perl>
</form>
<& '/widgets/wrappers/sharky/footer.mc', param => \%ARGS &>

%#-- End HTML --#

<%init>;
# Do any redirects first.
do_queued_redirect();

# split uri. expected url is in this format:
# /admin/profile/contrib/mode/id/subsys
my @tmp = split /\//, $r->uri;
my $mode = $ARGS{mode} || $tmp[4] || 'new';

my $id = $ARGS{contrib_id} || $tmp[5];

my $curSubsys = $tmp[6] ||  undef;
my $state     = get_state_data("contrib_profile");
my $extending = $state->{extending};

# Instantiate an object.
my $contrib = $ARGS{obj};
if (!$id) {
    $mode = 'new';
    $contrib ||= Bric::Biz::Person->new;
    clear_state("contrib_profile");
} else {
    $contrib ||= $class->lookup({ id => $id});
    $id ||= $contrib->get_id;
}

# gather all subsys names
my @subsys = $mode eq "new" ? () : $contrib->subsys_names;
# if there's just one, it must be the current one
$curSubsys ||= $subsys[0] if @subsys == 1;
# if there's none (ie, new contrib), assign the default
$curSubsys ||= "_MEMBER_SUBSYS" if !@subsys;

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

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

# Roll in any changes to the contributor if we're just adding contacts.
if (exists($ARGS{'addmore_type'}) && $ARGS{'addmore_type'} eq 'contact') {
    foreach my $meth ($contrib->my_meths(1)) {
	$meth->{set_meth}->($contrib, @{$meth->{set_args}}, $ARGS{$meth->{name}})
	  if defined $meth->{set_meth};
    }
}

my $context   = "Admin | Profile | $disp | $crumb";

# print standard header
$m->comp('/widgets/wrappers/sharky/header.mc',
	 title   => "$disp Profile",
	 context => $context);

################################################################################
################################################################################
</%init>

<%once>;
my $class = 'Bric::Util::Grp::Parts::Member::Contrib';
my $type = 'contrib';
my $section = 'admin';
my $disp = get_disp_name($type);

my $showAttrs = sub {
    my ($contrib, $id, $subsys, $extending, $ro, $param) = @_;
    my $preCaption = '&quot;' . ($subsys eq '_MEMBER_SUBSYS' ? 'Default'
				 : $subsys) . '&quot; Role';
    my $contacts = $contrib->get_obj->get_contacts;

    # Display the Contact info.
    $m->comp("/widgets/wrappers/sharky/table_top.mc",
	     caption => "Contacts",
	     number  => 2);

    $m->comp('/widgets/add_more/add_more.mc',
	     type      => 'contact',
	     fields    => [qw(type value)],
	     name      => 'contact',
	     formName  => 'contrib_profile',
	     reset_key => $id,
	     objs      => $contacts,
	     incr      => 2,
	     readOnly  => $ro,
	     useTable  => 0,
	     param     => $param,
	     deleteLabelOnly =>1
	    );

    $m->comp("/widgets/wrappers/sharky/table_bottom.mc");
    # end contact info

    # display attrs
    $m->comp('/widgets/profile/hidden.mc', value => $subsys, name => 'subsys')
      unless $ro;

    # if this is a new extension, get the meta data from the default instance
    my $default = $contrib->all_for_subsys;
    my $all = ($extending) ?  $default: $contrib->all_for_subsys($subsys);

    # sort the attrs and build an array
    my $attr = [];
    my @sortedAttrs = sort { $default->{$a}{meta}{pos}{value} <=>
			     $default->{$b}{meta}{pos}{value} } keys %$default;

    foreach my $key (@sortedAttrs ) {
	$default->{$key}{name} = $key;
	$default->{$key}{value} = $all->{$key}{value};
	push @$attr, $default->{$key};
    }

    my $num_fields = @$attr;
    if ($num_fields) {
	# display attrs
	$m->comp("/widgets/wrappers/sharky/table_top.mc",
		 caption => $preCaption . " Custom Fields",
		 number  => 3);
	$m->comp("/widgets/profile/displayAttrs.mc",
		 attr        => $attr,
		 form_name   => 'contrib_profile',
		 readOnly    => $ro,
		 usePosition => 0,
		 useDelete   => 0);

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

my $defaultFields = sub {

    my ($contrib, $ro) = @_;
    # Display the referential fields.
    $m->comp("/widgets/wrappers/sharky/table_top.mc",
	     caption => "Properties",
	     number  => 1);

    $m->comp('/widgets/profile/dumpRemainingFields.mc',
	     objref => $contrib, readOnly => $ro,
	     fieldsUsed => {
			    name   => 1,
			    active => 1
			   });

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

};

my $showGroups = sub {
    my $ro = shift;
    my $groups = Bric::Util::Grp::Person->list({ all => 1 });
    my $options;
    my $instanceGrpId = Bric::Biz::Person->INSTANCE_GROUP_ID;
    foreach my $group (@$groups) {
	$options->{$group->get_id} = $group->get_name
	  if ($group->get_id != $instanceGrpId);
    }

    $m->comp("/widgets/wrappers/sharky/table_top.mc",
	     caption => "Contributor Type",
	     number  => 2);

    $m->comp("/widgets/profile/select.mc",
	     value     => 'group',
	     disp      => 'Contributor Type',
	     options   => $options,
	     name      => 'group',
	     readOnly => $ro
	    );


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

my $stepOneOfTwo = sub {
    my ($type, $section) = @_;
    $m->comp('/widgets/profile/formButtons.mc',
             type    => $type,
             section => $section,
             # be careful that formButtons.mc doesn't depend on $widget eq 'profile'
             widget  => $type,
	     no_del  => 1,
	     val     => "next_dkgreen",
	     return  => '/admin/manager/contrib');
};
</%once>

<%doc>
###############################################################################

=head1 NAME

/admin/profile/contrib/dhandler - Contributor Profile.

=head1 VERSION

$LastChangedRevision$

=head1 DATE

$LastChangedDate$

=head1 DESCRIPTION

This dhandler manages contributor profiles.

</%doc>
