<?php
/** Tell WordPress to run thinkplace_setup() when the 'after_setup_theme' hook is run. */
//add_action( 'after_setup_theme', 'thinkplace_setup' );
$ThinkPlaceGroupController	= new thinkplace;

class thinkplace
{
	/**
	* @static string $prefix prefix for all fields 
	*/
	public static $prefix = 'thinkplace_';
	
	/**
	* @var array an array of custom fields for "papers" posts
	*/
	private static $custom_papers_fields 	= array(  
    array(  
      "name"          => "presenter",  
      "title"         => "Presenter",  
      "description"   => "",  
      "type"          => "select", 
      "capability"    => "edit_posts"  
    ),  
    array(  
        "name"          => "date",  
        "title"         => "Date",  
        "description"   => "<code>dd/mm/yyyy</code>, used to determine display order.",
        "type"          => "text",  
        "capability"    => "edit_posts"  
    ),  
    array(  
        "name"          => "display_date",  
        "title"         => "Display date",  
        "description"   => "Lets you set a more flexible date for display in pages: 'June, 2011'.",
        "type"          => "text",  
        "capability"    => "edit_posts"  
    ),
    array(  
        "name"          => "conference",  
        "title"         => "Conference/Journal",  
        "description"   => "",  
        "type"          => "text",  
        "capability"    => "edit_posts"  
    ), 
    array(  
        "name"          => "organisation",  
        "title"         => "Organisation",  
        "description"   => "",
        "type"          => "text",  
        "capability"    => "edit_posts"  
    ), 
    array(  
        "name"          => "location",  
        "title"         => "Location",  
        "description"   => "City and country",
        "type"          => "text",  
        "capability"    => "edit_posts"  
    ),
    array(  
        "name"          => "link_to_resource",  
        "title"         => "Link to resource",  
        "description"   => "",
        "type"          => "text",  
        "capability"    => "edit_posts"  
    ),
    array(  
      "name"          => "keywords",  
      "title"         => "Keywords",  
      "description"   => "Keywords don't appear on the page, but Google's really impressed by them.",  
      "type"          => "textarea", 
      "capability"    => "edit_posts",
      "breakBefore"	=> true 
    ),
    array(  
      "name"          => "metadesc",  
      "title"         => "Description",  
      "description"   => "This description doesn't appear on the page either, but if you don't include one Google kills a unicorn.",  
      "type"          => "textarea", 
      "capability"    => "edit_posts"  
    )
  );

	
	/**
	* @var array an array of custom fields for "people" posts
	*/
	private static $custom_people_fields 	= array(  
        array(  
            "name"          => "position",  
            "title"         => "Position",  
            "description"   => "",  
            "type"          => "text",  
            "capability"    => "edit_posts"  
        ),
		array(  
            "name"          => "Overview",  
            "title"         => "Person Overview",  
            "description"   => "Appears before the main content.",  
            "type"          => "textarea", 
            "capability"    => "edit_posts"  
	    ),
	    array(  
  	        "name"          => "author_record",  
  	        "title"         => "Author record",  
  	        "description"   => "",  
  	        "type"          => "select",
            "capability"    => "edit_posts"  
        ),
		  array(  
            "name"          => "image",  
            "title"         => "Image",  
            "description"   => "",  
            "type"          => "attachment", 
            "capability"    => "edit_posts"  
        ),        
    array(  
        "name"          => "order",  
        "title"         => "Order",  
        "description"   => "Order of appearance (ascending).",  
        "type"          => "text",  
        "capability"    => "edit_posts"  
    ),
		array(  
	        "name"          => "keywords",  
	        "title"         => "Keywords",  
	        "description"   => "Keywords don't appear on the page, but Google's really impressed by them.",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts",
			"breakBefore"	=> true 
	    ),
		array(  
	        "name"          => "metadesc",  
	        "title"         => "Description",  
	        "description"   => "This description doesn't appear on the page either, but if you don't include one Google kills a unicorn.",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts"  
	    )
    );

