<?php
//$prefix = 'fables_';

/*
$meta_box = array(
	'id' => 'my-meta-box',
	'title' => 'Custom meta box',
	'page' => 'page',
	'context' => 'normal',
	'priority' => 'high',
	'fields' => array(
		array(
			'name' => 'Text box',
			'desc' => 'Enter something here',
			'id' => $prefix . 'text',
			'type' => 'text',
			'std' => 'Default value 1'
		),
		array(
			'name' => 'Textarea',
			'desc' => 'Enter big text here',
			'id' => $prefix . 'textarea',
			'type' => 'textarea',
			'std' => 'Default value 2'
		),
		array(
			'name' => 'Select box',
			'id' => $prefix . 'select',
			'type' => 'select',
			'options' => array('Option 1', 'Option 2', 'Option 3')
		),
		array(
			'name' => 'Select box category',
			'id' => $prefix . 'select',
			'desc' => 'Enter big text here',
			'type' => 'select',
			'options' => get_select_target_options('portfolio_category')
		),
		array(
			'name' => 'Radio',
			'id' => $prefix . 'radio',
			'desc' => 'Enter big text here',
			'type' => 'radio',
			'options' => array(
				array('name' => 'Name 1', 'value' => 'Value 1'),
				array('name' => 'Name 2', 'value' => 'Value 2')
			)
		)
	)
);
*/

global $meta_box,$common_page_box;

$sidebar_options=array('Default Sidebar');
for ($sidebar_count=1; $sidebar_count <=MAX_SIDEBARS; $sidebar_count++ ) {

	if ( of_get_option('theme_sidebar'.$sidebar_count) <> "" ) {
		$active_sidebar = of_get_option('theme_sidebar'.$sidebar_count);
		array_push($sidebar_options, $active_sidebar);
	}
}

// Pull all the Featured into an array
$bg_slideshow_pages = get_posts('post_type=mtheme_featured&orderby=title&numberposts=-1&order=ASC');

if ($bg_slideshow_pages) {
	$options_bgslideshow['none'] = "Not Selected";
	foreach($bg_slideshow_pages as $key => $list) {
		$custom = get_post_custom($list->ID);
		if ( isset($custom["fullscreen_type"][0]) ) { 
			$slideshow_type=$custom["fullscreen_type"][0]; 
		} else {
		$slideshow_type="";
		}
		if ($slideshow_type<>"Fullscreen-Video") {
			$options_bgslideshow[$list->ID] = $list->post_title;
		}
	}
} else {
	$options_bgslideshow[0]="Featured pages not found.";
}

$common_page_box = array(
	'id' => 'common-pagemeta-box',
	'title' => 'General Page Metabox',
	'page' => 'page',
	'context' => 'normal',
	'priority' => 'high',
	'fields' => array(
		array(
			'name' => 'Background Slideshow / Image from',
			'id' => MTHEME . '_meta_background_choice',
			'type' => 'select',
			'desc' => '<div class="metabox-note"><strong>Background Slideshow:</strong> Generate slideshow from theme options set Featured Slideshow</br>
			<strong>Image Attachments:</strong> Generate slideshow from this page/post image attachements</br>
			<strong>Theme options set image:</strong> Display image set from theme options</br>
			<strong>Use featured image:</strong> Display image using current page/post featured image</br>
			<strong>Use custom background:</strong> Display image using a url</br>
			</div>
			',
			'options' => array('Background Slideshow','Image Attachments Slideshow','Theme options set image', 'Use featured image', 'Use custom background', 'none')
		),
		array(
			'name' => 'Custom background image URL',
			'id' => MTHEME . '_meta_background_url',
			'type' => 'text',
			'std' => '',
			'desc' => '<div class="metabox-note">Please provide full url of background. eg. <code>http://www.domain.com/path/image.jpg</code></div>'
		),
		array(
			'name' => 'Background slideshow from a Fullscreen Slideshow post',
			'id' => MTHEME . '_slideshow_bgfeaturedpost',
			'type' => 'selectpost',
			'desc' => '<div class="metabox-note"><strong>Note :</strong>If selected, your choice of fullscreen slideshow post is used to create the  page background slideshow</div>',
			'options' => $options_bgslideshow
		),
		array(
			'name' => 'Choice of Sidebar',
			'id' => MTHEME . '_sidebar_choice',
			'type' => 'select',
			'desc' => '<div class="metabox-note">For Sidebar Active Pages and Posts</div>',
			'options' => $sidebar_options
		)
	)
);

