# Copyright 2002-2008 Josh Clark and Global Moxie, LLC. This code cannot be
# redistributed without permission from globalmoxie.com.  For more
# information, consult your Big Medium license.
#
# $Id: SiteConfig.pm 3043 2008-03-31 14:00:38Z josh $

package BigMed::App::Web::SiteConfig;
use strict;
use warnings;
use utf8;
use Carp;
$Carp::Verbose = 1;
use base qw(BigMed::App::Web::CP);
use BigMed::Format;
use BigMed::Plugin;
use BigMed::Media::Image;

my @TIME_FORMATS = qw( %r %R %T );
my @DATE_FORMATS = (
    '%b %e, %Y',
    '%B %e, %Y',
    '%n-%e-%Y',
    '%m-%d-%Y',
    '%n.%e.%Y',
    '%Y-%m-%d',
    '%Y.%m.%d',
    '%a, %b %e, %Y',
    '%A, %B %e, %Y',
    '%a %n-%e-%Y',
    '%a %m-%d-%Y',
    '%a %n.%e.%Y',
    '%a %Y-%m-%d',
    '%a %Y.%m.%d',
    
    '%e %b, %Y',
    '%e %B, %Y',
    '%e-%n-%Y',
    '%d-%m-%Y',
    '%e.%n.%Y',
    '%e.%b.%Y',
    '%Y-%d-%m',
    '%Y.%d.%m',
    '%d.%m.%Y',
    '%a, %e %b, %Y',
    '%A, %e %B, %Y',
    '%a %e-%n-%Y',
    '%a %d-%m-%Y',
    '%a %e.%n.%Y',
    '%a %d.%m.%Y',
    '%a %Y-%d-%m',
    '%a %Y.%d.%m',
);

sub setup {
    my $app = shift;
    $app->start_mode('properties');
    $app->set_cp_selected_nav('Settings');
    $app->run_modes(
        'AUTOLOAD'        => sub { $_[0]->rm_properties() },
        'properties'      => 'rm_properties',
        'save-properties' => 'rm_save_properties',
        'section'         => 'rm_section',
        'save-section'    => 'rm_save_section',
        'images'          => 'rm_images',
        'save-images'     => 'rm_save_images',
        'ajax-add-imagesize' => 'rm_ajax_add_imagesize',
        'ajax-sectionslug-avail' => 'rm_ajax_sectionslug_avail',
        'ajax-delete-imagesize' => 'rm_ajax_delete_imagesize',
    );
    return;
}

sub cgiapp_prerun {
    my $app = shift;
    $app->SUPER::cgiapp_prerun;
    $app->require_privilege_level(5);    #webmaster or better
    return;
}

###########################################################
# RUN MODES
###########################################################