	/**
	* @var array an array of custom fields for "services" posts
*/
	private static $custom_services_fields 	= array(  
		array(  
	        "name"          => "service_type",  
	        "title"         => "Services Type",  
	        "description"   => "",  
	        "type"          => "select",
	 		"values"		=> array(
								'strategy-design' => 'Strategy Design',
								'service-design' => 'Service Design',
								'organisation-design' => 'Organisation Design',
								'design-support' => 'Design Support'
								),
	        "capability"    => "edit_posts"  
	    ),
		array(  
	        "name"          => "Overview",  
	        "title"         => "Service Overview",  
	        "description"   => "",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts"  
	    ),
		array(  
	        "name"          => "byline",  
	        "title"         => "Service Byline",  
	        "description"   => "",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts"  
	    ),
		array(  
            "name"          => "image",  
            "title"         => "Image",  
            "description"   => "",  
            "type"          => "attachment", 
            "capability"    => "edit_posts"  
        ),
		array(  
            "name"          => "reference",  
            "title"         => "Project Reference",  
            "description"   => "",  
            "type"          => "textarea", 
            "capability"    => "edit_posts"  
        ),
		array(  
	        "name"          => "products",  
	        "title"         => "Products",  
	        "description"   => "",  
	        "type"          => "products_list", 
	        "capability"    => "edit_posts"  
	    ),
		array(  
	        "name"          => "keywords",  
	        "title"         => "Keywords",  
	        "description"   => "Keywords don't appear on the page, but Google's really impressed by them.",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts",
			"breakBefore"	=> true 
	    ),
		array(  
	        "name"          => "metadesc",  
	        "title"         => "Description",  
	        "description"   => "This description doesn't appear on the page either, but if you don't include one Google kills a unicorn.",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts"  
	    )
	);

	/**
	* @var array an array of custom fields for "page" posts
	*/
	private static $custom_page_fields 	= array(  
        array(  
            "name"          => "Overview",  
            "title"         => "Page Overview",  
            "description"   => "Appears before the main content.",  
            "type"          => "textarea", 
            "capability"    => "edit_posts"  
        ),
		array(  
	        "name"          => "Nav",  
	        "title"         => "Navigation Description",  
	        "description"   => "For the internal navigation description",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts"  
	    ),
		array(  
            "name"          => "image",  
            "title"         => "Image",  
            "description"   => "",  
            "type"          => "attachment", 
            "capability"    => "edit_posts"  
        ),
		array(  
            "name"          => "image_2",  
            "title"         => "Image 2",  
            "description"   => "",  
            "type"          => "attachment", 
            "capability"    => "edit_posts"  
        ),
        
  	array(  
            "name"          => "image_3",  
            "title"         => "Image 3",  
            "description"   => "",  
            "type"          => "attachment", 
            "capability"    => "edit_posts"  
        ),
		array(  
	        "name"          => "intro",  
	        "title"         => "Page Introduction",  
	        "description"   => "For service pages only - this is the text that appears on the home page Services feature.",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts"  
	    ),
		array(  
	        "name"          => "keywords",  
	        "title"         => "Keywords",  
	        "description"   => "Keywords don't appear on the page, but Google's really impressed by them.",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts",
			"breakBefore"	=> true 
	    ),
		array(  
	        "name"          => "metadesc",  
	        "title"         => "Description",  
	        "description"   => "This description doesn't appear on the page either, but if you don't include one Google kills a unicorn.",  
	        "type"          => "textarea", 
	        "capability"    => "edit_posts"  
	    )
    );
	
	/**
	* PHP4 constructor
	*/
	public function thinkplace(){
		$this->__construct();
	}
	