$meta_box = array(
	'id' => 'my-meta-box',
	'title' => MTHEME_NAME . ' metabox',
	'page' => 'page',
	'context' => 'normal',
	'priority' => 'high',
	'fields' => array(
		array(
			'name' => 'Portfolio Style',
			'id' => MTHEME . '_portfolio_style',
			'type' => 'select',
			'desc' => '<div class="metabox-note">Select Style of Porfolio</div>',
			'options' => array('4 Column','3 Column', '2 Column', '1 Column','Filterable Portfolio' )
		),
		array(
			'name' => 'Portfolio Category',
			'id' => MTHEME . '_portfolio_category',
			'desc' => '<div class="metabox-note">Select Portfolio category to generate items from</div>',
			'type' => 'select',
			'options' => get_select_target_options('portfolio_category')
		),
		array(
			'name' => 'Portfolio Photo Link',
			'id' => MTHEME . '_portfolio_link',
			'type' => 'select',
			'desc' => '<div class="metabox-note">Link portfolio image to lightbox or link direct to its post</div>',
			'options' => array('Lightbox', 'Direct link')
		),
		array(
			'name' => 'Portfolio Items per page',
			'id' => MTHEME . '_portfolio_perpage',
			'type' => 'select',
			'desc' => '<div class="metabox-note">Pagination for portfolios</div>',
			'options' => array('list all','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20')
		)
	)
);

if ('post-new.php' == basename($_SERVER['PHP_SELF']) || 'post.php' == basename($_SERVER['PHP_SELF'])) {
	add_action('admin_init', 'mytheme_add_box');
	add_action('save_post', 'mytheme_save_data');
}

function generate_pageboxes($meta_data,$post) {
		// Use nonce for verification
	//echo basename(__FILE__);
	echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
	
	echo '<div class="metabox-wrapper">';


	foreach ($meta_data['fields'] as $field) {
		// get current post meta data
		$meta = get_post_meta($post->ID, $field['id'], true);
		$class="";
		$trigger_element="";
		$trigger="";
		
		$titleclass="is_title";
		if ( isSet($field['heading']) ) {
			if ( $field['heading']=="subhead" ) $titleclass="is_subtitle";
		}

		if (isset($field['class'])) {
			$class = $field['class'];
		}
		if (isset($field['triggerStatus'])) {
			if ($field['triggerStatus']=="on") $trigger_element="trigger_element";
			$trigger = "<span data-toggleClass='".$field['toggleClass']."' ";
			$trigger .= "data-toggleAction='".$field['toggleAction']."' ";
			$trigger .= "data-toggleTrigger='".$field['toggleTrigger']."' ";
			$trigger .= "></span>";
		}
		
		echo '<div class="metabox-fields metaboxtype_', $field['type'] ,' '. $class ." " . $trigger_element .'">',
				$trigger,
				'<div class="metabox_label '.$titleclass.'"><label for="', $field['id'], '"></label></div>';
		if ( isSet($field['type']) ) {
			
			if ( $field['type']!="break" ) {
				echo '<div id="'.$field['id'].'" class="sectiontitle clearfix">'.$field['name'].'</div>';
			}

			if ( $field['type']=="break" ) {
				echo '<div id="'.$field['id'].'" class="maintitle clearfix">'.$field['sectiontitle'].'</div>';
			}
			
			switch ($field['type']) {
				case 'text':
					if ( !isset($field['std']) ) { $field['std']=""; }
					echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />';
					break;
				case 'textarea':
					if ( !isset($field['std']) ) { $field['std']=""; }
					echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>';
					break;
				case 'select':
					$class='';
					if (isset($field['target'])) {
						$field['options'] = get_select_target_options($field['target']);
					}
					
					if (isset($field['target'])) {
						echo '<div class="selectbox"><select name="', $field['id'], '" id="', $field['id'], '">';
						foreach ($field['options'] as $key => $option) {
							if ($key=='0') { $key = 'All the items'; }
							echo '<option value="'.$key.'"', $meta == $key ? ' selected="selected"' : '', '>', $option , '</option>';
						}
						echo '</select></div>';
					} else {
						echo '<div class="selectbox '.$class.'"><select name="', $field['id'], '" id="', $field['id'], '">';
						foreach ($field['options'] as $option) {
							echo '<option', $meta == $option ? ' selected="selected"' : '', '>', $option , '</option>';
						}
						echo '</select></div>';
					}
					
					break;

			case 'selectpost':
				echo '<div class="selectbox"><select name="', $field['id'], '" id="', $field['id'], '">';
				foreach ($field['options'] as $option => $list) {
					echo '<option value=', $option , $meta == $option ? ' selected="selected"' : '', '>', $list, '</option>';
				}
				echo '</select></div>';
				break;

				// Basic text input
				case 'range':
					$output="";
					if ( isset($field['unit']) ) {
						$output .= '<div class="ranger-min-max-wrap"><span class="ranger-min-value">'.$field['min'].'</span>';
						$output .= '<span class="ranger-max-value">'.$field['max'].'</span></div>';
						$output .= '<div id="' . esc_attr( $field['id'] ) . '_slider"></div>';
						$output .= '<div class="ranger-bar">';
					}
					if ( !isSet($meta) || $meta=="" ) { 
						if ($meta==0) {$meta="0";} else {$meta=$field['std'];}
					}
					$meta=floatval($meta);
					$output .= '<input id="' . esc_attr( $field['id'] ) . '" class="of-input" name="' . esc_attr( $field['id'] ) . '" type="text" value="'.$meta.'"';
					
					if ( isset($field['unit']) ) {
						if (isset($field['min'])) {
							$output .= ' min="' . $field['min'];
						}
						if (isset($field['max'])) {
							$output .= '" max="' . $field['max'];
						}
						if (isset($field['step'])) {
							$output .= '" step="' . $field['step'];
						}
						$output .= '" />';
						if (isset($field['unit'])) {
							$output .= '<span>' . $field['unit'] . '</span>';
						}
						$output .= '</div>';
					} else {
						$output .= ' />';
					}

					echo $output;
					
				break;

				case 'radio':
					foreach ($field['options'] as $option) {
						echo '<input type="radio" name="', $field['id'], '" value="', $option, '"', $meta == $option ? ' checked="checked"' : '', ' />', $option;
					}
					break;

				case 'image':
					$output="";
					foreach ($field['options'] as $key => $option) {
						$selected = '';
						$checked = '';
						//echo "---".$meta . "-----".$key;
						if ( $meta == '' ) {
							if ( isSet($field['std']) ) $meta=$field['std'];
							}
						if ( $meta != '' ) {
							if ( $meta == $key ) {
								$selected = ' of-radio-img-selected';
								$checked = ' checked="checked"';
							}
						}
						$output .= '<input type="radio" id="' . esc_attr( $field['id'] .'_'. $key) . '" class="of-radio-img-radio" value="' . esc_attr( $key ) . '" name="' . esc_attr( $field['id']) . '" '. $checked .' />';
						$output .= '<div class="of-radio-img-label">' . esc_html( $key ) . '</div>';
						$output .= '<img data-value="' . esc_attr( $key ) . '" src="' . esc_url( $option ) . '" alt="' . $option .'" class="of-radio-img-img' . $selected .'" onclick="document.getElementById(\''. esc_attr($field['id'] .'_'. $key) .'\').checked=true;" />';
					}
					echo $output;
					break;

				case 'checkbox':
					echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
					break;
			}
		}
		if ( isSet($field['desc']) ) echo '<div class="metabox-description">', $field['desc'], '</div>';
		echo '</div>';
	}
	
	echo '</div>';
}

