function cpm_action_manage_subcomic()
{
    global $cpm_config;
    $target_category_id = (int) $_POST['comic'];
    extract(cpm_normalize_storyline_structure());
    $final_category_id = false;
    $first = true;
    foreach ($category_tree as $node) {
        $category = get_category(end(explode("/", $node)));
        if ($first) {
            $final_category_id = $category->term_id;
        }
        if ($target_category_id == $category->term_id) {
            if (is_dir(CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties['comic_folder'] . '/' . $category->slug)) {
                $final_category_id = $category->term_id;
                break;
            }
        }
        $first = false;
    }
    update_option('comicpress-manager-manage-subcomic', $final_category_id);
    cpm_read_information_and_check_config();
    $cpm_config->messages[] = sprintf(__("Now managing <strong>%s</strong>.", 'comicpress-manager'), get_cat_name($final_category_id));
}
/**
 * Generate &lt;option&gt; elements for all comic categories.
 */
function generate_comic_categories_options($form_name, $label = true)
{
    global $cpm_config;
    $number_of_categories = 0;
    $first_category = null;
    extract(cpm_normalize_storyline_structure());
    if (cpm_get_subcomic_directory() !== false) {
        $default_category = get_option('comicpress-manager-manage-subcomic');
    } else {
        if (cpm_option('cpm-default-comic-category-is-last-storyline') == 1) {
            $default_category = end(explode("/", end($category_tree)));
        } else {
            $default_category = $cpm_config->properties['comiccat'];
        }
    }
    ob_start();
    foreach (get_all_category_ids() as $cat_id) {
        $ok = $cat_id == $default_category;
        if ($ok) {
            $number_of_categories++;
            $category = get_category($cat_id);
            if (is_null($first_category)) {
                $first_category = $category;
            }
            ?>
      <option
        value="<?php 
            echo $category->cat_ID;
            ?>
"
        <?php 
            if (!is_null($cpm_config->comic_category_info)) {
                echo $default_category == $cat_id ? " selected" : "";
            }
            ?>
        ><?php 
            echo $category->cat_name;
            ?>
</option>
    <?php 
        }
    }
    $output = ob_get_clean();
    if ($number_of_categories == 0) {
        return false;
    } else {
        if ($number_of_categories == 1) {
            $output = "<input type=\"hidden\" name=\"{$form_name}\" value=\"{$first_category->cat_ID}\" />";
            if ($label) {
                $output .= $first_category->cat_name;
            }
            return $output;
        } else {
            return "<select name=\"{$form_name}\">" . $output . "</select>";
        }
    }
}
/**
 * Show the comic in the Post editor.
 */
