<?php
/*
Plugin Name: CF Whiteboard
Plugin URI: http://cfwhiteboard.com
Description: Connects CF Whiteboard to your blog. Please contact help@cfwhiteboard.com for more information or for a product demo.
Version: 2.6
Author: CF Whiteboard
*/
global $CFWHITEBOARD_VERSION;
$CFWHITEBOARD_VERSION = '2.6';


register_activation_hook(__FILE__, 'cfwhiteboard_install');
register_deactivation_hook( __FILE__, 'cfwhiteboard_uninstall');
function cfwhiteboard_install() {
    if (!cfwhiteboard_is_site_enabled())
        return;

    cfwhiteboard_activate_athletes_page();
    cfwhiteboard_activate_example_post();
}
function cfwhiteboard_uninstall() {
    if (!cfwhiteboard_is_site_enabled())
        return;

    cfwhiteboard_deactivate_athletes_page();
    // cfwhiteboard_deactivate_example_post();
}


// Manage the "Athletes Page" on activation/deactivation
function cfwhiteboard_activate_athletes_page() {
    $options = cfwhiteboard_get_options();

    $page_id = $options['athletes_page_id'];
    $page = null;
    if(!empty($page_id)) $page = get_page($page_id);

    if (empty($page_id) || empty($page)) {
        // there was never a page or the page no longer exists
        // create an athletes page
        $page = array(
            // 'ID' => [ <post id> ] //Are you updating an existing post?
            // 'menu_order' => [ <order> ] //If new post is a page, sets the order should it appear in the tabs.
            'comment_status' => 'closed', // 'closed' means no comments.
            'ping_status' => 'closed', // 'closed' means pingbacks or trackbacks turned off
            // 'post_author' => [ <user ID> ] //The user ID number of the author.
            // 'post_category' => [ array(<category id>, <...>) ] //Add some categories.
            'post_content' => 'Loading athletes...', //The full text of the post.
            // 'post_content' => 'Click Edit Post to see how to setup the Whiteboard when you&apos;re posting a WOD.', //The full text of the post.
            // 'post_date' => [ Y-m-d H:i:s ] //The time post was made.
            // 'post_date_gmt' => [ Y-m-d H:i:s ] //The time post was made, in GMT.
            // 'post_excerpt' => [ <an excerpt> ] //For all your post excerpt needs.
            // 'post_name' => 'athletes' // The name (slug) for your post
            // 'post_parent' => [ <post ID> ] //Sets the parent of the new post.
            'post_status' => 'publish', // [ 'draft' | 'publish' | 'pending'| 'future' | 'private' ] //Set the status of the new post.
            'post_title' => 'Athletes', //The title of your post.
            'post_type' => 'page' //You may want to insert a regular post, page, link, a menu item or some custom post type
            // 'tags_input' => [ '<tag>, <tag>, <...>' ] //For tags.
            // 'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // support for custom taxonomies.
        );
        $options['athletes_page_id'] = wp_insert_post( $page );

        if ($options['athletes_page_id'] == 0) return;  // retreat!

        cfwhiteboard_update_options($options);
    } elseif ($page->post_status != 'publish') {
        // make sure the post is not trashed
        wp_publish_post( $page->ID );
    }
}
function cfwhiteboard_deactivate_athletes_page() {
    $options = cfwhiteboard_get_options();

    if( !empty($options['athletes_page_id']) ) {

        wp_trash_post( $options['athletes_page_id'] ); // send page to 'trash'

    }
}


// Manage the private Whiteboard example post on activation/deactivation
function cfwhiteboard_activate_example_post() {
    global $CFWHITEBOARD_WODS_META_KEY;
    global $CFWHITEBOARD_WHITEBOARD_ID_META_KEY;
    $options = cfwhiteboard_get_options();

    $post_id = $options['example_post_id'];
    $post = null;
    if (!empty($post_id)) $post = get_post($post_id);

    if (empty($post_id) || empty($post)) {
        // there was never a page or the page no longer exists
        // create an example post
        $post = array(
            // 'ID' => [ <post id> ] //Are you updating an existing post?
            // 'menu_order' => [ <order> ] //If new post is a page, sets the order should it appear in the tabs.
            'comment_status' => 'closed', // 'closed' means no comments.
            'ping_status' => 'closed', // 'closed' means pingbacks or trackbacks turned off
            // 'post_author' => [ <user ID> ] //The user ID number of the author.
            // 'post_category' => [ array(<category id>, <...>) ] //Add some categories.
            // 'post_content' => 'The body of this page is automatically generated by CF Whiteboard. You\'re welcome to edit the page title, the page permalink, or any other fields for this page.', //The full text of the post.
            'post_content' => '<em>This is an example post generated for you to see how CF Whiteboard works. Edit this post to enter your WOD, write your blog post, delete this message, and publish! Don\'t forget to change it to a Public post. Please <strong><a href="mailto:help@cfwhiteboard.com" target="_blank">email us</a></strong> with any questions!</em>

What\'s that button in the top right corner of today\'s post? It\'s a new <a href="http://cfwhiteboard.com">CrossFit workout tracker</a> for you to use. Click the Whiteboard button to add your score for today\'s workout. Each athlete who tracks their score will automatically get an athlete profile on <a href="'.get_permalink($options['athletes_page_id']).'">our new Athletes page</a> where you can search your past workouts and track your progress. Use it and let us know what you think!

<strong>Workout of the Day</strong>
Back Squat
10-10-10-10-10
at 60% of 1RM
<em>then</em>
21-15-9 reps for time of:
Wall Balls (20/14)
Burpee Pull-ups

<strong>Endurance</strong>
5 Rounds For Time:
200m uphill sprint
Rest 1 minute
200m downhill sprint
Rest 1 minute
', //The full text of the post.
            // 'post_date' => [ Y-m-d H:i:s ] //The time post was made.
            // 'post_date_gmt' => [ Y-m-d H:i:s ] //The time post was made, in GMT.
            // 'post_excerpt' => [ <an excerpt> ] //For all your post excerpt needs.
            // 'post_name' => 'athletes' // The name (slug) for your post
            // 'post_parent' => [ <post ID> ] //Sets the parent of the new post.
            'post_status' => 'private', // [ 'draft' | 'publish' | 'pending'| 'future' | 'private' ] //Set the status of the new post.
            'post_title' => 'Athletes - Track your progress using CF Whiteboard!', //The title of your post.
            'post_type' => 'post' //You may want to insert a regular post, page, link, a menu item or some custom post type
            // 'tags_input' => [ '<tag>, <tag>, <...>' ] //For tags.
            // 'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // support for custom taxonomies.
        );
        $options['example_post_id'] = wp_insert_post( $post );

        if ($options['example_post_id'] == 0) return;  // retreat!

        $wods = array();
        $wods[] = array(
            'name' => 'Workout of the Day',
            'components' => array(
                array(
                    'description' => 'Back Squat
10-10-10-10-10
Every 2 minutes
at 60% of 1RM
',
                    'label' => 'Back Squat',
                    'wp_id' => 1
                ),
                array(
                    'description' => '21-15-9 reps for time of:
Wall Balls (20/14)
Burpee Pull-ups
',
                    'label' => '21-15-9',
                    'wp_id' => 2
                )
            ),
            'wp_id' => 1
        );
        $wods[] = array(
            'name' => 'Endurance',
            'components' => array(
                array(
                    'description' => '5 Rounds For Time:
200m uphill sprint
Rest 1 minute
200m downhill sprint
Rest 1 minute
',
                    'label' => 'Hill Sprints',
                    'wp_id' => 3
                )
            ),
            'wp_id' => 2
        );
        update_post_meta($options['example_post_id'], $CFWHITEBOARD_WODS_META_KEY, $wods);
        update_post_meta($options['example_post_id'], $CFWHITEBOARD_WHITEBOARD_ID_META_KEY, cfwhiteboard_generate_whiteboard_id($options['example_post_id']));

        cfwhiteboard_update_options($options);
    }
}
// We don't really want to do this...  If the coach uses the example post as intended,
// ("Edit the workouts and publish!"), then the "example" post is actually a "real" post,
// so we wouldn't want to delete it.
// function cfwhiteboard_deactivate_example_post() {
//     $options = cfwhiteboard_get_options();
//
//     if( !empty($options['example_post_id']) ) {
//
//         wp_trash_post( $options['example_post_id'] ); // send page to 'trash'
//
//     }
// }





/* Display a welcome notice that can be dismissed.  This notice is displayed on all admin pages until dismissed. */
add_action('admin_notices', 'cfw_admin_notice');
function cfw_admin_notice() {
    global $current_user;
    $user_id = $current_user->ID;

    if (current_user_can('manage_options') && cfwhiteboard_is_site_enabled()) {
        /* Before showing any messages, check that the user hasn't already clicked to ignore them */

        $hide_upgrade_notice = get_user_meta($user_id, 'cfw_upgrade_notice_feb2013');
        $hide_getstarted_notice = get_user_meta($user_id, 'cfw_getstarted_notice');
        $hide_installation_notice = get_user_meta($user_id, 'cfw_installation_notice');

        $show_installation_notice = !($hide_getstarted_notice || $hide_installation_notice);
        $show_upgrade_notice = !$show_installation_notice && !$hide_upgrade_notice;


        if (!$show_installation_notice && !$show_upgrade_notice) return;

        $pointer_content = '<div class="updated" style="background:url('.plugins_url('images/cfwhiteboard.png', __FILE__).') no-repeat 10px 10px #fff; color:#283c42; border:4px solid #a0a9af; padding:14px 0; text-align:left; line-height:1.4; font-size:13px; font-family:\'Helvetica Neue\', Helvetica, Verdana, sans-serif; border-radius:15px; max-width:650px;">';
        $pointer_content .= '<div style="margin-left:167px; border-left:1px solid #ddd; min-height:23px; padding:0 16px 0 13px;">';
        $pointer_content .= '<p style="margin:0; padding:0 0 12px;">';

        if ($show_installation_notice) {
            $pointer_content .= 'Thank you for installing <a href="http://cfwhiteboard.com" target="_blank" style="color:#01a1ff; text-decoration:underline;">CF Whiteboard</a>! Please visit Settings > CF Whiteboard > <a href="options-general.php?page=cf-whiteboard.php#account" style="color:#01a1ff; text-decoration:underline;">Account</a> to activate your free trial and get started.';
        } elseif ($show_upgrade_notice) {
            // benchmarks upgrade 1 of 3 (admin side)
            $pointer_content .= '<strong style="display:block; font-size:19px; font-weight:bold; line-height:26px; color:#e63108;">Start tracking benchmarks now.</strong> Watch the <strong><a href="http://cfwhiteboard.com/wp-admin-tour" target="_blank">tour video</a></strong> to find out how.';
            $pointer_content .= '</p>';
            $pointer_content .= '<p style="margin:0; padding:0 0 12px;">';
            $pointer_content .= '<strong style="display:block; font-size:19px; font-weight:bold; line-height:26px; color:#e63108;">Why track benchmarks?</strong> In the next couple of months, we are releasing brand new athlete profiles with all the weightlifting PRs and benchmark workouts available at a glance.  We will also be able to display leaderboards on your site, and send you email alerts when athletes repeat a benchmark workout.';
        }

        $current_url = 'http://'.$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
        if (stripos($current_url, '?') === false) {
            $current_url .= '?';
        }
        $pointer_content .= '</p>';
        $pointer_content .= '<p style="text-align:right; margin:0;">';
        if ($show_installation_notice) {
            $pointer_content .= '<a href="options-general.php?page=cf-whiteboard.php#account" class="button-primary">Activate Free Trial</a>';
        } elseif ($show_upgrade_notice) {
            $pointer_content .= '<a href="http://blog.cfwhiteboard.com" target="_blank" class="button-primary">Read More</a>';
        }
        $pointer_content .= '<a href="'.$current_url.'&cfw_ignore[]=cfw_installation_notice&cfw_ignore[]=cfw_upgrade_notice_feb2013" class="button" style="margin-left:10px;">Destroy this message</a>';
        $pointer_content .= '</p>';
        $pointer_content .= '</div>';
        $pointer_content .= '</div>';
        echo $pointer_content;

    }
}
add_action('admin_init', 'cfw_notice_ignore');
function cfw_notice_ignore() {
    global $current_user;
    $user_id = $current_user->ID;
    /* If user clicks to ignore the notice, add that to their user meta */
    if ( isset($_GET['cfw_ignore']) && is_array($_GET['cfw_ignore']) ) {
        foreach ($_GET['cfw_ignore'] as $ignore) {
            add_user_meta($user_id, $ignore, 'true', true);
        }
    }
}


/* enable auto-update of this plugin.  contact us at help@cfwhiteboard.com if you would like us to add a setting to turn off auto-updates */
// add_action('admin_init', 'cfwhiteboard_init_auto_update');
// function cfwhiteboard_init_auto_update() {
//     add_filter('auto_update_plugin', 'cfwhiteboard_auto_update', 999999, 2);
// }
// function cfwhiteboard_auto_update($update, $item) {
// //     set_transient('cfw-auto-update-item', 'please let this work', 30);
//     if (0 == strcmp($item, 'cf-whiteboard/cf-whiteboard.php')) {
//         return true;
//         //     set_transient('cfw-auto-update-item', $item, 30);
//     }
//     return $update;
// }



// Utility Classes for normalization of Settings values
abstract class cfwhiteboard_Visibility {
    const Users = 'users'; // logged-in WP users only
    const Everyone = 'everyone';
}
abstract class cfwhiteboard_Position {
    const TitleRight = 'titleright'; // to the right of the title
    const CustomSelector = 'customselector'; // custom jquery selector

    // Custom Selector: Insertion Method
    const CustomSelectorInsertionAppend = 'append';
    const CustomSelectorInsertionPrepend = 'prepend';
    const CustomSelectorInsertionBefore = 'before';
    const CustomSelectorInsertionAfter = 'after';

    // Custom Selector: Alignment
    const CustomSelectorAlignmentFloatLeft = 'floatleft';
    const CustomSelectorAlignmentFloatRight = 'floatright';
    const CustomSelectorAlignmentInline = 'inline';
    const CustomSelectorAlignmentBlock = 'block';

    // Custom Selector: Embed the Whiteboard?
    const CustomSelectorDisplayButton = 'button';
    const CustomSelectorDisplayEmbed = 'embed';
}
abstract class cfwhiteboard_AthletesTheme {
    const Auto = 'auto';
    const Dark = 'dark';
    const Light = 'light';
}

global $CFWHITEBOARD_DEFAULT_OPTIONS;
$CFWHITEBOARD_DEFAULT_OPTIONS = array();
$CFWHITEBOARD_DEFAULT_OPTIONS['affiliate_id'] = strtolower( preg_replace( '/[^a-zA-Z0-9-]/', '', str_replace( array('.', '/'), '-', str_replace(array('http://', 'https://', 'www.'), '', home_url()) ) ) );
$CFWHITEBOARD_DEFAULT_OPTIONS['visibility'] = cfwhiteboard_Visibility::Everyone;
$CFWHITEBOARD_DEFAULT_OPTIONS['position'] = cfwhiteboard_Position::CustomSelector;
$CFWHITEBOARD_DEFAULT_OPTIONS['position_customselectorinsertion'] = cfwhiteboard_Position::CustomSelectorInsertionPrepend;
$CFWHITEBOARD_DEFAULT_OPTIONS['position_customselectortarget'] = '';
$CFWHITEBOARD_DEFAULT_OPTIONS['position_customselectorparent'] = '';
$CFWHITEBOARD_DEFAULT_OPTIONS['position_customselectoralignment'] = cfwhiteboard_Position::CustomSelectorAlignmentFloatRight;
$CFWHITEBOARD_DEFAULT_OPTIONS['position_customselectormargin'] = '0 0 10px 10px';
$CFWHITEBOARD_DEFAULT_OPTIONS['position_customselectordisplay'] = cfwhiteboard_Position::CustomSelectorDisplayButton;
$CFWHITEBOARD_DEFAULT_OPTIONS['whiteboard_exclude_selector'] = '';
$CFWHITEBOARD_DEFAULT_OPTIONS['metabox_on_custom_post_types'] = false;
$CFWHITEBOARD_DEFAULT_OPTIONS['noncrossfit_branding'] = false;
$CFWHITEBOARD_DEFAULT_OPTIONS['athletes_theme'] = cfwhiteboard_AthletesTheme::Auto;
// $CFWHITEBOARD_DEFAULT_OPTIONS['categories'] = array();

function cfwhiteboard_get_options() {
    global $CFWHITEBOARD_DEFAULT_OPTIONS;
    global $CFWHITEBOARD_SITE_OPTIONS;

    if (empty($CFWHITEBOARD_SITE_OPTIONS)) {
        $CFWHITEBOARD_SITE_OPTIONS = get_option('cfwhiteboard_options');
        if ($CFWHITEBOARD_SITE_OPTIONS == FALSE) $CFWHITEBOARD_SITE_OPTIONS = array();


        if (empty($CFWHITEBOARD_DEFAULT_OPTIONS)) $CFWHITEBOARD_DEFAULT_OPTIONS = array();
        $CFWHITEBOARD_SITE_OPTIONS = array_merge($CFWHITEBOARD_DEFAULT_OPTIONS, $CFWHITEBOARD_SITE_OPTIONS);

        if (function_exists('cfwhiteboard_custom_branding')) {
            $custom_branding = cfwhiteboard_custom_branding();
            if (is_array($custom_branding)) {
                $CFWHITEBOARD_SITE_OPTIONS['custom_branding'] = $custom_branding;
            }
        }

        if (cfwhiteboard_is_preview_mode($CFWHITEBOARD_SITE_OPTIONS)) {
            $CFWHITEBOARD_SITE_OPTIONS['affiliate_id'] = $CFWHITEBOARD_SITE_OPTIONS['affiliate_id'] . '_preview';
        }
    }

    return $CFWHITEBOARD_SITE_OPTIONS;
}
function cfwhiteboard_update_options($new_options) {
    global $CFWHITEBOARD_SITE_OPTIONS;

    $return = update_option('cfwhiteboard_options', $new_options);

    if ($return) {
        $CFWHITEBOARD_SITE_OPTIONS = $new_options;
    }
    return $return;
}

function cfwhiteboard_is_site_enabled() {
    return !function_exists('is_multisite') || !is_multisite() || (get_option('cfwhiteboard_enabled') == 'yes');
}

function cfwhiteboard_is_authorized($options) {
    if (empty($options) || empty($options['visibility'])) {
        $options = cfwhiteboard_get_options();
    }

    if ($options['visibility'] == cfwhiteboard_Visibility::Users) {
        return is_user_logged_in();
    }

    // assume $options['visibility'] == cfwhiteboard_Visibility::Everyone
    return true;
}

function cfwhiteboard_is_preview_mode($options) {
    if (is_array($options) && $options['visibility'] == cfwhiteboard_Visibility::Users) {
        return true;
    }

    // assume $options['visibility'] == cfwhiteboard_Visibility::Everyone
    return false;
}

function cfwhiteboard_is_proper_post($id = -1) {
    $currentId = get_the_ID();

    return ($id == $currentId) &&
        !is_feed();

        // old post_type check -- removed to allow whiteboards on custom post types
        // (get_post_type() == 'post');

        // old !is_page test -- removed because is_page returns true if we're currently rendering a 'post' within a 'page'
        // !is_page() &&

        // old in_the_loop test -- removed because sometimes posts are rendered outside the loop
        // in_the_loop() &&

        // old categories test -- removed because we used to display whiteboards on every post of a certain category ->
        // now we show them only on specific posts that they were added to, regardless of category
        // (
        //     empty($options['categories']) ||
        //     in_category($options['categories'])
        // );
}

function cfwhiteboard_get_wods($post_id) {
    global $CFWHITEBOARD_WODS_META_KEY;

    return get_post_meta($post_id, $CFWHITEBOARD_WODS_META_KEY, true);
}
function cfwhiteboard_get_whiteboard_id($post_id, $db_only=false) {
    global $CFWHITEBOARD_WHITEBOARD_ID_META_KEY;

    $whiteboard_id = get_post_meta($post_id, $CFWHITEBOARD_WHITEBOARD_ID_META_KEY, true);

    // optional $db_only parameter prevents the use of a default value in the event that the whiteboard ID is missing from the post meta
    if (isset($db_only) && $db_only == true) {
        return $whiteboard_id;
    }

    if (empty($whiteboard_id)) {
        return cfwhiteboard_generate_legacy_whiteboard_id($post_id);
    }

    return $whiteboard_id;
}
function cfwhiteboard_generate_whiteboard_id($post_id) {
    return "$post_id" . strftime('%y%d%M%S');
}
function cfwhiteboard_generate_legacy_whiteboard_id($post_id) {
    return $post_id;
}

function cfwhiteboard_generate_placeholder($post_id, $options, $wods) {
    if (empty($options) || empty($options['affiliate_id'])) {
        $options = cfwhiteboard_get_options();
    }

    $affiliateId = !empty($options['affiliate_id']) ? $options['affiliate_id'] : 'testaffiliate';

    if (!is_array($wods)) $wods = array();

    $data = array(
        'affiliateId' => $affiliateId,
        'whiteboardId' => cfwhiteboard_get_whiteboard_id($post_id),
        'postId' => $post_id,
        'postPermalink' => get_permalink( $post_id ),
        'postModified' => get_the_modified_time('Y-m-d H:i:s'),
        'wods' => $wods
    );

    $authorization = is_user_logged_in() ? 'data-authorization="admin"' : '';

    return '<div class="cfwhiteboard cleanslate" data-cfwhiteboard="'. esc_attr(json_encode($data)) .'" '. $authorization .'></div>';
}


add_action('wp', 'cfwhiteboard_init_whiteboard');
function cfwhiteboard_init_whiteboard() {
    $options = cfwhiteboard_get_options();

    if (!cfwhiteboard_is_site_enabled())
        return;

    // always allow template_redirect, as long as the plugin is activated.
    add_action('template_redirect', 'cfwhiteboard_json_meta', 1);

    // Debugging
    // if (! (is_user_logged_in() && wp_get_current_user()->first_name == "Collin"))
    //     return;

    // don't include cfw files on admin pages, the athletes pages, or if the whiteboard is not visible to the current user
    if (is_admin() || !cfwhiteboard_is_authorized($options))// || is_page($options['athletes_page_id']))
        return;

    add_action('wp_print_styles', 'cfwhiteboard_stylesheet', 999999);
    add_action('wp_enqueue_scripts', 'cfwhiteboard_scripts', 999999);
    add_action('wp_enqueue_scripts', 'cfwhiteboard_scripts_data', 1000000);
    add_action('wp_head', 'cfwhiteboard_latest_jquery', 1);
    add_action('wp_print_scripts', 'cfwhiteboard_latest_jquery', 100);

    if ($options['position'] == cfwhiteboard_Position::CustomSelector) {
        add_filter('the_content', 'cfwhiteboard_add_to_post', 999999, 2);
        add_filter('the_excerpt', 'cfwhiteboard_add_to_post', 999999, 2);
    } else {
        add_filter('the_title', 'cfwhiteboard_add_to_post', 999999, 2);
    }
}

function cfwhiteboard_add_to_post($titleOrContent, $id = NULL) {
    $options = cfwhiteboard_get_options();

    if (empty($id)) $id = get_the_ID();

    // Workaround for bug in WP < 3.3 where title filters are passed the entire post object instead of just the id
    if (isset($id, $id->ID)) {
        $id = $id->ID;
    }

    // Debug info
    // if (cfwhiteboard_is_preview_mode($options)) {
    //     $titleOrContent .= '<span style="display:none !important;width:0;height:0;">' .
    //         '  title_for_id: ' . $id .
    //         ', current_id = ' . get_the_ID() .
    //         ', is_feed = ' . (is_feed() ? 'true' : 'false') .
    //         ', is_page = ' . (is_page() ? 'true' : 'false') .
    //         ', in_the_loop = ' . (in_the_loop() ? 'true' : 'false') .
    //         ', post_type = ' . get_post_type() .
    //         '</span>';
    // }

    if (post_password_required($id))
        return $titleOrContent;

    if (! cfwhiteboard_is_proper_post($id))
        return $titleOrContent;

    $wods = cfwhiteboard_get_wods($id);
    if ((!is_array($wods)) || empty($wods))
        return $titleOrContent;

    $wods = cfwhiteboard_clean_post_meta($wods);
    if ((!is_array($wods)) || empty($wods))
        return $titleOrContent;

    $cfw_placeholder = cfwhiteboard_generate_placeholder(get_the_ID(), $options, $wods);
	return $cfw_placeholder . $titleOrContent;
}

function cfwhiteboard_stylesheet() {
    global $CFWHITEBOARD_VERSION;
    if (!isset($CFWHITEBOARD_VERSION)) $CFWHITEBOARD_VERSION = '0.0';

    wp_register_style('cfwhiteboard',
        plugins_url("cfwhiteboard-$CFWHITEBOARD_VERSION.css", __FILE__),
        false,
        $CFWHITEBOARD_VERSION
    );
    wp_enqueue_style( 'cfwhiteboard');
}