sub rm_properties {
    my $app     = shift;
    my %options = @_;

    my $site = $app->current_site;
    my @fieldsets;

    #NAME FIELDSET ----------------------------

    my $name_field = $app->prompt_field_ref(
        data_class  => 'BigMed::Site',
        column      => 'name',
        required    => 1,
        ajax_status => 1,
        value => $site->name || $app->language('CONFIG_Default site name'),
        focus => 1,
        description => 'CONFIG_DESC_Site Name',
        validate_as => 'sitename',
    );

    #assemble the fieldset
    push @fieldsets,
      $app->prompt_fieldset_ref(
        id        => 'bmfs_site_name',
        fields    => [$name_field],
        title     => 'CONFIG_LABEL_fs_Site Name',
        query     => $options{query},
        field_msg => $options{field_msg},
        help      => 'CONFIG_HELP_Site name',
      );

    #TIME FIELDSET ----------------------------

    #time offset
    my $time_offset = $site->time_offset || q{};
    my $offset_field = $app->prompt_field_ref(
        data_class  => 'BigMed::Site',
        column      => 'time_offset',
        value       => $app->escape($time_offset),
        description => 'CONFIG_DESC_Time Zone Offset',
    );

    my $time             = BigMed->time_obj;
    my $time_offset_help = [
        'CONFIG_HELP_Time Zone Offset',
        $time->time_ampm,
        $app->language( $time->wkday_abbr ),
        $time->day,
        $app->language( $time->month_abbr )
    ];

    #get time
    my $bm       = $app->bigmed;
    my $time_obj = $bm->time_obj( offset => $time_offset );

    #time format
    my $tformat = $site->time_format || $site->default_value('time_format');
    my %tlabel;
    foreach my $f (@TIME_FORMATS) {
        my $label = $app->language("CONFIG_time $f");
        $tlabel{$f} = $label . ' ('
          . $app->format_time( $time_obj,
            { dformat => $f, no_time => 1, not_relative => 1 } )
          . ')';
    }

    my $tformat_field = $app->prompt_field_ref(
        data_class => 'BigMed::Site',
        column     => 'time_format',
        prompt_as  => 'value_list',
        value      => $app->escape($tformat),
        options    => \@TIME_FORMATS,
        labels     => \%tlabel,
    );

    my $dformat = $site->date_format || $site->default_value('date_format');
    my %dlabel;
    foreach my $f (@DATE_FORMATS) {
        my $label = $app->language("CONFIG_date $f");
        $dlabel{$f} = $label . ' ('
          . $app->format_time( $time_obj,
            { dformat => $f, no_time => 1, not_relative => 1 } )
          . ')';
    }
    my $dformat_field = $app->prompt_field_ref(
        data_class => 'BigMed::Site',
        column     => 'date_format',
        prompt_as  => 'value_list',
        value      => $app->escape($dformat),
        options    => \@DATE_FORMATS,
        labels     => \%dlabel,
    );

    #assemble the fieldset
    push @fieldsets,
      $app->prompt_fieldset_ref(
        id        => 'bmfs_time_zone',
        fields    => [$offset_field, $tformat_field, $dformat_field],
        title     => 'CONFIG_LABEL_Time Zone',
        query     => $options{query},
        field_msg => $options{field_msg},
        help      => $time_offset_help,
      );

    #FILE UPLOAD LIMIT ----------------------------
    my $admin_limit = $app->env('ADMIN_DOCLIMIT') || 5120;
    my $site_limit  = $site->site_doclimit        || $admin_limit;
    $site_limit = $admin_limit if $site_limit > $admin_limit;

    my $display_admin = _display_admin_doclimit($admin_limit);

    my $upload_limit = $app->prompt_field_ref(
        data_class  => 'BigMed::Site',
        column      => 'site_doclimit',
        value       => $site_limit,
        description => ['SITECONFIG_DESC_Doc limit', $display_admin],
        required    => 1,
    );
    push @fieldsets,
      $app->prompt_fieldset_ref(
        id        => 'bmfs_upload_limit',
        fields    => [$upload_limit],
        title     => 'SITECONFIG_LABEL_File Upload Limit',
        query     => $options{query},
        field_msg => $options{field_msg},
      );

    #DISPLAY PREFS FIELDSET ----------------------------
    #only display if there are format flags set
    my @formats    = BigMed::Plugin->load_formats();
    my @site_flags = BigMed::Format->site_flags;
    if (@site_flags) {
        my %labels = map { $_ => $app->language("SITEFLAG_$_") } @site_flags;
        my $display_prefs = $app->prompt_field_ref(
            data_class => 'BigMed::Site',
            column     => 'flags',
            value      => { $site->flags } || {},
            options    => \@site_flags,
            labels     => \%labels,
        );
        push @fieldsets,
          $app->prompt_fieldset_ref(
            id        => 'bmfs_display_prefs',
            fields    => [$display_prefs],
            title     => 'SITECONFIG_LABEL_Display Prefs',
            query     => $options{query},
            field_msg => $options{field_msg},
          );
    }

    #SUBMIT FIELDSET ----------------------------
    my $submit = $app->prompt_field_ref(
        id        => 'site_submit',
        prompt_as => 'submit',
        value     => $app->language('BM_SUBMIT_LABEL_Save'),
    );
    push @fieldsets, $app->prompt_fieldset_ref( fields => [$submit], );

    #PAGE INFO AND DISPLAY ----------------------------
    $app->js_add_script( $app->env('BMADMINURL') . '/js/bm-config.js' );
    my ( $title, $message ) = $app->title_and_message(
        field_msg => $options{field_msg},
        message   => $options{message},
        title     => 'SITECONFIG_Site Settings',
    );
    _set_breadcrumbs( $app, 'SITECONFIG_Site Settings' );
    my $form_url = $options{form_url}
      || $app->build_url(
        script => 'bm-siteconfig.cgi',
        rm     => 'save-properties',
        site   => $site->id
      );
    return $app->html_template_screen(
        'screen_cp_generic.tmpl',
        bmcp_title => $title,
        form_url   => $form_url,
        message    => $message,
        fieldsets  => \@fieldsets,
    );
}