function cpm_show_comic()
{
    global $post, $cpm_config;
    $form_target = plugin_basename(realpath(dirname(__FILE__) . "/../comicpress_manager_admin.php"));
    read_current_theme_comicpress_config();
    $has_comic_file = false;
    $in_comics_category = false;
    $thumbnails_to_generate = cpm_get_thumbnails_to_generate();
    $post_categories = array();
    $comic_categories = array();
    extract(cpm_normalize_storyline_structure());
    foreach ($category_tree as $node) {
        $comic_categories[] = end(explode("/", $node));
    }
    if ($post->ID !== 0) {
        $post_time = time();
        foreach (array('post_date', 'post_modified', 'post_date_gmt', 'post_modified_gmt') as $time_value) {
            if (($result = strtotime($post->{$time_value})) !== false) {
                $post_time = $result;
                break;
            }
        }
        $post_categories = wp_get_post_categories($post->ID);
        if (isset($cpm_config->properties['comiccat'])) {
            $in_comics_category = count(array_intersect($comic_categories, $post_categories)) > 0;
        }
        $ok = true;
        if (cpm_get_subcomic_directory() !== false) {
            $ok = in_array(get_option('comicpress-manager-manage-subcomic'), wp_get_post_categories($post->ID));
        }
        if ($ok) {
            if (($comic = find_comic_by_date($post_time)) !== false) {
                $comic_uri = cpm_build_comic_uri($comic);
                $comic_filename = preg_replace('#^.*/([^\\/]*)$#', '\\1', $comic_uri);
                $link = "<strong><a target=\"comic_window\" href=\"{$comic_uri}\">{$comic_filename}</a></strong>";
                $date_root = substr($comic_filename, 0, strlen(date(CPM_DATE_FORMAT)));
                $thumbnails_found = cpm_find_thumbnails_by_filename($comic);
                $icon_file_to_use = $comic;
                foreach (array('rss', 'archive') as $type) {
                    if (isset($thumbnails_found[$type])) {
                        $icon_file_to_use = $thumbnails_found[$type];
                    }
                }
                $icon_uri = cpm_build_comic_uri($icon_file_to_use);
                $has_comic_file = true;
            }
        }
    }
    ?>

  <script type="text/javascript">
    function show_comic() {
      if ($('comic-icon').offsetWidth > $('comic-icon').offsetHeight) {
        $('preview-comic').width = 400;
      } else {
        $('preview-comic').height = 400;
      }
      Element.clonePosition('comic-hover', 'comic-icon', { setWidth: false, setHeight: false, offsetTop: -((Element.getDimensions('comic-hover')['height'] - Element.getDimensions('comic-icon')['height'])/2) });
      $('comic-hover').show();
    }

    function hide_comic() { $('comic-hover').hide(); }

    var all_comic_categories = [ <?php 
    echo implode(",", $comic_categories);
    ?>
 ];
    var storyline_enabled = <?php 
    echo get_option('comicpress-enable-storyline-support') == 1 ? 'true' : 'false';
    ?>
;

    Event.observe(window, 'load', function() {
      $('post').encoding = "multipart/form-data";
    });
  </script>

  <?php 
    if (count($cpm_config->comic_files) == 0) {
        ?>
    <div style="border: solid #daa 1px; background-color: #ffe7e7; padding: 5px">
      <strong>It looks like this is a new ComicPress install.</strong> You should test to make
      sure uploading works correctly by visiting <a href="admin.php?page=<?php 
        echo plugin_basename(realpath(dirname(__FILE__) . '/../comicpress_manager_admin.php'));
        ?>
">ComicPress -> Upload</a>.
    </div>
  <?php 
    }
    ?>
  <?php 
    if ($has_comic_file) {
        ?>
    <div id="comic-hover" style="border: solid black 1px; position: absolute; display: none" onmouseout="hide_comic()">
      <img id="preview-comic" src="<?php 
        echo $comic_uri;
        ?>
" />
    </div>
    <a href="#" onclick="return false" onmouseover="show_comic()"><img id="comic-icon" src="<?php 
        echo $icon_uri;
        ?>
" height="100" align="right" /></a>
    <p>
      <?php 
        printf(__("The comic that will be shown with this post is %s.", 'comicpress-manager'), $link);
        ?>
      <?php 
        _e("Mouse over the icon to the right to see a larger version of the image.", 'comicpress-manager');
        ?>
    </p>

    <?php 
        if (cpm_get_subcomic_directory() !== false) {
            printf(__("Comic files will be uploaded to the <strong>%s</strong> comic subdirectory.", 'comicpress-manager'), get_cat_name(get_option('comicpress-manager-manage-subcomic')));
        }
        ?>

    <?php 
        if (count($thumbnails_found) > 0) {
            ?>
      <p><?php 
            _e("The following thumbnails for this comic were also found:", 'comicpress-manager');
            ?>
        <?php 
            foreach ($thumbnails_found as $type => $file) {
                ?>
          <a target="comic_window" href="<?php 
                echo cpm_build_comic_uri(CPM_DOCUMENT_ROOT . '/' . $file);
                ?>
"><?php 
                echo $type;
                ?>
</a>
        <?php 
            }
            ?>
      </p>
    <?php 
        }
        ?>
  <?php 
    }
    ?>

  <?php 
    if (cpm_option("cpm-edit-post-integrate") == 1) {
        ?>
    <p><em><strong>ComicPress Manager Edit Post file management is enabled.</strong></em> Any changes to post date, or deleting this post, will affect any associated comic files.</p>
  <?php 
    }
    ?>

  <p><strong>NOTE: Upload errors will not be reported.</strong> If you are having trouble uploading files, use the <a href="admin.php?page=<?php 
    echo plugin_basename(realpath(dirname(__FILE__) . '/../comicpress_manager_admin.php'));
    ?>
">ComicPress -> Upload</a> screen.</p>

  <table class="form-table">
    <tr>
      <th scope="row">
        <?php 
    if ($has_comic_file) {
        ?>
          <?php 
        _e("Replace This Image", 'comicpress-manager');
        ?>
        <?php 
    } else {
        ?>
          <?php 
        _e("Upload a New Single Image", 'comicpress-manager');
        ?>
        <?php 
    }
    ?>
      </th>
      <td>
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php 
    echo cpm_short_size_string_to_bytes(ini_get('upload_max_filesize'));
    ?>
" />
        <input type="file" id="comicpress-replace-image" name="comicpress-replace-image" class="button" /> <?php 
    echo empty($thumbnails_to_generate) ? "" : __("<em>(thumbnails will be generated)</em>", 'comicpress-manager');
    ?>
<br />
        <?php 
    if ($has_comic_file) {
        ?>
          <input type="hidden" name="overwrite-existing-file-choice" value="<?php 
        echo $comic_filename;
        ?>
" />
        <?php 
    }
    ?>
        <input type="hidden" name="upload-destination" value="comic" />
        <input type="hidden" name="thumbnails" value="yes" />
      </td>
      <script type="text/javascript">
        var handle_click = function() {
          var any_checked = false
          $$('input[name="post_category[]"]').each(function(i) {
            if (i.type == "radio") {
              if (i.checked) {
                any_checked = true;
              }
            }
          });

          if (!any_checked) {
            var has_checked = false;
            $$('input[name="post_category[]"]').each(function(i) {
              if (!has_checked) {
                if (i.type == "radio") {
                  i.checked = true;
                  has_checked = true;
                }
              }
            });
          }
        };

        [ 'click', 'blur' ].each(function(w) { $('comicpress-replace-image').observe(w, handle_click); });
      </script>
    </tr>
    <?php 
    if (cpm_option('cpm-skip-checks') != 1) {
        if (!function_exists('get_comic_path')) {
            ?>
          <tr>
            <td colspan="2" style="background-color: #fee; border: solid #daa 1px">
              <?php 
            _e('<strong>It looks like you\'re running an older version of ComicPress.</strong> Storyline, hovertext, and transcript are fully supported in <a href="http://comicpress.org/">ComicPress 2.7</a>. You can use hovertext and transcripts in earlier themes by using <tt>get_post_meta($post->ID, "hovertext", true)</tt> and <tt>get_post_meta($post->ID, "transcript", true)</tt>.', 'comicpress-manager');
            ?>
            </td>
          </tr>
        <?php 
        }
    }
    ?>
    <?php 
    if (get_option('comicpress-enable-storyline-support') == 1) {
        ?>
      <tr>
        <th scope="row">
          <?php 
        if (count($category_tree) > 1) {
            _e("Storyline", 'comicpress-manager');
        } else {
            _e("Category", 'comicpress-manager');
        }
        ?>
        </th>
        <td>
          <?php 
        cpm_display_storyline_checkboxes($category_tree, $post_categories, null, "post_category");
        ?>
        </td>
      </tr>
    <?php 
    }
    ?>
    <tr>
      <th scope="row"><?php 
    _e('&lt;img title&gt;/hover text', 'comicpress-manager');
    ?>
</th>
      <td><input type="text" name="comicpress-img-title" style="width:99%" value="<?php 
    echo get_post_meta($post->ID, 'hovertext', true);
    ?>
" /></td>
    </tr>
    <tr>
      <th scope="row"><?php 
    _e("Transcript", 'comicpress-manager');
    ?>
</th>
      <td>
        <textarea name="comicpress-transcript" rows="8" style="width:99%"><?php 
    echo get_post_meta($post->ID, 'transcript', true);
    ?>
</textarea>
        <?php 
    if (!is_plugin_active('what-did-they-say/what-did-they-say.php')) {
        ?>
          <p>
            <?php 
        _e('Want even better control over your transcripts? Try <a href="http://wordpress.org/extend/plugins/what-did-they-say/" target="wdts">What Did They Say?!?</a>', 'comicpress-manager');
        ?>
          </p>
        <?php 
    }
    ?>
      </td>
    </tr>
  </table>
  
  <?php 
}
/**
 * The generate status dialog.
 */