	/**
	* PHP5 Constructor
	*
	* @uses add_theme_support() To add support for post thumbnails and automatic feed links.
	* @uses register_nav_menus() To add support for navigation menus.
	* @uses add_editor_style() To style the visual editor.
	*/
	public function __construct()
	{
		// This theme styles the visual editor with editor-style.css to match the theme style.
		add_editor_style();

		// Add default posts and comments RSS feed links to head
		add_theme_support( 'automatic-feed-links' );

		// This theme uses wp_nav_menu() in one location.
		register_nav_menus( array(
			'primary' => __( 'Primary Navigation'),
			'secondary' => __( 'Secondary Navigation' ),
		));
		
		
		// Set up the WP settings 
		add_filter( 'wp_title', array(&$this, 'set_wp_title') );
		add_filter( 'wp_page_menu_args', array(&$this, 'set_page_menu_args') );
		add_filter( 'excerpt_length', array(&$this, 'set_excerpt_length') );
		add_filter( 'excerpt_more', array(&$this, 'set_auto_excerpt_more') );
		
		add_filter( 'the_content', array(&$this, 'content_filter' ) );
		
		add_action( 'widgets_init', array(&$this, 'widgetsInit') );
		add_action( 'after_setup_theme', array(&$this, 'additionalImages') );
		add_action('admin_menu', array(&$this, 'pageFieldsInit'));
		add_action( 'init', array(&$this, 'customPostsInit') );
		add_action('init', array(&$this, 'scriptsInit') );
		
		add_action( 'save_post', array( &$this, 'processCustomFields' ), 1, 2 );  
	}

	
	/**
	 * Makes some changes to the <title> tag, by filtering the output of wp_title().
	 *
	 * If we have a site description and we're viewing the home page or a blog posts
	 * page (when using a static front page), then we will add the site description.
	 *
	 * If we're viewing a search result, then we're going to recreate the title entirely.
	 * We're going to add page numbers to all titles as well, to the middle of a search
	 * result title and the end of all other titles.
	 *
	 * The site title also gets added to all titles.
	 *
	 * @since ThinkPlace 1.0
	 *
	 * @param string $title Title generated by wp_title()
	 * @param string $separator The separator passed to wp_title(). ThinkPlace uses a
	 * 	vertical bar, "|", as a separator in header.php.
	 * @return string The new title, ready for the <title> tag.
	 */
	public function set_wp_title( $title, $separator = '|' )
	{
		// Don't affect wp_title() calls in feeds.
		if ( is_feed() )
			return $title;

		// The $paged global variable contains the page number of a listing of posts.
		// The $page global variable contains the page number of a single post that is paged.
		// We'll display whichever one applies, if we're not looking at the first page.
		global $paged, $page;

		if ( is_search() ) {
			// If we're a search, let's start over:
			$title = sprintf( __( 'Search results for %s', 'thinkplace' ), '"' . get_search_query() . '"' );
			// Add a page number if we're on page 2 or more:
			if ( $paged >= 2 )
				$title .= " $separator " . sprintf( __( 'Page %s', 'thinkplace' ), $paged );
			// Add the site name to the end:
			$title .= " $separator " . get_bloginfo( 'name', 'display' );
			// We're done. Let's send the new title back to wp_title():
			return $title;
		}

		// Otherwise, let's start by adding the site name to the end:
		$title .= get_bloginfo( 'name', 'display' );

		// If we have a site description and we're on the home/front page, add the description:
		$site_description = get_bloginfo( 'description', 'display' );
		if ( $site_description && ( is_home() || is_front_page() ) )
			$title .= " $separator " . $site_description;

		// Add a page number if necessary:
		if ( $paged >= 2 || $page >= 2 )
			$title .= " $separator " . sprintf( __( 'Page %s', 'thinkplace' ), max( $paged, $page ) );

		// Return the new title to wp_title():
		return $title;
	}

	/**
	 * Get our wp_nav_menu() fallback, wp_page_menu(), to show a home link.
	 *
	 * To override this in a child theme, remove the filter and optionally add
	 * your own function tied to the wp_page_menu_args filter hook.
	 *
	 * @since ThinkPlace 1.0
	 */
	public function set_page_menu_args( $args )
	{
		//$args['show_home'] = true;
		return $args;
	}
	
	public function getAuthors()
	{
  	global $post, $wpdb;
	  $authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users ORDER BY display_name");
	  $output = array();
	  foreach ($authors as $author) {
	    $output[$author->ID] = $author->user_nicename;
	  }
    return $output;
	}


