<?php

global $opt, $custom_sidebar_page, $portfolio_layouts;
$lastID = get_option("cloud_created_att_page");

$prefix = PFIX . '_';

$sidebar_values[] = $sidebar_names[] = "";
if ($_opt[PFIX . "_custom_sidebars"]):
    foreach ((array) $_opt[PFIX . "_custom_sidebars"] as $bar_id => $bar) {
        $sidebar_names[]  = $bar["name"];
        $sidebar_values[] = $bar_id;
    }
endif;

if (is_array($portfolio_layouts)):
    foreach ((array) $portfolio_layouts as $layout_id => $layout) {
        $portfolio_layouts_names[]  = $layout["name"];
        $portfolio_layouts_values[] = $layout_id;
    }
endif;


$slider_names[] = $slider_values[] = "";

$sliders = $_opt[PFIX . '_slider_ids'];
if (is_array($sliders)):
    foreach ((array) $sliders as $slider_id => $slider) {
        if ($slider["type"] !== 'default_slider')
            continue;
        
        $slider_names[]  = $slider["title"];
        $slider_values[] = $slider_id;
    }
endif;


$meta_boxes = array();


$meta_boxes[5] = array(
    'id' => 'cloud_page_slider_settings',
    'title' => __('Header Slider', 'cloudfw'),
    'pages' => array(
        'page',
        'post',
        'portfolio'
    ),
    'context' => 'side',
    'priority' => 'high',
    'fields' => array(
        5 => array(
            'name' => __('Sliders', 'cloudfw'),
            'id' => $prefix . 'slider_id',
            'class' => 'input input_150',
            'type' => 'select',
            'std' => '',
            'options' => $slider_names,
            'values' => $slider_values
        )
    )
);

$meta_boxes[10] = array(
    'id' => 'cloud_page_header_box',
    'title' => __('Header Blurb Area', 'cloudfw'),
    'pages' => array(
        'page','post','portfolio'
    ),
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
        5 => array(
            'name' => __('Blurb Area Title:', 'cloudfw'),
            'desc' => '',
            'id' => $prefix . 'blurb_title',
            'type' => 'text',
            'class' => 'input input_400_bold'
        ),
        10 => array(
            'name' => __('Blurb Area Description:', 'cloudfw'),
            'desc' => '',
            'id' => $prefix . 'blurb_text',
            'type' => 'textarea',
            'class' => 'input input textarea_95per_3line '
        )
    )
);


$meta_boxes[15] = array(
    'id' => 'cloud_page_post_settings',
    'title' => __('Page Settings', 'cloudfw'),
    'pages' => array(
        'post', 'page'
    ),
    'context' => 'side',
    'priority' => 'high',
    'fields' => array(
        5 => array(
            'name' => __('Custom Sidebar:', 'cloudfw'),
            'id' => $prefix . 'custom_sidebar',
            'class' => 'input input_150',
            'desc' => '<a href="' . $custom_sidebar_page . '" target="_blank" >' . __('Add New Custom Sidebar', 'cloudfw') . '</a>',
            'type' => 'select',
            'std' => '',
            'options' => $sidebar_names,
            'values' => $sidebar_values
        )
    )
);

$meta_boxes[20] = array(
    'id' => 'cloud_page_portfolio_settings',
    'title' => __('Portfolio Settings', 'cloudfw'),
    'pages' => array(
        'portfolio'
    ),
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
        5 => array(
            'name' => __('Portfolio Description:', 'cloudfw'),
            'desc' => __('It will get displayed in portfolios page above the featured image', 'cloudfw'),
            'id' => $prefix . 'port_desc',
            'type' => 'textarea',
            'class' => 'input input textarea_95per_3line'
        ),
        10 => array(
            'name' => __('When Click The Link Of The Post:', 'cloudfw'),
            'id' => $prefix . 'port_lightbox',
            'class' => 'input input_300',
            'type' => 'select',
            'std' => 'Left',
            'options' => array(
                '',
                __('Classic: Go to the post', 'cloudfw'),
                __('Lightbox: Display this post\'s featured image or video in the lightbox', 'cloudfw'),
                __('Ajax: Call this post\'s content via ajax by not leaving the page', 'cloudfw')
            ),
            'values' => array(
                '',
                'post',
                'lightbox',
                'inpage'
            )
        ),
        15 => array(
            'name' => __('Video URL For Lightbox:', 'cloudfw'),
            'desc' => '',
            'id' => $prefix . 'port_video',
            'type' => 'text',
            'class' => 'input input_400'
        ),
        20 => array(
            'name' => __('Custom Full Size Image For Lightbox:', 'cloudfw'),
            'desc' => __('(optional) it\'s full size of featured image as default', 'cloudfw'),
            'id' => $prefix . 'custom_image',
            'type' => 'text',
            'class' => 'input input_400'
        ),
        25 => array(
            'name' => __('Custom URL:', 'cloudfw'),
            'desc' => __('(optional) Only for "Go to the post" option', 'cloudfw'),
            'id' => $prefix . 'custom_url',
            'type' => 'text',
            'class' => 'input input_400'
        )
    )
);