function cfwhiteboard_scripts() {
    global $CFWHITEBOARD_VERSION;
    if (!isset($CFWHITEBOARD_VERSION)) $CFWHITEBOARD_VERSION = '0.0';

    wp_deregister_script('underscore');
    wp_enqueue_script('underscore',
        plugins_url('js/underscore.js', __FILE__),
        false,
        '1.8.3'
    );

    wp_deregister_script('backbone');
    wp_enqueue_script('backbone',
        plugins_url('js/backbone.js', __FILE__),
        array('underscore', 'jquery'),
        '1.3.3'
    );

    wp_enqueue_script('cfwhiteboard',
        plugins_url("js/all-whiteboard-$CFWHITEBOARD_VERSION.js", __FILE__),
        array('underscore', 'jquery', 'backbone'),
        $CFWHITEBOARD_VERSION
    );
}

function cfwhiteboard_latest_jquery($version) {
    // wp_deregister_script('jquery');
    // wp_register_script('jquery',
    //     plugins_url('js/jquery.js', __FILE__),
    //     false,
    //     '1.8.3'
    // );
    wp_enqueue_script('jquery');
}

function cfwhiteboard_scripts_data() {
    $options = cfwhiteboard_get_options();

    $data = array();
    $data['athletes_page_permalink'] = preg_replace('/\/$/', '', get_permalink($options['athletes_page_id']) ) . '/';

    if (!empty($options['whiteboard_exclude_selector'])) {
        $data['whiteboard_exclude_selector'] = $options['whiteboard_exclude_selector'];
    }
    if ($options['position'] == cfwhiteboard_Position::CustomSelector) {
        $data['position'] = array();
        $data['position']['insertion'] = $options['position_customselectorinsertion'];
        $data['position']['target'] = $options['position_customselectortarget'];
        $data['position']['parent'] = $options['position_customselectorparent'];
        $data['position']['alignment'] = $options['position_customselectoralignment'];
        $data['position']['margin'] = $options['position_customselectormargin'];
        $data['position']['display'] = $options['position_customselectordisplay'];
    }
    if (!empty($options['custom_branding'])) {
        $data['custom_branding_url'] = $options['custom_branding']['url'];
        $data['custom_branding_email'] = $options['custom_branding']['email'];
        $data['custom_branding_button_text'] = $options['custom_branding']['button_text'];
    } elseif ($options['noncrossfit_branding']) {
        $data['custom_branding_url'] = 'mailto:athletesupport@cfwhiteboard.com';
        $data['custom_branding_email'] = 'athletesupport@cfwhiteboard.com';
    }

    wp_localize_script('cfwhiteboard', 'CFW_OPTIONS', $data);
}


function cfwhiteboard_options_page() {
    global $CFWHITEBOARD_DEFAULT_OPTIONS;
    if (!isset($CFWHITEBOARD_DEFAULT_OPTIONS)) $CFWHITEBOARD_DEFAULT_OPTIONS = array();

	// Require admin privs
	if ( ! current_user_can('manage_options') )
		return false;


    // $category_prefix = 'CFWHITEBOARD_category_';

    // Make available services extensible via plugins, themes (functions.php), etc.
    // $CFW_SHARE_SAVE_services = apply_filters('CFW_SHARE_SAVE_services', $CFW_SHARE_SAVE_services);

    if (isset($_POST['cfwhiteboard-enable-site'])) {

        // Nonce verification
        check_admin_referer('cfwhiteboard-update-options');

        // Site Enabled (for Multisite)
        add_option('cfwhiteboard_enabled', 'yes', '', 'no');

        cfwhiteboard_activate_athletes_page();
        cfwhiteboard_activate_example_post();

        ?>
        <div class="updated fade">
            <p>
                CF Whiteboard has been <strong>enabled</strong> on this site.
            </p>
        </div>
        <?php

    } else if (isset($_POST['cfwhiteboard-disable-site'])) {

        // Nonce verification
        check_admin_referer('cfwhiteboard-update-options');

        // Site Disabled (for Multisite)
        delete_option('cfwhiteboard_enabled');

        cfwhiteboard_deactivate_athletes_page();
        // cfwhiteboard_deactivate_example_post();

        ?>
        <div class="updated fade">
            <p>
                CF Whiteboard has been <strong>disabled</strong> on this site.
            </p>
        </div>
        <?php

    } else if (isset($_POST['Submit'])) {

        // Nonce verification
        check_admin_referer('cfwhiteboard-update-options');

        $new_options = cfwhiteboard_get_options();

        // Affiliate ID
        if (!empty($_POST['CFWHITEBOARD_affiliate_id']))
            $new_options['affiliate_id'] = @$_POST['CFWHITEBOARD_affiliate_id'];

        // Visibility (Preview Mode)
        if (isset($_POST['CFWHITEBOARD_visibility']))
            $new_options['visibility'] = @$_POST['CFWHITEBOARD_visibility'];

        // Position
        if (isset($_POST['CFWHITEBOARD_position']))
            $new_options['position'] = @$_POST['CFWHITEBOARD_position'];

        // Custom Selector Fields
        if (!empty($_POST['CFWHITEBOARD_position_customselectorinsertion']))
            $new_options['position_customselectorinsertion'] = @$_POST['CFWHITEBOARD_position_customselectorinsertion'];
        if (is_string($_POST['CFWHITEBOARD_position_customselectortarget']))
            $new_options['position_customselectortarget'] = @$_POST['CFWHITEBOARD_position_customselectortarget'];
        if (is_string($_POST['CFWHITEBOARD_position_customselectorparent']))
            $new_options['position_customselectorparent'] = @$_POST['CFWHITEBOARD_position_customselectorparent'];
        if (!empty($_POST['CFWHITEBOARD_position_customselectoralignment']))
            $new_options['position_customselectoralignment'] = @$_POST['CFWHITEBOARD_position_customselectoralignment'];
        if (is_string($_POST['CFWHITEBOARD_position_customselectormargin']))
            $new_options['position_customselectormargin'] = @$_POST['CFWHITEBOARD_position_customselectormargin'];
        if (!empty($_POST['CFWHITEBOARD_position_customselectordisplay']))
            $new_options['position_customselectordisplay'] = @$_POST['CFWHITEBOARD_position_customselectordisplay'];

        // Whiteboard Exclude Selector
        if (is_string($_POST['CFWHITEBOARD_whiteboard_exclude_selector']))
            $new_options['whiteboard_exclude_selector'] = @$_POST['CFWHITEBOARD_whiteboard_exclude_selector'];

        // Athletes Theme
        if (isset($_POST['CFWHITEBOARD_athletes_theme']))
            $new_options['athletes_theme'] = @$_POST['CFWHITEBOARD_athletes_theme'];

        // Show meta box on custom post types?
        if (isset($_POST['CFWHITEBOARD_metabox_on_custom_post_types']))
            $new_options['metabox_on_custom_post_types'] = (@$_POST['CFWHITEBOARD_metabox_on_custom_post_types'] == 'yes');

        // Hide CrossFit references in our branding
        if (isset($_POST['CFWHITEBOARD_noncrossfit_branding']))
            $new_options['noncrossfit_branding'] = (@$_POST['CFWHITEBOARD_noncrossfit_branding'] == 'yes');

        // Categories
        // $new_options['categories'] = array();
        // $categories = get_categories($category_args);
        // foreach($categories as $category) {
        //     if (!empty($_POST[$category_prefix . $category->cat_ID])) {
        //         array_push($new_options['categories'], $category->cat_ID);
        //     }
        // }

        // Preview Only (Whiteboard is only visible to logged-in WordPress users.  Workout entries will not be saved.)
        // Active (Whiteboard is visible to anyone who visits your website.  Workout entries will be saved.)

        // $new_options['position'] = ($_POST['A2A_SHARE_SAVE_position']) ? @$_POST['A2A_SHARE_SAVE_position'] : 'bottom';
        // $new_options['display_in_posts_on_front_page'] = (@$_POST['A2A_SHARE_SAVE_display_in_posts_on_front_page']=='1') ? '1':'-1';
        // $new_options['display_in_excerpts'] = (@$_POST['A2A_SHARE_SAVE_display_in_excerpts']=='1') ? '1':'-1';
        // $new_options['display_in_posts'] = (@$_POST['A2A_SHARE_SAVE_display_in_posts']=='1') ? '1':'-1';
        // $new_options['display_in_pages'] = (@$_POST['A2A_SHARE_SAVE_display_in_pages']=='1') ? '1':'-1';
        // $new_options['display_in_feed'] = (@$_POST['A2A_SHARE_SAVE_display_in_feed']=='1') ? '1':'-1';
        // $new_options['show_title'] = (@$_POST['A2A_SHARE_SAVE_show_title']=='1') ? '1':'-1';
        // $new_options['onclick'] = (@$_POST['A2A_SHARE_SAVE_onclick']=='1') ? '1':'-1';
        // $new_options['button'] = @$_POST['A2A_SHARE_SAVE_button'];
        // $new_options['button_custom'] = @$_POST['A2A_SHARE_SAVE_button_custom'];
        // $new_options['additional_js_variables'] = trim(@$_POST['A2A_SHARE_SAVE_additional_js_variables']);
        // $new_options['inline_css'] = (@$_POST['A2A_SHARE_SAVE_inline_css']=='1') ? '1':'-1';
        // $new_options['cache'] = (@$_POST['A2A_SHARE_SAVE_cache']=='1') ? '1':'-1';
        //
        // // Schedule cache refresh?
        // if (@$_POST['A2A_SHARE_SAVE_cache']=='1') {
        //  A2A_SHARE_SAVE_schedule_cache();
        //  A2A_SHARE_SAVE_refresh_cache();
        // } else {
        //  A2A_SHARE_SAVE_unschedule_cache();
        // }
        //
        // // Store desired text if 16 x 16px buttons or text-only is chosen:
        // if( $new_options['button'] == 'favicon.png|16|16' )
        //  $new_options['button_text'] = $_POST['A2A_SHARE_SAVE_button_favicon_16_16_text'];
        // elseif( $new_options['button'] == 'share_16_16.png|16|16' )
        //  $new_options['button_text'] = $_POST['A2A_SHARE_SAVE_button_share_16_16_text'];
        // else
        //  $new_options['button_text'] = ( trim($_POST['A2A_SHARE_SAVE_button_text']) != '' ) ? $_POST['A2A_SHARE_SAVE_button_text'] : __('Share/Bookmark','add-to-any');
        //
        // // Store chosen individual services to make active
        // $active_services = Array();
        // if ( ! isset($_POST['A2A_SHARE_SAVE_active_services']))
        //  $_POST['A2A_SHARE_SAVE_active_services'] = Array();
        // foreach ( $_POST['A2A_SHARE_SAVE_active_services'] as $dummy=>$sitename )
        //  $active_services[] = substr($sitename, 7);
        // $new_options['active_services'] = $active_services;
        //
        // // Store special service options
        // $new_options['special_facebook_like_options'] = array(
        //  'verb' => ((@$_POST['addtoany_facebook_like_verb'] == 'recommend') ? 'recommend' : 'like')
        // );
        // $new_options['special_twitter_tweet_options'] = array(
        //  'show_count' => ((@$_POST['addtoany_twitter_tweet_show_count'] == '1') ? '1' : '-1')
        // );
        // $new_options['special_google_plusone_options'] = array(
        //  'show_count' => ((@$_POST['addtoany_google_plusone_show_count'] == '1') ? '1' : '-1')
        // );

    	cfwhiteboard_update_options($new_options);

		?>
    	<div class="updated fade">
            <p>
                <strong><?php _e('Settings saved.'); ?></strong>
                <?php _e('Please empty the page cache for new settings to take effect.', 'cf-whiteboard'); ?>
            </p>
        </div>
		<?php

    } else if (isset($_POST['Reset'])) {
        // Nonce verification
        check_admin_referer('cfwhiteboard-update-options');

		delete_option('cfwhiteboard_options');
    }

    $options = cfwhiteboard_get_options();

    $show_multisite_welcome = !cfwhiteboard_is_site_enabled();

    // Get info for the categories options
    // $category_args = array(
    //     'orderby' => 'name',
    //     'hide_empty' => 0
    // );
    // $categories = get_categories($category_args);
    // foreach($categories as $category) {
    //     $category->selected = empty($options['categories']) ? true : in_array($category->cat_ID, $options['categories']);
    // }

    ?>

    <!--
    <style>
        form > fieldset {
            border: 1px solid #ccc;
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
            padding: 10px 15px;
        }
        fieldset + fieldset {
            margin-top: 15px;
        }
        fieldset ul {
            margin: 0;
        }
        form > fieldset > ul > li {
            padding-left: 24px;
            text-indent: -24px;
        }
        form > fieldset > ul > li > * {
            text-indent: 0;
        }
        fieldset h1 {
            font-size: 1em;
        }

        fieldset ul li fieldset {
            background: #f5f5f5;
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
            margin-top: 7px;
            padding: 10px 12px;
            text-shadow: 0 1px 0 #fff;
        }
        fieldset ul li fieldset label {
            display: inline-block;
            width: 100px;
            *zoom: 1;
            *display: inline;
        }

        input[type="radio"],
        input[type="checkbox"] {
            font-size: 19px;
        }
        input[type="radio"] + label,
        input[type="checkbox"] + label {
            line-height: 19px;
            margin-left: 5px;
        }
    </style>
    -->
    <style>
        .wrap input[type="text"],
        .wrap input[type="password"],
        .wrap input[type="number"],
        .wrap input[type="search"],
        .wrap input[type="email"],
        .wrap input[type="url"],
        .wrap textarea {
            -webkit-box-sizing: content-box;
            -moz-box-sizing: content-box;
            -ms-box-sizing: content-box;
            box-sizing: content-box;
        }
        .cfw-twb select.input-xlarge {
            width: 284px;
        }
        .cfw-twb .checkbox {
            background: none;
        }
        .cfw-twb .radio input[type="radio"] {
            margin-top: 3px;
        }
    </style>

    <div class="wrap">

        <h2><!-- Leave Empty so that admin notices don't separate our navbar from our content --></h2>

        <div class="cfw-twb">
            <form method="post" action="<?php echo $show_multisite_welcome ? '' : '#whiteboard'; ?>" style="max-width:600px;">

                <?php wp_nonce_field('cfwhiteboard-update-options'); ?>

                <div class="navbar js-scroll-here-on-iframe-reload">
                    <div class="navbar-inner" style="padding-right:0;">
                        <ul class="nav">
                            <li class="dropdown">
                                <a href="javascript://" class="dropdown-toggle brand" data-toggle="bsdropdown" data-target=".cfw-dummy-selector" style="background:url(<?php echo plugins_url('images/cfwhiteboard.png', __FILE__); ?>) no-repeat 5px 4px; text-indent:140px;">
                                    <b class="caret"></b>
                                </a>
                                <ul class="dropdown-menu" style="left:-14px;">
                                    <li><a href="http://cfwhiteboard.com" target="_blank"><i class="icon-home"></i> CFWhiteboard.com</a></li>
                                    <li><a href="mailto:help@cfwhiteboard.com" target="_blank"><i class="icon-comment"></i> Contact Us</a></li>
                                    <li><a href="http://cfwhiteboard.com/terms" target="_blank"><i class="icon-bookmark"></i> Terms of Service</a></li>
                                </ul>
                            </li>
                        </ul>
                        <?php if ($show_multisite_welcome) { ?>
                            <ul class="nav pull-right" style="margin-right:0;">
                                <li><a>One Click Installation is available on this site.</a></li>
                            </ul>
                        <?php } else { ?>
                            <ul class="nav internal pull-right" style="margin-right:0;">
                                <li class="divider-vertical" style="margin:0;"></li>
                                <li class="active"><a href="#welcome">Get Started</a></li>
                                <li class="divider-vertical" style="margin:0;"></li>
                                <li><a href="#whiteboard">Whiteboard Settings</a></li>
                                <li class="divider-vertical" style="margin:0;"></li>
                                <li><a href="#account">Account</a></li>
                            </ul>
                        <?php } ?>
                    </div>
                </div>
                <div class="clearfix"></div>

                <div id="unsaved-changes-alert" class="alert alert-info" style="display:none;">
                    <!-- <button type="button" class="close" data-dismiss="alert">&times;</button> -->
                    <strong>Yo!</strong> You have unsaved changes.
                    <input class="btn btn-primary btn-mini pull-right" type="submit" name="Submit" style="margin:-1px -25px 0 10px;" value="<?php esc_attr_e('Save Now', 'cf-whiteboard' ); ?>" />
                </div>

                <?php if ($show_multisite_welcome) { ?>

                    <!-- what is cf whiteboard? -->
                    <h3>What is CF Whiteboard?</h3>
                    <p class="lead">
                        CF Whiteboard is a workout tracker that's built into your website.
                    </p>
                    <h3>What's special about it?</h3>
                    <ul style="list-style:disc outside; font-size:16px; font-weight:200;">
                        <li>Athletes love it &ndash; just ask the 1000+ athletes that have used it in the last week.</li>
                        <li>Keeps members engaged with your online community on your website.</li>
                        <li>Free social marketing when your athletes share their progress on Facebook.</li>
                        <li>Increases your new member conversion and athlete retention.</li>
                        <li>Get email alerts whenever your athletes complete a benchmark workout.</li>
                    </ul>
                    <p style="font-size:16px; font-weight:200;">
                        Find out more at <strong><a href="http://cfwhiteboard.com" target="_blank">www.cfwhiteboard.com</a></strong>
                    </p>

                    <h3>
                        What happens when I install it?
                    </h3>
                    <p style="font-size:16px; font-weight:200;">
                        <strong>Add a Whiteboard to any blog post</strong> by filling out the CF Whiteboard box on your Add New Post page.
                    </p>
                    <p style="font-size:16px; font-weight:200;">
                        <strong>Athletes track their scores using the Whiteboard</strong> that appears next to the blog post.
                    </p>
                    <p style="font-size:16px; font-weight:200;">
                        Every athlete who uses the Whiteboard will automatically get an <strong>athlete profile on your website</strong> where they can search their history, add a bio, and more.
                    </p>
                    <p style="font-size:16px; font-weight:200;">
                        <strong>The first month is free</strong>, so install it now and try it out. No credit card required.
                        After that, the service costs just <strong>$50/month for your entire gym</strong>.
                    </p>

                    <div style="text-align:center; padding:33px 0 50px;">
                        <input class="btn btn-primary btn-large" type="submit" name="cfwhiteboard-enable-site" value="<?php esc_attr_e('Install CF Whiteboard', 'cf-whiteboard' ); ?>" />
                        <a class="btn disabled btn-large" href="javascript:// Uninstall"><?php _e('Uninstall'); ?></a>
                    </div>

                    <p style="font-size:16px; font-weight:200;">
                        While installation is just one click away, it's always good to contact us for free support so we can make sure there aren't any conflicts with themes, plugins, or site specific settings. <strong><a href="mailto:help@cfwhiteboard.com" target="_blank">help@cfwhiteboard.com</a></strong>
                    </p>
                <?php } else { ?>

                    <div class="tab-content" style="overflow:visible;">
                        <div id="welcome" class="tab-pane active">

                            <h3>
                                Welcome!
                                <!--
                                <a style="display:inline-block;vertical-align:text-top;font-size:12px;background:#eee;border-radius:3px;padding:0 6px;margin:0;line-height:2;*zoom:1;*display:inline;" href="http://cfwhiteboard.com">Company Website</a>
                                <a style="display:inline-block;vertical-align:text-top;font-size:12px;background:#eee;border-radius:3px;padding:0 6px;margin:0;line-height:2;*zoom:1;*display:inline;" href="http://cfwhiteboard.com/terms">Terms of Service</a>
                                -->
                            </h3>
                            <!-- <p style="background:#444; border:none; color:#fff; padding:12px 15px; border-radius:3px; text-shadow:0 -1px 0 #000; box-shadow:inset 0 1px 13px #000;"> -->
                            <p>
                                Please <a href="mailto:help@cfwhiteboard.com" target="_blank">email us</a> with any questions.
                                CF Whiteboard works great out of the box for most sites, but everyone's setup is a little different.
                                Let us know right away if you run into any issues - it's usually an easy fix.
                            </p>

                            <h3 style="margin-top:40px; margin-bottom:20px;">
                                Get Started
                            </h3>

                            <?php $example_post_url = get_permalink($options['example_post_id']); ?>
                            <?php $athletes_page_url = get_permalink($options['athletes_page_id']); ?>
                            <?php $example_href = empty($example_post_url) ? "javascript:alert('We had trouble generating an example post on your site. To try out the whiteboard, just create a new Post - look for the CF Whiteboard box where you can enter your workout details.');" : $example_post_url; ?>
                            <?php $athletes_href = empty($athletes_page_url) ? "javascript:alert('We had trouble generating an athletes page on your site. Please contact us right away so we can fix that for you. help@cfwhiteboard.com');" : $athletes_page_url; ?>

                            <div class="accordion" id="accordion76i2c">
                                <div class="accordion-group">
                                    <div class="accordion-heading">
                                        <a class="accordion-toggle" data-toggle="bscollapse" data-parent="#accordion76i2c" href="#collapse2398yg">
                                            1. Try out the whiteboard
                                        </a>
                                    </div>
                                    <div id="collapse2398yg" class="accordion-body collapse">
                                        <div class="accordion-inner">
                                            <p>
                                                Check out the <a target="_blank" href="<?php echo $example_href ?>">private example post</a> on your website.
                                                Click the <strong>Whiteboard</strong> button, then click the <strong>[+]</strong> button and create a test entry.
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                <div class="accordion-group">
                                    <div class="accordion-heading">
                                        <a class="accordion-toggle" data-toggle="bscollapse" data-parent="#accordion76i2c" href="#collapse23lfi">
                                            2. Check out your athlete profile
                                        </a>
                                    </div>
                                    <div id="collapse23lfi" class="accordion-body collapse">
                                        <div class="accordion-inner">
                                            <p>
                                                An athlete profile was automatically generated for you when you created that test entry above. There are two ways to get to your profile:
                                            </p>
                                            <ul style="list-style:disc outside; margin-left:30px;">
                                                <li>
                                                    Visit your new <a target="_blank" href="<?php echo $athletes_href; ?>">Athletes Page</a>, then click your name to get to your profile.
                                                </li>
                                                <li>
                                                    Go back to the <a target="_blank" href="<?php echo $example_href ?>">example post</a>, open the Whiteboard, and click on your name to get to your athlete profile.
                                                </li>
                                            </ul>
                                            <p>
                                                Don't forget to add the Athletes Page to the menu bar on your website so your athletes have an easy way to find it.
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                <div class="accordion-group">
                                    <div class="accordion-heading">
                                        <a class="accordion-toggle" data-toggle="bscollapse" data-parent="#accordion76i2c" href="#collapse45k5">
                                            3. Activate your free trial
                                        </a>
                                    </div>
                                    <div id="collapse45k5" class="accordion-body collapse">
                                        <div class="accordion-inner">
                                            <p>
                                                Click the <strong>Account</strong> tab above!
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                <div class="accordion-group">
                                    <div class="accordion-heading">
                                        <a class="accordion-toggle" data-toggle="bscollapse" data-parent="#accordion76i2c" href="#collapse87ae2">
                                            4. Update the example post &amp; publish
                                        </a>
                                    </div>
                                    <div id="collapse87ae2" class="accordion-body collapse">
                                        <div class="accordion-inner">
                                            <p>
                                                Click Edit Post and look for the CF Whiteboard box near the top of the page (under the post title, above the post body). Then:
                                            </p>
                                            <ul style="list-style:disc outside; margin-left:30px;">
                                                <li>
                                                    Replace the example WODs with your WOD for today.
                                                </li>
                                                <li>
                                                    Write your blog post.
                                                </li>
                                                <li>
                                                    Change it from a private post to a public post.
                                                </li>
                                                <li>
                                                    Publish.
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <h3 style="margin-top:40px;">
                                Latest Features
                            </h3>
                            <p>
                                CF Whiteboard now has Android and iPhone apps to make it easier than ever to track your workouts! It's hard to explain how good it is
                                to track a new weightlifting number in between sets.
                            </p>

                            <h3 style="margin-top:40px;">
                                What We're Working On Now
                            </h3>
                            <p>
                                Right now we're working on benchmark reports.  Anytime an athlete completes a benchmark workout, you will get a report about how they're progressing. You will also be able to set reminders to program the same benchmark in a few months to measure everyone's progress.  Athletes will get their own report of their progress too, and also be able to set their own reminders for benchmark workouts they care about.
                            </p>
<!--
                            <div class="row-fluid">
                                <div class="span4">
                                    <h4 style="text-align:center;">Comments, Likes, and Leaderboards</h4>
                                    <p>
                                        An easy way to post results to Facebook and Twitter. It's fun for your athletes, and it's great marketing for your business.
                                    </p>
                                </div>
                                <div class="span4">
                                    <h4 style="text-align:center;">Custom Benchmark Workouts / Gym Favorites</h4>
                                    <p>
                                        In-depth benchmark tracking and analysis, without sacrificing the ease-of-use that brought you here in the first place.
                                        Athlete-by-athlete and gym-wide analysis, charts, and monthly emails to keep you up-to-date with your gym's progress.
                                    </p>
                                </div>
                                <div class="span4">
                                    <h4 style="text-align:center;">Profile Pictures</h4>
                                    <p>
                                        Track your results, see how your friends did, and search your past workouts. All on-the-go.
                                    </p>
                                </div>
                            </div>
     -->
                        </div><!-- #welcome -->

                        <!--<hr style="max-width:600px; border:2px solid #CCC; margin:25px 0 5px;" />-->

                        <div id="whiteboard" class="tab-pane">

                            <h3>
                                <div id="icon-options-general" class="icon32" style="margin-top:2px;"></div>
                                Whiteboard <?php _e( 'Settings' ); ?>
                            </h3>

                            <fieldset style="margin-bottom:40px;">
                                <label for="CFWHITEBOARD_affiliate_id">
                                    <legend>
                                        <?php _e('Affiliate ID', 'cf-whiteboard'); ?>
                                    </legend>
                                </label>
                                <input type="text" id="CFWHITEBOARD_affiliate_id" name="CFWHITEBOARD_affiliate_id" placeholder="myaffiliate" value="<?php echo esc_attr( preg_replace('/_preview$/', '', $options['affiliate_id']) ); ?>" />
                                <span class="help-inline">
                                    <span class="label label-important"><?php _e('Danger', 'cf-whiteboard'); ?></span>
                                    <?php _e('Changing this value could result in data loss.', 'cf-whiteboard'); ?>
                                </span>
                            </fieldset>

                            <fieldset style="margin-bottom:40px;">
                                <legend><?php _e('Whiteboard Position', 'cf-whiteboard'); ?></legend>
                                <script type="text/javascript">
                                    jQuery(function($) {
                                        $('input[name="CFWHITEBOARD_position"]').click(function() {
                                            var $this = $(this);
                                            if ($this.val() == '<?php echo cfwhiteboard_Position::CustomSelector; ?>') {
                                                $this.closest('fieldset').find('fieldset').css('opacity', 0).slideDown().queue(function() {
                                                    $(this).animate({opacity: 1});
                                                    $(this).dequeue();
                                                });
                                            } else {
                                                $this.closest('fieldset').find('fieldset').animate({opacity: 0}).queue(function() {
                                                    $(this).slideUp();
                                                    $(this).dequeue();
                                                });
                                            }
                                        });
                                    });
                                </script>
                                <label for="CFWHITEBOARD_position_customselector" class="radio">
                                    <input type="radio" id="CFWHITEBOARD_position_customselector" name="CFWHITEBOARD_position" value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelector ); ?>" <?php echo $options['position'] == cfwhiteboard_Position::CustomSelector ? 'checked="checked"' : ''; ?> />
                                    <strong><?php _e('Custom Position.', 'cf-whiteboard'); ?></strong> <?php _e('<a href="mailto:help@cfwhiteboard.com" target="_blank">We would be happy to help you with this.</a>', 'cf-whiteboard'); ?>
                                </label>
                                <fieldset style="margin-left:19px; <?php echo $options['position'] == cfwhiteboard_Position::CustomSelector ? '' : 'display:none'; ?>" class="form-horizontal well">
                                    <!-- <span class="help-block"><em><?php _e('All fields are required.', 'cf-whiteboard'); ?></em></span> -->

                                    <div class="control-group" style="margin-top:10px;">
                                        <label for="CFWHITEBOARD_position_customselectorinsertion" class="control-label"><?php _e('Insertion Method', 'cf-whiteboard'); ?></label>
                                        <div class="controls">
                                            <select id="CFWHITEBOARD_position_customselectorinsertion" name="CFWHITEBOARD_position_customselectorinsertion" class="input-xlarge">
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorInsertionAppend ); ?>" <?php echo $options['position_customselectorinsertion'] == cfwhiteboard_Position::CustomSelectorInsertionAppend ? 'selected="selected"' : ''; ?> >Append To</option>
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorInsertionPrepend ); ?>" <?php echo $options['position_customselectorinsertion'] == cfwhiteboard_Position::CustomSelectorInsertionPrepend ? 'selected="selected"' : ''; ?> >Prepend To</option>
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorInsertionBefore ); ?>" <?php echo $options['position_customselectorinsertion'] == cfwhiteboard_Position::CustomSelectorInsertionBefore ? 'selected="selected"' : ''; ?> >Insert Before</option>
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorInsertionAfter ); ?>" <?php echo $options['position_customselectorinsertion'] == cfwhiteboard_Position::CustomSelectorInsertionAfter ? 'selected="selected"' : ''; ?> >Insert After</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="control-group">
                                        <label for="CFWHITEBOARD_position_customselectortarget" class="control-label"><?php _e('Target Selector', 'cf-whiteboard'); ?></label>
                                        <div class="controls">
                                            <input id="CFWHITEBOARD_position_customselectortarget" type="text" name="CFWHITEBOARD_position_customselectortarget" value="<?php echo esc_attr( $options['position_customselectortarget'] ); ?>" class="input-xlarge" placeholder=".title-for-post" />
                                        </div>
                                    </div>

                                    <div class="control-group">
                                        <label for="CFWHITEBOARD_position_customselectorparent" class="control-label"><?php _e('Parent Selector', 'cf-whiteboard'); ?></label>
                                        <div class="controls">
                                            <input id="CFWHITEBOARD_position_customselectorparent" type="text" name="CFWHITEBOARD_position_customselectorparent" value="<?php echo esc_attr( $options['position_customselectorparent'] ); ?>" class="input-xlarge" placeholder=".post-outer-container" />
                                        </div>
                                    </div>

                                    <div class="control-group">
                                        <label for="CFWHITEBOARD_position_customselectoralignment" class="control-label"><?php _e('Alignment', 'cf-whiteboard'); ?></label>
                                        <div class="controls">
                                            <select id="CFWHITEBOARD_position_customselectoralignment" name="CFWHITEBOARD_position_customselectoralignment" class="input-xlarge">
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorAlignmentFloatLeft ); ?>" <?php echo $options['position_customselectoralignment'] == cfwhiteboard_Position::CustomSelectorAlignmentFloatLeft ? 'selected="selected"' : ''; ?> >Float Left</option>
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorAlignmentFloatRight ); ?>" <?php echo $options['position_customselectoralignment'] == cfwhiteboard_Position::CustomSelectorAlignmentFloatRight ? 'selected="selected"' : ''; ?> >Float Right</option>
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorAlignmentInline ); ?>" <?php echo $options['position_customselectoralignment'] == cfwhiteboard_Position::CustomSelectorAlignmentInline ? 'selected="selected"' : ''; ?> >Inline</option>
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorAlignmentBlock ); ?>" <?php echo $options['position_customselectoralignment'] == cfwhiteboard_Position::CustomSelectorAlignmentBlock ? 'selected="selected"' : ''; ?> >Block</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="control-group">
                                        <label for="CFWHITEBOARD_position_customselectormargin" class="control-label"><?php _e('Margin', 'cf-whiteboard'); ?></label>
                                        <div class="controls">
                                            <input id="CFWHITEBOARD_position_customselectormargin" type="text" name="CFWHITEBOARD_position_customselectormargin" value="<?php echo esc_attr( $options['position_customselectormargin'] ); ?>" class="input-xlarge" placeholder="10px 10px 10px 10px" />
                                        </div>
                                    </div>

                                    <div class="control-group" style="margin-bottom:10px;">
                                        <label for="CFWHITEBOARD_position_customselectordisplay" class="control-label"><?php _e('Display Type', 'cf-whiteboard'); ?></label>
                                        <div class="controls">
                                            <select id="CFWHITEBOARD_position_customselectordisplay" name="CFWHITEBOARD_position_customselectordisplay" class="input-xlarge">
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorDisplayButton ); ?>" <?php echo $options['position_customselectordisplay'] == cfwhiteboard_Position::CustomSelectorDisplayButton ? 'selected="selected"' : ''; ?> >Show Whiteboard Button</option>
                                                <option value="<?php echo esc_attr( cfwhiteboard_Position::CustomSelectorDisplayEmbed ); ?>" <?php echo $options['position_customselectordisplay'] == cfwhiteboard_Position::CustomSelectorDisplayEmbed ? 'selected="selected"' : ''; ?> >Embed Whiteboard</option>
                                            </select>
                                        </div>
                                    </div>

                                </fieldset>

                                <label for="CFWHITEBOARD_position_titleright" class="radio">
                                    <input type="radio" id="CFWHITEBOARD_position_titleright" name="CFWHITEBOARD_position" value="<?php echo esc_attr( cfwhiteboard_Position::TitleRight ); ?>" <?php echo $options['position'] == cfwhiteboard_Position::TitleRight ? 'checked="checked"' : ''; ?> />
                                    <strong><?php _e('Post Title.', 'cf-whiteboard'); ?></strong> <?php _e('The whiteboard is positioned to the right of the post title. Optimized for performance but not compatible with all themes.', 'cf-whiteboard'); ?>
                                </label>
                            </fieldset>

                            <fieldset style="margin-bottom:60px;">
                                <label for="CFWHITEBOARD_whiteboard_exclude_selector">
                                    <legend>
                                        <?php _e('Whiteboard Exclude Selector', 'cf-whiteboard'); ?>
                                    </legend>
                                </label>
                                <input class="input-xlarge" type="text" id="CFWHITEBOARD_whiteboard_exclude_selector" name="CFWHITEBOARD_whiteboard_exclude_selector" placeholder=".page-header, .related-posts-widget, .sidebar-widgets" value="<?php echo esc_attr( $options['whiteboard_exclude_selector'] ); ?>" />
                                <p>
                                    <?php _e('The Whiteboard will NEVER be displayed within elements matching this selector. Commonly used to clean up after other widgets or plugins that cause the Whiteboard to be displayed in places you didn\'t expect. Any jQuery-compatible selector is allowed.', 'cf-whiteboard'); ?>
                                </p>
                            </fieldset>

                    <!--
                            <fieldset>
                                <legend><php _e('WOD Blog Category', 'cf-whiteboard'); ?></legend>
                                <h1><php _e('Which post categories should the whiteboard be added to?', 'cf-whiteboard'); ?></h1>
                                <ul>
                                    <php foreach($categories as $category) { ?>
                                        <li>
                                            <input type="checkbox" id="<php echo $category_prefix . $category->cat_ID; ?>" name="<php echo $category_prefix . $category->cat_ID; ?>" <php echo $category->selected ? 'checked="checked"' : ''; ?> />
                                            <label for="<php echo $category_prefix . $category->cat_ID; ?>">
                                                <php echo $category->cat_name; ?>
                                            </label>
                                        </li>
                                    <php } ?>
                                </ul>
                            </fieldset>
                    -->

                            <fieldset style="margin-bottom:40px;">
                                <legend><?php _e('Athletes Theme', 'cf-whiteboard'); ?></legend>
                                <label for="CFWHITEBOARD_athletes_theme_auto" class="radio">
                                    <input type="radio" id="CFWHITEBOARD_athletes_theme_auto" name="CFWHITEBOARD_athletes_theme" value="<?php echo esc_attr( cfwhiteboard_AthletesTheme::Auto ); ?>" <?php echo $options['athletes_theme'] == cfwhiteboard_AthletesTheme::Auto ? 'checked="checked"' : ''; ?> />
                                    <strong><?php _e('Auto.', 'cf-whiteboard'); ?></strong> <?php _e('The theme will be chosen automatically.', 'cf-whiteboard'); ?>
                                </label>
                                <label for="CFWHITEBOARD_athletes_theme_dark" class="radio">
                                    <input type="radio" id="CFWHITEBOARD_athletes_theme_dark" name="CFWHITEBOARD_athletes_theme" value="<?php echo esc_attr( cfwhiteboard_AthletesTheme::Dark ); ?>" <?php echo $options['athletes_theme'] == cfwhiteboard_AthletesTheme::Dark ? 'checked="checked"' : ''; ?> />
                                    <strong><?php _e('Dark.', 'cf-whiteboard'); ?></strong> <?php _e('Best for websites with light backgrounds.', 'cf-whiteboard'); ?>
                                </label>
                                <label for="CFWHITEBOARD_athletes_theme_light" class="radio">
                                    <input type="radio" id="CFWHITEBOARD_athletes_theme_light" name="CFWHITEBOARD_athletes_theme" value="<?php echo esc_attr( cfwhiteboard_AthletesTheme::Light ); ?>" <?php echo $options['athletes_theme'] == cfwhiteboard_AthletesTheme::Light ? 'checked="checked"' : ''; ?> />
                                    <strong><?php _e('Light.', 'cf-whiteboard'); ?></strong> <?php _e('Best for websites with dark backgrounds.', 'cf-whiteboard'); ?>
                                </label>
                            </fieldset>

                            <fieldset style="margin-bottom:60px;">
                                <legend><?php _e('Custom Post Types', 'cf-whiteboard'); ?></legend>
                                <input type="hidden" name="CFWHITEBOARD_metabox_on_custom_post_types" value="no">
                                <label for="CFWHITEBOARD_metabox_on_custom_post_types" class="checkbox">
                                    <input type="checkbox" id="CFWHITEBOARD_metabox_on_custom_post_types" name="CFWHITEBOARD_metabox_on_custom_post_types" value="yes" <?php echo esc_attr( !!$options['metabox_on_custom_post_types'] ? 'checked="checked"' : '' ); ?> />
                                    Display the CF Whiteboard meta box when editing a custom post type?
                                </label>
                            </fieldset>

                            <fieldset style="margin-bottom:40px;">
                                <legend><?php _e('Whiteboard Visibility', 'cf-whiteboard'); ?></legend>
                                <label for="CFWHITEBOARD_visibility_everyone" class="radio">
                                    <input type="radio" id="CFWHITEBOARD_visibility_everyone" name="CFWHITEBOARD_visibility" value="<?php echo esc_attr( cfwhiteboard_Visibility::Everyone ); ?>" <?php echo $options['visibility'] == cfwhiteboard_Visibility::Everyone ? 'checked="checked"' : ''; ?> />
                                    <strong><?php _e('Live Mode.', 'cf-whiteboard'); ?></strong> <?php _e('Anyone on the web can see the whiteboard. Whiteboard entries will be saved.', 'cf-whiteboard'); ?>
                                </label>
                                <label for="CFWHITEBOARD_visibility_users" class="radio">
                                    <input type="radio" id="CFWHITEBOARD_visibility_users" name="CFWHITEBOARD_visibility" value="<?php echo esc_attr( cfwhiteboard_Visibility::Users ); ?>" <?php echo $options['visibility'] == cfwhiteboard_Visibility::Users ? 'checked="checked"' : ''; ?> />
                                    <strong><?php _e('Developer Mode.', 'cf-whiteboard'); ?></strong> <?php _e('Only logged-in WordPress users can see the whiteboard.  Whiteboard entries will be removed when you switch to Live Mode, so feel free to experiment.', 'cf-whiteboard'); ?>
                                </label>
                            </fieldset>

                            <fieldset style="margin-bottom:40px;">
                                <legend><?php _e('Non-CrossFit Branding', 'cf-whiteboard'); ?></legend>
                                <input type="hidden" name="CFWHITEBOARD_noncrossfit_branding" value="no">
                                <label for="CFWHITEBOARD_noncrossfit_branding" class="checkbox">
                                    <input type="checkbox" id="CFWHITEBOARD_noncrossfit_branding" name="CFWHITEBOARD_noncrossfit_branding" value="yes" <?php echo esc_attr( !!$options['noncrossfit_branding'] ? 'checked="checked"' : '' ); ?> />
                                    Hide all references to CrossFit.
                                </label>
                                <p>
                                    Activating this setting does not remove any features. It simply removes references to "CF" or "CrossFit" and replaces them with suitable alternatives, such as "fitness" or "gym". The setting will take effect immediately for the Whiteboard app. It may take up to 24 hours to go into effect for the athlete profiles and facebook sharing. <a href="mailto:help@cfwhiteboard.com" target="_blank">Email us</a> for more information.
                                </p>
                            </fieldset>

                            <?php if (function_exists('is_multisite') && is_multisite()) { ?>
                                <fieldset style="margin-bottom:40px;">
                                    <label>
                                        <legend>
                                            <?php _e('Uninstall CF Whiteboard', 'cf-whiteboard'); ?>
                                        </legend>
                                    </label>
                                    <p>
                                        <?php _e('You can always reinstall again later. You will not lose any data or settings.', 'cf-whiteboard'); ?>
                                    </p>
                                    <input class="btn btn-mini" type="submit" name="cfwhiteboard-disable-site" value="<?php esc_attr_e('Uninstall CF Whiteboard', 'cf-whiteboard' ); ?>" />
                                </fieldset>
                            <?php } ?>

                        </div><!-- #whiteboard -->

                        <div id="account" class="tab-pane">
                            <?php if (preg_match('/localhost-dev/', $options['affiliate_id']) ) { ?>
                              <iframe src="//localhost:3000/affiliates/<?php esc_attr_e( preg_replace('/_preview$/', '', $options['affiliate_id']) ); ?>/subscription" style="background:transparent; border:none; padding:0; width:100%; height:1200px; overflow:hidden;" seamless></iframe>
                            <?php } else { ?>
                              <iframe src="//<?php esc_attr_e(preg_match('/testaffiliate/', $options['affiliate_id']) ? 'tameron.herokuapp.com' : 'cfwhiteboard.com'); ?>/affiliates/<?php esc_attr_e( preg_replace('/_preview$/', '', $options['affiliate_id']) ); ?>/subscription" style="background:transparent; border:none; padding:0; width:100%; height:1200px; overflow:hidden;" seamless></iframe>
                            <?php } ?>
                        </div><!-- #account -->

                    </div><!-- .tab-content -->

                    <div class="form-actions">
                        <input class="btn btn-primary" type="submit" name="Submit" value="<?php esc_attr_e('Save Changes', 'cf-whiteboard' ); ?>" />
                        <!-- <input type="submit" name="Reset" onclick="return confirm('<php esc_attr_e('Are you sure you want to delete all CF Whiteboard options?', 'cf-whiteboard'); ?>')" value="<php esc_attr_e('Reset', 'cf-whiteboard'); ?>" /> -->
                        <span class="help-inline pull-right">
                            <a href="mailto:help@cfwhiteboard.com" target="_blank" class="btn btn-link">help@cfwhiteboard.com</a>
                        </span>
                    </div>

                <?php } ?>

            </form>
        </div><!-- .cfw-twb -->

    </div><!-- .wrap -->

    <script type="text/javascript">
        jQuery(function($) {
            $('.cfw-twb .navbar .nav.internal a').click(function(event) {
                event.preventDefault();
                $(this).bootstrap_tab('show');
            });

            $('a[href="'+window.location.hash+'"]').click();

            $(document.body).on('change', 'input, select', function(event) {
                if ($('[type=submit]:active').length == 0) {
                    $('#unsaved-changes-alert').fadeIn();
                }
            });

            $('#account iframe').one('load', function() {
                $(this).on('load', function() {
                    $(document.body).animate({scrollTop: $('.js-scroll-here-on-iframe-reload').offset().top}, 800);
                });
            });
        });
    </script>