	/**
	* Custom filters for our content
	*
	* Replaces things like [PRODUCT_MATRIX] with the product matrix
	* @since ThinkPlace 1.1
	* @return string the adjusted content
	*/
	public function content_filter($content)
	{
		if (strstr($content, '[PRODUCT_MATRIX]')){
			//$content	= str_replace('[PRODUCT_MATRIX]', $this->displayProductMatrix(), $content);
			$content = $this->displayProductMatrix(); // To get rid of those fucking p tags that wordpress feels it has to wrap everything in.
		}
		
		if (strstr($content, '[SERVICE_OVERVIEW]')){
			$content	= str_replace('[SERVICE_OVERVIEW]', $this->displayServicesOverview(), $content);
		}
		
		
		return $content;
	}
	
	/**
	 * Register Javascript includes.
	 *
	 * We're doing things this way so if plugins also require JS, we don't end up including the scripts multiple times
	 *
	 * @since ThinkPlace 1.0
	 * @uses wp_enqueue_script, wp_register_script
	 */
	public function scriptsInit()
	{
		wp_enqueue_script('jquery');
		wp_register_script('thinkplace',get_bloginfo('template_directory').'/js/thinkplace.js');
		wp_enqueue_script('thinkplace',get_bloginfo('template_directory').'/js/thinkplace.js',array('jquery'),'0.1',true);
	}
	
	/**
	 * Register widgetized areas, including two sidebars and three widget-ready columns in the footer.
	 *
	 * To override widgetsInit() in a child theme, remove the action hook and add your own
	 * function tied to the init hook.
	 *
	 * @since ThinkPlace 1.0
	 * @uses register_sidebar
	 */
	public function widgetsInit()
	{
		register_sidebar( array(
			'name' => __( 'Primary Widget Area', 'thinkplace' ),
			'id' => 'first-widget-area',
			'description' => __( 'The primary widget area', 'thinkplace' ),
			'before_widget' => '<div class="widget-container %2$s">',
			'after_widget' => '</div>',
			'before_title' => '<h3 class="widget-title">',
			'after_title' => '</h3>',
		) );
	}
	
	/**
	 * Add additional image sizes
	 *
	 * @since ThinkPlace 1.0
	 * @uses register_sidebar
	 */
	public function additionalImages()
	{
  	add_image_size('services-thumb', 220,160, true);
	}
	
	/**
	 * Register custom post types.
	 *
	 * To override customPostsInit() in a child theme, remove the action hook and add your own
	 * function tied to the init hook.
	 *
	 * @since ThinkPlace 1.0
	 * @uses register_post_type
	 */
	public function customPostsInit()
	{
		register_post_type('people', array(
				'labels'				=> array(
					'name'					=> __('People'),
					'singular_label'		=> __('Person'),
					'add_new_item'			=> __('Add a Person'),
					'edit_item'				=> __('Edit Person'),
					'view_item'				=> __('View Person'),
					'search_items'			=> __('Search People'),
					'not_found'				=> __('No people found'),
					'not_found_in_trash'	=> __('No people found in Trash')
				),
				'description'			=> "A collection of ThinkPlace's key employees.",
				'public'				=> true,
				'show_ui'				=> true,
				'capability_type'		=> 'post',
				'heirarchical'			=> false,
				'rewrite'				=> false,
				'query_var'				=> false,
				'supports'				=> array('title','custom-fields','editor'),
				'register_meta_box_cb'	=> array(&$this,'customFieldsInit')
			));
			
			
 		register_post_type('papers', array(
				'labels'				=> array(
					'name'					=> __('Papers'),
					'singular_label'		=> __('Paper'),
					'add_new_item'			=> __('Add a Paper'),
					'edit_item'				=> __('Edit Paper'),
					'view_item'				=> __('View Paper'),
					'search_items'			=> __('Search Papers'),
					'not_found'				=> __('No papers found'),
					'not_found_in_trash'	=> __('No papers found in Trash')
				),
				'description'			=> "Papers and Presentations",
				'public'				=> true,
				'show_ui'				=> true,
				'capability_type'		=> 'post',
				'heirarchical'			=> false,
				'rewrite'				=> false,
				'query_var'				=> false,
				'supports'				=> array('title','custom-fields','editor'),
				'register_meta_box_cb'	=> array(&$this,'customFieldsInit')
			));
			
			register_post_type('products', array(
					'labels'				=> array(
						'name'					=> __('Products'),
						'singular_label'		=> __('Product'),
						'add_new_item'			=> __('Add a Product'),
						'edit_item'				=> __('Edit Product'),
						'view_item'				=> __('View Product'),
						'search_items'			=> __('Search Products'),
						'not_found'				=> __('No products found'),
						'not_found_in_trash'	=> __('No products found in Trash')
					),
					'description'			=> "A collection of ThinkPlace's products.",
					'public'				=> true,
					'show_ui'				=> true,
					'capability_type'		=> 'post',
					'heirarchical'			=> false,
					'rewrite'				=> false,
					'query_var'				=> false,
					'supports'				=> array('title','custom-fields','editor'),
					'register_meta_box_cb'	=> array(&$this,'customFieldsInit')
				));
		
			register_post_type('services', array(
					'labels'				=> array(
						'name'					=> __('Services'),
						'singular_label'		=> __('Service'),
						'add_new_item'			=> __('Add a Service'),
						'edit_item'				=> __('Edit Service'),
						'view_item'				=> __('View Service'),
						'search_items'			=> __('Search Services'),
						'not_found'				=> __('No services found'),
						'not_found_in_trash'	=> __('No services found in Trash')
					),
					'description'			=> "A collection of ThinkPlace's services.",
					'public'				=> true,
					'show_ui'				=> true,
					'capability_type'		=> 'post',
					'hierarchical'			=> false,
					'rewrite'				=> false,
					'query_var'				=> false,
					'supports'				=> array('title','custom-fields','editor'),
					'register_meta_box_cb'	=> array(&$this,'customFieldsInit')
				));
	}
	