function cpm_manager_status()
{
    global $cpm_config;
    $cpm_config->need_calendars = true;
    if (cpm_get_subcomic_directory() !== false) {
        $cpm_config->messages[] = sprintf(__("<strong>Reminder:</strong> You are managing the <strong>%s</strong> comic subdirectory.", 'comicpress-manager'), get_cat_name(get_option('comicpress-manager-manage-subcomic')));
    }
    if (cpm_option('cpm-skip-checks') != 1) {
        if (!function_exists('get_comic_path')) {
            $cpm_config->warnings[] = __('<strong>It looks like you\'re running an older version of ComicPress.</strong> Storyline, hovertext, and transcript are fully supported in <a href="http://comicpress.org/">ComicPress 2.7</a>. You can use hovertext and transcripts in earlier themes by using <tt>get_post_meta($post->ID, "hovertext", true)</tt> and <tt>get_post_meta($post->ID, "transcript", true)</tt>.', 'comicpress-manager');
        }
    }
    ob_start();
    ?>
  
  <h2 style="padding-right:0;"><?php 
    _e("Bulk Edit", 'comicpress-manager');
    ?>
</h2>
  <p><strong>ComicPress-related information, such as transcripts and Storyline categories for posts, and thumbnail regeneration, can be bulk edited here.</strong> To edit post-specific information, such as title and publishing date, use <strong><a href="edit.php">Edit Posts</a></strong>.

  <?php 
    $data_by_date = array();
    $dates_per_page = 15;
    foreach ($cpm_config->comic_files as $comic_filepath) {
        $comic_file = pathinfo($comic_filepath, PATHINFO_BASENAME);
        if (($result = cpm_breakdown_comic_filename($comic_file)) !== false) {
            $timestamp = strtotime($result['date']);
            $comic_date = date("Y-m-d", $timestamp);
            if (!isset($data_by_date[$comic_date])) {
                $data_by_date[$comic_date] = array();
            }
            $comic_info = array('type' => 'comic', 'timestamp' => $timestamp, 'comic_file' => $comic_file, 'file_title' => $result['converted_title'], 'comic_uri' => cpm_build_comic_uri($comic_filepath, CPM_DOCUMENT_ROOT));
            if (count($thumbnails_found = cpm_find_thumbnails_by_filename($comic_filepath)) > 0) {
                foreach ($thumbnails_found as $thumb_type => $thumb_filename) {
                    $comic_info["thumbnails_found_{$thumb_type}"] = cpm_build_comic_uri(CPM_DOCUMENT_ROOT . $thumb_filename, CPM_DOCUMENT_ROOT);
                }
            }
            $icon_file_to_use = $comic_filepath;
            foreach (array('rss', 'archive', 'mini') as $type) {
                if (isset($thumbnails_found[$type])) {
                    $icon_file_to_use = CPM_DOCUMENT_ROOT . $thumbnails_found[$type];
                }
            }
            $comic_info['icon_uri'] = cpm_build_comic_uri($icon_file_to_use, CPM_DOCUMENT_ROOT);
            $data_by_date[$comic_date][] = $comic_info;
        }
    }
    foreach (cpm_query_posts() as $comic_post) {
        $ok = true;
        if (cpm_get_subcomic_directory() !== false) {
            $ok = in_array(get_option('comicpress-manager-manage-subcomic'), wp_get_post_categories($comic_post->ID));
        }
        if ($ok) {
            $timestamp = strtotime($comic_post->post_date);
            $post_date = date("Y-m-d", $timestamp);
            if (!isset($data_by_date[$post_date])) {
                $data_by_date[$post_date] = array();
            }
            $post_info = array('type' => 'post', 'timestamp' => $timestamp, 'post_id' => $comic_post->ID, 'post_title' => $comic_post->post_title, 'post_object' => (array) $comic_post);
            $data_by_date[$post_date][] = $post_info;
        }
    }
    krsort($data_by_date);
    $all_months = array();
    foreach (array_keys($data_by_date) as $date) {
        list($year, $month, $day) = explode("-", $date);
        $key = "{$year}-{$month}";
        if (!isset($all_months[$key])) {
            $all_months[$key] = date("F Y", strtotime($date));
        }
    }
    krsort($all_months);
    if (isset($_POST['dates'])) {
        if ($_POST['dates'] != -1) {
            $new_data_by_date = array();
            foreach ($data_by_date as $date => $data) {
                if (strpos($date, $_POST['dates']) === 0) {
                    $new_data_by_date[$date] = $data;
                }
            }
            $data_by_date = $new_data_by_date;
        }
    }
    if (!isset($_GET['paged'])) {
        $_GET['paged'] = 1;
    }
    $page_links = paginate_links(array('base' => add_query_arg('paged', '%#%'), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => ceil(count($data_by_date) / $dates_per_page), 'current' => $_GET['paged']));
    $total_data_by_date = count($data_by_date);
    $data_by_date = array_slice($data_by_date, ($_GET['paged'] - 1) * $dates_per_page, $dates_per_page);
    extract(cpm_normalize_storyline_structure());
    $comic_categories = array();
    foreach ($category_tree as $node) {
        $comic_categories[] = end(explode("/", $node));
    }
    $thumbnail_writes = cpm_get_thumbnails_to_generate();
    if ($total_data_by_date > 0) {
        $displaying_num_content = sprintf(__("Displaying %d-%d of %d", 'comicpress-manager'), ($_GET['paged'] - 1) * $dates_per_page + 1, min($total_data_by_date, ($_GET['paged'] - 1) * $dates_per_page + $dates_per_page), $total_data_by_date);
    } else {
        $displaying_num_content = __('No items to display', 'comicpress-manager');
    }
    ?>

  <style type="text/css">
    .storyline-checklist {
      overflow-y: scroll;
      border: solid #ddd 1px;
      height: 12em
    }

    #wpbody-content .bulk-edit-row-post .inline-edit-col-right {
      width: 42%
    }
  </style>
  <div id="table-holder">
    <form id="bulk-form" action="" method="post">
      <input type="hidden" name="action" value="batch-processing" />
      <div class="tablenav">
        <div class="alignleft actions">
          <select id="bulk-action" name="bulk-action">
            <option selected value="-1">Bulk Actions</option>
            <option value="individual">Submit Individual Changes</option>
            <option value="edit">Edit Selected</option>
            <option value="delete">Delete Selected</option>
            <option value="import">Create Posts for Selected Files</option>
            <option value="regen-thumbs">Regenerate Thumbs</option>
          </select>
          <input id="doaction" class="button-secondary action" type="submit" value="Apply" />
          <select id="dates" name="dates">
            <option selected value="-1">Show all dates</option>
            <?php 
    foreach ($all_months as $key => $date) {
        ?>
              <option value="<?php 
        echo $key;
        ?>
"<?php 
        echo $key == $_POST['dates'] ? " selected" : "";
        ?>
><?php 
        echo $date;
        ?>
</option>
            <?php 
    }
    ?>
          </select>
          <input id="dofilter" class="button-secondary action" type="submit" value="Filter" />
        </div>
        <div class="tablenav-pages">
          <span class="displaying-num"><?php 
    echo $displaying_num_content;
    ?>
</span>
          <?php 
    echo $page_links;
    ?>
        </div>
      </div>
      <table class="widefat fixed" id="status-table">
        <thead>
          <tr>
            <th class="check-column" width="3%">
              <input type="checkbox" name="toggle-all" class="batch-all" value="yes" />
            </th>
            <th width="12%"><?php 
    _e("Date", 'comicpress-manager');
    ?>
</th>
            <th width="34%"><?php 
    _e("Object Info", 'comicpress-manager');
    ?>
</th>
            <th width="61%"><?php 
    _e("Operations", 'comicpress-manager');
    ?>
</th>
          </tr>
        </thead>
        <tfoot>
          <tr>
            <th class="check-column">
              <input type="checkbox" name="toggle-all" class="batch-all" value="yes" />
            </th>
            <th><?php 
    _e("Date", 'comicpress-manager');
    ?>
</th>
            <th><?php 
    _e("Object Info", 'comicpress-manager');
    ?>
</th>
            <th><?php 
    _e("Operations", 'comicpress-manager');
    ?>