<?php

}


add_filter('admin_menu', 'cfwhiteboard_add_menu_link');
function cfwhiteboard_add_menu_link() {
    // if( current_user_can('manage_options') ) {
    // }

    $hook_suffix = add_options_page(
        'CF Whiteboard ' . __("Settings"),
        (cfwhiteboard_is_site_enabled() ? 'CF Whiteboard' : 'Workout Tracking by CF Whiteboard'),
        'manage_options',
        basename(__FILE__),
        'cfwhiteboard_options_page'
    );

    /* Using registered $hook_suffix handle to hook script load, to only load in CFW admin */
    add_action('admin_print_scripts-' . $hook_suffix, 'cfwhiteboard_settings_scripts');
    /* Using registered $hook_suffix handle to hook stylesheet load, to only load in CFW admin */
    add_action( 'admin_print_styles-' . $hook_suffix, 'cfwhiteboard_settings_styles' );
}
function cfwhiteboard_settings_scripts() {
    global $CFWHITEBOARD_VERSION;
    if (!isset($CFWHITEBOARD_VERSION)) $CFWHITEBOARD_VERSION = '0.0';

    // wp_enqueue_script('bootstrap',
    //     plugins_url('bootstrap/js/bootstrap.min.js', __FILE__),
    //     array('jquery'),
    //     $CFWHITEBOARD_VERSION
    // );
    wp_enqueue_script('cfwbootstrap',
        plugins_url('bootstrap/js/bootstrap-3.0.2.3.js', __FILE__),
        array('jquery'),
        $CFWHITEBOARD_VERSION
    );

    wp_enqueue_script('bootstrap-namespacer',
        plugins_url('js/bootstrap-namespacer-3.0.2.3.js', __FILE__),
        array('cfwbootstrap'),
        $CFWHITEBOARD_VERSION
    );
}
function cfwhiteboard_settings_styles() {
    global $CFWHITEBOARD_VERSION;
    if (!isset($CFWHITEBOARD_VERSION)) $CFWHITEBOARD_VERSION = '0.0';

    wp_enqueue_style('cfwbootstrap',
        plugins_url('bootstrap/css/bootstrap.min.css', __FILE__),
        false,
        $CFWHITEBOARD_VERSION
    );
}


// Place in Option List on Plugins page
function cfwhiteboard_actlinks($links, $file){
    // Static so we don't call plugin_basename on every plugin row.
    static $this_plugin;
    if ( ! $this_plugin ) $this_plugin = plugin_basename(__FILE__);

    if ( $file == $this_plugin ){
        $support_link = '<a href="mailto:help@cfwhiteboard.com" target="_blank">' . __('Help') . '</a>';
        $settings_link = '<a href="options-general.php?page=cf-whiteboard.php">' . __('Settings') . '</a>';

        array_unshift( $links, $support_link ); // before other links
        array_unshift( $links, $settings_link ); // before other links
    }
    return $links;
}
add_filter("plugin_action_links", 'cfwhiteboard_actlinks', 10, 2);



// Custom Meta Boxes on Add/Edit Post page
global $CFWHITEBOARD_WODS_META_KEY;
$CFWHITEBOARD_WODS_META_KEY = 'cfwhiteboard-wods';
global $CFWHITEBOARD_WHITEBOARD_ID_META_KEY;
$CFWHITEBOARD_WHITEBOARD_ID_META_KEY = 'cfw-whiteboard-id';

add_action('admin_init', 'cfwhiteboard_init_admin');
function cfwhiteboard_init_admin() {

    if (!cfwhiteboard_is_site_enabled())
        return;

    add_action('load-post.php', 'cfwhiteboard_setup_post_meta_boxes');
    add_action('load-post-new.php', 'cfwhiteboard_setup_post_meta_boxes');
    /* Save post meta on the 'save_post' hook. */
    add_action('save_post', 'cfwhiteboard_save_post_meta_boxes', 10, 2);
    /* Clean post meta on the 'publish_post' hook. */
    // add_action('publish_post', 'cfwhiteboard_clean_post_meta', 10, 1);
    // add_action('admin_enqueue_scripts', 'cfwhiteboard_latest_jquery');

}