	public function pageFieldsInit()
	{
		add_meta_box( self::$prefix.'custom_fields', 'Page Extras', array( &$this, 'displayCustomFields' ), 'page', 'normal', 'high' );  
		remove_meta_box( 'postcustom', 'page', 'normal' );
	}
	
	public function customFieldsInit($post)
	{
		if (! property_exists('thinkplace', 'custom_'.$post->post_type.'_fields')){
			return false;
		}
		
		add_meta_box( self::$prefix.'custom_fields', ucwords($post->post_type).' Information', array( &$this, 'displayCustomFields' ), $post->post_type, 'normal', 'high' );  
		remove_meta_box( 'postcustom', $post->post_type, 'normal' ); 
	}

	public function displayCustomFields($post)
	{
		$fieldVarName	= 'custom_'.$post->post_type.'_fields';
		
		if (! property_exists('thinkplace', $fieldVarName ))
			return false;
		
		$customFields	= self::$$fieldVarName;
		
		?>  
	    <div class="form-wrap">  
	        <?php  
	        wp_nonce_field( self::$prefix.'custom_fields', self::$prefix.'custom_fields_wpnonce', false, true );  
	        foreach ( $customFields as $customField ) {  

	            // Check capability  
	            if ( !current_user_can( $customField['capability'], $post->ID ) )  
	                continue;

	             ?>  
	                <div class="form-field form-required">  
	                    <?php 
	 					$fieldValue	= get_post_meta( $post->ID, self::$prefix . $customField[ 'name' ], true );
	                    switch ( $customField[ 'type' ] ) {  
	                        case "products_list": {  
	                            // Product List
	  							$products	= self::getProductsList();
								echo "<h4>Products Included</h4>";
								foreach ($products as $a=>$product){
	                            	echo '<label for="' . self::$prefix . $customField[ 'name' ] . $a .'" style="display:inline;">&nbsp;&nbsp;';  
		                            echo '<input type="checkbox" name="' . self::$prefix . $customField['name'] . '[]" id="' . self::$prefix . $customField['name'] . $a .'" value="'.$product->ID.'"';  
		                            if ( is_array($fieldValue) && in_array($product->ID, $fieldValue) )  
		                                echo ' checked="checked"';  
		                            echo '" style="width: auto;" /> <b>' . $product->post_title . '</b></label>'; 
								}
	                            break;  
	                        }
							case "checkbox": {  
	                            // Checkbox  
	                            echo '<label for="' . self::$prefix . $customField[ 'name' ] .'" style="display:inline;"><b>' . $customField[ 'title' ] . '</b></label>&nbsp;&nbsp;';  
	                            echo '<input type="checkbox" name="' . self::$prefix . $customField['name'] . '" id="' . self::$prefix . $customField['name'] . '" value="yes"';  
	                            if ( $fieldValue == "yes" )  
	                                echo ' checked="checked"';  
	                            echo '" style="width: auto;" />';  
	                            break;  
	                        }  
	                        case "textarea": { 
	                            // Text area 
	                            echo '<label for="' . self::$prefix . $customField[ 'name' ] .'"><b>' . $customField[ 'title' ] . '</b></label>';  
	                            echo '<textarea name="' . self::$prefix . $customField[ 'name' ] . '" id="' . self::$prefix . $customField[ 'name' ] . '" columns="30" rows="3">' . htmlspecialchars( $fieldValue ) . '</textarea>';  
	                            break;  
	                        }  
	                        case "select": {
                              // Max: Hack
                              if($customField['name'] == 'author_record') {
                                $customField['values'] = self::getAuthors();
                              } else if ($customField['name'] == 'presenter') {
                                $customField['values'] = self::getPeopleSelectList();
                              }
	                            // Select field  
	                            echo '<label for="' . self::$prefix . $customField[ 'name' ] .'"><b>' . $customField[ 'title' ] . '</b></label>';  
	                            echo '<select name="' . self::$prefix . $customField[ 'name' ] . '" id="' . self::$prefix . $customField[ 'name' ] . '">';  
	                            foreach ($customField['values'] as $value=>$valueDisplay){
									echo '<option value="'.$value.'"'.(($value == $fieldValue) ? ' selected="selected"' : '').'>'.__($valueDisplay).'</option>';
								}
								echo '</select>';
								break;  
	                        }
							case "attachment": {  
								$attachments		= get_posts(
													array(
														'numberposts'	=> -1,
														'post_type' 	=> 'attachment',
														'order'			=> 'ASC',
														'orderby'		=> 'title'
														)
													);
								
	                            // Select field  
	                            echo '<label for="' . self::$prefix . $customField[ 'name' ] .'"><b>' . $customField[ 'title' ] . '</b></label>';  
	                            echo '<select name="' . self::$prefix . $customField[ 'name' ] . '" id="' . self::$prefix . $customField[ 'name' ] . '">'; 
	 							echo '<option value="">None</option>';
	                            foreach ($attachments as $attachment){
									echo '<option value="'.$attachment->ID.'"'.(($attachment->ID == $fieldValue) ? ' selected="selected"' : '').'>'.__($attachment->post_title).'</option>';
								}
								echo '</select>';
								break;  
	                        }
							default: {  
	                            // Plain text field  
	                            echo '<label for="' . self::$prefix . $customField[ 'name' ] .'"><b>' . $customField[ 'title' ] . '</b></label>';  
	                            echo '<input type="text" name="' . self::$prefix . $customField[ 'name' ] . '" id="' . self::$prefix . $customField[ 'name' ] . '" value="' . htmlspecialchars( $fieldValue ) . '" />';  
	                            break;  
	                        }  
	                    }  
	                    ?>  
	                    <?php if ( $customField[ 'description' ] ) echo '<p>' . $customField[ 'description' ] . '</p>'; ?>  
	                </div>  
	            <?php  
	        } ?>  
	    </div>  
	    <?php
	}