sub rm_save_properties {
    my $app  = shift;
    my $site = $app->current_site;

    my @fields = (
        {   data_class => 'BigMed::Site',
            column     => 'name',
            required   => 1,
        },
        {   data_class => 'BigMed::Site',
            column     => 'time_offset',
        },
        {   id       => 'date_format',
            parse_as => 'value_list',
            required => 1,
            options  => \@DATE_FORMATS,
        },
        {   id       => 'time_format',
            parse_as => 'value_list',
            required => 1,
            options  => \@TIME_FORMATS,
        },
        {   data_class => 'BigMed::Site',
            column     => 'site_doclimit',
            required   => 1,
        },
    );

    #collect display prefs if we have 'em
    my @formats    = BigMed::Plugin->load_formats();
    my @site_flags = BigMed::Format->site_flags;
    if (@site_flags) {
        push @fields,
          { data_class => 'BigMed::Site',
            column     => 'flags',
            options    => \@site_flags,
          };
    }

    my %field = $app->parse_submission(@fields);
    if ( $field{_ERROR} ) {
        return $app->rm_properties(
            query     => $app->query,
            field_msg => $field{_ERROR}
        );
    }

    #update site
    my $orig_name = $site->name;
    $site->set_name( $field{name} );
    $site->set_date_format( $field{date_format} );
    $site->set_time_format( $field{time_format} );
    $site->set_time_offset( $field{time_offset} );
    $site->set_site_doclimit( $field{site_doclimit} );
    $site->set_flags( $field{flags} ) if $field{flags};

    #check site name uniqueness
    defined( my $unique = $site->is_unique('name') )
      or return $app->rm_properties( query => $app->query );
    if ( !$unique ) {
        $site->set_name($orig_name);
        $field{_ERROR}->{name} = [
            'BM_Not unique', $app->language('site:name'),
            $app->language('CONFIG_site')
        ];
        $field{_ERROR}->{_FIRST_ERR} ||= 'name';
    }

    #doc limit cannot exceed admin limit
    my $admin_limit = $app->env('ADMIN_DOCLIMIT') || 5120;
    if ( $field{site_doclimit} > $admin_limit ) {
        $field{_ERROR}->{site_doclimit} = [
            'SITECONFIG_DESC_Doc limit',
            _display_admin_doclimit($admin_limit),
        ];
        $field{_ERROR}->{_FIRST_ERR} ||= 'site_doclimit';
    }

    #kick back if we have an error
    if ( $field{_ERROR} ) {    #one or more non-unique values
        return $app->rm_properties(
            query     => $app->query,
            field_msg => $field{_ERROR}
        );
    }

    #everything looks good...
    $site->save or return $app->rm_properties( query => $app->query );

    return $app->_redirect_to_main_menu('BM_Your changes have been saved.');
}

