if (isset($GLOBALS['wp_post_types'][$post_type]->cap->edit_posts)) {
    $cap = $GLOBALS['wp_post_types'][$post_type]->cap->edit_posts;
}
if (!current_user_can($cap)) {
    die('<pre>You do not have permission to do that.</pre>');
}
require_once CCTM_PATH . '/includes/GetPostsQuery.php';
//print '<div>'. print_r($_POST, true).'</div>';
$post_id = CCTM::get_value($_POST, 'post_id');
$target_id = CCTM::get_value($_POST, 'target_id');
// Will be either the single or the multi, depending.
$tpl = '';
$tpl = CCTM::load_tpl('widgets/post_item.tpl');
// Just in case...
if (empty($tpl)) {
    print '<p>' . __('Formatting template not found!', CCTM_TXTDOMAIN) . '</p>';
    return;
}
$Q = new GetPostsQuery();
$post = $Q->get_post($post_id);
$post['edit_selected_post_label'] = __('Edit Selected Post', CCTM_TXTDOMAIN);
$post_type = $post['post_type'];
$post['post_icon'] = CCTM::get_thumbnail($post_id);
if ($post_type == 'attachment') {
    $post['edit_url'] = get_admin_url('', 'media.php') . "?attachment_id={$post_id}&action=edit";
} else {
    $post['edit_url'] = get_admin_url('', 'post.php') . "?post={$post_id}&action=edit";
}
$post['target_id'] = $target_id;
print CCTM::parse($tpl, $post);
/*EOF*/
$hash['post_status'] = __('Status', CCTM_TXTDOMAIN);
$hash['post_parent'] = __('Parent', CCTM_TXTDOMAIN);
$hash['post_type'] = __('Post Type', CCTM_TXTDOMAIN);
$hash['add_to_post'] = __('Add to Post', CCTM_TXTDOMAIN);
$hash['add_to_post_and_close'] = __('Add to Post and Close', CCTM_TXTDOMAIN);
//$hash['filter'] 		= __('Filter', CCTM_TXTDOMAIN);
//$hash['show_all']		= __('Show All', CCTM_TXTDOMAIN);
$hash['content'] = '';
// And the items
//$results = array();
foreach ($results as $r) {
    $r['name'] = $raw_fieldname;
    $r['preview'] = __('Preview', CCTM_TXTDOMAIN);
    $r['select'] = __('Select', CCTM_TXTDOMAIN);
    $r['field_id'] = $raw_fieldname;
    $r['thumbnail_url'] = CCTM::get_thumbnail($r['ID']);
    // Translate stuff (issue 279)
    $r['post_title'] = __($r['post_title']);
    $r['post_content'] = __($r['post_content']);
    $r['post_excerpt'] = __($r['post_excerpt']);
    $hash['content'] .= CCTM::parse($item_tpl, $r);
}
$d['content'] .= CCTM::parse($wrapper_tpl, $hash);
$d['content'] .= '<div class="cctm_pagination_links">' . $Q->get_pagination_links() . '</div>';
if (isset($_POST['wrap_thickbox'])) {
    print CCTM::load_view('templates/thickbox.php', $d);
} else {
    //print CCTM::load_view('templates/thickbox_inner.php', $d);
    print $d['content'];
}
exit;
    /**
     * This should return (not print) form elements that handle all the controls required to define this
     * type of field.  The default properties correspond to this class's public variables,
     * e.g. name, label, etc. The form elements you create should have names that correspond
     * with the public $props variable. A populated array of $props will be stored alongside
     * the custom-field data for the containing post-type.
     *
     * @param array $def
     * @return string HTML input fields
     */
    public function get_edit_field_definition($def)
    {
        // Used to fetch the default value.
        require_once CCTM_PATH . '/includes/GetPostsQuery.php';
        // Standard
        $out = $this->format_standard_fields($def);
        // Options
        $Q = new GetPostsQuery();
        $out .= '
			<div class="postbox">
				<div class="handlediv" title="Click to toggle"><br /></div>
				<h3 class="hndle"><span>' . __('Options', CCTM_TXTDOMAIN) . '</span></h3>
				<div class="inside">';
        // Note fieldtype: used to set the default value on new fields
        $out .= '<input type="hidden" id="fieldtype" value="image" />';
        // Initialize / defaults
        $preview_html = '';
        $click_label = __('Choose Relation');
        $label = __('Default Value', CCTM_TXTDOMAIN);
        $this->remove_label = __('Remove All');
        // Handle the display of the default value
        if (!empty($def['default_value'])) {
            $hash = CCTM::get_thumbnail($def['default_value']);
            $fieldtpl = CCTM::load_tpl(array('fields/elements/' . $this->name . '.tpl', 'fields/elements/_' . $this->type . '.tpl', 'fields/elements/_relation.tpl'));
            $preview_html = CCTM::parse($fieldtpl, $hash);
        }
        // Button Label
        $out .= '<div class="' . self::wrapper_css_class . '" id="button_label_wrapper">
			 		<label for="button_label" class="' . self::label_css_class . '">' . __('Button Label', CCTM_TXTDOMAIN) . '</label>
			 		<input type="text" name="button_label" class="' . self::css_class_prefix . 'text" id="button_label" value="' . htmlspecialchars($def['button_label']) . '"/>
			 		' . $this->get_translation('button_label') . '
			 	</div>';
        // Set Search Parameters
        $seach_parameters_str = '';
        if (isset($def['search_parameters'])) {
            $search_parameters_str = $def['search_parameters'];
        }
        $search_parameters_visible = $this->_get_search_parameters_visible($seach_parameters_str);
        $out .= '
			<div class="cctm_element_wrapper" id="search_parameters_wrapper">
				<label for="name" class="cctm_label cctm_text_label" id="search_parameters_label">' . __('Search Parameters', CCTM_TXTDOMAIN) . '</label>
				<span class="cctm_description">' . __('Define which posts are available for selection by narrowing your search parameters.', CCTM_TXTDOMAIN) . '</span>
				<br/>
				<span class="button" onclick="javascript:search_form_display(\'' . $def['name'] . '\',\'' . $def['type'] . '\');">' . __('Set Search Parameters', CCTM_TXTDOMAIN) . '</span>
				<div id="cctm_thickbox"></div>
				<span id="search_parameters_visible">' . $search_parameters_visible . '</span>
				<input type="hidden" id="search_parameters" name="search_parameters" value="' . $search_parameters_str . '" />
				<br/>
			</div>';
        $out .= '</div><!-- /inside -->
			</div><!-- /postbox -->';
        // Validations / Required
        $out .= $this->format_validators($def, false);
        // Output Filter
        $out .= $this->format_available_output_filters($def);
        return $out;
    }
    /**
     * Create only form elements.
     */
    public function form($instance)
    {
        require_once CCTM_PATH . '/includes/GetPostsQuery.php';
        $formatted_post = '';
        // Formatted post
        if (!isset($instance['title'])) {
            $instance['title'] = '';
            // default value
        }
        if (isset($instance['post_id']) && !empty($instance['post_id'])) {
            $Q = new GetPostsQuery();
            $post = $Q->get_post($instance['post_id']);
            $tpl = CCTM::load_tpl('widgets/post_item.tpl');
            $post['edit_selected_post_label'] = __('Edit Selected Post', CCTM_TXTDOMAIN);
            $post['post_icon'] = CCTM::get_thumbnail($instance['post_id']);
            if ($post['post_type'] == 'attachment') {
                $post['edit_url'] = get_admin_url('', 'media.php') . "?attachment_id={$post['ID']}&action=edit";
            } else {
                $post['edit_url'] = get_admin_url('', 'post.php') . "?post={$post['ID']}&action=edit";
            }
            $post['target_id'] = $this->get_field_id('target_id');
            $formatted_post = CCTM::parse($tpl, $post);
        } else {
            $instance['post_id'] = '';
        }
        if (!isset($instance['formatting_string'])) {
            $instance['formatting_string'] = '[+post_content+]';
            // default value
        }
        if (!isset($instance['post_type'])) {
            $instance['post_type'] = 'post';
            // default value
        }
        $post_types = get_post_types(array('public' => 1));
        $post_type_options = '';
        foreach ($post_types as $k => $v) {
            $is_selected = '';
            if ($k == $instance['post_type']) {
                $is_selected = ' selected="selected"';
            }
            $post_type_options .= sprintf('<option value="%s" %s>%s</option>', $k, $is_selected, $v);
        }
        $is_checked = '';
        if (isset($instance['override_title']) && $instance['override_title'] == 1) {
            $is_checked = ' checked="checked"';
        }
        print '<p>' . $this->description . '<a href="http://code.google.com/p/wordpress-custom-content-type-manager/wiki/Post_Widget"><img src="' . CCTM_URL . '/images/question-mark.gif" width="16" height="16" /></a></p>
			<label class="cctm_label" for="' . $this->get_field_id('post_type') . '">Post Type</label>
			<input type="hidden" id="' . $this->get_field_id('post_id') . '" name="' . $this->get_field_name('post_id') . '" value="' . $instance['post_id'] . '" />
			<select name="' . $this->get_field_name('post_type') . '" id="' . $this->get_field_id('post_type') . '">
				' . $post_type_options . '
			</select><br/><br/>
			<span class="button" onclick="javascript:select_post(\'' . $this->get_field_id('post_id') . '\',\'' . $this->get_field_id('target_id') . '\',\'' . $this->get_field_id('post_type') . '\');">' . __('Choose Post', CCTM_TXTDOMAIN) . '</span>

			<br/><br/>
			<strong>Selected Post</strong><br/>
			<!-- This is where we wrote the preview HTML -->
			<div id="' . $this->get_field_id('target_id') . '">' . $formatted_post . '</div>
			<!-- Thickbox ID -->
			<div id="thickbox_' . $this->get_field_id('target_id') . '"></div>
			<br/><br/>
			
			<input type="checkbox" name="' . $this->get_field_name('override_title') . '" id="' . $this->get_field_id('override_title') . '" value="1" ' . $is_checked . '/> <label class="" for="' . $this->get_field_id('override_title') . '">' . __('Override Post Title', CCTM_TXTDOMAIN) . '</label><br/><br/>
			<label class="cctm_label" for="' . $this->get_field_id('title') . '">' . __('Title', CCTM_TXTDOMAIN) . '</label>
			<input type="text" name="' . $this->get_field_name('title') . '" id="' . $this->get_field_id('title') . '" value="' . $instance['title'] . '" />
			
			
			<label class="cctm_label" for="' . $this->get_field_id('formatting_string') . '">' . __('Formatting String', CCTM_TXTDOMAIN) . '</label>
			<textarea name="' . $this->get_field_name('formatting_string') . '" id="' . $this->get_field_id('formatting_string') . '" rows="3" cols="30">' . $instance['formatting_string'] . '</textarea>
			';
    }
    /**
     * This should return (not print) form elements that handle all the controls required to define this
     * type of field.  The default properties correspond to this class's public variables,
     * e.g. name, label, etc. The form elements you create should have names that correspond
     * with the public $props variable. A populated array of $props will be stored alongside
     * the custom-field data for the containing post-type.
     *
     * @param array   $def
     * @return string HTML input fields
     */
    public function get_edit_field_definition($def)
    {
        // Used to fetch the default value.
        require_once CCTM_PATH . '/includes/GetPostsQuery.php';
        // So we can arrange the metafields
        $out = '<script>
          jQuery(function() {
            jQuery( "#sortable" ).sortable();
            jQuery( "#sortable" ).disableSelection();
          });
          </script>';
        // Standard
        $out .= $this->format_standard_fields($def);
        // Options
        $Q = new GetPostsQuery();
        $out .= '
			<div class="postbox">
				<div class="handlediv" title="Click to toggle"><br /></div>
				<h3 class="hndle"><span>' . __('Options', CCTM_TXTDOMAIN) . '</span></h3>
				<div class="inside">';
        // Note fieldtype: used to set the default value on new fields
        $out .= '<input type="hidden" id="fieldtype" value="image" />';
        // Initialize / defaults
        $preview_html = '';
        $click_label = __('Choose Relation');
        $label = __('Default Value', CCTM_TXTDOMAIN);
        $remove_label = __('Remove');
        // Handle the display of the default value
        if (!empty($def['default_value'])) {
            $hash = CCTM::get_thumbnail($def['default_value']);
            $fieldtpl = CCTM::load_tpl(array('fields/elements/' . $this->name . '.tpl', 'fields/elements/_' . $this->type . '.tpl', 'fields/elements/_relation.tpl'));
            $preview_html = CCTM::parse($fieldtpl, $hash);
        }
        // Button Label
        $out .= '<div class="' . self::wrapper_css_class . '" id="button_label_wrapper">
			 		<label for="button_label" class="' . self::label_css_class . '">' . __('Button Label', CCTM_TXTDOMAIN) . '</label>
			 		<input type="text" name="button_label" class="' . self::css_class_prefix . 'text" id="button_label" value="' . htmlspecialchars($def['button_label']) . '"/>
			 		' . $this->get_translation('button_label') . '
			 	</div>';
        // Set Search Parameters
        $seach_parameters_str = '';
        if (isset($def['search_parameters'])) {
            $search_parameters_str = $def['search_parameters'];
        }
        $search_parameters_visible = $this->_get_search_parameters_visible($seach_parameters_str);
        $out .= '
			<div class="cctm_element_wrapper" id="search_parameters_wrapper">
				<label for="name" class="cctm_label cctm_text_label" id="search_parameters_label">' . __('Search Parameters', CCTM_TXTDOMAIN) . '</label>
				<span class="cctm_description">' . __('Define which posts are available for selection by narrowing your search parameters.', CCTM_TXTDOMAIN) . '</span>
				<br/>
				<span class="button" onclick="javascript:search_form_display(\'' . $def['name'] . '\',\'' . $def['type'] . '\');">' . __('Set Search Parameters', CCTM_TXTDOMAIN) . '</span>
				<div id="cctm_thickbox"></div>
				<span id="search_parameters_visible">' . $search_parameters_visible . '</span>
				<input type="hidden" id="search_parameters" name="search_parameters" value="' . $search_parameters_str . '" />
				<br/>
			</div>';
        $out .= '</div><!-- /inside -->
			</div><!-- /postbox -->';
        // Validations / Required
        $out .= $this->format_validators($def, false);
        $defs = CCTM::get_custom_field_defs();
        $li = '<li><input type="checkbox"
			     name="metafields[]" class="cctm_checkbox" id="metafield_%s" value="%s"%s/>
			 <label for="metafield_%s"><strong>%s</strong> (%s)</label>
			 </li>';
        //$out .= '<pre>'.print_r($defs,true).'</pre>';
        $out .= '<div class="postbox">
			<div class="handlediv" title="Click to toggle"><br /></div>
			<h3 class="hndle"><span>' . __('Meta Fields', CCTM_TXTDOMAIN) . '</span></h3>
			<div class="inside">
                <p>' . __('Select which fields should appear as meta data for this relation.', CCTM_TXTDOMAIN) . '</p>
                <ul id="sortable">';
        // First show the ones already assigned here
        foreach ($this->props['metafields'] as $fieldname) {
            $out .= sprintf($li, $fieldname, $fieldname, ' checked="checked"', $fieldname, $defs[$fieldname]['label'], $fieldname);
        }
        // Grab all the others
        foreach ($defs as $fieldname => $d) {
            if ($d['type'] == 'relationmeta' || in_array($fieldname, $this->props['metafields'])) {
                continue;
            }
            $out .= sprintf($li, $fieldname, $fieldname, '', $fieldname, $d['label'], $fieldname);
        }
        $out .= '</ul>
            </div><!-- /inside -->
		</div><!-- /postbox -->';
        // Output Filter
        $out .= $this->format_available_output_filters($def);
        return $out;
    }