	public function processCustomFields($post_id, $post)
	{
		$fieldVarName	= 'custom_'.$post->post_type.'_fields';
		
		if (! property_exists('thinkplace', $fieldVarName ))
			return false;
		if ( !wp_verify_nonce( $_POST[ self::$prefix.'custom_fields_wpnonce' ], self::$prefix.'custom_fields' ) )  
	        return false;  
	    if ( !current_user_can( 'edit_post', $post_id ) )  
	        return false;  
		
		$customFields	= self::$$fieldVarName;
		
	    foreach ( $customFields as $customField ) {  
	        if ( current_user_can( $customField['capability'], $post_id ) ) {  
	            if ( isset( $_POST[ self::$prefix . $customField['name'] ] ) ) {  
	                $fieldVal	= $_POST[ self::$prefix . $customField['name'] ]; 
					if (! is_array($fieldVal)){
						$fieldVal	= trim($fieldVal);
					}
					
					update_post_meta( $post_id, self::$prefix . $customField[ 'name' ], $fieldVal );  
	            } else {  
	                delete_post_meta( $post_id, self::$prefix . $customField[ 'name' ] );  
	            }  
	        }  
	    }
	}

	public function displayPostedOn()
	{
		printf( __( '%1$s', 'thinkplace' ),
			sprintf( '<h4 title="%1$s" class="entry-date">%2$s</h4>',
				esc_attr( get_the_time() ),
				get_the_date()
			)
		);
	}