sub rm_section {
    my $app     = shift;
    my %options = @_;
    my $site    = $app->current_site;
    my $section = $app->_section_from_path($site)
      or return $app->_err_to_section_menu();
    my $page = $section->section_page_obj
      or return $app->err_to_section_menu();

    my @fieldsets;

    #POWER SWITCH FIELDSET ----------------------------
    if ( !$section->is_homepage ) {
        my $active_field = $app->prompt_field_ref(
            data_class   => 'BigMed::Section',
            column       => 'active',
            value        => $section->active,
            option_label => 'SITECONFIG_Section Active Checkbox',
        );
        push @fieldsets,
          $app->prompt_fieldset_ref(
            id        => 'bmfs_active',
            fields    => [$active_field],
            title     => 'SITECONFIG_LABEL_Section Active',
            query     => $options{query},
            field_msg => $options{field_msg},
          );
    }

    #IDENTIFIERS FIELDSET ----------------------------
    my @identifiers;
    push @identifiers,
      $app->prompt_field_ref(
        data_class => 'BigMed::Section',
        column     => 'id',
        value      => $section->id,
      );
    push @identifiers,
      $app->prompt_field_ref(
        data_class  => 'BigMed::Section',
        column      => 'name',
        value       => $section->name,
        required    => 1,
        description => 'SITECONFIG_DESC_Section Name',
      );
    push @identifiers,
      $app->prompt_field_ref(
        data_class  => ref $page,
        column      => 'title',
        value       => $page->title,
        required    => 1,
        description => 'SITECONFIG_DESC_Page Title',
      );
    if ( !$section->is_homepage ) {
        push @identifiers,
          $app->prompt_field_ref(
            data_class  => 'BigMed::Section',
            column      => 'slug',
            value       => $section->slug,
            required    => 1,
            description => 'SITECONFIG_DESC_Slug Name',
            ajax_status => 1,
            validate_as => 'section-slug',
          );
    }
    push @fieldsets,
      $app->prompt_fieldset_ref(
        id        => 'bmfs_identifier',
        fields    => \@identifiers,
        title     => 'SITECONFIG_LABEL_Identifiers',
        query     => $options{query},
        field_msg => $options{field_msg},
      );

    #ALIAS FIELDSET ----------------------------
    my $alias_field = $app->prompt_field_ref(
        data_class  => 'BigMed::Section',
        column      => 'alias',
        value       => $section->alias,
        description => 'SITECONFIG_DESC_Section_Alias',
    );
    push @fieldsets,
      $app->prompt_fieldset_ref(
        id        => 'bmfs_identifier',
        fields    => [$alias_field],
        title     => 'SITECONFIG_LABEL_Alternate URL',
        help      => 'SITECONFIG_HELP_Alternate URL',
        query     => $options{query},
        field_msg => $options{field_msg},
      );

    #CONTENT PREFS FIELDSET ----------------------------
    if ( !$section->is_homepage ) {
        my @formats   = BigMed::Plugin->load_formats();
        my @sec_flags = BigMed::Format->section_flags;
        if (@sec_flags) {
            my %labels =
              map { $_ => $app->language("SECFLAG_$_") } @sec_flags;
            my $content_prefs = $app->prompt_field_ref(
                data_class => 'BigMed::Section',
                column     => 'flags',
                value      => { $section->flags } || {},
                options    => \@sec_flags,
                labels     => \%labels,
            );
            push @fieldsets,
              $app->prompt_fieldset_ref(
                id        => 'bmfs_display_prefs',
                fields    => [$content_prefs],
                title     => 'SITECONFIG_LABEL_Prefs',
                query     => $options{query},
                field_msg => $options{field_msg},
              );
        }
    }

    #SUBMIT FIELDSET ----------------------------
    my $submit = $app->prompt_field_ref(
        id        => 'section_submit',
        prompt_as => 'submit',
        value     => $app->language('BM_SUBMIT_LABEL_Save'),
    );
    push @fieldsets, $app->prompt_fieldset_ref( fields => [$submit], );

    #PAGE INFO AND DISPLAY ----------------------------
    $app->js_add_script( $app->env('BMADMINURL') . '/js/bm-config.js' );
    my $orig_title = ['SITECONFIG_Section Properties', $section->name];
    my ( $title, $message ) = $app->title_and_message(
        field_msg => $options{field_msg},
        message   => $options{message},
        title     => $orig_title,
    );
    my $rcrumbs = [
        {   bc_label => 'PREFS_Section Menu',
            bc_url   => $app->build_url(
                script => 'bm-prefs.cgi',
                rm     => 'section-menu',
                site   => $app->current_site->id,
            ),
        },
        { bc_label => $orig_title },
    ];
    _set_breadcrumbs( $app, $rcrumbs );
    my $form_url = $app->build_url(
        script => 'bm-siteconfig.cgi',
        rm     => 'save-section',
        site   => $site->id,
        args   => [$section->id],
    );
    return $app->html_template_screen(
        'screen_cp_generic.tmpl',
        bmcp_title => $title,
        form_url   => $form_url,
        message    => $message,
        fieldsets  => \@fieldsets,
    );

}

