<?php

/*Blog Caption*/
function prefix_caption_metaboxes()
{
	global $wp_meta_boxes;
	add_meta_box('post_caption', __('รายละเอียดเบื้องต้น'), 'prefix_caption_metaboxes_html', 'post', 'normal', 'high');
}

add_action('add_meta_boxes_post', 'prefix_caption_metaboxes');


function prefix_caption_metaboxes_html()
{
	global $post;
//	$custom = get_post_custom($post->ID);
	$caption = get_custom_field('caption', $post->ID);
	?>
    <div class="form-wrap">
        <div class="form-field">
            <label>คำอธิบายบทความ:</label>
            <textarea name="caption" rows="3" cols="40"><?php echo $caption; ?></textarea>
            <p>คำอธิบายแสดงในหน้าหมวดหมู่ (Blog items)</p>
        </div>
    </div>
	<?php
}

function prefix_caption_save_post()
{
	if (empty($_POST)) return; //why is prefix_teammembers_save_post triggered by add new?
	global $post;
	update_post_meta($post->ID, "caption", $_POST["caption"]);
}

add_action('save_post_post', 'prefix_caption_save_post');


/*Category*/
add_action('edit_category_form_fields', 'extra_category_fields');

function extra_category_fields($tag)
{    //check for existing featured ID
	wp_enqueue_media();
	$t_id = $tag->term_id;
	$cat_meta = get_option("category_$t_id");
	$media_id = $cat_meta['image_id'] ? $cat_meta['image_id'] : '';
	$image = wp_get_attachment_image($media_id, 'medium');
	?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="cat_Image_url"><?php _e('ชื่อที่แสดงในหน้าหมวดหมู่'); ?></label></th>
        <td>
            <input type="text" name="Cat_meta[title]" id="Cat_meta[title]" value="<?php echo $cat_meta['title'] ? $cat_meta['title'] : ''; ?>"><br/>
        </td>
    </tr>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="cat_Image_url"><?php _e('เลือกรูปภาพ'); ?></label></th>
        <td>
            <button type="button" class="button misha_upload_image_button">
                <span class="wp-media-buttons-icon"></span> เลือกรูปภาพ
            </button>

            <div id="image-preview" style="margin: 15px 0">
				<?php echo $image; ?>
            </div>
            <input type="hidden" name="Cat_meta[image_id]" value="<?php echo $cat_meta['image_id'] ? $cat_meta['image_id'] : ''; ?>">
            <script>
                jQuery(function ($) {
                    $('body').on('click', '.misha_upload_image_button', function (e) {
                        e.preventDefault();
                        var button = $(this), custom_uploader = wp.media({
                            title: 'Insert image',
                            library: {
                                type: 'image'
                            },
                            button: {
                                text: 'Use this image' // button label text
                            },
                            multiple: false // for multiple image selection set to true
                        }).on('close', function () { // it also has "open" and "close" events
                            var attachment = custom_uploader.state().get('selection').first().toJSON();
                            console.log(attachment);
                            $('#image-preview').html('<img class="true_pre_image" src="' + attachment.sizes.medium.url + '" style="max-width:80%;display:block;" />').next().val(attachment.id).next().show();
                        }).open();
                    });
                });
            </script>
        </td>
    </tr>
	<?php
}

add_action('edited_category', 'save_extra_category_fileds');

function save_extra_category_fileds($term_id)
{
	if (isset($_POST['Cat_meta'])) {
		$t_id = $term_id;
		$cat_meta = get_option("category_$t_id");
		$cat_keys = array_keys($_POST['Cat_meta']);
		foreach ($cat_keys as $key) {
			if (isset($_POST['Cat_meta'][$key])) {
				$cat_meta[$key] = $_POST['Cat_meta'][$key];
			}
		}
		//save the option array
		update_option("category_$t_id", $cat_meta);
	}
}

/*Get Field*/
if (!function_exists('get_custom_field')) {
	function get_custom_field($name, $post_id = null, $default = null)
	{
		global $post;
		$post_id = $post_id ? $post_id : $post->ID;
		$custom = get_post_custom($post_id);
		return (isset($custom[$name][0]) and !empty($custom[$name][0])) ? $custom[$name][0] : $default;
	}
}