$meta_boxes = apply_filters('cloudfw_metaboxes', $meta_boxes);



function _show_gallery($init, $meta = ''){
    global $post;
    return do_shortcode("[gallery size='thumbnail' link='file' columns='5']");
}


function _admin_create_onoff($init, $meta = ''){
    return admin_create_onoff($init, $meta, TRUE);
}

function _admin_create_onoff_off($init, $meta = ''){
    if ($meta == "")
        $meta = "FALSE";
    return admin_create_onoff($init, $meta, TRUE);
}

function _admin_create_upload_button($init, $meta = ''){
    return admin_create_upload_button($init, // id of input:text
        $meta, // value
        TRUE, //preview
        array(
        'src' => $meta,
        'w' => 600
    ), // thumbnail creator url
        'Upload An Image', // upload button test,
        $GLOBALS[lastID], // refference Post ID of Uploading Images
        '	<ul class="description">
			
			<li> Maximum Width: 920px</li>
			
			</ul>
			<div class="clear"></div>
			
		', // description
        FALSE, // delete button text
        'input_500' // external classes for the text input
        );
}



function _admin_create_select_page_button($init, $meta = '') {
    admin_create_select_page_button('internal', $init, //rel
        $meta, //preview
        TRUE, 'id', //cases @ url or id
        FALSE, //hidden
        TRUE, // hide parent: true or false
        'Select A Page', //text
        NULL, // post, page or NULL
        'input_400', // external class for text:input
        NULL // external class for button
        );  
}


function _admin_create_slider($init, $meta = ''){
    $meta ? NULL : $meta = 100;
    
    return admin_create_slider($init, //id
        $meta, //value
        0, // min value
        100, // max value
        10, //step
        NULL, 'jQuery("#amount_' . $init . '").html(ui.value);', // slide function
        '<div style="float:left; padding-top:8px;"><strong><span id="amount_' . $init . '">' . $meta . '</span></strong>%</div>', // preview function
        NULL, // orientation
        'input_400' //class
        );
}


foreach ((array) $meta_boxes as $meta_box) {
    $my_box = new My_meta_box($meta_box);
}

class My_meta_box
{
    protected $_meta_box;
    
    // create meta box based on given data
    function __construct($meta_box)
    {
        if (!is_admin())
            return;
        
        $this->_meta_box = $meta_box;
        
        // fix upload bug: http://www.hashbangcode.com/blog/add-enctype-wordpress-post-and-page-forms-471.html
        $current_page = substr(strrchr($_SERVER['PHP_SELF'], '/'), 1, -4);
        if ($current_page == 'page' || $current_page == 'page-new' || $current_page == 'post' || $current_page == 'post-new') {
            add_action('admin_head', array(
                &$this,
                'add_post_enctype'
            ));
        }
        
        add_action('admin_menu', array(
            &$this,
            'add'
        ));
        
        add_action('save_post', array(
            &$this,
            'save'
        ));
    }
    
    function add_post_enctype()
    {
        echo '
		<script type="text/javascript">
		jQuery(document).ready(function(){
			jQuery("#post").attr("enctype", "multipart/form-data");
			jQuery("#post").attr("encoding", "multipart/form-data");
		});
		</script>';
    }
    
    /// Add meta box for multiple post types
    function add()
    {
        foreach ((array) $this->_meta_box['pages'] as $page) {
            add_meta_box($this->_meta_box['id'], $this->_meta_box['title'], array(
                &$this,
                'show'
            ), $page, $this->_meta_box['context'], $this->_meta_box['priority']);
        }
    }
    