sub rm_save_section {
    my $app     = shift;
    my %options = @_;
    my $site    = $app->current_site;
    my $section = $app->_section_from_path($site)
      or return $app->rm_section( query => $app->query );
    my $page = $section->section_page_obj
      or return $app->rm_section( query => $app->query );

    my @fields = (
        {   data_class => 'BigMed::Section',
            column     => 'name',
            required   => 1,
        },
        {   data_class => ref $page,
            column     => 'title',
            required   => 1,
        },
        {   data_class => 'BigMed::Section',
            column     => 'alias',
        },
    );
    if ( !$section->is_homepage ) {
        push @fields,
          ( {   data_class => 'BigMed::Section',
                column     => 'active',
            },
            {   data_class => 'BigMed::Section',
                column     => 'slug',
                required   => 1,
            }
          );

        #collect display prefs if we have 'em
        my @formats   = BigMed::Plugin->load_formats();
        my @sec_flags = BigMed::Format->section_flags;
        if (@sec_flags) {
            push @fields,
              { data_class => 'BigMed::Section',
                column     => 'flags',
                options    => \@sec_flags,
              };
        }
    }

    my %field = $app->parse_submission(@fields);
    if ( $field{_ERROR} ) {
        return $app->rm_section(
            query     => $app->query,
            field_msg => $field{_ERROR}
        );
    }

    my $orig_slug = $section->slug;
    undef $field{alias} if $field{alias} eq q{};
    $field{active} = 1 if $section->is_homepage;

    my $was_active = $section->active || q{};
    $section->set_active( $field{active} );
    $section->set_slug( $field{slug} );
    $section->set_name( $field{name} );
    $section->set_alias( $field{alias} );
    $section->set_flags( $field{flags} );

    if ( !$section->is_homepage ) {

        #check section slug uniqueness; gets done by section->save but
        #good to do it here so that we can display as field message.
        defined( my $unique = $section->is_unique('slug') )
          or return $app->rm_section( query => $app->query );
        if ( !$unique ) {
            $section->set_slug($orig_slug);
            $field{_ERROR}->{slug} = [
                'BM_Not unique', $app->language('section:slug'),
                $app->language('section')
            ];
            $field{_ERROR}->{_FIRST_ERR} ||= 'slug';
            return $app->rm_section(
                query     => $app->query,
                field_msg => $field{_ERROR}
            );
        }
    }

    #save and update slug directory if necessary
    $section->save or return $app->rm_section( query => $app->query );
    my $slug_change = defined $orig_slug
      && $orig_slug ne q{}    #zero value okay
      && $section->slug;
    if ($slug_change) {
        $section->update_html_directory($orig_slug);
    }

    $page->set_title( $field{title} );    
    $page->save    or return $app->rm_section( query => $app->query );

    #update search engine index
    if ($was_active ne $section->active) {
        _update_search_index( $site, $section )
          or return $app->rm_section(
            query     => $app->query,
            field_msg => $field{_ERROR}
          );
    }

    my $rebuild_url = $app->build_url(
        script => 'bm-build.cgi',
        rm     => 'build-all',
        site   => $site->id,
    );
    my $message =
      ['SITECONFIG_Section Properties Saved', $section->name, $rebuild_url,];
    return $app->_redirect_to_section_menu($message);
}