/* Meta box setup function. */
function cfwhiteboard_setup_post_meta_boxes() {
    global $typenow;

    if ($typenow == 'page' || $typenow == 'attachment' || $typenow == 'revision' || $typenow == 'nav_menu_item')
        return;

    $options = cfwhiteboard_get_options();
    if (!$options['metabox_on_custom_post_types'] && $typenow != 'post')
        return;

    /* Add meta boxes on the 'add_meta_boxes' hook. */
    add_action('add_meta_boxes', 'cfwhiteboard_add_post_meta_boxes', 1);

    /* Add tinymce button & plugin */
    // add_filter('tiny_mce_before_init','cfwhiteboard_tinymce_settings');
    add_filter('mce_buttons_2', 'cfwhiteboard_mce_buttons');
    add_filter('mce_external_plugins', 'cfwhiteboard_mce_external_plugins');

    /* Add admin notices (if post was just saved) */
    add_action('admin_notices', 'cfwhiteboard_save_post_meta_notices');

    add_action('admin_print_scripts', 'cfwhiteboard_post_meta_scripts');
    add_action('admin_print_styles', 'cfwhiteboard_post_meta_styles');

}
function cfwhiteboard_post_meta_scripts() {
    global $CFWHITEBOARD_VERSION;
    if (!isset($CFWHITEBOARD_VERSION)) $CFWHITEBOARD_VERSION = '0.0';

    wp_enqueue_script('cfwbootstrap',
        plugins_url('bootstrap/js/bootstrap-3.0.2.3.js', __FILE__),
        array('jquery'),
        '3.0.2.1'
    );

    wp_enqueue_script('bootstrap-namespacer',
        plugins_url('js/bootstrap-namespacer-3.0.2.3.js', __FILE__),
        array('cfwbootstrap'),
        $CFWHITEBOARD_VERSION
    );

    wp_enqueue_script('jquery-ui-datepicker',
        plugins_url('js/jquery-ui.datepicker.js', __FILE__),
        array('jquery'),
        $CFWHITEBOARD_VERSION
    );

    wp_enqueue_script('underscore',
        plugins_url('js/underscore.js', __FILE__),
        false,
        '1.8.3'
    );

    wp_enqueue_script('backbone',
        plugins_url('js/backbone.js', __FILE__),
        array('underscore', 'jquery'),
        '1.3.3'
    );

    wp_enqueue_script('easyxdm',
        plugins_url('js/easyXDM.min.js', __FILE__),
        false,
        '2.4.18.25'
    );
}
function cfwhiteboard_post_meta_styles() {
    global $CFWHITEBOARD_VERSION;
    if (!isset($CFWHITEBOARD_VERSION)) $CFWHITEBOARD_VERSION = '0.0';

    wp_enqueue_style('cfwbootstrap',
        plugins_url('bootstrap/css/bootstrap.min.css', __FILE__),
        false,
        $CFWHITEBOARD_VERSION
    );

    wp_enqueue_style('jquery-ui-datepicker',
        plugins_url('jquery-ui.datepicker.css', __FILE__),
        false,
        $CFWHITEBOARD_VERSION
    );
}

/* Create one or more meta boxes to be displayed on the post editor screen. */
function cfwhiteboard_add_post_meta_boxes() {
    global $typenow;

    add_meta_box(
        'cfwhiteboard-wods-meta', // Unique ID
        esc_html__('CF Whiteboard', 'cf-whiteboard'),      // Title
        'cfwhiteboard_wods_meta_box',     // Callback function
        $typenow,                 // Admin page (or post type)
        'normal',                 // Context
        'core'                   // Priority
    );
}