</th>
          </tr>
        </tfoot>
        <tbody>
          <tr style="display: none" id="bulk-edit" class="inline-edit-row inline-edit-row-post bulk-edit-row bulk-edit-row-post inline-editor">
            <td colspan="4">
              <fieldset class="inline-edit-col-left">
                <div class="inline-edit-col">
                  <h4>Bulk Edit Comic Posts</h4>
                  <div id="bulk-title-div">
                    <div id="bulk-titles" />
                  </div>
                </div>
              </fieldset>
              <fieldset class="inline-edit-col-center inline-edit-categories">
                <div class="inline-edit-col">
                  <span class="title inline-edit-categories-label">
                    Storyline
                  </span>
                  <div class="storyline-checklist">
                    <?php 
    cpm_display_storyline_checkboxes($category_tree, array(), "bulk-storyline");
    ?>
                  </div>
                </div>
              </fieldset>
              <fieldset class="inline-edit-col-right">
                <label>
                  <span class="title" style="width: auto; margin-right: 5px">&lt;img title&gt;/hovertext</span>
                  <input type="text" name="bulk-hovertext" style="width: 100%" />
                </label>
                <label>
                  <span class="title" style="width: auto; margin-right: 5px">Transcript</span>
                  <textarea name="bulk-transcript" style="height: 7em"></textarea>
                </label>
              </fieldset>
              <p class="submit inline-edit-save">
                <a id="cancel" class="button-secondary cancel alignleft" title="Cancel" href="#">Cancel</a>
                <input class="button-primary alignright" id="bulk-edit-submit" type="submit" value="Update Comic Posts" name="bulk-comic-edit" />
                <br class="clear" />
              </p>
            </td>
          </tr>
          <?php 
    $is_grey = false;
    $image_index = 0;
    foreach ($data_by_date as $date => $data) {
        $all_objects_by_type = array();
        foreach ($data as $object) {
            if (!isset($all_objects_by_type[$object['type']])) {
                $all_objects_by_type[$object['type']] = array();
            }
            $all_objects_by_type[$object['type']][] = $object;
        }
        $classes = array("data-row");
        if ($is_grey) {
            $classes[] = "grey";
        }
        $is_first_row = true;
        foreach ($data as $object) {
            ?>
              <tr class="<?php 
            echo implode(" ", $classes);
            ?>
">
                <?php 
            if ($is_first_row) {
                ?>
                  <td align="center" rowspan="<?php 
                echo count($data);
                ?>
">
                    <input id="batch-<?php 
                echo $date;
                ?>
" type="checkbox" class="batch" name="batch-<?php 
                echo $date;
                ?>
" value="yes" />
                  </td>
                  <td rowspan="<?php 
                echo count($data);
                ?>
"><?php 
                echo $date;
                ?>
</td>
                  <?php 
                $is_first_row = false;
            }
            ?>
                <td class="<?php 
            echo $object['type'];
            ?>
">
                  <?php 
            switch ($object['type']) {
                case "comic":
                    ?>
                        <div style="overflow: hidden">
                          <div><strong>
                            Comic: <?php 
                    echo empty($object['file_title']) ? $object['comic_file'] : $object['file_title'];
                    ?>
                          </strong></div>

                          <a href="<?php 
                    echo $object['comic_uri'];
                    ?>
"><img style="float: right; display: inline; margin-right: 5px; max-height: 100px" id="comic-icon-<?php 
                    echo $image_index;
                    ?>
" src="<?php 
                    echo $object['icon_uri'];
                    ?>
" /></a>

                        <?php 
                    $all_found = array();
                    foreach (array('rss', 'archive', 'mini') as $type) {
                        if (isset($object["thumbnails_found_{$type}"])) {
                            $all_found[$type] = $object["thumbnails_found_{$type}"];
                        }
                    }
                    if (count($all_found) > 0) {
                        ?>
                            [
                              <?php 
                        foreach ($all_found as $type => $uri) {
                            ?>
                                <a href="<?php 
                            echo $uri;
                            ?>
"><?php 
                            echo $type;
                            ?>
</a>
                              <?php 
                        }
                        ?>
                            ]
                          <?php 
                    } else {
                        ?>
                            [ No thumbnails found ]
                          <?php 
                    }
                    $image_index++;
                    ?>
                        </div>
                        <?php 
                    break;
                case "post":
                    if (isset($object['post_id'])) {
                        ?>
                          <strong>Post: <?php 
                        echo $object['post_title'];
                        ?>
</strong>
                          <em>(<?php 
                        echo $object['post_id'];
                        ?>
)</em><br />
                          [ <?php 
                        echo generate_view_edit_post_links($object['post_object']);
                        ?>
 ]
                        <?php 
                    }
                    break;
            }
            ?>
                </td>
                <td class="individual-operations <?php 
            echo $object['type'];
            ?>
">
                  <?php 
            switch ($object['type']) {
                case "comic":
                    ?>
                        <input type="hidden" name="file,<?php 
                    echo $date;
                    ?>
,<?php 
                    echo $object['comic_file'];
                    ?>
" value="yes" />

                        <?php 
                    if (count($all_objects_by_type['post']) == 0) {
                        ?>
                          <label><input type="checkbox" name="generate-post-<?php 
                        echo $object['comic_file'];
                        ?>
" value="yes" /> Generate a Post <em>(as a draft)</em></label><br />
                        <?php 
                    }
                    ?>

                        <?php 
                    if (count($thumbnail_writes) > 0) {
                        ?>
                          <label><input type="checkbox" name="regen-<?php 
                        echo $object['comic_file'];
                        ?>
" value="yes" /> Regenerate Thumbs</label><br />
                        <?php 
                    }
                    ?>

                        <label><input type="checkbox" class="delete-file" name="delete-file-<?php 
                    echo $object['comic_file'];
                    ?>
" value="yes" /> Delete Comic</label><br />
                        <!-- <input type="checkbox" id="do-redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" name="do-redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" /> Move to: <input class="needs-calendar" id="redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" type="text" name="redate-file-<?php 
                    echo $object['comic_file'];
                    ?>
" value="<?php 
                    echo $date;
                    ?>
" /> -->

                        <?php 
                    break;
                case "post":
                    $post_categories = array_intersect(wp_get_post_categories($object['post_id']), $comic_categories);
                    $post_category_names = array();
                    foreach ($post_categories as $category_id) {
                        $post_category_names[] = get_cat_name($category_id);
                    }
                    ?>
                        <input type="hidden" name="post,<?php 
                    echo $date;
                    ?>
,<?php 
                    echo $object['post_id'];
                    ?>
" value="yes" />
                        <label><input type="checkbox" class="delete-post" name="delete-post-<?php 
                    echo $object['post_id'];
                    ?>
" value="yes" /> Delete Post</label><br />
                        <!-- <input type="checkbox" id="do-redate-post-<?php 
                    echo $object['post_id'];
                    ?>
" name="do-redate-post-<?php 
                    echo $object['post_id'];
                    ?>
" /> Move to: <input type="text" class="needs-calendar" id="redate-post-<?php 
                    echo $object['post_id'];
                    ?>
" name="redate-post-<?php 
                    echo $object['post_if'];
                    ?>
" value="<?php 
                    echo $date;
                    ?>
" /><br /> -->

                        <?php 
                    $hovertext = get_post_meta($object['post_id'], 'hovertext', true);
                    if (!empty($hovertext)) {
                        ?>
                          <strong>&lt;img title&gt;/hovertext:</strong> <?php 
                        echo $hovertext;
                        ?>
<br />
                        <?php 
                    }
                    ?>

                         <?php 
                    $transcript = get_post_meta($object['post_id'], 'transcript', true);
                    if (!empty($transcript)) {
                        ?>
                          <strong>Transcript:</strong>
                          <div class="transcript-holder"><?php 
                        echo $transcript;
                        ?>
</div>
                        <?php 
                    }
                    ?>

                        <strong>Storyline:</strong> <span class="category-names"><?php 
                    echo implode(", ", $post_category_names);
                    ?>
</span> [ <a href="#" id="category-<?php 
                    echo $object['post_id'];
                    ?>
" class="category">Edit</a> ]
                        <div id="category-holder-<?php 
                    echo $object['post_id'];
                    ?>
" style="display: none">
                          <?php 
                    cpm_display_storyline_checkboxes($category_tree, $post_categories, $object['post_id']);
                    ?>
                        </div>

                        <?php 
                    break;
            }
            ?>
                </td>
              </tr>
            <?php 
        }
        $is_grey = !$is_grey;
    }
    ?>
        </tbody>
      </table>
      <div class="tablenav">
        <div class="alignleft actions">
          <select id="linked-bulk-action" name="linked-bulk-action">
            <option selected value="-1">Bulk Actions</option>
            <option value="individual">Submit Individual Changes</option>
            <option value="edit">Edit Selected</option>
            <option value="delete">Delete Selected</option>
            <option value="import">Create Posts for Selected Files</option>
            <option value="regen-thumbs">Regenerate Thumbs</option>
          </select>
          <input id="linked-doaction" class="button-secondary action" type="submit" value="Apply" />
        </div>
        <div class="tablenav-pages">
          <span class="displaying-num"><?php 
    echo $displaying_num_content;
    ?>
</span>
          <?php 
    echo $page_links;
    ?>
        </div>
      </div>
    </form>
    <script type="text/javascript">
      Event.observe(window, 'load', function() {
        Event.observe($('linked-bulk-action'), 'change', function() {
          $('bulk-action').selectedIndex = $('linked-bulk-action').selectedIndex;
        });

        Event.observe($('bulk-action'), 'change', function() {
          $('linked-bulk-action').selectedIndex = $('bulk-action').selectedIndex;
        });

        $$('.needs-calendar').each(function(element) {
          Calendar.setup({
            inputField: element.id,
            ifFormat: "%Y-%m-%d",
            button: element.id
          });

          Event.observe(element, 'click', function(e) {
            var element = Event.element(e);
            $("do-" + element.id).checked = true;
          });
        });

        $$('a.category').each(function(element) {
          Event.observe(element, 'click', function(e) {
            Event.stop(e);
            Element.toggle("category-holder-" + Event.element(e).id.replace(/^.*\-([0-9]+)$/, '$1'));
          });
        });
      });

      $$('.batch-all').each(function(element) {
        Event.observe(element, 'change', function(e) {
          $$('.batch').each(function(b) { b.checked = element.checked; });
          $$('.batch-all').each (function(b) { b.checked = element.checked; });
        });
      });

      $$('.individual-operations input[type=checkbox]').each(function(element) {
        Event.observe(element, 'click', function(e) {
          $('bulk-action').selectedIndex = 1;
          $('linked-bulk-action').selectedIndex = 1;
        });
      });

      var ok_to_submit = false;

      Event.observe($('bulk-form'), 'submit', function(e) {
        return ok_to_submit;
      });

      Event.observe($('bulk-edit-submit'), 'click', function(e) {
        ok_to_submit = true;
        $('bulk-form').submit();
      });

      Event.observe($('cancel'), 'click', function(e) {
        Event.stop(e);
        $('bulk-edit').hide();
        $('bulk-action').selectedIndex = 0;
      });

      Event.observe($('dofilter'), 'click', function(e) {
        Event.stop(e);
        $('bulk-action').selectedIndex = 0;
        ok_to_submit = true;
        $('bulk-form').submit();
      });

      ['doaction', 'linked-doaction'].each(function(which) {
        Event.observe($(which), 'click', function(e) {
          Event.stop(e);

          switch ($F('bulk-action')) {
            case -1:
            case "-1":
              break;
            case "edit":
              $('bulk-titles').innerHTML = "";
              var any_checked = false;
              $$('.batch').each(function(element) {
                if (element.checked) {
                  any_checked = true;
                  /\-(.*)$/.test(element.id);
                  var date = RegExp.$1;

                  var node = Builder.node("div", [
                    Builder.node("a", { id: date, className: "ntdelbutton", title: "Remove From Bulk Edit" }, [ "X" ]),
                    date
                  ]);

                  $('bulk-titles').insert(node);

                  Event.observe(node, 'click', function(evt) {
                    var node = Event.element(evt);
                    $('batch-' + node.id).checked = false;
                    Element.remove(node.parentNode);

                    var any_checked = false;
                    $$('.batch').each(function(n) {
                      if (n.checked) { any_checked = true; }
                    });

                    if (!any_checked) { $('bulk-edit').hide(); }
                  });
                }
              });

              if (any_checked) { $('bulk-edit').show(); }

              break;
            case "delete":
              if (confirm("<?php 
    _e('You are about to delete the selected posts and comic files. Are you sure?', 'comicpress-manager');
    ?>
")) {
                ok_to_submit = true;
                $('bulk-form').submit();
              }
              break;
            default:
              ok_to_submit = true;
              $('bulk-form').submit();
              break;
          }
        });
      });
    </script>
  </div>

  <?php 
    $activity_content = ob_get_clean();
    cpm_wrap_content($help_content, $activity_content, false);
}
/**
 * The config editor dialog.
 */
function cpm_manager_config()
{
    global $cpm_config;
    extract(cpm_normalize_storyline_structure());
    ob_start();
    ?>

  <h2 style="padding-right:0;"><?php 
    _e("Edit ComicPress Config", 'comicpress-manager');
    ?>
</h2>
  <?php 
    if (!$cpm_config->can_write_config) {
        ?>
    <p>
      <?php 
        _e("<strong>You won't be able to automatically update your configuration.</strong> After submitting, you will be shown the code to paste into comicpress-config.php. If you want to enable automatic updating, check the permissions of your theme folder and comicpress-config.php file.", 'comicpress-manager');
        ?>
    </p>
  <?php 
    }
    echo cpm_manager_edit_config();
    ?>

  <?php 
    if (get_option('comicpress-enable-storyline-support') == 1) {
        ?>
    <form action="" method="post">
      <input type="hidden" name="action" value="manage-subcomic" />
      <table class="form-table" cellspacing="0">
        <tr>
          <th scope="row">Manage a subcomic</th>
          <td>
            <select name="comic">
              <?php 
        $first = true;
        $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties['comic_folder'];
        foreach ($category_tree as $node) {
            $category = get_category(end(explode("/", $node)));
            $selected = get_option('comicpress-manager-manage-subcomic') == $category->term_id ? " selected" : "";
            if (is_dir($path . '/' . $category->slug) || $first) {
                ?>
                    <option value="<?php 
                echo $category->term_id;
                ?>
"<?php 
                echo $selected;
                ?>
><?php 
                echo $category->name . ($first ? " (default)" : "");
                ?>
</option>
                  <?php 
            }
            $first = false;
        }
        ?>
            </select>
            <input type="submit" value="Submit" />
          </td>
        </tr>
      </table>
    </form>
  <?php 
    }
    $activity_content = ob_get_clean();
    cpm_wrap_content(null, $activity_content);
}
/**
 * Generate a hash for passing to wp_insert_post()
 * @param string $filename_date The post date.
 * @param string $filename_converted_title The title of the comic.
 * @return array The post information or false if the date is invalid.
 */
function generate_post_hash($filename_date, $filename_converted_title)
{
    if (isset($_POST['time']) && !empty($_POST['time'])) {
        if (strtolower($_POST['time']) == "now") {
            $filename_date .= " " . strftime("%H:%M:%S");
        } else {
            $filename_date .= " " . $_POST['time'];
        }
    }
    if (($timestamp = strtotime($filename_date)) !== false) {
        if ($filename_converted_title == "") {
            $filename_converted_title = strftime("%m/%d/%Y", $timestamp);
        }
        extract(cpm_normalize_storyline_structure());
        $selected_categories = array();
        if (isset($_POST['in-comic-category'])) {
            foreach ($category_tree as $node) {
                $category_id = end(explode("/", $node));
                if (in_array($category_id, $_POST['in-comic-category'])) {
                    $selected_categories[$category_id] = get_cat_name($category_id);
                }
            }
        }
        $category_name = implode(",", array_values($selected_categories));
        $post_content = "";
        if (isset($_POST['content']) && !empty($_POST['content'])) {
            $post_content = $_POST['content'];
            $post_content = preg_replace('/\\{date\\}/', date('F j, Y', $timestamp), $post_content);
            $post_content = preg_replace('/\\{title\\}/', $filename_converted_title, $post_content);
            $post_content = preg_replace('/\\{category\\}/', $category_name, $post_content);
        }
        $override_title = $_POST['override-title-to-use'];
        $tags = $_POST['tags'];
        if (get_magic_quotes_gpc()) {
            foreach (array('override_title', 'tags', 'post_content') as $field) {
                ${$field} = stripslashes(${$field});
            }
        }
        $post_title = !empty($override_title) ? $override_title : $filename_converted_title;
        $post_date = date('Y-m-d H:i:s', $timestamp);
        $post_date_gmt = get_gmt_from_date($post_date);
        $post_category = array_keys($selected_categories);
        if (isset($_POST['additional-categories'])) {
            if (is_array($_POST['additional-categories'])) {
                $post_category = array_merge($post_category, array_intersect(get_all_category_ids(), $_POST['additional-categories']));
            }
        }
        $publish_mode = $timestamp > time() ? "future" : "publish";
        $post_status = isset($_POST['publish']) ? $publish_mode : "draft";
        $tags_input = $tags;
        return compact('post_content', 'post_title', 'post_date', 'post_date_gmt', 'post_category', 'post_status', 'tags_input');
    }
    return false;
}
function cpm_action_batch_processing()
{
    global $cpm_config;
    $files_to_delete = array();
    $posts_to_delete = array();
    $thumbnails_to_regenerate = array();
    $files_to_redate = array();
    $posts_to_redate = array();
    $posts_to_generate = array();
    $posts_that_exist = array();
    $posts_to_recategorize = array();
    extract(cpm_normalize_storyline_structure());
    $comic_categories = array();
    foreach ($category_tree as $node) {
        $comic_categories[] = end(explode("/", $node));
    }
    $cpm_config->is_cpm_managing_posts = true;
    foreach ($_POST as $field => $value) {
        if ($_POST['bulk-action'] != "-1" && $_POST['bulk-action'] != "individual") {
            $bulk_posts_updated = array();
            if (preg_match("#^(file|post),([^\\,]*),(.*)\$#", $field, $matches) > 0) {
                list($all, $type, $date, $id) = $matches;
                if (isset($_POST["batch-{$date}"])) {
                    switch ($_POST['bulk-action']) {
                        case "delete":
                            switch ($type) {
                                case "file":
                                    if (($result = cpm_match_id_to_file($id)) !== false) {
                                        $files_to_delete[] = $result;
                                    }
                                    break;
                                case "post":
                                    $posts_to_delete[] = $id;
                                    break;
                            }
                            break;
                        case "regen-thumbs":
                            if ($type == "file") {
                                if (($result = cpm_match_id_to_file($id)) !== false) {
                                    $thumbnails_to_regenerate[] = $result;
                                }
                            }
                            break;
                        case "edit":
                            if ($type == "post") {
                                foreach (array('hovertext' => 'bulk-hovertext', 'transcript' => 'bulk-transcript') as $meta_name => $post_name) {
                                    if (isset($_POST[$post_name])) {
                                        update_post_meta($id, $meta_name, $_POST[$post_name]);
                                    }
                                }
                                $post_categories = wp_get_post_categories($id);
                                $did_change = false;
                                if (isset($_POST['bulk-storyline-in-comic-category'])) {
                                    foreach ($comic_categories as $category_id) {
                                        if (in_array($category_id, $_POST['bulk-storyline-in-comic-category'])) {
                                            if (!in_array($category_id, $post_categories)) {
                                                $did_change = true;
                                                $post_categories[] = $category_id;
                                            }
                                        } else {
                                            if (($index = array_search($category_id, $post_categories)) !== false) {
                                                $did_change = true;
                                                array_splice($post_categories, $index, 1);
                                            }
                                        }
                                    }
                                }
                                if ($did_change) {
                                    wp_set_post_categories($id, $post_categories);
                                }
                                $bulk_posts_updates[] = $id;
                            }
                            break;
                        case "import":
                            switch ($type) {
                                case "file":
                                    if (($result = cpm_match_id_to_file($id)) !== false) {
                                        $posts_to_generate[] = $result;
                                    }
                                    break;
                                case "post":
                                    $posts_that_exist[] = $date;
                                    break;
                            }
                            break;
                    }
                }
            }
        } else {
            if (preg_match('#^([0-9]+)-in-comic-category#', $field, $matches) > 0) {
                if (get_post($matches[1])) {
                    $posts_to_recategorize[$matches[1]] = $value;
                }
            }
            if (preg_match("#^delete-file-(.*)\$#", $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $files_to_delete[] = $result;
                }
            }
            if (preg_match("#^delete-post-(.*)\$#", $field, $matches) > 0) {
                if (get_post($matches[1])) {
                    $posts_to_delete[] = $matches[1];
                }
            }
            if (preg_match('#^regen-(.*)$#', $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $thumbnails_to_regenerate[] = $result;
                }
            }
            if (preg_match("#^do-redate-file-(.*)\$#", $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $files_to_redate[$result] = $value;
                }
            }
            if (preg_match("#^generate-post-(.*)\$#", $field, $matches) > 0) {
                if (($result = cpm_match_id_to_file($matches[1])) !== false) {
                    $posts_to_generate[] = $result;
                }
            }
            if (preg_match("#^delete-post-(.*)\$#", $field, $matches) > 0) {
                if (get_post($matches[1])) {
                    $posts_to_redate[$matches[1]] = $value;
                }
            }
        }
    }
    $did_generate_thumbs = array();
    $ok_to_keep_uploading = true;
    $files_created_in_operation = array();
    if (count($thumbnails_to_regenerate) > 0) {
        $thumbnails_written = array();
        $thumbnails_not_written = array();
        foreach ($thumbnails_to_regenerate as $file) {
            $comic_file = pathinfo($file, PATHINFO_BASENAME);
            $wrote_thumbnail = cpm_write_thumbnail($file, $comic_file, true);
            if (!is_null($wrote_thumbnail)) {
                if (is_array($wrote_thumbnail)) {
                    $files_created_in_operation = array_merge($files_created_in_operation, $wrote_thumbnail);
                    $thumbnails_written[] = $comic_file;
                } else {
                    $thumbnails_not_written[] = $comic_file;
                }
            }
            if (function_exists('cpm_wpmu_is_over_storage_limit')) {
                if (cpm_wpmu_is_over_storage_limit()) {
                    $ok_to_keep_uploading = false;
                    break;
                }
            }
        }
        if (count($thumbnails_written) > 0) {
            $cpm_config->messages[] = sprintf(__("<strong>The following thumbnails were written:</strong> %s", 'comicpress-manager'), implode(", ", $thumbnails_written));
        }
        if (count($thumbnails_not_written) > 0) {
            $cpm_config->warnings[] = sprintf(__("<strong>The following thumbnails were not written:</strong> %s", 'comicpress-manager'), implode(", ", $thumbnails_not_written));
        }
    }
    if (count($bulk_posts_updates) > 0) {
        $cpm_config->messages[] = sprintf(__("<strong>The following posts were updated:</strong> %s", 'comicpress-manager'), implode(", ", $bulk_posts_updates));
    }
    if (count($files_to_delete) > 0) {
        $comic_files_deleted = array();
        foreach ($files_to_delete as $file) {
            $comic_file = pathinfo($file, PATHINFO_BASENAME);
            $delete_targets = array($file);
            foreach ($cpm_config->thumbs_folder_writable as $type => $value) {
                $path = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$type . "_comic_folder"];
                if (($subdir = cpm_get_subcomic_directory()) !== false) {
                    $path .= '/' . $subdir;
                }
                $path .= '/' . $comic_file;
                $delete_targets[] = $path;
            }
            foreach ($delete_targets as $target) {
                if (file_exists($target)) {
                    @unlink($target);
                }
            }
            $comic_files_deleted[] = $comic_file;
        }
        $cpm_config->messages[] = sprintf(__("<strong>The following comic files and their associated thumbnails were deleted:</strong> %s", 'comicpress-manager'), implode(", ", $comic_files_deleted));
    }
    if (count($posts_to_delete) > 0) {
        foreach ($posts_to_delete as $post) {
            wp_delete_post($post);
        }
        $cpm_config->messages[] = sprintf(__("<strong>The following posts were deleted:</strong> %s", 'comicpress-manager'), implode(", ", $posts_to_delete));
    }
    $master_category = end(explode("/", reset($category_tree)));
    foreach ($posts_to_generate as $file) {
        $ok = false;
        $comic_file = pathinfo($file, PATHINFO_BASENAME);
        if (($result = cpm_breakdown_comic_filename($comic_file)) !== false) {
            if (!in_array(date("Y-m-d", strtotime($result['date'])), $posts_that_exist)) {
                if (($post_hash = generate_post_hash($result['date'], $result['converted_title'])) !== false) {
                    $post_hash['post_category'] = array($master_category);
                    $ok = !is_null($post_id = wp_insert_post($post_hash));
                }
            }
        }
        if ($ok) {
            $cpm_config->messages[] = sprintf(__('<strong>Created post %1$s for %2$s.</strong>', 'comicpress-manager'), $post_id, $comic_file);
        } else {
            $cpm_config->warnings[] = sprintf(__("<strong>Could not create post for %s.</strong>", 'comicpress-manager'), $comic_file);
        }
    }
    foreach ($posts_to_recategorize as $id => $requested_comic_categories) {
        if (!in_array($id, $posts_to_delete)) {
            $post_categories = wp_get_post_categories($id);
            $did_change = false;
            foreach ($comic_categories as $category_id) {
                if (in_array($category_id, $requested_comic_categories)) {
                    if (!in_array($category_id, $post_categories)) {
                        $did_change = true;
                        $post_categories[] = $category_id;
                    }
                } else {
                    if (($index = array_search($category_id, $post_categories)) !== false) {
                        $did_change = true;
                        array_splice($post_categories, $index, 1);
                    }
                }
            }
            if ($did_change) {
                wp_set_post_categories($id, $post_categories);
                $cpm_config->messages[] = sprintf(__("<strong>Storyline for post %s updated.</strong>", 'comicpress-manager'), $id);
            }
        }
    }
    if (!$ok_to_keep_uploading) {
        $cpm_config->warnings = array($cpm_config->wpmu_disk_space_message);
        foreach ($files_created_in_operation as $file) {
            @unlink($file);
        }
    }
    $cpm_config->comic_files = cpm_read_comics_folder();
}
/**
 * The Storyline Structure editor
 */