sub _update_search_index {
    my ($site, $section) = @_;

    require BigMed::Content::Page;
    require BigMed::Search::Scheduler;
    import BigMed::Search::Scheduler;
    my @all_sec = ($section->id, $site->all_descendants_ids($section));
    my $select =
      BigMed::Content::Page->select(
        { site => $site->id, sections => \@all_sec } )
      or return;
    my $rkids = map { $_ => 1} $site->all_active_descendants_ids();
    my ($page, @add, @remove);
    while ( $page = $select->next ) {
        if ( $page->active_page_url($site, {rkids=>$rkids}) ) {
            push @add, $page->id;
        }
        else {
            push @remove, $page->id;
        }
    }
    return if !defined $page;
    schedule_index($site, \@add) or return;
    schedule_deindex($site, \@remove) or return;
    return 1;
}

my @IMG_OPTIONS = qw(squeeze crop squeeze-crop);
sub rm_images {
    my $app     = shift;
    my %options = @_;
    my $site = $app->current_site;

    my %image_action = BigMed::Media::Image->image_actions($site);
    my @default_sizes = BigMed::Media::Image->default_sizes();
    my %is_default = map { $_ => 1 } @default_sizes;
    
    my %labels =
      map { $_ => $app->language("SITECONFIG_IMG_$_") } @IMG_OPTIONS;

    my (@default, @custom);
    foreach my $rdim ( BigMed::Media::Image->image_formats($site) ) {
        my ($name, $dim) = @{$rdim};
        if ( $is_default{$dim} ) {
            push @default,
              $app->prompt_field_ref(
                id          => "imageformat_$dim",
                label       => "SITECONFIG_IMG_$dim",
                description => ['SITECONFIG_IMG_DESC', $dim],
                prompt_as   => 'value_list',
                options     => \@IMG_OPTIONS,
                labels      => \%labels,
                value       => $image_action{$dim},
              );
        }
        else {
            push @custom,
              $app->_prompt_custom_image( $dim, $image_action{$dim},
                \%labels );
        }
    }
    
    my $submit = $app->prompt_field_ref(
        id        => 'site_submit',
        prompt_as => 'submit',
        value     => $app->language('BM_SUBMIT_LABEL_Save'),
    );
    
    my @image_fieldsets = (
        $app->prompt_fieldset_ref(
            id        => 'bmfs_default_images',
            fields    => \@default,
            title     => 'SITECONFIG_LABEL_Standard sizes',
            query     => $options{query},
            field_msg => $options{field_msg},
        ),
        $app->prompt_fieldset_ref(
            id        => 'bmfs_custom_images',
            fields    => \@custom,
            title     => 'SITECONFIG_LABEL_Custom sizes',
            query     => $options{query},
            field_msg => $options{field_msg},
        ),
    );
    my @submit_fieldset = ( $app->prompt_fieldset_ref( fields => [$submit], ) );


    #PAGE INFO AND DISPLAY ----------------------------
    my $configured =
      BigMed::Media::Image->can_thumbnail
      ? q{ }
      : $app->language('SITECONFIG_IMG_Not configured');
    my $orig_message =
      $options{message} || ['SITECONFIG_IMG_MSG_Image Formats',$configured];
    my ( $title, $message ) = $app->title_and_message(
        field_msg => $options{field_msg},
        message   => $orig_message,
        title     => 'SITECONFIG_Image Sizes',
    );
    _set_breadcrumbs( $app, 'SITECONFIG_Image Sizes' );
    my $form_url = $options{form_url}
      || $app->build_url(
        script => 'bm-siteconfig.cgi',
        rm     => 'save-images',
        site   => $site->id
      );
    
    $app->js_add_script($app->env('BMADMINURL') . '/js/bm-imagesize.js');
    return $app->html_template_screen(
        'screen_siteconfig_images.tmpl',
        bmcp_title => $title,
        form_url   => $form_url,
        message    => $message,
        image_fieldsets  => \@image_fieldsets,
        submit_fieldset  => \@submit_fieldset,
    );
}