/* Generate the fields for a "class" in the post meta box. */
function cfwhiteboard_generate_class_nav($class) {
    $class_id = esc_attr( $class['wp_id'] );
    $class_prefix = 'cfw-wods';
    $class_id_attr = $class_prefix .'-'. $class_id .'-name';
    $class_name_attr = $class_prefix .'['. $class_id .'][name]';
    $class_components_name = $class_prefix .'['. $class_id .'][components][]';

    $components_nav = '';
    foreach ($class['components'] as $component) {
        $components_nav .= cfwhiteboard_generate_class_component_nav('cfw-components', $component, $class_components_name);
    }

    return '
        <li id="cfw-wod-'. $class_id .'">
            <h5>
                <div class="btn-group pull-right cfw-class-options">
                    <a href="javascript:// More Options" class="btn btn-stealth dropdown-toggle" data-toggle="bsdropdown" data-target=".cfw-dummy-selector">
                        <i class="cfw-settings-icon"></i><span class="caret"></span>
                    </a>
                    <ul class="dropdown-menu">
                        <li class="divider"></li>
                        <li><a tabindex="-1" href="javascript://">Delete entire class</a></li>
                    </ul>
                </div>
                <input type="text" id="'. $class_id_attr .'" name="'. $class_name_attr .'" value="'. esc_attr( $class['name'] ) .'"
                    placeholder="Enter the class name" title="Class Name - Click to Edit" class="cfw-edit-wod-title" data-toggle="bstab" data-target="#cfwhiteboard-wods-meta .cfw-overview" />
            </h5>
            '. $components_nav .'
            <div class="cfw-new-component-row">
                <a href="javascript:// Add A Component" title="Add Another Component" class="cfw-new-component btn btn-link" data-classid="'. $class_id .'">
                    <i class="icon-plus"></i>add a component
                </a>
            </div>
        </li>
    ';
}
function cfwhiteboard_generate_class_component_nav($component_prefix, $component, $class_components_name) {
    $cmp_id = $component['wp_id'];
    // $description_name = $component_prefix . $cmp_id . '-description';
    // $label_name = $component_prefix . $cmp_id . '-label';

    $description = empty($component['benchmark_id']) ? (empty($component['description']) ? "New Component\r\nClick to add details." : esc_html($component['description'])) : 'Benchmark Component
Loading&hellip;';

    return '
        <div class="cfw-component">
            <input type="hidden" class="cfw-component-id" name="'. $class_components_name .'" value="'. $cmp_id .'">
            <a href="javascript:// Edit Component" class="cfw-edit-component" data-toggle="bstab" data-target="#'. $component_prefix .'-'. $cmp_id .'">
                <i class="icon-chevron-right"></i>
                <small class="cfw-hover-text pull-right muted">edit</small>
                <span class="cfw-description">'. $description .'</span>
            </a>
        </div>
    ';
}
/* Generate the fields for a "class" in the post meta box. */
function cfwhiteboard_generate_class_fields($class) {
    $class_id = esc_attr( $class['wp_id'] );
    $class_prefix = 'cfwhiteboard-wod-' . $class_id;
    $class_name_attr = $class_prefix . '-name';

    $component_fields = '';
    foreach ($class['components'] as $component) {
        $component_fields .= cfwhiteboard_generate_class_component_fields('cfw-components', $component);
    }

    return $component_fields;
}
function cfwhiteboard_generate_class_component_fields($component_prefix, $component) {
    $cmp_id = $component['wp_id'];
    $description_id = $component_prefix .'-'. $cmp_id .'-description';
    $description_name = $component_prefix .'['. $cmp_id . '][description]';
    $label_id = $component_prefix .'-'. $cmp_id .'-label';
    $label_name = $component_prefix .'['. $cmp_id . '][label]';

    $has_label = !empty($component['label']);


    return '
        <div class="tab-pane cfw-component-fields" id="'. $component_prefix .'-'. $cmp_id .'" data-cid="'. $cmp_id .'">
            <div class="cfw-header">
                <a class="pull-right cfw-admin-tour" href="http://cfwhiteboard.com/wp-admin-tour" target="_blank"><i class="icon-play"></i> Tour the New Admin Area</a>
                <div class="cfw-breadcrumbs">
                    <div class="muted">Currently Editing:</div>
                    <div><span class="cfw-class-name">Workout of the Day</span> / Component <span class="cfw-component-index"></span></div>
                </div>
            </div>
            <div class="cfw-main">
                <ul class="nav nav-tabs cfw-component-fields-nav">
                    <li class="active">
                        <a href="javascript://" data-target="#cfw-component-benchmark-'. $cmp_id .'" class="cfw-benchmarks" data-toggle="bstab">Benchmarks</a>
                    </li>
                    <li>
                        <a href="javascript://" data-target="#cfw-component-custom-'. $cmp_id .'" class="cfw-custom-component-tab" data-toggle="bstab">Non-Benchmark Component</a>
                    </li>
                </ul>
                <div class="tab-content">
                    <div class="tab-pane cfw-custom-component" id="cfw-component-custom-'. $cmp_id .'">
                        <label for="'. $description_id .'">
                            <div class="lead" style="margin:0;">Component Description</div>
                            <small class="muted">Required. Full component description. This is the text that athletes can search when they&apos;re looking up past workouts.</small>
                        </label>
                        <textarea id="'. $description_id .'" name="'. $description_name .'" class="input-block-level" rows="5">'.
                            esc_textarea( $component['description'] )
                        .'</textarea>
                        <label for="'. $label_id .'" style="margin-top:15px;">
                            <div class="lead" style="margin:0;">Component Label</div>
                            <small class="muted">Required. Short component description used in the Whiteboard and in the athlete logbooks.</small>
                        </label>
                        <input type="text" id="'. $label_id .'" name="'. $label_name .'" value="'. esc_attr( $component['label'] ) .'">
                    </div>
                    <div class="tab-pane cfw-benchmark-component active" id="cfw-component-benchmark-'. $cmp_id .'">
                        <div class="cfw-browse-pane active">
                            <input type="hidden" class="cfw-benchmark-id" name="cfw-components['. $cmp_id .'][benchmark_id]" value="'. (empty($component['benchmark_id']) ? '' : $component['benchmark_id']) .'">
                            <input type="hidden" class="cfw-benchmark-repcount" name="cfw-components['. $cmp_id .'][repcount]" value="'. (empty($component['repcount']) ? '' : $component['repcount']) .'">
                            <input type="hidden" class="cfw-benchmark-repscheme" name="cfw-components['. $cmp_id .'][repscheme]" value="'. (empty($component['repscheme']) ? '' : $component['repscheme']) .'">
                            <div class="search-form">
                                <input  id="cfw-component-benchmark-'. $cmp_id .'-search" type="text" class="search-query input-block-level" placeholder="Search by name or movement..." value="" data-val="" autocomplete="off">
                                <label for="cfw-component-benchmark-'. $cmp_id .'-search" style="margin:0; cursor:text;"><i class="icon-search"></i></label>
                                <label for="cfw-component-benchmark-'. $cmp_id .'-search" class="cfw-clear">&times;</label>
                            </div>
                            <ul class="cfw-benchmark-nav">
                                <li class="active">
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-weightlifting" title="Weightlifting">Weightlifting</a>
                                </li><li>
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-named-workouts" title="Named Workouts">Named Workouts</a>
                                </li><li style="display:none;">
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-girls" title="Girls">Girls</a>
                                </li><li style="display:none;">
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-heroes" title="Heroes">Heroes</a>
                                </li><li>
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-gymnastics" title="Gymnastics">Gymnastics</a>
                                </li><li>
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-monostructural" title="Monostructural">Monostructural</a>
                                </li><li class="cfw-other" style="display:none;">
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-other-benchmarks" title="Other">Other</a>
                                </li><li class="cfw-games-tab">
                                    <a href="javascript://" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-games-workouts" title="Games">Games</a>
                                </li><li style="display:none;">
                                    <a href="javascript://" class="cfw-all" data-toggle="bstab" data-target="#cfw-component-benchmark-'. $cmp_id .' .cfw-all-benchmarks">All</a>
                                </li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-weightlifting active nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-named-workouts nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-girls nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-heroes nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-gymnastics nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-monostructural nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-other-benchmarks nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-games-workouts nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                            <ul class="cfw-benchmark-list cfw-all-benchmarks nav nav-tabs nav-stacked">
                                <li style="text-align:center; padding-top:12px;" class="muted"><i class="icon-download"></i> Loading...</li>
                            </ul>
                        </div>
                        <div class="cfw-details-pane">
                        </div>
                    </div>
                </div>
            </div>
            <ul class="cfw-footer">
                <li class="cfw-component-actions">
                    <div><!-- without this div, the bootstrap.js tab functionality only works once. after that, it thinks this is a "tab" thats already active so it does nothing -->
                        <a class="cfw-remove-this-component" href="javascript:// Remove this Component" data-toggle="bstab" data-target="#cfwhiteboard-wods-meta .cfw-overview">
                            <i class="icon-minus-sign icon-white"></i><div class="cfw-text">Delete this Component</div>
                        </a><a class="cfw-select-and-continue" href="javascript:// Select & Go Back to Classes Overview" data-toggle="bstab" data-target="#cfwhiteboard-wods-meta .cfw-overview">
                            <i class="icon-ok icon-white"></i><div class="cfw-text">Continue</div>
                        </a>
                    <div>
                </li>
            </ul>
        </div>
<!--
        <tbody>
            <tr>
                <th>
                    <label for="'. $description_name .'">
                        '. esc_html__("Component", 'cf-whiteboard') .' <span class="component-index"></span>
                        <a href="javascript://" class="help-alert" data-message="Each class needs 1 or more components. Athletes will be able to search the component descriptions to recall workout results in the future.<br><br>Example WOD:<br><br>Component 1:<br>Deadlift<br>5-5-5-5-5<br><br>Component 2:<br>&quot;Fran&quot;<br>21-15-9 reps, for time<br>Thruster 95 lbs<br>Pull-ups">(Help)</a>
                    </label>
                    <p>
                        '. esc_html__("Include rep scheme & loading", 'cf-whiteboard') .'
                    </p>
                    <p>
                        '. esc_html__("Break strength/skill work into separate components if you want athletes to track them individually", 'cf-whiteboard') .'
                    </p>
                </th>
                <td>
                    <textarea id="'. $description_name .'" name="'. $description_name .'" class="input-block-level" rows="5">'.
                        esc_textarea( $component['description'] )
                    .'</textarea>
                </td>
            </tr>
            <tr>
                <th>
                    <label for="'. $label_name .'" '. ($has_label ? '' : 'class="hidden"') .'>
                        '. esc_html__("Component Label", 'cf-whiteboard') .'
                        <a href="javascript://" class="help-alert" data-message="The label is used as a short description for the component on the Whiteboard and on athlete profiles. Shorter labels are better, but they&apos;re just labels so they don&apos;t have to be perfect.<br><br>Example Component Labels: Deadlift, Fran, 3 Rounds, AMRAP 20min, 21-15-9">(Help)</a>
                    </label>
                </th>
                <td>
                    <span class="component-label-show '. ($has_label ? '' : 'hidden') .'">
                        <span>'. esc_html( $component['label'] ) .'</span>
                        <a href="javascript://" class="button edit">'. esc_html__("Edit") .'</a>
                    </span>
                    <span class="component-label-edit hidden">
                        <input type="text" id="'. $label_name .'" name="'. $label_name .'"
                            value="'. esc_attr( $component['label'] ) .'" />
                        <a href="javascript://" class="button save">'. esc_html__("OK") .'</a>
                        <a href="javascript://" class="cancel">'. esc_html__("Cancel") .'</a>
                    </span>
                    <a href="javascript://" class="multi-component remove-component delete">
                        &ndash; '. esc_html__("Remove This Component", 'cf-whiteboard') .'
                    </a>
                </td>
            </tr>
        </tbody>
-->
    ';
}
function cfwhiteboard_wods_meta_box($object, $box) {
    global $CFWHITEBOARD_WODS_META_KEY;
    $options = cfwhiteboard_get_options();

    // $auto_update_item = get_transient('cfw-auto-update-item');
    // var_dump($auto_update_item);
    // echo '<br>';
    // var_dump(get_site_transient('update_plugins')->response);
    ?>

    <?php wp_nonce_field(basename( __FILE__ ), $CFWHITEBOARD_WODS_META_KEY); ?>
    <style type="text/css">
        .cfw-twb .btn-stealth {
            background-color: transparent;
            background-image: none;
            border-color: transparent;
            -webkit-border-radius: 0;
            -moz-border-radius: 0;
            border-radius: 0;
            -webkit-box-shadow: none;
            -moz-box-shadow: none;
            box-shadow: none;
            color: #0088cc;
        }
        .cfw-twb .btn-stealth:hover,
        .cfw-twb .btn-stealth:focus {
            background-color: #f5f5f5;
            background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6);
            background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));
            background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6);
            background-image: -o-linear-gradient(top, #ffffff, #e6e6e6);
            background-image: linear-gradient(to bottom, #ffffff, #e6e6e6);
            background-position: 0 0;
            background-repeat: repeat-x;
            border-color: #e6e6e6 #e6e6e6 #bfbfbf;
            border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
            *background-color: #e6e6e6;
            /* Darken IE7 buttons by default so they stand out more given they won't have borders */
            border: 1px solid #bbbbbb;
            *border: 0;
            border-bottom-color: #a2a2a2;
            -webkit-border-radius: 4px;
            -moz-border-radius: 4px;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);
            -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);
            box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);
            color: #333333;
            -webkit-transition: none;
            -moz-transition: none;
            -o-transition: none;
            transition: none;
        }
        .cfw-twb .btn-stealth:active,
        .cfw-twb .btn-stealth.active,
        .cfw-twb .btn-group.open .btn-stealth.dropdown-toggle {
            background-color: #e6e6e6;
            *background-color: #d9d9d9;
            background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6);
            background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));
            background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6);
            background-image: -o-linear-gradient(top, #ffffff, #e6e6e6);
            background-image: linear-gradient(to bottom, #ffffff, #e6e6e6);
            background-position: 0 -15px;
            border-color: #e6e6e6 #e6e6e6 #bfbfbf;
            border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
            border: 1px solid #bbbbbb;
            *border: 0;
            border-bottom-color: #a2a2a2;
            -webkit-box-shadow: none;
            -moz-box-shadow: none;
            box-shadow: none;
            color: #333333;
            text-decoration: none;
        }
        #cfwhiteboard-wods-meta {
            margin-top: 30px;
            margin-bottom: 40px;
            /* Some themes, ahem, Fortis 7, apply a float to .postbox items */
            float: none !important;
        }
        #cfwhiteboard-wods-meta .nobr {
            white-space: nowrap;
        }
        #cfwhiteboard-wods-meta .inside {
            background: #fff;
            margin: 0 -1px -1px;
            overflow: hidden;
            padding: 0;
        }
        #cfwhiteboard-wods-meta textarea {
            resize: vertical;
        }
        #cfwhiteboard-wods-meta .cfw-header {
            background: #30393f;
            color: #fff;
            height: 48px;
            margin: 0;
            padding: 0;
            text-transform: uppercase;
            text-shadow: 0 1px 0 #000;
            white-space: nowrap;
        }
        #cfwhiteboard-wods-meta .cfw-header .cfw-admin-tour,
        #cfwhiteboard-wods-meta .cfw-header .cfw-breadcrumbs,
        #cfwhiteboard-wods-meta .cfw-wods-date-container label,
        #cfwhiteboard-wods-meta .cfw-wods-date-container input {
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;
            height: 48px;
            margin: 0;
            padding: 0;
            vertical-align: top;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-header .cfw-admin-tour {
            background: #30393f;
            color: #00a5b8;
            font-size: 11px;
            font-weight: bold;
            line-height: 14px;
            padding: 10px 10px 0;
            position: relative;
            text-decoration: none;
            white-space: normal;
            width: 130px;
        }
        #cfwhiteboard-wods-meta .cfw-header .cfw-admin-tour:hover {
            background: #56829F;
            background: #2b4d64;
            z-index: 2;
        }
        #cfwhiteboard-wods-meta .cfw-header .cfw-admin-tour i {
            background: url(<?php echo plugins_url('images/admin-arrows.png', __FILE__); ?>) no-repeat center -4px;
            float: left;
            margin: 7px 6px 0 1px;
        }
        /*
        #cfwhiteboard-wods-meta .cfw-header .cfw-admin-tour:hover i {
            background-position: center -26px;
        }
        */
        #cfwhiteboard-wods-meta .cfw-wods-date-container {
            display: inline-block;
            margin: 0;
            padding: 0;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-wods-date-container label,
        #cfwhiteboard-wods-meta .cfw-wods-date-container input {
            width: 287px;
        }
        #cfwhiteboard-wods-meta .cfw-wods-date-container label {
            /*background: #30393f;*/
            background: #40494f;
            font-size: 11px;
            font-weight: bold;
            margin-left: -287px;
            padding: 7px 0 0 12px;
            text-indent: -9999em;
        }
        #cfwhiteboard-wods-meta .cfw-wods-date-container label i {
            background: url(<?php echo plugins_url('images/admin-icon-calendar.png', __FILE__); ?>) no-repeat 0 0 transparent;
            display: inline-block; *zoom: 1; *display: inline;
            float: left;
            height: 25px;
            margin: 5px 0 0;
            width: 26px;
        }
        #cfwhiteboard-wods-meta .cfw-wods-date-container input {
            background: transparent;
            border: none;
            -webkit-border-radius: 0;
            -moz-border-radius: 0;
            border-radius: 0;
            -webkit-box-shadow: none;
            -moz-box-shadow: none;
            box-shadow: none;
            color: #fff;
            font-size: 12px;
            font-size: 20px;
            padding: 18px 24px 0px 12px;
            padding: 0px 2px 1px 46px;
            position: relative;
            text-align: left;
            text-shadow: 0 1px 0 #000;
            z-index: 1;
        }
        #cfwhiteboard-wods-meta .cfw-wods-date-container:hover label {
            /*background: #08c;*/
            /*border-color: #21759b;*/
        }
        #cfwhiteboard-wods-meta .cfw-wods-date-container:hover label,
        #cfwhiteboard-wods-meta .cfw-wods-date-container input:focus + label {
            background: #08c;
            box-shadow: none;
            /*border-color: #08c;*/
        }
        #cfwhiteboard-wods-meta .cfw-header .cfw-breadcrumbs {
            background: #30393f;
            -webkit-box-shadow: 8px 0 5px -5px #30393f;
            -moz-box-shadow: 8px 0 5px -5px #30393f;
            box-shadow: 8px 0 5px -5px #30393f;
            color: #fff;
            font-size: 11px;
            font-weight: bold;
            line-height: 14px;
            padding: 10px 12px 0;
            position: relative;
            text-decoration: none;
            white-space: normal;
            z-index: 1;
        }
        #cfwhiteboard-wods-meta .cfw-header .muted {
            color: #aaa;
        }
        #cfwhiteboard-wods-meta .cfw-main {
            background: #fff;
            border-color: #ddd;
            border-style: solid;
            border-width: 3px 1px 1px;
            -webkit-border-radius: 0;
            -moz-border-radius: 0;
            border-radius: 0;
            margin: 0;
            padding: 0;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-main {
            padding: 12px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-single-column {
            margin: 0 auto;
            width: 380px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-overview-header {
            font-size: 11px;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 4px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-overview-help {
            position: relative;
            padding-right: 0;
            padding-left: 0;
        }
        #cfwhiteboard-wods-meta .cfw-overview .tooltip {
            font-weight: normal;
            text-shadow: none;
            text-transform: none;
        }
        #cfwhiteboard-wods-meta .cfw-overview-header .tooltip {
            width: 320px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .tooltip-inner {
            max-width: none;
            text-align: left;
        }
        #cfwhiteboard-wods-meta .cfw-overview .tooltip-inner ul {
            margin: 6px 0 6px 25px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .tooltip-inner ul li {
            list-style: disc outside;
            line-height: 16px;
        }
        #cfwhiteboard-wods-meta .cfw-overview ul.cfw-wods {
            margin: 0;
        }
        #cfwhiteboard-wods-meta .cfw-overview ul.cfw-wods > li {
            margin: 0;
            padding: 0 0 10px;
        }
        #cfwhiteboard-wods-meta .cfw-overview ul.cfw-wods h5 {
            margin: 0 0 0px;
            position: relative;
        }
        #cfwhiteboard-wods-meta .cfw-overview ul.cfw-wods h5 .cfw-class-options {
            position: absolute;
            right: 6px;
            top: 6px;
        }
        #cfwhiteboard-wods-meta .cfw-overview ul.cfw-wods h5 .cfw-class-options .dropdown-toggle {
            padding-right: 6px;
            padding-left: 6px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-settings-icon {
            background: url(<?php echo plugins_url('images/admin-icon-options.png', __FILE__); ?>) no-repeat center center;
            display: inline-block;
            height: 20px;
            padding: 0;
            width: 20px;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-class-options a .cfw-settings-icon {
            opacity: .5;
            margin-right: 5px;
            vertical-align: top;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-class-options a:hover .cfw-settings-icon,
        #cfwhiteboard-wods-meta .cfw-overview .cfw-class-options.open .dropdown-toggle .cfw-settings-icon {
            opacity: 1;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-edit-wod-title {
            border: 1px solid transparent;
            border-top-color: #90999f;
            border-bottom-color: #eee;
            -webkit-border-radius: 0;
            -moz-border-radius: 0;
            border-radius: 0;
            -webkit-box-shadow: none;
            -moz-box-shadow: none;
            box-shadow: none;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            color: #50595f;
            cursor: text;
            font-size: 20px;
            font-weight: 300;
            height: auto;
            margin: 0;
            padding: 8px 55px 8px 0;
            -webkit-transition: 200ms padding-left ease-out;
            -moz-transition: 200ms padding-left ease-out;
            transition: 200ms padding-left ease-out;
            width: 100%;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-edit-wod-title:hover,
        #cfwhiteboard-wods-meta .cfw-overview .cfw-edit-wod-title:focus {
            color: #30393f;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-edit-wod-title:hover {
            border-color: #90999f #ddd #ddd;
            -webkit-box-shadow: inset 0 0 0 3px #eee;
            -moz-box-shadow: inset 0 0 0 3px #eee;
            box-shadow: inset 0 0 0 3px #eee;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-edit-wod-title:focus {
            border-color: #21759b;
            -webkit-box-shadow: inset 0 0 0 3px #08c;
            -moz-box-shadow: inset 0 0 0 3px #08c;
            box-shadow: inset 0 0 0 3px #08c;
            outline: none;
            padding-left: 6px;
        }
        #cfwhiteboard-wods-meta .cfw-sidebar .nav .active a {
            background-color: #08C;
            border-right: 1px solid #21759B;
            color: white;
            margin-right: -1px;
            text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2);
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component .icon-chevron-right {
            float: right;
            margin-top: 2px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component i {
            opacity: .25;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component a {
            display: block;
            font-weight: 300;
            padding: 10px 3px 0 4px;
            text-decoration: none;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component a .cfw-hover-text {
            display: none;
            font-size: 11px;
            font-weight: bold;
            line-height: 12px;
            margin: 4px 2px 0 0;
            text-transform: uppercase;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component a:hover {
            /*background: #eee;*/
            color: #30393f;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component a:hover .cfw-hover-text {
            display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component a:hover i {
            opacity: .5;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-component .active a i {
            opacity: 1;
        }
        #cfwhiteboard-wods-meta .cfw-edit-component .cfw-description {
            color: #90999f;
            display: block;
            font-size: 13px;
            line-height: 1.35;
            white-space: pre-line;
        }
        #cfwhiteboard-wods-meta .cfw-edit-component .cfw-description:first-line {
            color: #60696f;
        }
        #cfwhiteboard-wods-meta .cfw-edit-component:hover .cfw-description {
            color: #70797f;
        }
        #cfwhiteboard-wods-meta .cfw-edit-component:hover .cfw-description:first-line {
            color: #20292f;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-new-component-row {
            text-align: left;
            padding: 3px 0 0px;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-wods .cfw-new-wod-row {
            border-top: 1px solid #eee;
            padding-top: 5px;
            padding-bottom: 18px;
        }
        #cfwhiteboard-wods-meta .cfw-footer {
            background: #fafafa;
            border-color: #ddd;
            border-style: none solid solid;
            border-width: 1px;
            list-style: none;
            margin: 0;
            padding: 0;
            white-space: nowrap;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-footer {
            background: #40494f;
            border: none;
            border-top: 4px solid #08c;
            text-align: right;
        }
        #cfwhiteboard-wods-meta .cfw-footer li {
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;
            margin: 0;
            padding: 0;
            vertical-align: top;
            white-space: normal;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-overview .cfw-footer li {
            height: 55px;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-copy-wods-message {
            color: #80898f;
            font-size: 11px;
            font-weight: bold;
            line-height: 13px;
            padding: 4px 0 0 8px;
            text-transform: uppercase;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-copy-wods-message strong {
            color: #40494f;
            line-height: 18px;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-copy-wods-message .btn-mini {
            margin: -7px 0 -5px 4px;
            text-transform: none;
        }
        #cfwhiteboard-wods-meta .cfw-footer .btn-group {
            margin-top: 11px;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-vertical-links {
            border-left: 1px solid #e5e5e5;
            padding: 0;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-vertical-links a {
            border-bottom: 1px solid #e5e5e5;
            display: block;
            font-size: 11px;
            font-weight: bold;
            height: 27px;
            line-height: 26px;
            padding: 0 10px;
            text-align: center;
            text-decoration: none;
            text-transform: uppercase;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-vertical-links a + a {
            border: none;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-vertical-links a:hover {
            background: #eee;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions {
            padding: 6px;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-select-and-continue,
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-remove-this-component {
            display: inline-block;
            -webkit-border-radius: 2px;
            -moz-border-radius: 2px;
            border-radius: 2px;
            font-size: 11px;
            font-weight: bold;
            text-decoration: none;
            text-transform: uppercase;
            vertical-align: middle;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-remove-this-component {
            /*background: #bbb;*/
            color: #fff;
            text-shadow: 0 1px 0 rgba(0,0,0,.15);
            padding: 7px 10px;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-remove-this-component:hover {
            background: #70797f;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-select-and-continue {
            background: #FA9161;
            color: #fff;
            margin-left: 6px;
            padding: 7px 10px;
            text-shadow: 0 1px 0 rgba(0,0,0,.15);
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-select-and-continue.disabled {
            background: #60696f;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-select-and-continue:hover {
            background: #f86825;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-select-and-continue:active,
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions .cfw-remove-this-component:active {
            -webkit-box-shadow: inset 0 1px 3px rgba(0,0,0,.4);
            -moz-box-shadow: inset 0 1px 3px rgba(0,0,0,.4);
            box-shadow: inset 0 1px 3px rgba(0,0,0,.4);
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions a .cfw-text {
            display: inline-block;
            line-height: 22px;
            vertical-align: middle;
            white-space: normal;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions a.cfw-select-and-continue .cfw-text {
            padding: 0 0 0 10px;
        }
        #cfwhiteboard-wods-meta .cfw-footer .cfw-component-actions a.cfw-remove-this-component .cfw-text {
            padding: 0 0 0 8px;
        }
        #cfwhiteboard-wods-meta .cfw-new-component,
        #cfwhiteboard-wods-meta .cfw-new-wod {
            background: #fff;
            font-size: 13px;
            font-weight: 300;
            padding-right: 0;
            padding-left: 0;
        }
        #cfwhiteboard-wods-meta .cfw-new-component {
            padding-left: 5px;
        }
        #cfwhiteboard-wods-meta .cfw-new-wod {
            font-size: 20px;
        }
        #cfwhiteboard-wods-meta .cfw-new-component i,
        #cfwhiteboard-wods-meta .cfw-new-wod i {
            margin-top: 3px;
            margin-right: 3px;
            opacity: .25;
            vertical-align: top;
        }
        #cfwhiteboard-wods-meta .cfw-new-component:hover i,
        #cfwhiteboard-wods-meta .cfw-new-wod:hover i {
            opacity: .5;
        }
/*
        #cfwhiteboard-wods-meta .cfw-content-container {
            background: #40494f;
            border-bottom-right-radius: 3px;
            -webkit-box-shadow: inset 10px 0 3px -10px rgba(0,0,0,.5);
            -moz-box-shadow: inset 10px 0 3px -10px rgba(0,0,0,.5);
            box-shadow: inset 10px 0 3px -10px rgba(0,0,0,.5);
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            left: 0;
            margin-left: 180px;
            position: relative;
            top: 0;
            padding: 16px 10px 0;
        }
        #cfwhiteboard-wods-meta p.help {
            color: #ddd;
            font-size: 11px;
            font-style: normal;
            line-height: 1.3;
            margin: 0;
            padding: 16px 20px 4px;
        }
        #cfwhiteboard-wods-meta p.help + p.help {
            padding-top: 4px;
            padding-bottom: 16px;
        }
        #cfwhiteboard-wods-meta p.help:hover {
            color: #fff;
        }
*/
        #cfwhiteboard-wods-meta .hidden {
            display: none;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields {
/*
            background: #fff;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
*/
            /*margin: 0 0 20px;*/
            /*padding: 5px;*/
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-main {
            border-bottom: none;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields-nav {
            background: #fafafa;
            border-bottom: 1px solid #ddd;
            margin-bottom: 0;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields-nav > li > a {
            background-color: transparent;
            border-color: transparent transparent #ddd;
            -webkit-border-radius: 0;
            -moz-border-radius: 0;
            border-radius: 0;
            margin: 0;
            padding-bottom: 10px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields-nav .active a,
        #cfwhiteboard-wods-meta .cfw-component-fields-nav .active a:hover {
            background-color: #fff;
            border-bottom-color: #21759B;
            border-bottom-color: transparent;
            border-right-color: #ddd;
            color: #21557B;
            cursor: default;
            font-weight: bold;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields-nav .active a.cfw-benchmarks,
        #cfwhiteboard-wods-meta .cfw-component-fields-nav .active a.cfw-benchmarks:hover {
            border-bottom-color: #ccc;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields-nav .active a.cfw-custom-component-tab,
        #cfwhiteboard-wods-meta .cfw-component-fields-nav .active a.cfw-custom-component-tab:hover {
            border-left-color: #ddd;
        }
/*
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-delete {
            color: #d00;
            margin-right: 0;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-delete .caret {
            border-top-color: #d00;
            border-bottom-color: #d00;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-delete:hover {
            color: #933;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-delete:hover .caret {
            border-top-color: #933;
            border-bottom-color: #933;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-save-and-close a,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-save-and-close a:visited {
            color: #0b0;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-save-and-close a:hover {
            color: #080;
        }
*/
        #cfwhiteboard-wods-meta .cfw-component-fields input {
            -webkit-box-sizing: content-box;
            -moz-box-sizing: content-box;
            box-sizing: content-box;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .input-block-level {
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .tab-content {
            background: #fff;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .tab-pane {
            overflow: hidden;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .tab-pane .nav-stacked {
            height: 315px;
            overflow: auto;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-custom-component {
            padding: 10px 13px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-browse-pane,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-details-pane {
            display: none;
            margin: 0 -1px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-browse-pane.active,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-details-pane.active {
            display: block;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form {
            background: #eee;
            border-color: #ddd;
            border-style: none solid solid;
            border-width: 1px;
            padding: 8px 11px 7px;
            position: relative;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form .icon-search {
            left: 24px;
            opacity: .5;
            position: absolute;
            top: 15px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form .icon-search:hover,
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form input:hover + label .icon-search,
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form input:focus + label .icon-search {
            opacity: .85;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form input {
            padding-right: 32px;
            padding-left: 34px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form label.cfw-clear {
            background: #999;
            -webkit-border-radius: 100px;
            -moz-border-radius: 100px;
            border-radius: 100px;
            color: white;
            display: none;
            font-size: 19px;
            height: 20px;
            line-height: 16px;
            margin: 0;
            padding: 0;
            position: absolute;
            right: 16px;
            text-align: center;
            text-shadow: 0 -1px 0 #555;
            top: 13px;
            width: 20px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .search-form label.cfw-clear:hover {
            background: #555;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav {
            background: #fff;
            margin: 0;
            overflow: hidden;
            padding: 0;
            white-space: nowrap;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li {
            border-bottom: 1px solid #999;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;
            margin: 0;
            padding: 0;
            vertical-align: top;
            width: 20%;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li:hover {
            border-bottom-color: #08c;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active {
            border-bottom-color: #555;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.cfw-other {
            width: 15%;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li a,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li a:visited {
            border-color: #ddd;
            border-style: none solid;
            border-width: 1px;
            color: #999;
            display: block;
            font-size: 11px;
            font-weight: bold;
            overflow: hidden;
            padding: 9px 2px;
            text-align: center;
            text-decoration: none;
            text-overflow: ellipsis;
            text-transform: uppercase;
            white-space: nowrap;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li + li a {
            border-left: none;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li:hover a {
            color: #08c;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active a,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active a:visited,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active a:hover {
            color: #555;
            cursor: default;
            font-weight: bold;
        }
/* highlight games tab
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.cfw-games-tab a,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.cfw-games-tab a:visited {
            color: #e51231;
            font-size: 18px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.cfw-games-tab:hover {
            border-bottom-color: #b61c26;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active.cfw-games-tab a,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active.cfw-games-tab a:visited,
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active.cfw-games-tab a:hover {
            color: #2d2e2e;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-nav li.active.cfw-games-tab {
            border-bottom-color: #2d2e2e;
        }
/* end highlight games tab */
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list {
            display: none;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list.active {
            display: block;
        }
        #cfwhiteboard-wods-meta .nav-stacked .icon-chevron-right {
            float: right;
            margin-top: 2px;
            margin-right: -6px;
        }
        #cfwhiteboard-wods-meta .nav-stacked i {
            opacity: .25;
        }
        #cfwhiteboard-wods-meta .nav-stacked a:hover i {
            opacity: .85;
        }
        #cfwhiteboard-wods-meta .nav-stacked .active a i {
            opacity: 1;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked {
            margin: 0;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a {
            background: #fff;
            border-radius: 0;
            color: #fff;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a:hover,
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a.cfw-description-match {
            color: #888;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a small {
            font-weight: normal;
            font-size: 12px;
        }
        /* search result highlighting */
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a strong,
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a .cfw-title strong {
            color: #000;
            font-weight: bold;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a .cfw-title {
            margin-right: 10px;
            font-size: 14px;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a .cfw-title,
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a small {
            color: #08c;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a:hover strong,
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a:hover small {
            color: #005580;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a .btn-mini {
            color: #666;
            font-weight: bold;
            margin: -1px 5px 0 10px;
            opacity: .1;
            padding-left: 4px;
            position: relative;
            z-index: 1;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a .btn-mini i {
            margin-top: 0;
            opacity: .5;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a:hover .btn-mini {
            opacity: 1;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a:hover .btn-mini i {
            opacity: .25;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a .btn-mini:hover {
            color: #444;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a .btn-mini:hover i {
            opacity: .9;
        }
/*
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a .cfw-select-benchmark.active {
            background: #00a5b8;
            color: #fff;
            text-shadow: 0 1px 0 rgba(0, 0, 0, .2);
            opacity: 1;
        }
        #cfwhiteboard-wods-meta .cfw-component-fields .cfw-benchmark-list a .cfw-select-benchmark.active i {
            opacity: 1;
        }
*/
        #cfwhiteboard-wods-meta .cfw-component-fields .nav-stacked a small.pull-right {
            margin: 1px 10px 0 10px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view {
            text-align: center;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .container {
            margin: 0 auto;
            padding: 8px 0 25px;
            text-align: left;
            width: 380px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .cfw-back {
            margin: 0 0 2px;
            padding-right: 0;
            padding-left: 0;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .cfw-back i {
            margin-right: 1px;
        }
/*
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .cfw-select-benchmark {
            font-size: 14px;
            margin-top: 2px;
            padding-left: 7px;
            position: relative;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .cfw-select-benchmark.active {
            background: #00a5b8;
            color: #fff;
            text-shadow: 0 1px 0 rgba(0, 0, 0, .2);
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .cfw-select-benchmark .tooltip-inner {
            max-width: none;
            text-shadow: none;
            width: 190px;
        }
*/
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details {
            border: 1px solid #ddd;
            margin: 0;
            padding: 10px 18px 15px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details .repcount {
            text-align: center;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details .repcount .btn-group {
            display: inline-block;
            line-height: 26px;
            margin: 0 3px;
            text-align: left;
            vertical-align: middle;
            *zoom: 1;
            *display: inline;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details h2 {
            font-size: 24px;
            margin: 0;
            padding: 0 0 5px;
            text-align: center;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details .lead {
            font-size: 17px;
            line-height: 1.3;
            margin: 0;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details .cfw-description {
            white-space: pre-line;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details label {
            line-height: 26px;
            margin: 0;
            padding: 18px 0 6px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details label small {
            display: block;
            font-size: 11px;
            font-weight: normal;
            line-height: 16px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details label small a {
            position: relative;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details label small a .tooltip {
            width: 140px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .details label small a .tooltip-inner {
            text-align: left;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .history {
            margin: 0;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .history p {
            font-size: 21px;
            margin: 0;
            padding: 12px 18px 8px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .history ul {
            background: #f8f8f8;
            border-style: none solid solid;
            border-width: 1px;
            border-color: #ddd;
            margin: 0;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .history ul li {
            border-top: 1px solid #ddd;
            margin: 0;
            padding: 8px 10px 8px 18px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .history ul li small {
            color: #888;
            font-size: 12px;
            margin-left: 8px;
        }
        #cfwhiteboard-wods-meta .cfw-benchmark-detail-view .history ul li a i {
            margin-left: 4px;
        }
        /* admin notices */
        #cfwhiteboard-admin-notice em {
            font-style: normal;
            color: red;
        }
        /* tinyMCE styling */
        a.mceAction.mce_cfwhiteboard_button {
            overflow: hidden;
            width: 93px !important;
        }
        /* "Please activate your trial" notice */
        .meta-box-overlay {
            background: rgba(0, 0, 0, .7);
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
            bottom: 0;
            left: 0;
            position: absolute;
            right: 0;
            top: 0;
            z-index: 100;
        }
        .meta-box-overlay .cfw-notice {
            background: #fff;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
            box-sizing: border-box;
            left: 50%;
            margin-left: -150px;
            max-width: 100%;
            padding: 0 30px 20px;
            position: absolute;
            top: 40px;
            width: 300px;
        }
    </style>
    <?php
        $wods = cfwhiteboard_get_wods($object->ID);

        $next_wod_id = 1;
        $next_component_id = 1;

        if (! is_array($wods)) {
            // no wods yet - instantiate empty array
            $wods = array();
            $wods[] = array(
                'name' => 'Workout of the Day',
                'components' => array(),
                'wp_id' => $next_wod_id++,
                'date' => ''
            );
        } else {
            // Gather the next_wod_id and next_component_id values
            foreach ($wods as $wod) {
                $next_wod_id = max($next_wod_id, intval( $wod['wp_id'] ));

                if (is_array($wod['components']) && !empty($wod['components'])) {
                    foreach ($wod['components'] as $component) {
                        $next_component_id = max($next_component_id, intval( $component['wp_id'] ));
                    }
                }
            }
        }

        $next_wod_id += 10;
        $next_component_id += 10;

        // Ensure each wod has a components array with at least one component
        foreach ($wods as $wod) {
            if ((!is_array( $wod['components'] )) || empty($wod['components'])) {
                $wod['components'] = array();
                $wod['components'][] = array(
                    'description' => '',
                    'label' => '',
                    'wp_id' => $next_component_id++
                );
            }
        }

        $wods_date = $wods[0]['date'];
    ?>
    <div id="cfw-activation-notice" class="meta-box-overlay" style="display:none;">
        <div class="cfw-notice">
            <h2>Welcome to CF Whiteboard!</h2>
            <p>Please <a href="options-general.php?page=cf-whiteboard.php#account">activate your trial</a> so you can start playing around!</p>
        </div>
    </div>
    <div class="cfw-twb">
        <div class="tab-content cfw-component-fields-container">
            <div class="cfw-overview tab-pane active">
                <div class="cfw-header">
                    <a class="pull-right cfw-admin-tour" href="http://cfwhiteboard.com/wp-admin-tour" target="_blank"><i class="icon-play"></i> Tour the Admin Area</a>
                    <div class="cfw-wods-date-container" title="Date of Workouts (click to edit)" rel="tooltip" data-placement="right">
                        <input id="cfwhiteboard-wods-date" type="text" name="cfwhiteboard-wods-date" class="cfw-datepicker" value="<?php esc_attr_e(empty($wods_date) ? '(use publish date)' : $wods_date); ?>"
                        /><label for="cfwhiteboard-wods-date">
                            <i></i>
                            Date of Workouts
                        </label>
                    </div>
                </div>
                <div class="cfw-main">
                    <?php
                        // this article helped me: http://wp.tutsplus.com/tutorials/plugins/a-guide-to-the-wordpress-http-api-automatic-plugin-updates/
                        $plugin_updates = get_site_transient('update_plugins');
                        if (!empty($plugin_updates) && !empty($plugin_updates->response) && !empty($plugin_updates->response["cf-whiteboard/cf-whiteboard.php"])) {
                            // echo '<p>'.var_dump($plugin_updates->response["cf-whiteboard/cf-whiteboard.php"]).'</p>';
                            $file = plugin_basename(__FILE__);
                            ?>
                                <div class="well well-small" style="margin:0 0 20px;">
                                    <!-- <button type="button" class="close" data-dismiss="alert">×</button> -->
                                    <strong>New Features!</strong>
                                    <span style="margin-right: 10px;">A new version of CF Whiteboard is ready.</span>
                                    <a class="btn btn-primary" style="margin:0 2px 2px 0;" target="_blank" href="<?php echo wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=') . $file, 'upgrade-plugin_' . $file) ?>">
                                        <i class="icon-circle-arrow-up icon-white" style="margin-left:-4px;"></i>
                                        Update Now
                                    </a>
                                    <span class="nobr">
                                        or
                                        <a href="http://blog.cfwhiteboard.com" target="_blank">Read about the new features</a>
                                    </span>
                                </div>
                            <?php
                        }
                    ?>
                    <div id="cfw-subscription-status-notice" style="display:none;">
                        <div class="trial_expired well well-small" style="margin:0 0 20px; display:none;">
                            <strong>Your free trial has expired.</strong>
                            <a href="options-general.php?page=cf-whiteboard.php#account">Choose a subscription</a> to continue using CF Whiteboard, or <a href="mailto:help@cfwhiteboard.com" target="_blank">email us</a> with any questions.
                        </div>
                        <div class="past_due well well-small" style="margin:0 0 20px; display:none;">
                            <strong>Your subscription is past due.</strong>
                            Visit Settings > CF Whiteboard > <a href="options-general.php?page=cf-whiteboard.php#account">Account</a> for more information, or <a href="mailto:help@cfwhiteboard.com" target="_blank">email us</a> with any questions.
                        </div>
                        <div class="canceled well well-small" style="margin:0 0 20px; display:none;">
                            <strong>Your subscription is canceled.</strong>
                            Visit Settings > CF Whiteboard > <a href="options-general.php?page=cf-whiteboard.php#account">Account</a> for more information, or <a href="mailto:help@cfwhiteboard.com" target="_blank">email us</a> with any questions.
                        </div>
                        <div class="expired well well-small" style="margin:0 0 20px; display:none;">
                            <strong>Your subscription has expired.</strong>
                            Visit Settings > CF Whiteboard > <a href="options-general.php?page=cf-whiteboard.php#account">Account</a> for more information, or <a href="mailto:help@cfwhiteboard.com" target="_blank">email us</a> with any questions.
                        </div>
                    </div>
                    <div id="cfw-error-fetching-benchmarks-notice" style="display:none;">
                        <div class="well well-small" style="margin:0 0 20px;">
                            Error getting data for the benchmark workouts. If <a href="javascript:window.location.reload(true);">refreshing the page</a> doesn't help (don't forget to save your work!),
                            please contact us so that we can look into it. <strong><a href="mailto:help@cfwhiteboard.com" target="_blank">help@cfwhiteboard.com</a></strong>
                        </div>
                    </div>
                <!--
                    <p class="help">
                        Add the classes that you want to track for today.  Each class will have a separate tab in the CF Whiteboard widget.
                    </p>
                    <p class="help">
                        You can track multiple components for each class.  Each component will have a separate entry field so athletes can lookup their results separately for each component.
                    </p>
                -->
                    <div class="cfw-single-column">
                        <div class="cfw-overview-header muted">
                            Classes Programmed for this Date
                            <a href="javascript://" rel="tooltip" class="btn btn-link btn-mini pull-right cfw-overview-help" title="Each class appears as a separate tab in the whiteboard.<br>Example:<ul><li>CrossFit Rise offers 3 classes today - Endurance, Oly, and the WOD.</li><li>They can add 1 or all of those classes to the whiteboard so their athletes can track their results.</li></ul>" data-html="true" data-placement="in left">Help</a>
                        </div>
                        <ul class="cfw-wods">
                            <?php
                                foreach ($wods as $wod) {
                                    echo cfwhiteboard_generate_class_nav($wod);
                                }
                            ?>
                            <li class="cfw-new-wod-row">
                                <a href="javascript:// Add Another Class" title="Add Another Class" class="cfw-new-wod btn btn-link">
                                    <i class="icon-plus"></i>add a class
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
                <ul class="cfw-footer">
                    <li class="cfw-vertical-links pull-right">
                        <a href="http://blog.cfwhiteboard.com" target="_blank">
                            CFW Blog
                        </a>
                        <a href="mailto:help@cfwhiteboard.com" target="_blank">
                            Contact Us
                        </a>
                    </li><li class="cfw-copy-wods-message">
                        <strong>Finished?</strong>
                        <br>
                        1. Copy Workouts Into Post. <span style="font-weight:normal; text-transform:none;">(Use the CFW button above <a href="#postdivrich">the post editor</a>.)</span> <!--<a href="javascript:// Copy to Clipboard" class="btn btn-mini">1-Click Copy</a>-->
                        <br>
                        2. Save the Post! <!--<input type="submit" class="btn btn-mini">Save Now</a>-->
                    </li>
                </ul>
            </div>
            <?php
                foreach ($wods as $wod) {
                    echo cfwhiteboard_generate_class_fields($wod);
                }
            ?>
        </div>
    </div>
    <div style="clear:both;"></div>
    <script type="text/javascript">
        typeof(jQuery) == 'function' && jQuery(function($) {
            // Don't let the script run more than once
            if (window.CFW) {
                return;
            }
            window.CFW = {};
            if (host_string.indexOf('localhost-dev')) {
              CFW.domain =  'http://localhost:3000'
            } else if (host_string.indexOf('testaffiliate')) {
              CFW.domain =  'http://tameron.herokupp.com'
            }  else {
              CFW.domain = (window.location.protocol == 'https:' ? 'https:' : 'http:') + (/[.]local/.test(window.location.host) || /ollli/.test(window.location.host) || /squatc/.test(window.location.host) ? '//tameron.herokuapp.com' : '//cfwhiteboard.com');
            }
            // Safely pull a property from the depths of an object.  Default value is returned if the requested property was not defined.
            // CFW.oxygenTank = function(base_object, 'level_1_property_name', ..., 'level_N_property_name', default_value) {...};
            CFW.oxygenTank = function() {
                var args = Array.prototype.slice.call(arguments);
                var default_value = args.pop();
                var attempt = _.inject(args, function(memo, arg) { return typeof(memo) != 'undefined' ? memo[arg] : memo }, args.shift());
                return typeof(attempt) != 'undefined' ? attempt : default_value;
            };
            CFW.tunnel = new easyXDM.Rpc({
                remote: CFW.domain + '/tunnel'
            }, {
                remote: {
                    request: {}
                }
            });
            CFW.ajax = function(options) {
                var deferred = jQuery.Deferred();
                deferred.done(function() {
                    options.success && options.success.apply(this, arguments);
                });
                deferred.fail(function(errorObject) {
                    var xhr = errorObject.message;
                    options.error && options.error.apply(this, [xhr]);
                });
                deferred.always(function() {
                    options.complete && options.complete.apply(this);
                });

                options.method = options.type;
                CFW.tunnel.request(_.extend({}, options, {model: null, collection: null}), function() {
                    deferred.resolveWith(this, arguments);
                }, function() {
                    deferred.rejectWith(this, arguments);
                });

                return deferred.promise();
            };
            Backbone.ajax = CFW.ajax;

            // XXX Don't buy Theme Fusion themes. They are on the naughty list.
            // Here's an email response from their support team, after I offered to help them fix
            // their code, which currently damages a shared code library called BackboneJS.
            // Essentially, they're too big and powerful to care.
            //
            // Salman wrote:
            // Hi There,
            // Current plugin was released after lot of beta, alpha testing and QA. Any modification to plugin code will require us to go through same process from start. We have 100k+ users of this plugin. So, I'd suggest you to modify code at your end as per your requirements.
            // However, we're always listening to our users. If you have any feature requests, recommendations or ideas – you can add them to our idea section. Each idea that is submitted can be voted on by other users. This allows our team to have a list of the most popular requests for future development. We value everyone's opinion and continue to improve Avada with your help!
            // Click Here To Submit Your Idea!
            // Thanks for choosing Avada
            // -Salman
            if (typeof(window.Palette) != 'undefined') {
                // Restore original version of Backbone.sync...
                // BackboneJS v1.3.3
                (function() {
                    // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
                    var methodMap = {
                      'create': 'POST',
                      'update': 'PUT',
                      'patch': 'PATCH',
                      'delete': 'DELETE',
                      'read': 'GET'
                    };

                    var urlError = function() {
                        throw new Error('A "url" property or function must be specified');
                    };

                    Backbone.sync = function(method, model, options) {
                      var type = methodMap[method];

                      // Default options, unless specified.
                      _.defaults(options || (options = {}), {
                        emulateHTTP: Backbone.emulateHTTP,
                        emulateJSON: Backbone.emulateJSON
                      });

                      // Default JSON-request options.
                      var params = {type: type, dataType: 'json'};

                      // Ensure that we have a URL.
                      if (!options.url) {
                        params.url = _.result(model, 'url') || urlError();
                      }

                      // Ensure that we have the appropriate request data.
                      if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
                        params.contentType = 'application/json';
                        params.data = JSON.stringify(options.attrs || model.toJSON(options));
                      }

                      // For older servers, emulate JSON by encoding the request into an HTML-form.
                      if (options.emulateJSON) {
                        params.contentType = 'application/x-www-form-urlencoded';
                        params.data = params.data ? {model: params.data} : {};
                      }

                      // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
                      // And an `X-HTTP-Method-Override` header.
                      if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
                        params.type = 'POST';
                        if (options.emulateJSON) params.data._method = type;
                        var beforeSend = options.beforeSend;
                        options.beforeSend = function(xhr) {
                          xhr.setRequestHeader('X-HTTP-Method-Override', type);
                          if (beforeSend) return beforeSend.apply(this, arguments);
                        };
                      }

                      // Don't process data on a non-GET request.
                      if (params.type !== 'GET' && !options.emulateJSON) {
                        params.processData = false;
                      }

                      // Pass along `textStatus` and `errorThrown` from jQuery.
                      var error = options.error;
                      options.error = function(xhr, textStatus, errorThrown) {
                        options.textStatus = textStatus;
                        options.errorThrown = errorThrown;
                        if (error) error.call(options.context, xhr, textStatus, errorThrown);
                      };

                      // Make the request, allowing the user to override any Ajax options.
                      var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
                      model.trigger('request', model, xhr, options);
                      return xhr;
                    };
                })();
            }

            CFW.getAffiliateDetails = function() {
                $.getJSON(CFW.domain+'/affiliates/<?php echo preg_replace('/_preview$/', '', $options['affiliate_id']); ?>.json', function(data) {
                    CFW.affiliateDetails = data;
                    $(window).trigger('affiliateDetailsReady');
                });
            };
            CFW.getAffiliateDetails();

            CFW.displayActivationNotice = function() {
                $('#cfw-activation-notice').show();
            };
            CFW.displayStatusNotice = function(textStatus) {
                var $notice = $('#cfw-subscription-status-notice');
                $notice.find('.'+textStatus).show();
                $notice.fadeIn(300);
            }
            $(window).on('affiliateDetailsReady', function() {
                if (!CFW.affiliateDetails || !CFW.affiliateDetails.activated_at) {
                    CFW.displayActivationNotice();
                } else if (CFW.affiliateDetails.subscription_status == "trial_expired" || CFW.affiliateDetails.subscription_status == "past_due" || CFW.affiliateDetails.subscription_status == "expired" || CFW.affiliateDetails.subscription_status == "canceled") {
                    CFW.displayStatusNotice(CFW.affiliateDetails.subscription_status);
                }
            });


            CFW.parseClassDescription = function($container) {
                var classDescription = {
                    name: $container.find('.cfw-edit-wod-title').val(),
                    components: []
                }

                $container.find('.cfw-component').each(function() {
                    var $componentFields = $( $(this).find('a').data('target') );
                    classDescription.components.push({
                        description: $componentFields.triggerHandler('descriptionrequest')
                    });
                });

                return classDescription;
            };
            CFW.generateClassDescriptionMarkup = function(classDescription) {
                var linebreak = '\n';

                var markup = '';
                markup += '<strong>'+classDescription.name+'</strong>' + linebreak;
                var count = 0; // must count separately from index because components with blank descriptions are skipped
                for (var i = 0; i < classDescription.components.length; ++i) {
                    var trimmedDescription = classDescription.components[i].description.replace(/^\s+/,'').replace(/\s+$/,'');
                    if (!trimmedDescription) continue;

                    if (count++ > 0) markup += '<em>then</em>' + linebreak;
                    markup += classDescription.components[i].description + linebreak;
                }

                return markup + linebreak;
            };
            // CFW.newlineToBr() is used by MCE plugin!
            CFW.newlineToBr = function(str) {
                return str.replace(/\r\n/g, '<br />').replace(/\r/g, '<br />').replace(/\n/g, '<br />');
            };


            // Move the CF Whiteboard meta box just under the Post Title
            $('#titlediv').after( $('#cfwhiteboard-wods-meta') );


            // Update component numbers
            CFW.updateComponentNumbers = function($container) {
                $container.find('tbody label span').each(function(index) {
                    $(this).text(index + 1); // component numbers start at 1
                });
            };
            // intial numbering
            $('#cfwhiteboard-wods-meta li').each(function() {
                CFW.updateComponentNumbers( $(this) );
            });


            // Date Picker(s)
            if ($.fn.datepicker) {
                $('.cfw-datepicker').each(function() {
                    var $this = $(this);
                    $this.datepicker({
                        showAnim: 'slideDown',
                        dateFormat: 'DD, M d, yy',
                        showOtherMonths: true,
                        selectOtherMonths: true
                    });
                    // if (!$this.datepicker('getDate')) {
                        // $this.datepicker('setDate', new Date());
                    // }
                });
            }


            /* define this function so coaches don't think the Whiteboard link is broken */
            CFW.goToHash = function() {
                alert('When you publish this post, clicking this link will show people where the Whiteboard is in case they can\'t find it.');
            };
            /* needed for Whiteboard link when inserting workouts into the post */
            CFW.postId = '<?php echo $object->ID; ?>';



            // tinyMCE.settings.paste_postprocess function for pasting Wods html
            // var old_paste_postprocess = "<?php
            //     $old = get_transient($CFWHITEBOARD_WODS_META_KEY.'-old_paste_postprocess');
            //     delete_transient($CFWHITEBOARD_WODS_META_KEY.'-old_paste_postprocess');
            //     echo empty($old) ? '' : $old;
            // ?>";
            // if (old_paste_postprocess.indexOf('function') == 0) {
            //     eval('old_paste_postprocess='+old_paste_postprocess);
            // } else {
            //     var orig = old_paste_postprocess.split('.');
            //     old_paste_postprocess = window;
            //     for (var i = 0; i < orig.length; i++) {
            //         old_paste_postprocess = typeof(old_paste_postprocess[orig[i]]) == 'undefined' ? false : old_paste_postprocess[orig[i]];
            //     }
            // }
            // CFW.mce_paste_postprocess = function(pl, o) {
            //     typeof(old_paste_postprocess) == 'function' && old_paste_postprocess(pl, o);

            //     // Content DOM node containing the DOM structure of the clipboard
            //     // console.log(o.node.innerHTML);
            //     // o.node.innerHTML = o.node.innerHTML + "\n-: CLEANED :-";

            //     var $node = $(o.node);
            //     if ($($node.text()).hasClass('cfw-wods')) {
            //         $node.html($node.text());
            //     }
            // };
            // QuickTag Button for HTML editor
            if (QTags && QTags.addButton && !CFW.edButtonAdded) {
                QTags.addButton(
                    'cfw_wods', // id
                    'CF Whiteboard', // display
                    function(button){
                        var $button = $(button);

                        var $menu = $button.data('cfwmenu');
                        if (!$menu) {
                            $button.attr('data-toggle','bsdropdown');
                            $button.attr('data-target','.cfw-dummy-selector');
                            $button.wrap('<div class="dropdown" style="display:inline-block; vertical-align:top; *zoom:1; *display:inline;"></div>');
                            $button.closest('.dropdown').wrap('<span class="cfw-twb"></span>');
                            $button.after('<ul class="dropdown-menu"></ul>');

                            $menu = $button.closest('.dropdown').find('.dropdown-menu');
                            $menu.on('click', function() {
                                $button.bootstrap_dropdown('toggle');
                            });

                            $button.data('cfwmenu', $menu);
                        }
                        $menu.empty();

                        // Gather class names/descriptions
                        var classes = [];
                        var tempClass;
                        $('#cfwhiteboard-wods-meta .cfw-wods li').each(function() {
                            tempClass = CFW.parseClassDescription( $(this) );

                            var hasDescription = false;
                            for (var i = 0; i < tempClass.components.length; i++) {
                                if (tempClass.components[i].description.replace(/^\s+/,'').replace(/\s+$/,'')) {
                                    hasDescription = true;
                                    break;
                                }
                            }
                            // only add classes that have descriptions
                            if (!hasDescription) return;

                            // Generate the markup for the class description
                            tempClass.markup = CFW.generateClassDescriptionMarkup(tempClass);

                            classes.push( tempClass );
                        });

                        var footerText = classes.length > 0 ? 'Post your results to <span class="cfw-link-to-whiteboard" data-post-id="'+CFW.postId+'" style="border-bottom: 1px dotted;">the Whiteboard</span>.\n\n' : '';

                        var options = [];
                        if (!classes.length) {
                            // no classes entered, provide link to CFW meta box
                            var $li = $('<li><a href="#cfwhiteboard-wods-meta">No workouts. Click to add one.</a></li>');
                            $li.on('click', function() {
                                var $metaBox = $('#cfwhiteboard-wods-meta');
                                if ($metaBox.find('.cfw-main:visible').length == 0) {
                                    $metaBox.find('.handlediv').click();
                                }
                            });
                            $menu.append($li);
                        } else if (classes.length > 1) {
                            // multiple classes entered, provide menu item for inserting all at once

                            var markupAll = '';
                            for (var i = 0; i < classes.length; i++) {
                                markupAll += classes[i].markup;
                            }
                            markupAll += footerText;

                            var $li = $('<li><a href="javascript:// Insert into Post">Insert All '+classes.length+' Classes</a></li>');
                            $li.on('click', function() {
                                QTags.insertContent( markupAll );
                            });
                            $menu.append($li);
                            $menu.append('<li class="divider"></li>');
                        }

                        var generateInsertMarkupFunc = function(markup) {
                            return function() {
                                QTags.insertContent( markup );
                            };
                        };
                        for (var i = 0; i < classes.length; i++) {
                            var $li = $('<li><a href="javascript:// Insert into Post">Insert '+classes[i].name+'</a></li>');
                            $li.on('click', generateInsertMarkupFunc(classes[i].markup + footerText));
                            $menu.append($li);
                        }
                    }, // arg1
                    function(){}, // arg2
                    'w', // access_key
                    'Insert Workout Description(s)', // title
                    140 // priority
                );
                CFW.edButtonAdded = true;
            }


            // Edit Wod Titles
            $(document.body).on('keypress', '.cfw-edit-wod-title', function(event) {
                if (event.which == "13") {
                    $(this).blur();

                    event.preventDefault();
                    event.stopImmediatePropagation();
                    return false;
                }
            });


            CFW.Component = Backbone.Model.extend({
                idAttribute: '_id',
                defaults: {
                    benchmark_group: '',
                    label: 'Error loading label.',
                    description: 'Error loading description.',
                    inline_description: '',
                    result_type: 'text',
                    result_notes: '',
                    history: [/*{
                        date: '',
                        time_ago_in_words: '',
                        post_permalink: ''
                    }*/]
                }
            });
            CFW.BenchmarkList = Backbone.Collection.extend({
                model: CFW.Component,

                url: function() {
                    return CFW.domain+'/affiliates/<?php echo preg_replace('/_preview$/', '', $options['affiliate_id']); ?>/benchmarks.json';
                },

                initialize: function(models, options) {

                    return this;
                },

                comparator: function(component) {
                    return component.get('label').toLowerCase();
                },

                query: function(str) {
                    if (!str) return;
                    var regexp = RegExp(_.inject(str.split(''), function(memo, c) {
                        return memo + '([^'+ c +']*)('+ c +')';
                    }, '') + '(.*)', 'i');

                    return this.chain()
                        .map(function(model) {
                            var match = regexp.exec(model.get('label'));
                            var descriptionMatch = regexp.exec(model.get('inline_description'));

                            if (!match && !descriptionMatch) return false;

                            if (match) {
                                match.shift();
                                var tail = match.pop();

                                model.queryResult = {
                                    score: 2 * _.inject(match, function(memo, val, index) {
                                        return memo + (index % 2 == 0 ? val.length * (match.length - index) : 0);
                                    }, 0),
                                    label: _.inject(match, function(memo, val, index) {
                                        return memo + (index % 2 == 0 ? val : '<strong>'+val+'</strong>');
                                    }, '') + tail
                                };
                            } else if (descriptionMatch) {
                                descriptionMatch.shift();
                                var tail = descriptionMatch.pop();

                                model.queryResult = {
                                    score: _.inject(descriptionMatch, function(memo, val, index) {
                                        return memo + (index % 2 == 0 ? val.length * (descriptionMatch.length - index) : 0);
                                    }, 0),
                                    inline_description: _.inject(descriptionMatch, function(memo, val, index) {
                                        return memo + (index % 2 == 0 ? val : '<strong>'+val+'</strong>');
                                    }, '') + tail
                                };
                            }

                            return model;
                        })
                        .compact()
                        .sortBy(function(model) {
                            return model.queryResult.score;
                        })
                        .value();
                }
            });
            CFW.BenchmarkItemView = Backbone.View.extend({
                tagName: "li",
                template: _.template('<?php echo <<<HEREDOC
                    <a href="javascript:// Click to Choose" class="<%- description_match ? "cfw-description-match" : "" %>" data-toggle="bstab" data-target="<%- component_selector %> .cfw-details-pane">\
                        <i class="icon-chevron-right"></i>\
                        <% if (history.length > 0) { %>\
                            <small class="pull-right"><%- history[0].time_ago_in_words %>, <%- history.length %> times total</small>\
                        <% } %>\
                        <strong class="cfw-title"><%= label %></strong>\
                        <%= inline_description %>\
                    </a>\

HEREDOC;
                ?>'),

                events: {
                    'show.bs.tab a': 'showDetail',
                    'shown.bs.tab a': 'deactivate'
                },
                // 'click .cfw-select-benchmark:not(.active)': 'triggerSelect',
                // 'click .cfw-select-benchmark.active': 'triggerDeselect'

                initialize: function(options) {
                    this.options = options || {};
                    // this.model.on('change', this.render, this);
                    // this.model.on('destroy', this.remove, this);

                    // this.model.on('show', this.lookSelected, this);
                    // this.model.on('unshow', this.unlookSelected, this);

                    this.component_selector = options.component_selector;
                    this.component_id = options.component_id;

                    // this.model.on('select:c'+this.component_id, this.activateSelect, this);
                    // this.model.on('deselect:c'+this.component_id, this.deactivateSelect, this);

                    return this.render();
                },

                render: function() {
                    // html
                    this.$el.html(
                        this.template(
                            _.extend(this.model.toJSON(), this.model.queryResult, {
                                component_selector: this.component_selector,
                                description_match: !!(this.model.queryResult && this.model.queryResult.inline_description)
                            })
                        )
                    );

                    delete this.model.queryResult;

                    return this;
                },

                lookSelected: function() {
                    this.$el.addClass('cfw-selected');
                },

                unlookSelected: function() {
                    this.$el.removeClass('cfw-selected');
                },

                showDetail: function(event) {
                    event.stopPropagation();

                    this.$el.trigger('showDetail', this.model);
                },

                deactivate: function() {
                    this.$el.removeClass('active');
                },

                // activateSelect: function() {
                //     this.$('.cfw-select-benchmark').addClass('active')
                //         .find('i').addClass('icon-white').end()
                //         .find('span').text('Selected');
                // },

                // deactivateSelect: function() {
                //     this.$('.cfw-select-benchmark').removeClass('active')
                //         .find('i').removeClass('icon-white').end()
                //         .find('span').text('Select');
                // },

                // triggerSelect: function(event) {
                //     event.preventDefault();
                //     this.model.trigger('select:c'+this.component_id, this.model);
                // },

                // triggerDeselect: function(event) {
                //     event.preventDefault();
                //     event.stopPropagation(); // prevent the detail view from being displayed
                //     this.model.trigger('deselect:c'+this.component_id);
                // }
            });
            CFW.BenchmarkDetailView = Backbone.View.extend({
                className: 'cfw-benchmark-detail-view',
                template: _.template('<?php echo <<<HEREDOC
                    <div class="container">\
                        <a href="javascript://" class="cfw-back btn btn-link" data-toggle="bstab" data-target="<%- back_selector %>">\
                            <i class="icon-chevron-left"></i>Other Benchmarks\
                        </a>\
                        <div class="details">\
                            <input type="hidden" name="cfw-components[<%- component_id %>][benchmark_id]" value="<%- _id %>">\
                            <h2><%- label %></h2>\
                            <% if (benchmark_group == "weightlifting") { %>\
                                <div class="lead repcount">\
                                    Find your\
                                    <input type="hidden" name="cfw-components[<%- component_id %>][repcount]" value="<%- repcount %>" class="cfw-repcount">\
                                    <div class="btn-group">\
                                        <button class="btn dropdown-toggle" data-toggle="bsdropdown">\
                                            <span class="value"><%- repcount %></span>\
                                            <span class="caret"></span>\
                                        </button>\
                                        <ul class="dropdown-menu">\
                                            <li><a tabindex="-1" href="javascript://">1</a></li>\
                                            <li><a tabindex="-1" href="javascript://">2</a></li>\
                                            <li><a tabindex="-1" href="javascript://">3</a></li>\
                                            <li><a tabindex="-1" href="javascript://">4</a></li>\
                                            <li><a tabindex="-1" href="javascript://">5</a></li>\
                                            <li><a tabindex="-1" href="javascript://">10</a></li>\
                                            <li><a tabindex="-1" href="javascript://">20</a></li>\
                                        </ul>\
                                    </div>\
                                    rep max.\
                                </div>\
                                <label class="lead" for="cfw-repscheme-<%- component_id %>">\
                                    Rep Scheme / Special Instructions\
                                    <small class="muted">Optional. <a href="javascript://" rel="tooltip" title="&quot;3-3-3-3&quot;<br>&quot;10 minute time limit&quot;<br>&quot;Must be touch-and-go&quot;" data-html="true" data-placement="in right">Examples</a></small>\
                                </label>\
                                <textarea id="cfw-repscheme-<%- component_id %>" name="cfw-components[<%- component_id %>][repscheme]" class="input-block-level cfw-repscheme" rows="2"><%- repscheme %></textarea>\
                            <% } else { %>\
                                <p class="lead cfw-description"><%- description.replace(/^[^\\\\n]*\\\\n/,"") %></p>\
                            <% } %>\
                        </div>\
                        <div class="history">\
                            <p class="lead">History</p>\
                            <ul>\
                                <% if (history.length) {\
                                    _.each(history, function(h) {\
                                    %>\
                                        <li>\
                                            <%- $.datepicker.formatDate(\'M d, yy\', new Date(h.date)) %>\
                                            <small><%- h.time_ago_in_words %></small>\
                                            <a href="<%- h.post_permalink %>" target="_blank" class="pull-right">\
                                                view post<i class="icon-chevron-right"></i>\
                                            </a>\
                                        </li>\
                                    <%\
                                    });\
                                } else { %>\
                                    <li>No history. <small>There\'s a first time for everything.</small></li>\
                                <% } %>\
                            </ul>\
                        </div>\
                    </div>\

HEREDOC;
                ?>'),
                events: {
                    'show.bs.tab a.cfw-back': 'triggerRemove',
                    'shown.bs.tab a.cfw-back': 'remove',
                    'click .repcount .dropdown-menu a': 'selectRepCount'
                },
                // 'click .cfw-select-benchmark:not(.active)': 'triggerSelect',
                // 'click .cfw-select-benchmark.active': 'triggerDeselect',
                // 'focus .cfw-repscheme': 'maybeRemindUserToSelectBenchmark'

                initialize: function(options) {
                    this.options = options || {};
                    this.back_selector = options.back_selector;
                    this.component_id = options.component_id;
                    // this.selected = options.selected;

                    // this.model.on('select:c'+this.component_id, this.select, this);
                    // this.model.on('deselect:c'+this.component_id, this.deselect, this);

                    return this.render(options.repcount || 1, options.repscheme || '');
                },

                render: function(repcount, repscheme) {
                    this.$el.html(
                        this.template(
                            _.extend(this.model.toJSON(), {
                                $: $,
                                component_id: this.component_id,
                                back_selector: this.back_selector,
                                repcount: repcount,
                                repscheme: repscheme
                            })
                        )
                    );

                    // tooltips
                    this.$el.bootstrap_tooltip({selector:'[rel="tooltip"]'});

                    return this;
                },

                repcount: function() {
                    return this.$('.cfw-repcount').val();
                },

                repscheme: function() {
                    return this.$('.cfw-repscheme').val();
                },

                triggerRemove: function() {
                    this.$el.trigger('cfwremove');
                },

                // select: function() {
                //     // this.$('.cfw-select-benchmark').addClass('active').bootstrap_tooltip('destroy')
                //     //     .find('i').addClass('icon-white').end()
                //     //     .find('span').text('Selected');

                //     this.selected = true;

                //     // prevent accidental overriding of cached repcount / repscheme fields for *selected* benchmark that occurs when
                //     // a detail view is rendered for a benchmark other than the selected one
                //     this.$('.cfw-repcount, .cfw-repscheme').each(function() {
                //         var $input = $(this);
                //         $input.attr('name', $input.attr('name').replace(/tmp-/g,''));
                //     });
                // },

                // deselect: function() {
                //     // this.$('.cfw-select-benchmark').removeClass('active')
                //     //     .find('i').removeClass('icon-white').end()
                //     //     .find('span').text('Select');

                //     this.selected = false;

                //     // prevent accidental overriding of cached repcount / repscheme fields for *selected* benchmark that occurs when
                //     // a detail view is rendered for a benchmark other than the selected one
                //     this.$('.cfw-repcount, .cfw-repscheme').each(function() {
                //         var $input = $(this);
                //         $input.attr('name', 'tmp-' + $input.attr('name'));
                //     });
                // },

                // triggerSelect: function(event) {
                //     event.preventDefault();
                //     this.model.trigger('select:c'+this.component_id, this.model);
                // },

                // triggerDeselect: function(event) {
                //     event.preventDefault();
                //     this.model.trigger('deselect:c'+this.component_id);
                // },

                selectRepCount: function(event) {
                    var $a = $(event.target);
                    $a.closest('.btn-group').find('.dropdown-toggle .value').text($a.text());
                    $a.closest('.repcount').find('input').val($a.text());

                    // this.maybeRemindUserToSelectBenchmark();
                }

                // maybeRemindUserToSelectBenchmark: function() {
                //     if (!this.selected) {
                //         var $button = this.$('.cfw-select-benchmark');
                //         $button.bootstrap_tooltip({placement:'in left', trigger:'manual', title:'Don\'t forget to select this benchmark!'});
                //         $button.bootstrap_tooltip('show');

                //         setTimeout(function() {
                //             $button.bootstrap_tooltip('destroy');
                //         }, 5000);
                //     }
                // }
            });
            CFW.BenchmarkListView = Backbone.View.extend({
                events: {
                    'query': 'renderQuery'
                },

                initialize: function(options) {
                    this.options = options || {};
                    // this.collection = options && options.collection || new CFW.BenchmarkList();
                    this.groupRegexp = RegExp(options && options.group || '', 'i');
                    this.component_selector = '#'+ this.$el.closest('.cfw-component-fields').attr('id');

                    this.component_id = this.$el.closest('.cfw-component-fields').data('cid');

                    return this.render();
                },

                render: function() {
                    this.$el.empty();

                    var view = this;
                    CFW.allBenchmarks.chain().select(function(model){
                        return view.groupRegexp.test(model.get('benchmark_group'));
                    }).each(this.addOne, this);

                    this.addNotFoundMessage();

                    return this;
                },

                renderQuery: function(event, queryString) {
                    // assumption: only used by "all benchmarks" list (does not filter based on benchmark_group)
                    this.$el.empty();

                    // ignore whitespace
                    queryString = queryString.replace('/\s/g','');

                    if (queryString) {
                        _.each(CFW.allBenchmarks.query(queryString), this.addOne, this);
                    } else {
                        // close to render() but faster for searching since we don't filter based on benchmark_group
                        CFW.allBenchmarks.each(this.addOne, this);
                    }

                    this.addNotFoundMessage();
                },

                addOne: function(component) {
                    // create view for model
                    var view = new CFW.BenchmarkItemView({
                        model: component,
                        component_selector: this.component_selector,
                        component_id: this.component_id
                    });

                    // add view to dom
                    this.$el.append(view.el);
                },

                addNotFoundMessage: function() {
                    this.$el.append('<li><a href="mailto:help@cfwhiteboard.com" target="_blank"><span class="muted">Can\'t find what you\'re looking for?</span> <small>Email Us</small></a></li>');
                }
            });
            CFW.allBenchmarks = new CFW.BenchmarkList();
            CFW.populateBenchmarkLists = function($uls) {
                // var byGroup = CFW.allBenchmarks.groupBy('benchmark_group');
                $uls.filter('.cfw-weightlifting').each(function(index, $ul) {
                    new CFW.BenchmarkListView({
                        el: $ul,
                        group: 'weightlifting'
                    });
                });
                $uls.filter('.cfw-named-workouts').each(function(index, $ul) {
                    new CFW.BenchmarkListView({
                        el: $ul,
                        group: 'girls|heroes|other'
                    });
                });
                // $uls.filter('.cfw-girls').each(function(index, $ul) {
                //     new CFW.BenchmarkListView({
                //         el: $ul,
                //         group: 'girls'
                //     });
                // });
                // $uls.filter('.cfw-heroes').each(function(index, $ul) {
                //     new CFW.BenchmarkListView({
                //         el: $ul,
                //         group: 'heroes'
                //     });
                // });
                $uls.filter('.cfw-gymnastics').each(function(index, $ul) {
                    new CFW.BenchmarkListView({
                        el: $ul,
                        group: 'gymnastics'
                    });
                });
                $uls.filter('.cfw-monostructural').each(function(index, $ul) {
                    new CFW.BenchmarkListView({
                        el: $ul,
                        group: 'monostructural'
                    });
                });
                // $uls.filter('.cfw-other-benchmarks').each(function(index, $ul) {
                //     new CFW.BenchmarkListView({
                //         el: $ul,
                //         group: 'other'
                //     });
                // });
                $uls.filter('.cfw-games-workouts').each(function(index, $ul) {
                    new CFW.BenchmarkListView({
                        el: $ul,
                        group: 'games'
                    });
                });
                $uls.filter('.cfw-all-benchmarks').each(function(index, $ul) {
                    new CFW.BenchmarkListView({
                        el: $ul
                    });
                });
            };
            CFW.allBenchmarks.fetch({
                success: function(collection, response, options) {
                    // Populate benchmark lists for all existing components
                    var $uls = $('#cfwhiteboard-wods-meta .cfw-benchmark-list');
                    CFW.populateBenchmarkLists($uls);

                    CFW.allBenchmarks.trigger('fetched');
                },
                error: function(collection, xhr, options) {
                    var $notice = $('#cfw-error-fetching-benchmarks-notice').css('opacity', 0).slideDown(function() {
                        $notice.fadeTo(300, 1);
                    });
                }
            });

            // // Save & Close events
            // // switching between Custom / Benchmarks tabs
            // $('.cfw-benchmarks').live('show', function() {
            //     var $this = $(this);
            //     $this.closest('ul').find('.cfw-save-and-close').toggle( $this.closest('.cfw-component-fields').find('.cfw-details-pane').hasClass('active') );
            // });
            // $('.cfw-custom-component-tab').live('show', function() {
            //     $(this).closest('ul').find('.cfw-save-and-close').show();
            // });
            // // closing the currently open component fields
            // $('.cfw-save-and-close a').live('click', function() {
            //     $(this).closest('.inside .cfw-sidebar .nav li:first input').click();

            //     // update component label ?  or should this be done dynamically?

            //     // do a little highlight thing on the label for this component?  either a flash or a light gray until they choose something else
            //         // add 'postactive' class to nav item
            //         // on 'show' for any nav item in sidebar, remove class 'postactive' from all nav items
            // });


            <?php
                $empty_component = array(
                    "description" => "",
                    "label" => "",
                    "wp_id" => "<%- component_id %>"
                );
            ?>
            CFW.ComponentNavView = Backbone.View.extend({
                template: _.template('<?php echo str_replace(array("\r\n", "\n", "\r"), "", cfwhiteboard_generate_class_component_nav("cfw-components", $empty_component, "cfw-wods[<%- wod_id %>][components][]")); ?>'),

                initialize: function(options) {
                    this.options = options || {};
                    this.wod_id = options.wod_id;
                    this.component_id = options.component_id;

                    return options.el ? this : this.render();
                },

                render: function() {
                    // html
                    this.$el.html(
                        this.template({
                            wod_id: this.wod_id,
                            component_id: this.component_id
                        })
                    );

                    // due to a shared server/client-side template, we render the template within a wrapper that we need to remove
                    this.setElement(this.$el.children());
                    this.$el.unwrap();

                    return this;
                },

                description: function(str) {
                    this.$('.cfw-description').text(str || 'New Component\r\nClick to add details.');
                }
            });
            CFW.ComponentFieldsView = Backbone.View.extend({
                template: _.template('<?php echo str_replace(array("\r\n", "\n", "\r"), "", cfwhiteboard_generate_class_component_fields("cfw-components", $empty_component)); ?>'),

                events: {
                    'showDetail': 'showDetail',
                    'descriptionrequest': 'getDescription',
                    'updatebreadcrumbs': 'updateBreadcrumbs',
                    'click .cfw-select-and-continue': 'updateOverview',
                    'click .cfw-select-and-continue  ': 'swapRemoveComponentText',
                    'click .cfw-remove-this-component': 'removeThisComponent',
                    'show.bs.tab .cfw-component-fields-nav a.cfw-benchmarks': 'attachBenchmarkFields',
                    'shown.bs.tab .cfw-component-fields-nav a.cfw-custom-component-tab': 'detachBenchmarkFields',
                    'shown.bs.tab .cfw-component-fields-nav a': 'updateSelectButtonHighlight',
                    'blur .cfw-custom-component textarea': 'updateSelectButtonHighlight',
                    'keyup .cfw-custom-component textarea': 'updateSelectButtonHighlight',
                    'paste .cfw-custom-component textarea': 'updateSelectButtonHighlight',
                    'input .cfw-custom-component textarea': 'updateSelectButtonHighlight',
                    'textInput .cfw-custom-component textarea': 'updateSelectButtonHighlight',
                    'blur .cfw-custom-component textarea  ': 'guessComponentLabel',
                    'keyup .cfw-custom-component textarea  ': 'guessComponentLabel',
                    'paste .cfw-custom-component textarea  ': 'guessComponentLabel',
                    'input .cfw-custom-component textarea  ': 'guessComponentLabel',
                    'textInput .cfw-custom-component textarea  ': 'guessComponentLabel',
                    'focus .cfw-custom-component input[type="text"]': 'monitorComponentLabelOwnership',
                    'blur .cfw-custom-component input[type="text"]': 'verifyComponentLabelOwnership'
                },
                // 'show.bs.tab .cfw-custom-component-tab': 'confirmDeselectBenchmark',

                initialize: function(options) {
                    this.options = options || {};
                    // this.model.on('change', this.render, this);
                    // this.model.on('destroy', this.remove, this);

                    // this.model.on('show', this.lookSelected, this);
                    // this.model.on('unshow', this.unlookSelected, this);

                    this.wod_id = options.wod_id;
                    this.component_id = options.component_id;
                    this.componentOverview = options.component_overview;

                    // CFW.allBenchmarks.on('select:c'+this.component_id, this.renderBenchmarkFields, this);
                    // CFW.allBenchmarks.on('deselect:c'+this.component_id, this.destroyBenchmarkFields, this);

                    if (options.el) {
                        this.initializeExistingElement();
                    } else {
                        this.render();
                    }

                    this.updateBreadcrumbs();
                    this.guessComponentLabel($.Event('init'));

                    return this;
                },

                initializeExistingElement: function() {
                    var onBenchmarksReady = _.bind(function() {
                        var selectedBenchmark = CFW.allBenchmarks.get(this.$('.cfw-benchmark-id').val());
                        if (selectedBenchmark) {
                            this.$('.cfw-benchmark-id').remove();

                            // selectedBenchmark.trigger('select:c'+this.component_id, selectedBenchmark);
                            this.$('.cfw-component-fields-nav .cfw-benchmarks').bootstrap_tab('show');
                            this.showDetail($.Event(), selectedBenchmark);

                            var $detailsPane = this.detailView.$el.closest('.cfw-details-pane');
                            (new $.fn.bootstrap_tab.Constructor()).activate($detailsPane, $detailsPane.parent());
                        } else {
                            this.$('.cfw-component-fields-nav .cfw-custom-component-tab').bootstrap_tab('show');
                        }

                        this.updateOverview();
                    }, this);

                    if (CFW.allBenchmarks.length > 0) {
                        onBenchmarksReady();
                    } else {
                        CFW.allBenchmarks.on('fetched', onBenchmarksReady);
                    }
                },

                render: function() {
                    // html
                    this.$el.html(
                        this.template({
                            component_id: this.component_id
                        })
                    );

                    // due to a shared server/client-side template, we render the template within a wrapper that we need to remove
                    this.setElement(this.$el.children());
                    this.$el.unwrap();

                    // If render() was called instead of initializeExistingElement(), then this is a "new" component ->
                    // Change the "remove component" text to say "Cancel"
                    this.$('.cfw-remove-this-component .cfw-text').text('Cancel');
                    this.updateSelectButtonHighlight();

                    return this;
                },

                updateBreadcrumbs: function() {
                    this.$('.cfw-class-name').text(this.componentOverview.$el.closest('li').find('.cfw-edit-wod-title').val());
                    this.$('.cfw-component-index').text(this.componentOverview.$el.prevAll('.cfw-component').length + 1);
                },

                // renderBenchmarkFields: function(model) {
                //     // console.log('adding benchmark fields for component '+this.component_id+', benchmark_id: '+model.id);

                //     if (this.selectedBenchmark) {
                //         this.selectedBenchmark.trigger('deselect:c'+this.component_id);
                //     }
                //     this.selectedBenchmark = model;

                //     this.$('.cfw-benchmark-id').val(model.id);

                //     if (this.lastSelectedBenchmark && model.id == this.lastSelectedBenchmark.id) {
                //         this.$('.cfw-benchmark-repcount').val(this.lastSelectedBenchmark.repcount);
                //         this.$('.cfw-benchmark-repscheme').val(this.lastSelectedBenchmark.repscheme);
                //     }
                //     delete this.lastSelectedBenchmark;
                // },

                selectedBenchmark: function() {
                    return this.detailView && this.$('.cfw-benchmark-component').hasClass('active') && this.detailView.model;
                },

                // destroyBenchmarkFields: function() {
                //     // console.log('destroying benchmark fields for component '+this.component_id);

                //     delete this.selectedBenchmark;

                //     // cache the repcount / repscheme data (if any) so that if the user reselects the same component, they don't lose data
                //     this.lastSelectedBenchmark = {
                //         id: this.$('.cfw-benchmark-id').val(),
                //         repcount: this.$('.cfw-benchmark-repcount').val(),
                //         repscheme: this.$('.cfw-benchmark-repscheme').val()
                //     };

                //     this.$('.cfw-benchmark-id').val('');
                //     this.$('.cfw-benchmark-repcount').val('');
                //     this.$('.cfw-benchmark-repscheme').val('');
                // },

                showDetail: function(event, model) {
                    // var selected = this.hasSelectedBenchmark() && model.id == this.selectedBenchmark.id;
                    this.detailView = new CFW.BenchmarkDetailView({
                        model: model,
                        back_selector: '#'+ this.$el.attr('id') + ' .cfw-browse-pane',
                        component_id: this.component_id,
                        repcount: this.$('.cfw-benchmark-repcount').val(),
                        repscheme: this.$('.cfw-benchmark-repscheme').val()
                    });
                    // selected: selected,
                    this.$('.cfw-benchmark-repcount').remove();
                    this.$('.cfw-benchmark-repscheme').remove();

                    this.$('.cfw-details-pane').empty().append(this.detailView.el);
                    this.detailView.$el.bind('cfwremove', _.bind(this.cleanupDetail, this));

                    this.updateSelectButtonHighlight();
                },

                cleanupDetail: function() {
                    if (this.$('cfw-all-benchmarks').hasClass('active')) {
                        this.$('.search-query').focus();
                    }

                    // if (this.hasSelectedBenchmark() && this.detailView.model.id == this.selectedBenchmark.id) {
                    //     // cache repcount / repscheme fields
                    //     this.$('.cfw-benchmark-repcount').val(this.detailView.repcount());
                    //     this.$('.cfw-benchmark-repscheme').val(this.detailView.repscheme());
                    // }

                    // this.$('.cfw-details-pane').empty();
                    delete this.detailView;

                    this.updateSelectButtonHighlight();
                },

                // confirmDeselectBenchmark: function(event) {
                //     if (this.hasSelectedBenchmark()) {
                //         if(confirm('This will cause the benchmark you chose to be deselected. Continue?')) {
                //             this.selectedBenchmark.trigger('deselect:c'+this.component_id);
                //         } else {
                //             event.preventDefault();
                //         }
                //     }
                // },

                getDescription: function() {
                    var selectedBenchmark = this.selectedBenchmark();
                    if (selectedBenchmark) {
                        if (selectedBenchmark.get('benchmark_group') == 'weightlifting') {
                            var $repscheme = this.$('textarea.cfw-repscheme');
                            if (!$repscheme.length) $repscheme = this.$('.cfw-benchmark-repscheme');
                            var d = $repscheme.val().replace(/^\s+/, '').replace(/\s+$/, '');
                            if (d.length) d = '\r\n' + d;

                            var $repcount = this.$('input.cfw-repcount');
                            if (!$repcount.length) $repcount = this.$('.cfw-benchmark-repcount');
                            d = selectedBenchmark.get('label') +'\r\nFind your '+ $repcount.val() +' rep max.' + d;

                            return d;
                        } else {
                            return selectedBenchmark.get('description');
                        }
                    } else {
                        return this.$('.cfw-custom-component textarea').val();
                    }
                },

                updateOverview: function() {
                    this.componentOverview.description( this.getDescription() );
                },

                swapRemoveComponentText: function() {
                    this.$('.cfw-remove-this-component .cfw-text').html('Remove this Component');
                },

                removeThisComponent: function(event) {
                    var message = 'Are you sure? There is no undo.';
                    if (this.options.el) message += ' This component will be removed from today\'s Whiteboard, but no athlete data will be affected.';
                    if (confirm(message)) {
                        var view = this;
                        this.$('.cfw-remove-this-component').on('shown.bs.tab', function() {
                            var $nav = view.componentOverview.$el;

                            view.componentOverview.remove();
                            view.remove();

                            // update breadcrumbs for remaining components (if any)
                            $nav.closest('.cfw-wods > li').find('.cfw-component a').each(function() {
                                $( $(this).data('target') ).trigger('updatebreadcrumbs');
                            });
                        });
                    } else {
                        event.stopPropagation();
                    }
                },

                attachBenchmarkFields: function() {
                    var $benchmarkFields = this.$('.cfw-benchmark-component');
                    $benchmarkFields.append( $benchmarkFields.data('children') );
                },

                detachBenchmarkFields: function() {
                    var $benchmarkFields = this.$('.cfw-benchmark-component');
                    $benchmarkFields.data('children', $benchmarkFields.children().detach());
                },

                toggleSelectButtonHighlight: function(isHighlighted) {
                    if (!this.$select) this.$select = this.$('.cfw-select-and-continue');
                    this.$select.toggleClass('disabled', !isHighlighted);
                },

                updateSelectButtonHighlight: function() {
                    if (this.$('.cfw-component-fields-nav .active a').hasClass('cfw-benchmarks')) {
                        this.toggleSelectButtonHighlight(!!this.detailView);
                    } else {
                        this.toggleSelectButtonHighlight(!!this.$('.cfw-custom-component textarea').val());
                    }
                },

                guessComponentLabel: function(event) {
                    var $textarea = this.$('.cfw-custom-component textarea');
                    var $labelInput = this.$('.cfw-custom-component input[type="text"]');

                    var guess = '';
                    var matches = $textarea.val().replace(/^\s+/, '').replace(/\s+$/, '').match(/[^\r\n]+/);
                    if (matches) guess = matches[0].replace(/^\s+/, '').replace(/:\s*$/, '');

                    if (!guess) {
                        // Resume guessing component labels if the text was cleared
                        $labelInput.removeClass('owned-by-user');
                    } else if (event.type == 'init' && $labelInput.val() != guess) {
                        $labelInput.addClass('owned-by-user');
                    }

                    $labelInput.not('.owned-by-user').val(guess).change();
                },

                monitorComponentLabelOwnership: function() {
                    var $labelInput = this.$('.cfw-custom-component input[type="text"]');
                    $labelInput.data('focusval', $labelInput.val());
                },

                verifyComponentLabelOwnership: function() {
                    var $labelInput = this.$('.cfw-custom-component input[type="text"]');
                    if ($labelInput.val() != $labelInput.data('focusval')) {
                        $labelInput.addClass('owned-by-user');
                    }
                }
            });


            // Initialize Server-Rendered Views
            $('.cfw-wods .cfw-component').each(function() {
                // initialize component nav view
                var $this = $(this);
                var classId = $this.closest('li').find('.cfw-new-component').data('classid');
                var componentId = $this.find('.cfw-component-id').val();

                var navView = new CFW.ComponentNavView({
                    el: this,
                    wod_id: classId,
                    component_id: componentId
                });

                var fieldsView = new CFW.ComponentFieldsView({
                    el: $($this.find('a').data('target')),
                    wod_id: classId,
                    component_id: componentId,
                    component_overview: navView
                });
            });
            $('.cfw-component-fields').each(function() {
                // initialize component fields view
            });


            // Add a Class Button
            <?php
                $empty_wod = array(
                    "name" => "",
                    "components" => array(),
                    "wp_id" => "#w#"
                );
            ?>
            var class_nav_template = '<?php echo str_replace(array("\r\n", "\n", "\r"), "", cfwhiteboard_generate_class_nav($empty_wod) ); ?>';
            var next_class_id = parseInt('<?php esc_attr_e( $next_wod_id ); ?>', 10);
            var next_component_id = parseInt('<?php esc_attr_e( $next_component_id ); ?>', 10);
            $('.cfw-new-wod').click(function() {
                var classId = next_class_id++;
                var componentId = next_component_id++;

                // new wod nav
                var html = class_nav_template.replace(/#w#/g, classId).replace(/#c#/g, componentId);
                var $new = $(html);
                $(this).closest('li').before($new);
                $new.find('input:first').focus().click();
            });

            // Add a Component Button
            $(document.body).on('click', '.cfw-new-component', function() {
                var componentId = next_component_id++;

                var $this = $(this);

                var navView = new CFW.ComponentNavView({
                    wod_id: $this.data('classid'),
                    component_id: componentId
                });
                $this.closest('.cfw-new-component-row').before(navView.$el);

                var $container = $('.cfw-component-fields-container');
                var fieldsView = new CFW.ComponentFieldsView({
                    wod_id: $this.data('classid'),
                    component_id: componentId,
                    component_overview: navView
                });
                CFW.populateBenchmarkLists(fieldsView.$('.cfw-benchmark-list'));
                $container.append( fieldsView.$el );

                // don't click "edit component" until after the fields are rendered
                navView.$('a').click();
            });

            // Class Options Dropdown
            $('#cfwhiteboard-wods-meta').on('click', '.cfw-class-options .dropdown-toggle', function(event) {
                var $menu = $(this).closest('.cfw-class-options').find('.dropdown-menu').empty();
                var $container = $(this).closest('li');

                var hasComponents = $container.find('.cfw-component').each(function() {
                    var $cmp = $(this);
                    var $menuItem = $('<li><a tabindex="-1" href="javascript://">Delete <span>"'+ $cmp.find('.cfw-description').text().replace(/^\s+/,'').split(/[\r\n]+/)[0] +'"</span></a></li>');
                    $menuItem.find('a').data('componentnav', $cmp);
                    $menu.append($menuItem);
                }).length > 0;

                if (hasComponents) $menu.append('<li class="divider"></li>');

                var $deleteAll = $('<li><a tabindex="-1" href="javascript://">Delete <span>Entire Class</span></a></li>');
                $deleteAll.find('a').data('componentnav', $container);
                $menu.append($deleteAll);
            });
            $(document.body).on('click', '.cfw-class-options .dropdown-menu a', function(event) {
                var $a = $(this);
                if (confirm($a.find('span').text() +' will be removed from the whiteboard. No athlete data will be deleted (if any athletes have already entered scores). Continue?')) {
                    $a.data('componentnav').find('.cfw-edit-component').each(function() {
                        $( $(this).data('target') ).remove();
                    }).end().remove();

                    // update breadcrumbs for remaining components (if any)
                    $a.closest('.cfw-wods > li').find('.cfw-component a').each(function() {
                        $( $(this).data('target') ).trigger('updatebreadcrumbs');
                    });
                }
            });

            // help messages!
            $(document.body).on('click', 'a.help-alert', function(event) {
                event.preventDefault();
                alert($(this).data('message').replace(/<br>/g,'\n').replace(/&apos;/g,"'").replace(/&quot;/g, '"'));
            });


            // Benchmarks Search Field

            // focus into the search field when the benchmarks tab is clicked
            // $('.cfw-component-fields-nav a.cfw-benchmarks').live('shown', function() {
            //     $(this).closest('.cfw-component-fields').find('.search-query').each(function(){ this.focus(); });
            // });
            // switch to hidden "all benchmarks" tab when the user clicks into the search field
            $(document.body).on('focus', '.cfw-component-fields .search-query', function(event) {
                $(this).closest('.cfw-component-fields').find('.cfw-benchmark-nav a.cfw-all').click();
            });
            // capture enter/escape keys
            $(document.body).on('keyup', '.cfw-component-fields .search-query', function(event) {
                if (event.which == 13) { // enter key
                    event.preventDefault();
                    event.stopImmediatePropagation();
                    return false;
                } else if (event.which == 27) { // esc key
                    $(this).val('').change();
                }
            });
            $(document.body).on('keyup change paste input textInput', '.cfw-component-fields .search-query', function(event) {
                var $this = $(this);
                var currentVal = $.trim($this.val());

                // show/hide the "clear search" button
                $this.siblings('.cfw-clear').toggle(!!currentVal);

                // filter the benchmarks list (if the input value has changed)
                if (currentVal != $this.data('val')) {
                    $this.data('val', currentVal);
                    $this.closest('.cfw-component-fields').find('.cfw-benchmark-list.cfw-all-benchmarks').trigger('query', currentVal);
                }
            });
            // clear the search field on click
            $(document.body).on('click', '.cfw-component-fields label.cfw-clear', function(event) {
                $('#' + $(this).attr('for')).val('').change();
            });

            // tooltips
            $('#cfwhiteboard-wods-meta').bootstrap_tooltip({selector:'[rel="tooltip"]'});
        });
    </script>

<?php

}

// function cfwhiteboard_tinymce_settings($settings)
// {
//     // editor.settings.plugins += ',paste';
//     if (empty($settings['plugins'])) {
//         $settings['plugins'] = 'paste,';
//     } else {
//         $settings['plugins'] .= ',paste,';
//     }

//     // editor.settings.paste_auto_cleanup_on_paste = true;
//     $settings['paste_auto_cleanup_on_paste'] = true;

//     // var old_paste_postprocess = editor.settings.paste_postprocess;
//     if (!empty($settings['paste_postprocess'])) {
//         set_transient($CFWHITEBOARD_WODS_META_KEY.'-old_paste_postprocess', $settings['paste_postprocess'], 30);
//     }
//     $settings['paste_postprocess'] = 'CFW.mce_paste_postprocess';

//     return $settings;
// }
function cfwhiteboard_mce_buttons( $buttons ) {
    array_unshift( $buttons, 'cfwhiteboard_button', '|' );
    return $buttons;
}
function cfwhiteboard_mce_external_plugins( $plugins ) {
    global $tinymce_version;

    if (substr($tinymce_version, 0, 1) === '4') {
        // TinyMCE 4.x
        $plugins['cfwhiteboard'] = plugins_url('cfwhiteboard-post-editor/cfw-mce-plugin-4x-140510.js' , __FILE__);
    } else {
        // TinyMCE 3.x
        $plugins['cfwhiteboard'] = plugins_url('cfwhiteboard-post-editor/cfw-mce-plugin-140510.js' , __FILE__);
    }
    return $plugins;
}

/* Save the meta box's post metadata. */
function cfwhiteboard_save_post_meta_boxes($post_id, $post) {
    global $CFWHITEBOARD_WODS_META_KEY;
    global $CFWHITEBOARD_WHITEBOARD_ID_META_KEY;

    /* Get the posted data. */
    // $param_prefix = 'cfwhiteboard-wod-';
    // $param_prefix_len = strlen( $param_prefix );

    /* avoid issues where $post_id parameter is actually a revision ID */
    $post_id = wp_is_post_revision($post);
    if (empty($post_id)) $post_id = $post->ID;

    if (! is_array($_POST)) return $post_id;

    /* Verify the nonce before proceeding. */
    if ( !isset($_POST[$CFWHITEBOARD_WODS_META_KEY]) || !wp_verify_nonce($_POST[$CFWHITEBOARD_WODS_META_KEY], basename(__FILE__)) ) {
        return $post_id;
    }

    /* Get the post type object. */
    $post_type = get_post_type_object( $post->post_type );

    /* Check if the current user has permission to edit the post. */
    if ( !current_user_can('edit_post', $post_id) ) {
        set_transient($CFWHITEBOARD_WODS_META_KEY.'-notice', 'Current user doesn\'t have privileges to edit the Whiteboard data for this post. Please contact us: help@cfwhiteboard.com', 30);
        return $post_id;
    }

    /* ok, all fail-fast mechanisms are in place. let's parse the wod data and save it */

    // ensure the post has a Whiteboard ID
    $whiteboard_id = cfwhiteboard_get_whiteboard_id($post_id, true);
    if (empty($whiteboard_id)) {
        $wods = cfwhiteboard_get_wods($post_id);
        if ((!is_array($wods)) || empty($wods)) {
            // it's new wod data - generate a new whiteboard_id
            update_post_meta($post_id, $CFWHITEBOARD_WHITEBOARD_ID_META_KEY, cfwhiteboard_generate_whiteboard_id($post_id));
        } else {
            // we're updating old wod data - generate a legacy whiteboard_id
            update_post_meta($post_id, $CFWHITEBOARD_WHITEBOARD_ID_META_KEY, cfwhiteboard_generate_legacy_whiteboard_id($post_id));
        }
    }

    $wods_date = $_POST['cfwhiteboard-wods-date'];
    if (empty($wods_date)) {
        $wods_date = '';
    }

    $wods = $_POST['cfw-wods'];
    $components = $_POST['cfw-components'];

    $new_wods = array();
    if (is_array($wods)) {
        foreach ($wods as $wod_id => $wod) {
            $wod['wp_id'] = $wod_id;
            $wod['date'] = $wods_date;

            $new_components = array();
            if (is_array($wod['components']) && is_array($components)) {
                foreach ($wod['components'] as $component_id) {
                    if (is_array($components[$component_id])) {
                        $components[$component_id]['wp_id'] = $component_id;
                        $new_components[] = $components[$component_id];
                    }
                }
            }

            $wod['components'] = $new_components;
            $new_wods[] = $wod;
        }
    }

    // $new_wods = array();
    // foreach ($_POST as $name => $value) {

    //     $name_prefix = substr($name, 0, $param_prefix_len);
    //     if (strcmp($name_prefix, $param_prefix) == 0) {
    //         $name = substr($name, $param_prefix_len);
    //         $name = explode('-', $name);

    //         $wod_id = $name[0];

    //         if (!is_array( $new_wods[$wod_id] )) {
    //             $new_wods[$wod_id] = array(
    //                 'name' => '',
    //                 'components' => array(),
    //                 'wp_id' => $wod_id,
    //                 'date' => $wods_date
    //             );
    //         }

    //         if (strcmp($name[1], 'name') == 0) {
    //             // cfwhiteboard-wod-<wod_id>-name
    //             $new_wods[$wod_id]['name'] = $value;

    //         } elseif (strcmp($name[1], 'cmp') == 0) {
    //             // cfwhiteboard-wod-<wod_id>-cmp-<component_id>-...
    //             $component_id = $name[2];

    //             if (!is_array( $new_wods[$wod_id]['components'][$component_id] )) {
    //                 $new_wods[$wod_id]['components'][$component_id] = array(
    //                     'description' => '',
    //                     'label' => '',
    //                     'wp_id' => $component_id
    //                 );
    //             }

    //             if (strcmp($name[3], 'description') == 0) {
    //                 // cfwhiteboard-wod-<wod_id>-cmp-<component_id>-description
    //                 $new_wods[$wod_id]['components'][$component_id]['description'] = $value;

    //             } elseif (strcmp($name[3], 'label') == 0) {
    //                 // cfwhiteboard-wod-<wod_id>-cmp-<component_id>-label
    //                 $new_wods[$wod_id]['components'][$component_id]['label'] = $value;

    //             }
    //         }
    //     }

    // }

    // Don't delete the users wods! instead just don't render them and tell them what's wrong
    // if (get_post_status($post_id) == "publish") {
    //     $new_wods = cfwhiteboard_clean_post_meta($new_wods);
    // } else {
        // reindex wods and their components
        // $temp_wods = array();
        // foreach ($new_wods as $wod) {

        //     $temp_cmps = array();
        //     foreach ($wod['components'] as $component) {
        //         $temp_cmps[] = $component;
        //     }

        //     $wod['components'] = $temp_cmps;
        //     $temp_wods[] = $wod;
        // }
        // $new_wods = $temp_wods;
    // }

    /* Update or Delete the meta value of the custom field key. */
    // if (! empty($new_wods)) {
        update_post_meta($post_id, $CFWHITEBOARD_WODS_META_KEY, $new_wods);
    // } else {
    //     delete_post_meta($post_id, $CFWHITEBOARD_WODS_META_KEY);
    // }

    set_transient($CFWHITEBOARD_WODS_META_KEY.'-notice', cfwhiteboard_validate_post_meta( $new_wods ), 30);
    // set_transient($CFWHITEBOARD_WODS_META_KEY.'-wods', $new_wods, 30);
}
function cfwhiteboard_clean_post_meta( $wods ) {
    // Clean the meta values (no blank fields)
    // $next_id = 10000;

    if (! is_array($wods)) return $wods;
    $temp_wods = array();

    foreach ($wods as $wod) {

        if (! is_array($wod['components'])) continue;
        $temp_cmps = array();

        foreach ($wod['components'] as $component) {
            if ((empty($component['label']) || empty($component['description'])) && empty($component['benchmark_id'])) continue;
            // if (empty($component['wp_id'])) $component['wp_id'] = $next_id++;
            $temp_cmps[] = $component;
        }
        $wod['components'] = $temp_cmps;

        if (empty($wod['components'])) continue;
        if (empty($wod['name'])) $wod['name'] = 'Untitled Class';
        // if (empty($wod['wp_id'])) $wod['wp_id'] = $next_id++;
        $temp_wods[] = $wod;
    }

    return $temp_wods;
}
function cfwhiteboard_validate_post_meta( $wods ) {
    $validations = array();

    if (! is_array($wods)) return $validations;

    foreach ($wods as $wod) {
        $key = $wod['wp_id'];
        $validations[$key] = array(
            'name' => empty($wod['name']) ? 'Untitled Class' : $wod['name'],
            'validComponents' => 0,
            'totalComponents' => 0
        );

        if (! is_array($wod['components'])) continue;

        foreach ($wod['components'] as $component) {
            $validations[$key]['totalComponents']++;
            if ((empty($component['label']) || empty($component['description'])) && empty($component['benchmark_id'])) continue;
            $validations[$key]['validComponents']++;
        }
    }

    return $validations;
}
function cfwhiteboard_save_post_meta_notices(){
    global $CFWHITEBOARD_WODS_META_KEY;

    $notice = get_transient($CFWHITEBOARD_WODS_META_KEY.'-notice');

    // $wods = get_transient($CFWHITEBOARD_WODS_META_KEY.'-wods');
    // echo '<div class="updated" style="white-space:pre-wrap;"><h2>Wods</h2>';
    // var_dump($wods);
    // echo '</div>';
    // delete_transient($CFWHITEBOARD_WODS_META_KEY.'-wods');

    if (empty($notice)) return;

    if (is_array($notice)) {
        $validation_items = '';
        $counter = 0;
        foreach ($notice as $wod_id => $validation) {
            $counter++;
            $hasName = !empty($validation['name']);
            $name = $hasName ? $validation['name'] : (__('Class', 'cf-whiteboard').' '.$counter);
            $willBePublished = $hasName && ($validation['validComponents'] > 0);
            $totallyValid = $validation['validComponents'] == $validation['totalComponents'];
            $publishedTail = 'will be published ('.($totallyValid ? '' : '<em>').$validation['validComponents'].' of '.$validation['totalComponents'].($totallyValid ? '' : '</em>').' components saved)';
            $notPublishedTail = 'will <em>not be published</em> ('.($hasName ? 'please add at least one component' : 'please enter a name for the class').')';
            $validation_items .= '<li><a href="#cfw-wod-'.$wod_id.'">'.$name.'</a> '.($willBePublished ? $publishedTail : $notPublishedTail ).'</li>';
        }

        echo '<div id="cfwhiteboard-admin-notice" class="updated">
           <p>'.__('CF Whiteboard Status:', 'cf-whiteboard').'</p>
           <ul>'. $validation_items .'</ul>
        </div>';
    } else {
        echo $notice;
    }


    delete_transient($CFWHITEBOARD_WODS_META_KEY.'-notice');
}


function cfwhiteboard_json_meta() {
    global $wpdb;
    global $CFWHITEBOARD_WODS_META_KEY;
    global $CFWHITEBOARD_VERSION;
    global $CFWHITEBOARD_WHITEBOARD_ID_META_KEY;
    $options = cfwhiteboard_get_options();

    $post = null;

    $query_var_post_id = cfwhiteboard_get_query_var('cfwhiteboard_post_id');
    $query_var_whiteboard_id = cfwhiteboard_get_query_var('cfw_whiteboard_id');
    if (!empty($query_var_post_id)) {
        $post = get_post($query_var_post_id);
    } elseif (!empty($query_var_whiteboard_id)) {
        // $args = array(
        //     'posts_per_page' => 1,
        //     'offset' => 0,
        //     'meta_query' => array(
        //         array(
        //             'key' => $CFWHITEBOARD_WHITEBOARD_ID_META_KEY,
        //             'value' => $query_var_whiteboard_id
        //         )
        //     ),
        //     'post_type' => 'any',
        //     'post_status' => 'any',
        //     'suppress_filters' => true
        // );
        // $posts = get_posts($args);
        // $post = $posts[0];

        $wpdbpostmeta = $wpdb->postmeta;
        $querystr = "SELECT * FROM $wpdbpostmeta WHERE $wpdbpostmeta.meta_key = '". $wpdb->escape($CFWHITEBOARD_WHITEBOARD_ID_META_KEY) ."' AND $wpdbpostmeta.meta_value = '". $wpdb->escape($query_var_whiteboard_id) ."'";
        $metas = $wpdb->get_results($querystr, OBJECT);
        $post = get_post($metas[0]->post_id);

        // fallback for legacy post meta that doesn't have a Whiteboard ID post_meta yet
        if (empty($post)) {
            // (legacy whiteboard_id defaults to post_id, so fetch by post_id=whiteboard_id)
            $post = get_post($query_var_whiteboard_id);
        }
    } else {
        return;
    }

    $response = array(
        'whiteboard_id' => cfwhiteboard_get_whiteboard_id($post->ID),
        'post_id' => $post->ID,
        'post_title' => $post->post_title,
        'post_date' => get_the_time('c', $post),
        'post_modified' => $post->post_modified,
        'post_permalink' => get_permalink( $post->ID ),
        'post_type' => $post->post_type,
        'meta' => cfwhiteboard_clean_post_meta( cfwhiteboard_get_wods($post->ID) ),
        'home_url' => home_url(),
        'athletes_page_id' => $options['athletes_page_id'],
        'athletes_url' => get_permalink( $options['athletes_page_id'] ),
        'wp_name' => get_bloginfo('name'),
        'noncrossfit_branding' => $options['noncrossfit_branding'],
        'custom_branding' => empty($options['custom_branding']) ? array() : $options['custom_branding'],
        'wp_version' => get_bloginfo('version'),
        'wp_language' => get_bloginfo('language'),
        'cfw_version' => $CFWHITEBOARD_VERSION
    );

    header('HTTP/1.1 200 OK', true);
    header('Content-Type: application/json; charset=UTF-8', true);
    // echo cfwhiteboard_strip_magic_quotes($response);

    $json_response = json_encode($response);

    if ($json_response[0] = chr(39)) {
       $json_response = str_replace(chr(39),'',$json_response,1)
       echo $json_response;
    } else
    {
       echo $json_response;
    }




    exit;
}
function cfwhiteboard_get_query_var($key) {
    $wp_query_var = get_query_var($key);
    if ($wp_query_var) {
      return $wp_query_var;
    }

    return isset($_REQUEST[$key]) ? $_REQUEST[$key] : null;
}
function cfwhiteboard_strip_magic_quotes($value) {
    if (get_magic_quotes_gpc()) {
        return stripslashes($value);
    } else {
        return $value;
    }
}
if (!function_exists('json_encode'))
{
  function json_encode($a=false)
  {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a))
    {
      if (is_float($a))
      {
        // Always use "." for floats.
        return floatval(str_replace(",", ".", strval($a)));
      }

      if (is_string($a))
      {
        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
      }
      else
        return $a;
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
    {
      if (key($a) !== $i)
      {
        $isList = false;
        break;
      }
    }
    $result = array();
    if ($isList)
    {
      foreach ($a as $v) $result[] = json_encode($v);
      return '[' . join(',', $result) . ']';
    }
    else
    {
      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return '{' . join(',', $result) . '}';
    }
  }
}


add_action('export_wp', 'cfwhiteboard_prepare_for_export');
// This function does 2 things:
// 1 - Fill missing whiteboard IDs in post meta.
// 2 - Replace all instances of \r\n with \n, to prevent data corruption when exporting serialized DB fields to XML.
// http://wordpress.stackexchange.com/questions/42360/with-wordpress-importer-why-cant-i-import-post-meta-containing-a-multi-dimensi
function cfwhiteboard_prepare_for_export() {
    global $CFWHITEBOARD_WODS_META_KEY;
    global $CFWHITEBOARD_WHITEBOARD_ID_META_KEY;

    /* get all posts that have wods meta data */
    $args = array(
        'meta_key' => $CFWHITEBOARD_WODS_META_KEY,
        'posts_per_page' => 9999999
    );
    $posts = get_posts($args);

    if (empty($posts)) return;

    // loop through every post, get the wods meta (if any), loop through every wod,
    // and cache the post ID (unless it's already there - don't overwrite!)
    foreach ($posts as $post) {
        $id = $post->ID;

        $wods = cfwhiteboard_get_wods($id);

        // 1 - Fill missing whiteboard IDs in post meta
        $whiteboard_id = cfwhiteboard_get_whiteboard_id($id, true);
        if (empty($whiteboard_id) && is_array($wods) && !empty($wods)) {
            update_post_meta($id, $CFWHITEBOARD_WHITEBOARD_ID_META_KEY, cfwhiteboard_generate_legacy_whiteboard_id($id));
        }

        // 2 - Replace all instances of \r\n with \n, to prevent data corruption when exporting serialized DB fields to XML.
        // http://wordpress.stackexchange.com/questions/42360/with-wordpress-importer-why-cant-i-import-post-meta-containing-a-multi-dimensi
        if (is_array($wods) && !empty($wods)) {
            $clean_wods = cfwhiteboard_clean_post_meta_linebreaks($wods);
            update_post_meta($id, $CFWHITEBOARD_WODS_META_KEY, $clean_wods);
        }


            // // update the post_modified time to force CFW servers to fetch new wod data
            // $new_post_modified = strtotime(get_the_modified_time('Y-m-d H:i:s')) + 1000;
            // $post_data = array(
            //     'ID' => $id,
            //     'edit_date' => true,
            //     'post_modified' => strftime('%Y-%m-%d %H:%M:%S', $new_post_modified),
            //     'post_modified_gmt' => gmstrftime('%Y-%m-%d %H:%M:%S', $new_post_modified)
            // );
            // wp_update_post($post_data);
    }
}
function cfwhiteboard_clean_post_meta_linebreaks( $wods ) {
    // Clean the meta values (\r\n line breaks replaced with just \n)

    if (! is_array($wods)) return $wods;

    foreach ($wods as &$wod) {
        if (! is_array($wod['components'])) continue;

        foreach ($wod['components'] as &$component) {
            if (!empty($component['label'])) {
                $component['label'] = str_replace("\r\n", "\n", $component['label']);
            }

            if (!empty($component['description'])) {
                $component['description'] = str_replace("\r\n", "\n", $component['description']);
            }
        }
    }

    return $wods;
}




/*************************
/*
/* Athletes Page
/*
/*************************/

add_action('wp', 'cfwhiteboard_init_athletes_page');
function cfwhiteboard_init_athletes_page() {
    $options = cfwhiteboard_get_options();

    // Debugging
    // if (! (is_user_logged_in() && wp_get_current_user()->first_name == "Collin"))
    //     return;

    if (!cfwhiteboard_is_site_enabled())
        return;

    $id = get_the_ID();
    if (post_password_required($id))
        return;

    if (! is_page($options['athletes_page_id']))
        return;

    // Paid Memberships Pro plugin compatibility.
    // They try to override the post content with a "You must register or login
    // to view this content", but then our athletes page rips it out and displays
    // the athletes page anyway. So let's just be nice and check for access here.
    if (function_exists('pmpro_has_membership_access') && !pmpro_has_membership_access())
        return;

    // add_action('wp_print_styles', 'cfwhiteboard_stylesheet', 999999);
    add_action('wp_enqueue_scripts', 'cfwhiteboard_athletes_scripts', 999999);
    add_action('wp_enqueue_scripts', 'cfwhiteboard_athletes_scripts_data', 1000000);
    add_action('wp_head', 'cfwhiteboard_latest_jquery', 1);
    // add_action('template_redirect', 'cfwhiteboard_json_meta');

    // add_filter('post_class', 'cfwhiteboard_trace_post', 999999, 2);
    // add_filter('the_title', 'cfwhiteboard_trace_title', 999999, 2);
    // add_filter('the_excerpt', 'cfwhiteboard_trace_excerpt', 999999, 2);
    add_filter('the_content', 'cfwhiteboard_trace_content', 999999, 2);
    // add_filter('the_category', 'cfwhiteboard_trace_category', 999999, 2);
    // add_filter('the_tags', 'cfwhiteboard_trace_tags', 999999, 2);
}
function cfwhiteboard_is_athletes_page($id) {
    $options = cfwhiteboard_get_options();

    if (empty($id)) $id = get_the_ID();

    // Workaround for bug in WP < 3.3 where title filters are passed the entire post object instead of just the id
    if (isset($id, $id->ID)) {
        $id = $id->ID;
    }

    return $id == $options['athletes_page_id'];
}
function cfwhiteboard_trace_post($post_classes, $id = NULL) {
    if (!cfwhiteboard_is_athletes_page($id))
        return $post_classes;

    $post_classes[] = 'cfw-post-tracer';
    return $post_classes;
}
function cfwhiteboard_trace_title($title, $id = NULL) {
    if (!cfwhiteboard_is_athletes_page($id))
        return $title;

    return '<span class="cfw-title-tracer">' . $title . '</span>';
}
function cfwhiteboard_trace_content($content, $id = NULL) {
    if (!cfwhiteboard_is_athletes_page($id))
        return $content;

    return '<div class="cfw-content-tracer">' . $content . '</div>';
}
function cfwhiteboard_trace_category($category, $id = NULL) {
    if (!cfwhiteboard_is_athletes_page($id))
        return $category;

    return '<span class="cfw-category-tracer">' . $category . '</span>';
}
function cfwhiteboard_trace_tags($tags, $id = NULL) {
    if (!cfwhiteboard_is_athletes_page($id))
        return $tags;

    return '<span class="cfw-tags-tracer">' . $tags . '</span>';
}

function cfwhiteboard_athletes_scripts() {
    global $CFWHITEBOARD_VERSION;
    if (!isset($CFWHITEBOARD_VERSION)) $CFWHITEBOARD_VERSION = '0.0';

    wp_enqueue_script('underscore',
        plugins_url('js/underscore.js', __FILE__),
        false,
        '1.8.3'
    );

    wp_enqueue_script('backbone',
        plugins_url('js/backbone.js', __FILE__),
        array('underscore', 'jquery'),
        '1.3.3'
    );

    wp_enqueue_script('cfwhiteboard-athletes',
        plugins_url('js/all-athletes.js', __FILE__),
        array('underscore', 'jquery', 'backbone'),
        $CFWHITEBOARD_VERSION
    );
}

function cfwhiteboard_athletes_scripts_data() {
    $options = cfwhiteboard_get_options();

    $page_id = $options['athletes_page_id'];
    $page = null;
    if(!empty($page_id)) $page = get_page($page_id);

    $data = array();
    $data['affiliate_id'] = $options['affiliate_id'];
    $data['athletes_page_permalink'] = preg_replace('/\/$/', '', get_permalink($options['athletes_page_id']) ) . '/';
    if (!empty($page)) {
        $data['athletes_page_name'] = $page->post_name;
        $data['athletes_page_title'] = $page->post_title;
    }
    $data['athletes_theme'] = $options['athletes_theme'];

    // global $wp_rewrite;
    // $data['rewrite_rules'] = $wp_rewrite->rules;

    wp_localize_script('cfwhiteboard-athletes', 'CFW_OPTIONS', $data);
}


// from http://codex.wordpress.org/Class_Reference/WP_Rewrite
add_filter('rewrite_rules_array', 'cfwhiteboard_athletes_insert_rewrite_rules', 1999999);
add_filter('query_vars', 'cfwhiteboard_athletes_insert_query_vars');
add_action('wp_loaded', 'cfwhiteboard_athletes_flush_rules');
// flush_rules() if our rules are not yet included
function cfwhiteboard_athletes_flush_rules() {
    if (!cfwhiteboard_is_site_enabled())
        return;

    $options = cfwhiteboard_get_options();
    $page_id = $options['athletes_page_id'];
    $page = null;
    if(!empty($page_id)) $page = get_page($page_id);

    $rules = get_option( 'rewrite_rules' );
    if (!empty($page) && !isset( $rules['('.$page->post_name.')/(.+)/?$'] ) ) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}
// Adding a new rule
function cfwhiteboard_athletes_insert_rewrite_rules($rules) {
    if (!cfwhiteboard_is_site_enabled())
        return $rules;

    $options = cfwhiteboard_get_options();
    $page_id = $options['athletes_page_id'];
    $page = null;
    if(!empty($page_id)) $page = get_page($page_id);

    $newrules = array();

    if (!empty($page)) {
        $newrules['('.$page->post_name.')/(.+)/?$'] = 'index.php?pagename=$matches[1]&cfwathlete=$matches[2]';
    }

    return $newrules + $rules;
}
// Adding the id var so that WP recognizes it
add_filter('query_vars', 'cfwhiteboard_athletes_insert_query_vars');
function cfwhiteboard_athletes_insert_query_vars($vars) {
    if (!cfwhiteboard_is_site_enabled())
        return $vars;

    array_push($vars, 'cfwathlete');
    return $vars;
}




?>