    // Callback function to show fields in meta box
    function show()
    {
        global $post;
        
        // Use nonce for verification
        echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
        
        echo '<table class="form-table">';
        
        foreach ((array) $this->_meta_box['fields'] as $field) {
            // get current post meta data
            $meta = get_post_meta($post->ID, $field['id'], true);
            
            echo '<tr>', '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>', '<td>';
            switch ($field['type']) {
                case 'text':
                    echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" ', ($field['class']) ? ' class="' . $field['class'] . '"' : NULL, ' />', '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
                case 'color':
                    echo '<div style="float:left;"><input type="text" name="', $field['id'], '" id="', $field['id'], '" class="color" value="', $meta ? $meta : $field['std'], '" title="live_color_', $field['id'], '" maxlength="6" size="6" /></div>
                  		<div class="color-live" id="live_color_', $field['id'], '"></div>', '<div class="the_og_desc" style="float:left; clear:left;">', $field['desc'], '</div>';
                    break;
                case 'textarea':
                    echo '<textarea name="', $field['id'], '" id="', $field['id'], '" ', ($field['class']) ? ' class="' . $field['class'] . '"' : NULL, '>', $meta ? $meta : $field['std'], '</textarea>', '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
                case 'select':
                    echo '<span class="select"><select name="', $field['id'], '" id="', $field['id'], '" ', ($field['class']) ? ' class="' . $field['class'] . '"' : NULL, '>';
                    $i = 0;
                    foreach ((array) $field['options'] as $option) {
                        $options_value = $field['values'][$i] ? $field['values'][$i] : $option;
                        
                        echo '<option value="' . $options_value . '"';
                        
                        if ($meta == "") {
                            if ($options_value == $field['std'])
                                echo 'selected="selected"';
                        } else {
                            if ($options_value == $meta)
                                echo 'selected="selected"';
                        }
                        
                        echo '>', $option, '</option>';
                        $i++;
                    }
                    echo '</select></span><div class="clear"></div>', '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
                case 'radio':
                    foreach ((array) $field['options'] as $option) {
                        echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '" id="', $option['value'], '"  ', $meta == $option['value'] ? ' checked="checked"' : '', ' style="margin:-3px 0 0 0" /><span style="margin: 0 15px 0 5px;"><label for="', $option['value'], '">', $option['name'], '</label></span>';
                    }
                    echo '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
                case 'checkbox':
                    echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' style="margin:-3px 5px 0 0"/> ', '<span class="the_og_desc"><label for="', $field['id'], '">', $field['desc'], '</label></span>';
                    break;
                case 'file':
                    echo $meta ? "$meta<br />" : '', '<input type="file" name="', $field['id'], '" id="', $field['id'], '"  />', '<br />', '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
                case 'image':
                    
                    $field['dimension'][0] = $field['dimension'][0] ? $field['dimension'][0] : 150;
                    $field['dimension'][1] = $field['dimension'][1] ? $field['dimension'][1] : 150;
                    $field['cropratio']    = $field['cropratio'] ? "&cropratio=" . ($field['dimension'][0] / $field['dimension'][1]) . ":1" : "";
                    
                    echo $meta ? "<div id=\"container_meta_" . $field['id'] . "\" class=\"container_meta_image\"><a href=\"$meta\" target=\"_blank\"><img src=\"" . get_bloginfo('template_directory') . "/i.php/thumb_cloud.jpg?width=" . $field['dimension'][0] . "&height=" . $field['dimension'][1] . "" . $field['cropratio'] . "&image=$meta&quality=90\" /></a><br />
<br />

					
					<input type=\"button\" id=\"" . $post->ID . "\" name=\"" . $field['id'] . "\" rel=\"" . get_bloginfo("template_directory") . "/functions/ajax/delete_meta.php\" class=\"button-secondary delete_image_button\" value=\"Delete Image\"><br />
<br />

					
					
					</div>" : '', '<input type="file" name="', $field['id'], '" id="', $field['id'], '" />', '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
                case 'cloudfw_onoff':
                    echo $meta ? $field['function']($field['function_init'], $meta) : $field['function']($field['function_init']);
                    echo '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
                case 'cloudfw_custom':
                    
                    echo $meta ? $field['function']($field['function_init'], $meta) : $field['function']($field['function_init']);
                    echo '<div class="the_og_desc">', $field['desc'], '</div>';
                    break;
            }
            echo '<td>', '</tr>';
        }
        
        echo '</table>';
    }
    
    // Save data from meta box
    function save($post_id)
    {
        global $prefix;
        
        // verify 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 ('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 ((array) $this->_meta_box['fields'] as $field) {
            $name = $field['id'];
            
            
            $old = get_post_meta($post_id, $name, true);
            $new = $_POST[$field['id']];
            
            if ($name == $prefix . 'blurb' && $_POST[$field['id']] == "") {
                $new = "FALSE";
            } elseif ($name == $prefix . 'show_title' && $_POST[$field['id']] == "") {
                $new = "FALSE";
            } elseif ($name == $prefix . 'show_thumb' && $_POST[$field['id']] == "") {
                $new = "FALSE";
            } elseif ($name == $prefix . 'featured_image' && $_POST[$field['id']] == "") {
                $new = "FALSE";
            } elseif ($name == $prefix . 'sb_pages' && $_POST[$field['id']] == "") {
                $new = "FALSE";
            }
            
            
            if ($field['type'] == 'file' || $field['type'] == 'image') {
                $file = wp_handle_upload($_FILES[$name], array(
                    'test_form' => false
                ));
                $new  = $file['url'];
                
                if ($new) {
                    $wp_filetype = wp_check_filetype(basename($new), null);
                    
                    $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title' => preg_replace('/\.[^.]+$/', '', basename($new)),
                        'post_content' => '',
                        'post_status' => 'inherit'
                    );
                    $attach_id  = wp_insert_attachment($attachment, $new, $post_id);
                    
                    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                    
                    
                    if (!is_wp_error($attach_id)) {
                        wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $filepath));
                    }
                    
                }
                
                
                
                
            }
            
            if ($new && $new != $old) {
                update_post_meta($post_id, $name, $new);
            } elseif ('' == $new && $old && $field['type'] != 'file' && $field['type'] != 'image') {
                delete_post_meta($post_id, $name, $old);
            }
        }
    }
}