sub rm_save_images {
    my $app          = shift;
    my $site         = $app->current_site;
    my $query        = $app->query;
    my %image_action = BigMed::Media::Image->image_actions($site);
    my @dims = keys %image_action;

    my @fields = map {
        {   id       => "imageformat_$_",
            parse_as => 'value_list',
            options  => \@IMG_OPTIONS,
            required => 1,
        }
    } @dims;
    my %field = $app->parse_submission(@fields);
    return $app->rm_images( query => $query, field_msg => $field{_ERROR} )
      if $field{_ERROR};

    foreach my $dim ( @dims ) {
        $image_action{$dim} = $field{"imageformat_$dim"};
    }
    $site->store_pref('image_actions', \%image_action)
      or return $app->rm_images(query => $query);
    
    return $app->_redirect_to_main_menu('BM_Your changes have been saved.');    
}

sub rm_ajax_add_imagesize {
    my $app = shift;
    $app->require_post() or return $app->ajax_system_error();
    
    my %field = $app->parse_submission(
        {   id => 'newimage_width',
            required   => 1,
            parse_as => 'number_integer_positive',
        },
        {   id => 'newimage_height',
            required   => 1,
            parse_as => 'number_integer_positive',
        },
    );
    return $app->ajax_parse_error( $field{_ERROR} ) if $field{_ERROR};

    #check for dupes
    my $site = $app->current_site;
    my %image_action = BigMed::Media::Image->image_actions($site);
    my $dimensions = "$field{newimage_width}x$field{newimage_height}";
    if ($image_action{$dimensions}) {
        $app->set_error(
            head => 'SITECONFIG_IMG_HEAD_Size already exists',
            text => 'SITECONFIG_IMG_Size already exists',
        );
        return $app->ajax_system_error();
    }
    
    #save the new image with the default squeeze image action
    $image_action{$dimensions} = 'squeeze';
    $site->store_pref('image_actions', \%image_action)
      or return $app->ajax_system_error();
    
    #return the new field entry to insert into the form
    my %labels =
      map { $_ => $app->language("SITECONFIG_IMG_$_") } @IMG_OPTIONS;
    my $rfield = $app->_prompt_custom_image( $dimensions, 'squeeze' );
    my %tmpl_params = %{ $app->prompt( @{$rfield} ) };
    my $html = $app->html_template( 'wi_prompt_field.tmpl', %tmpl_params );
    return $app->ajax_html($html);
}

sub rm_ajax_delete_imagesize {
    my $app = shift;
    $app->require_post() or return $app->ajax_system_error();
    
    my %field = $app->parse_submission(
        {   id => 'delete_width',
            required   => 1,
            parse_as => 'number_integer_positive',
        },
        {   id => 'delete_height',
            required   => 1,
            parse_as => 'number_integer_positive',
        },
    );
    return $app->ajax_parse_error( $field{_ERROR} ) if $field{_ERROR};

    my $site = $app->current_site;
    my %image_action = BigMed::Media::Image->image_actions($site);
    my $dimensions = "$field{delete_width}x$field{delete_height}";
    delete $image_action{$dimensions};
    $site->store_pref('image_actions', \%image_action)
      or return $app->ajax_system_error();

    return $app->ajax_json_response({valid => 1});
}