function cpm_manager_storyline()
{
    global $cpm_config;
    extract(cpm_normalize_storyline_structure());
    $category_tree_javascript = array();
    $category_names = array();
    foreach ($category_tree as $node) {
        $category_tree_javascript[] = "'{$node}'";
        $parts = explode("/", $node);
        $category = get_category(end($parts));
        $category_names[] = '"' . $category->name . '"';
    }
    $help_content = __("<p><strong>Set Up Storyline Structure</strong> lets you manage your site's categories so that they can be used for storyline management. You would name them with the <strong>names of the logical divisions of your story: Chapter 1, Volume 2, etc.</strong></p>", 'comicpress-manager');
    $help_content .= __("<p>If you want to <strong>change the parent/child relationships of categories</strong>, you'll have to do that at <a href=\"categories.php\"><strong>Manage -> Categories</strong></a> for now.</p>", 'comicpress-manager');
    $help_content .= __("<p>If you <strong>added or deleted categories, or changed parent/child relationships, via Manage -> Categories</strong>, you may need to <strong>rearrange your internal story structure</strong>, otherwise your navigation will be incorrect.</p>", 'comicpress-manager');
    if (!function_exists('get_comic_path')) {
        $cpm_config->warnings[] = __("<strong>It looks like you're running an older version of ComicPress.</strong> Storylines are only fully supported in <a href=\"http://comicpress.org/\" target=\"_new\">ComicPress 2.7</a> or with certain theme modifications.", 'comicpress-manager');
    }
    ob_start();
    ?>
  
  <h2 style="padding-right:0;"><?php 
    _e("Set Up Storyline Structure", 'comicpress-manager');
    ?>
</h2>
  <h3>&mdash; <?php 
    _e("remember, these are all categories and their details can be edited in Posts -> Categories", 'comicpress-manager');
    ?>
</h3>

  <form action="" method="post">
    <input type="hidden" name="action" value="build-storyline-schema" />
    <input type="hidden" name="order" id="order" value="" />
    <input type="hidden" name="original-categories" value="<?php 
    echo implode(",", $category_tree);
    ?>
" />
    <div style="margin-bottom: 5px">
      <label>
        <input type="checkbox"
               id="enable-storyline-support"
               name="enable-storyline-support"
               value="yes"
               <?php 
    echo get_option('comicpress-enable-storyline-support') == 1 ? "checked" : "";
    ?>
 /> Enable Storyline Support
      </label>
    </div>

    <div id="storyline-holder"
         style="margin-bottom: 10px<?php 
    echo get_option('comicpress-enable-storyline-support') == 1 ? "" : "; display: none";
    ?>
">
      <div style="text-align: center"><?php 
    _e("Loading...", 'comicpress-manager');
    ?>
</div>
    </div>
    <input type="submit" class="button" value="<?php 
    _e("Save Structure and Modify Categories", 'comicpress-manager');
    ?>
" /> | <a href="">Cancel Changes</a>
  </form>
  <script type="text/javascript">
    var max_id = <?php 
    echo $max_id;
    ?>
;

    var tree = [ <?php 
    echo implode(", ", $category_tree_javascript);
    ?>
 ];
    var category_names = [ <?php 
    echo implode(", ", $category_names);
    ?>
 ];

    var show_top_category = <?php 
    echo get_option('comicpress-storyline-show-top-category') == 1 ? "true" : "false";
    ?>
;

    function set_order() {
      var order = [];
      $$('#storyline-holder div').each(function(node) {
        if (get_cat_path(node.id) != "") {
          order.push(get_cat_path(node.id));
        }
      });
      $('order').value = order.join(",");
    }

    function new_category(parent) {
      max_id++;
      var parts = parent.split("/");
      var target_id = parent + "/" + max_id;

      return { target_id: target_id, holder: generate_cat_editor(target_id, "", true) };
    }

    function generate_cat_editor(target_id, name, ok_to_delete) {
      var commands;
      if (target_id.split("/").length == 2) {
        var input_parameters = { type: "checkbox", name: "show-top-category", value: "yes" };
        if (show_top_category) { input_parameters['checked'] = true; };
        commands = Builder.node("div", [
          "Create: [ ",
          Builder.node("a", { href: "#", className: "child", id: "child-" + target_id }, [ "Child" ]),
          "|",
          Builder.node("label", [
            Builder.node("input", input_parameters),
            " Show This Category on Site ",
          ]),
          " ]"
        ]);
      } else {
        commands = Builder.node("div", [
          "Create: [ ",
          Builder.node("a", { href: "#", className: "sibling", id: "sibling-" + target_id }, [ "Sibling" ]),
          " | ",
          Builder.node("a", { href: "#", className: "child", id: "child-" + target_id }, [ "Child" ]),
          " ] Move: [ ",
          Builder.node("a", { href: "#", className: "up", id: "up-" + target_id }, [ "Up" ]),
          " | ",
          Builder.node("a", { href: "#", className: "down", id: "down-" + target_id }, [ "Down" ]),
          " ] ",
          Builder.node("a", { href: "#", className: "delete", id: "delete-" + target_id }, [ "Delete" ])
        ]);
      }

      return Builder.node('div', { className: "holder", id: "holder-" + target_id, style: "margin-left: " + (target_id.split("/").length - 2) * 30 + "px" }, [
        Builder.node("input", { type: "text", value: name, name: target_id, size: 40 }),
        commands
      ]);
    }

    var css_search_path = "#storyline-holder .holder";

    function do_move(id, is_down) {
      var start_parts = id.split('/');
      var end_parts;
      var start_node = $('holder-' + id);
      var end_node = $('holder-' + id);
      while (end_node) {
        end_node = is_down ? end_node.next(css_search_path) : end_node.previous(css_search_path);
        if (end_node) {
          end_parts = get_cat_path(end_node.id).split("/");
          if (end_parts.length == start_parts.length) {
            break;
          }
        }
      }

      if (end_node) {
        var ok = true;
        for (i = 0; i < start_parts.length - 1; ++i) {
          if (start_parts[i] != end_parts[i]) { ok = false; break; }
        }

        if (ok) {
          var child_node_lists = {};
          [ [ "start", start_node ], [ "end", end_node ] ].each(function(info) {
            var child_node_list = [];
            var child_node = info[1];
            while (child_node) {
              child_node_list.push(child_node)
              child_node = child_node.next(css_search_path);
              if (child_node) {
                var child_parts = get_cat_path(child_node.id).split("/");
                if (child_parts.length <= start_parts.length) {
                  break;
                }
              }
            }
            child_node_lists[info[0]] = child_node_list;
          });

          if (is_down) { child_node_lists['start'].reverse(true); }

          child_node_lists['start'].each(function(node) {
            for (i = 0, il = child_node_lists['end'].length; i < il; ++i) {
              var target_swap_node = is_down ? node.next(css_search_path) : node.previous(css_search_path);

              is_down ? Element.swapWith(node, target_swap_node) : Element.swapWith(target_swap_node, node);
            }
          });
        }
      }
    }

    function set_up_handlers(id) {
      Event.observe("child-" + id, 'click', function(e) {
        Event.stop(e);
        var new_cat = new_category(id);

        $('holder-' + id).insert({ after: new_cat.holder });
        set_up_handlers(new_cat.target_id);
        set_order();
      });

      if ($("sibling-" + id)) {
        Event.observe("sibling-" + id, 'click', function(e) {
          Event.stop(e);
          var parent_id = id.replace(/\/[^\/]+$/, '');
          var new_cat = new_category(parent_id);

          var top_node = $('holder-' + id);
          do {
            var next_node = top_node.next(css_search_path);
            if (next_node) {
              if (get_cat_path(next_node.id).length > id.length) {
                top_node = next_node;
              } else {
                next_node = null;
              }
            }
          } while (next_node);

          top_node.insert({ after: new_cat.holder });
          set_up_handlers(new_cat.target_id);
          set_order();
        });

        Event.observe("up-" + id, 'click', function(e) {
          Event.stop(e);
          do_move(id, false);
          set_order();
        });

        Event.observe("down-" + id, 'click', function(e) {
          Event.stop(e);
          do_move(id, true);
          set_order();
        });
      }

      if ($("delete-" + id)) {
        Event.observe("delete-" + id, 'click', function(e) {
          Event.stop(e);
          var top_node = $('holder-' + id);
          do {
            var next_node = top_node.next(css_search_path);
            Element.remove(top_node);

            if (next_node) {
              if (get_cat_path(next_node.id).length > id.length) {
                top_node = next_node;
              } else {
                next_node = null;
              }
            }
          } while (next_node);
        });
      }
    }

    function get_cat_path(id) { return id.replace(/^.+\-([^\-]+)$/, '$1'); }

    Event.observe(window, 'load', function() {
      $('storyline-holder').innerHTML = "";
      for (i = 0, il = tree.length; i < il; ++i) {
        $('storyline-holder').insert(generate_cat_editor(tree[i], category_names[i]));
        set_up_handlers(tree[i]);
      }
      set_order();

      Event.observe($('enable-storyline-support'), 'click', function(e) {
        $('enable-storyline-support').checked ? $('storyline-holder').show() : $('storyline-holder').hide();
      });
    });

    Element.addMethods({
      swapWith: (function() {
        if ('swapNode' in document.documentElement)
          return function(element, other) {
            return $(element).swapNode($(other));
          };
        return function(element, other) {
           element = $(element);
           other = $(other);
           var next = other.nextSibling, parent = other.parentNode;
           element.parentNode.replaceChild(other, element);
           return parent.insertBefore(element, next);
        };
      })()
    });
  </script>

  <?php 
    $activity_content = ob_get_clean();
    cpm_wrap_content($help_content, $activity_content);
}