// Add meta box
function mytheme_add_box() {
	global $meta_box,$common_page_box;
	add_meta_box($common_page_box['id'], $common_page_box['title'], 'common_show_pagebox', $common_page_box['page'], $common_page_box['context'], $common_page_box['priority']);
	add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}

function common_show_pagebox() {
	global $common_page_box, $post;
	
	// Use nonce for verification
	generate_pageboxes($common_page_box,$post);
}


// Callback function to show fields in meta box
function mytheme_show_box() {
	global $meta_box, $post;
	
	// Use nonce for verification
	generate_pageboxes($meta_box,$post);
}


// Save data from meta box
function mytheme_save_data($post_id) {
	global $meta_box,$common_page_box;
	
	// verify nonce
	if ( isset($_POST['mytheme_meta_box_nonce']) ) {
		if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
			return $post_id;
		}
	}

	// check autosave
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
		return $post_id;
	}

	// check permissions
	if ( isset($_POST['post_type']) ) {
		if ('page' == $_POST['post_type']) {
			if (!current_user_can('edit_page', $post_id)) {
				return $post_id;
			}
		} elseif (!current_user_can('edit_post', $post_id)) {
			return $post_id;
		}
	}
	
	foreach ($common_page_box['fields'] as $field) {
		$old = get_post_meta($post_id, $field['id'], true);
		if ( isset($_POST[$field['id']]) ) {
			$new = $_POST[$field['id']];
		}
		
		if ( isset($new) ) {
			if ($new && $new != $old) {
				update_post_meta($post_id, $field['id'], $new);
			} elseif ('' == $new && $old) {
				delete_post_meta($post_id, $field['id'], $old);
			}
		}			
	}
	

	foreach ($meta_box['fields'] as $field) {
		$old = get_post_meta($post_id, $field['id'], true);
		if ( isset($_POST[$field['id']]) ) {
			$new = $_POST[$field['id']];
		}
		
		if ( isset($new) ) {
			if ($new && $new != $old) {
				update_post_meta($post_id, $field['id'], $new);
			} elseif ('' == $new && $old) {
				delete_post_meta($post_id, $field['id'], $old);
			}
		}			
	}
	
}

?>