sub rm_ajax_sectionslug_avail {
    return $_[0]->ajax_check_uniqueness(
        class  => 'BigMed::Section',
        column => 'slug',
        name   => 'section:slug',
        type   => 'section',
        site   => $_[0]->current_site->id,
    );
}

sub _display_admin_doclimit {
    my $kilobytes = shift;
    return $kilobytes >= 1024
      ? sprintf( '%.1f MB', $kilobytes / 1024 )
      : "$kilobytes KB";
}

sub _section_from_path {
    my ( $app, $site ) = @_;
    my ($sec_id) = $app->path_args;
    my $section;
    if ( $sec_id && $sec_id > 0 ) {
        defined( $section = $site->section_obj_by_id($sec_id) ) or return;
    }
    if ( !$section ) {    #no such section, bad ID
        $app->set_error(
            head => 'SECTIONS_HEAD_Section could not be found',
            text =>
              ['SECTIONS_Section could not be found', $sec_id, $site->name],
        );
    }
    return $section;
}

sub _set_breadcrumbs {
    my $app         = shift;
    my $title_or_bc = shift;
    my @bc          =
      ref $title_or_bc eq 'ARRAY'
      ? @{$title_or_bc}
      : { bc_label => $title_or_bc };
    unshift @bc,
      { bc_label => 'BM_CP_NAVLABEL_Settings',
        bc_url   => $app->build_url(
            script => 'bm-prefs.cgi',
            rm     => 'main-menu',
            site   => $app->current_site->id,
        ),
      };
    $app->set_cp_breadcrumbs(@bc);
    return;
}

sub _redirect_to_main_menu {
    my ( $app, $message, $is_error ) = @_;
    my $redirect = $app->build_url(
        script => 'bm-prefs.cgi',
        rm     => 'main-menu',
        site   => $app->current_site->id,
    );
    return $app->_redirect( $redirect, $message, $is_error );
}

sub _redirect_to_section_menu {
    my ( $app, $message, $is_error ) = @_;
    my $url = $app->build_url(
        script => 'bm-prefs.cgi',
        rm     => 'section-menu',
        site   => $app->current_site->id,
    );
    return $app->_redirect( $url, $message, $is_error );
}

sub _err_to_section_menu {
    my $app   = shift;
    my %error = $app->error_html_hash;
    return $app->_redirect_to_section_menu( $error{text}, 1 );
}

sub _redirect {
    my ( $app, $url, $message, $is_error ) = @_;
    $app->set_session_message( $message, $is_error ) if $message;
    $app->header_type('redirect');
    $app->header_props( -url => $url );
    return "Redirecting to $url";
}

sub _prompt_custom_image {
    my ( $app, $dimensions, $image_action, $rlabels ) = @_;
    my ( $width, $height ) = split( /x/ms, $dimensions );
    if ( !$rlabels ) {
        $rlabels =
          { map { $_ => $app->language("SITECONFIG_IMG_$_") } @IMG_OPTIONS };
    }
    my $delete = '<a href="#" class="canceler deleteImage" '
      . qq{id="delete_$dimensions">}
      . $app->language('BM_Delete')
      . '</a>';
    return $app->prompt_field_ref(
        id          => "imageformat_$dimensions",
        label       => ['SITECONFIG_IMG_CUSTOM', $width, $height],
        description =>
          ['SITECONFIG_IMG_CUSTOM_DESC', $width, $height, $delete],
        prompt_as => 'value_list',
        options   => \@IMG_OPTIONS,
        labels    => $rlabels,
        value     => $image_action,
        container_id => "formatContainer_$dimensions",
    );
}



1;

__END__