	public function displayPostedIn()
	{
		// Retrieves tag list of current post, separated by commas.
		$tag_list = get_the_tag_list( '', ', ' );
		if ( $tag_list ) {
			$posted_in = __( 'This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'thinkplace' );
		} elseif ( is_object_in_taxonomy( get_post_type(), 'category' ) ) {
			$posted_in = __( 'This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'thinkplace' );
		} else {
			$posted_in = __( 'Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'thinkplace' );
		}
		// Prints the string, replacing the placeholders.
		printf(
			$posted_in,
			get_the_category_list( ', ' ),
			$tag_list,
			get_permalink(),
			the_title_attribute( 'echo=0' )
		);
	}

	public function getPeopleList()
	{
		$people		= get_posts(
							array(
								'numberposts'	=> -1,
								'post_type' 	=> 'people'
								)
							);
		
		$newPeople	= array();
		foreach ($people as $person){
		  $person->metadata = get_post_custom( $person->ID  );
			$newPeople[ $person->ID ]	= $person;
		}
    uasort($newPeople, array('self', 'sortPeopleOrder'));
    // print_r($newPeople);
		return $newPeople;
	}
	
	public function getPeopleSelectList()
	{
		$people		= get_posts(
							array(
								'numberposts'	=> -1,
								'post_type' 	=> 'people'
								)
							);
		
		$newPeople	= array();
		foreach ($people as $person){
		  $person->metadata = get_post_custom( $person->ID  );
			$newPeople[ $person->ID ] = $person->post_title;
		}
    uasort($newPeople, array('self', 'sortPeopleOrder'));
    // print_r($newPeople);
		return $newPeople;
	}
	
	public function getPeopleAuthors()
	{
		$people		= get_posts(
							array(
								'numberposts'	=> -1,
								'post_type' 	=> 'people'
								)
							);
		
		$newPeople	= array();
		foreach ($people as $person){
		  $person->metadata = get_post_custom( $person->ID  );
			$newPeople[ $person->metadata['thinkplace_author_record'][0] ] = $person->ID;
		}
		return $newPeople;
	}
	
	function sortPeopleOrder($a, $b) {
	  $a = $a->metadata['thinkplace_order'][0];
	  $b = $b->metadata['thinkplace_order'][0];
	  if (!isset($a) && !isset($b)) {
	    return 0;
    } else if (!isset($a)) {
      return 1;
    } else if (!isset($b)) {
      return -1;
    } 
	  if ($a == $b) {
      return 0;
    }
    return ($a < $b) ? -1 : 1;
	}
	
	public function getProductsList($productIds = array())
	{
		$args		= array(
						'numberposts'	=> -1,
						'post_type' 	=> 'products'
						);
		if (! empty($productIds)){
			$args['include']	= implode(',',$productIds);
		}
		$products		= get_posts($args);
		
		$newProducts	= array();
		foreach ($products as $product){
			$newProducts[ $product->ID ]	= $product;
		}
		return $newProducts;
	}
	
	public function getServiceTypes()
	{
		foreach (self::$custom_services_fields as $custom_field){
			if ($custom_field['name'] == 'service_type'){
				return $custom_field['values'];
			}
		}
		return false;
	}
	
	public function getServicesList($serviceType = '')
	{
		$services		= get_posts(
							array(
								'numberposts'	=> -1,
								'post_type' 	=> 'services'
								)
							);
		
		$newServices	= array();
		foreach ($services as $service){
			if (! empty($serviceType)){
				$metadata	= get_post_custom( $service->ID  );
				if ($serviceType != $metadata[thinkplace::$prefix.'service_type'][0]){
					continue;
				}
			}
			$newServices[ $service->ID ]	= $service;
		}
		return $newServices;
	}
	
	public function displayServicesOverview()
	{
		$servicesPage	= get_page_by_title('services');
		
		$services		= get_posts(
							array(
								'numberposts'	=> -1,
								'post_type' 	=> 'page',
								'orderby'		=> 'menu_order',
								'post_parent'	=> $servicesPage->ID
								)
							);

		foreach ($services as $a=>$service){
			$serviceMetadata	= get_post_custom($service->ID);
			$serviceChildren	= thinkplace::getServicesList($service->post_name);

			echo '<div class="service '.$service->post_name.'">';
			echo '<a href="'.htmlentities(get_page_link($service->ID)).'">'.$service->post_title.'';
			if ((isset($serviceMetadata[thinkplace::$prefix.'intro'])) && (! empty($serviceMetadata[thinkplace::$prefix.'intro'][0]) )){
					echo '<span>'.$serviceMetadata[thinkplace::$prefix.'intro'][0].'</span></a>';
			}
			echo '</div>';
		}
	}
	
	public function displayProductMatrix()
	{
		$serviceTypes	= $this->getServiceTypes();
		$productMatrix	= $this->getProductMatrix();
		
		$html = '<table class="matrix">';
		
		// header row
		$html .= '<thead><tr><th></th>';
		foreach ($serviceTypes as $val=>$name){
			$pageObj	= get_page_by_title($name);
			$html .= '<th class="'.$val.'"><a href="'.htmlentities(get_page_link($pageObj->ID)).'">'.$name.'</a></th>';
		}
		$html .= '</tr></thead><tbody>';
		
		foreach ($productMatrix as $product){
			$html .= '<tr><th>'.$product['productObj']->post_title.'</th>';
			
			foreach ($serviceTypes as $val=>$name){
				$selected	= in_array($val, $product['serviceTypes']);
				$html .= '<td class="'.$val.($selected ? ' selected' : '').'"><span>'.($selected ? '*' : '').'</span></td>';
			}
			$html .= '</tr>';
		}
		
		$html .= '</tbody></table>';
		
		return $html;
	}
	
	private function getProductMatrix()
	{
		$services		= $this->getServicesList();
		$products		= $this->getProductsList();
		
		$productMatrix	= array();
		foreach ($products as $a => $product){
			$productMatrix[ $product->ID ]	= array(
													'productObj'	=> $product,
													'serviceTypes'	=> array()
												);
		}
		
		foreach ($services as $service){
			$metadata			= get_post_custom( $service->ID  );
			$serviceProducts	= unserialize($metadata[thinkplace::$prefix.'products'][0]);
			
			foreach ($productMatrix as $productId => $product){
				if (in_array($metadata[thinkplace::$prefix.'service_type'][0], $productMatrix[ $productId ]['serviceTypes'])){
					continue;
				}
				
				if ( (is_array($serviceProducts))&&(in_array($productId, $serviceProducts)) ){
					$productMatrix[ $productId ]['serviceTypes'][]	= $metadata[thinkplace::$prefix.'service_type'][0];
				}
			}
		}
		
		return $productMatrix;
	}
	
}

function is_subpage( $iID = null )
{
	global $post, $wpdb;

	if ( is_page() && isset( $post->post_parent ) != 0 ) 
	{		
		$aParent = $wpdb->get_row( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE ID = %d AND post_type = 'page' LIMIT 1", $post->post_parent ) );
		
		if ( is_int( $iID ) > 0 ) 
			if ( $aParent->ID == $iID ) return true; else return false;
		else
			if ( $aParent->ID )	return true; else return false;
		
	} 
	else 
	{
		return false;
	}
}

?>