<?php
/*
* San Kloud Theme Functions
*
* There's lots of stuff here, all the functions defined within
* the San_Kran class which is fired during after_setup_theme
* action. If you need to access the $sankloud object outside
* the class declare it as global.
*
* @package wordpress
* @subpackage San Kloud
* @version 1.0.3
*
*/
// Set the content width, for videos and photos for defaults
if ( ! isset( $content_width ) )
	$content_width = 540;
	
/**
 *
 * San Kloud
 *
 * This is our base class which defines all the theme options, settings,
 * bahoviour, sidebars, etc. The class is initialized into a global
 * $sankloud object upon after_setup_theme (see bottom of class).
 *
 */

class San_Kloud{
	var $options = array();
	var $defaults = array();
	
	/*
	 * Constructor
	 *
	 * Fired at Wordpress after_setup_theme (see add_action at the end
	 * of the class), registers the theme capabilities, navigation menus,
	 * as well as the set of actions and filters used by San Kloud.
	 *
	 * $this->options is used to store all the theme options, while
	 * $this->defaults holds their default values.
	 *
	 */
	 
	 function __construct() {
		// Load San Kloud text domain
		load_theme_textdomain('sankloud', TEMPLATEPATH. '/languages');
		
		// Default options, lower-level ones are added during first run
		
		$this->defaults = array(
			'color-scheme' => 'default',
			'custom-css' => ''
		);
		
		// Theme supports
		add_theme_support( 'automatic-feed-links' );
		add_theme_support( 'post-formats', array( 'aside', 'link', 'gallery', 'status', 'quote', 'image', 'chat', 'video', 'audio' ) );
		
		// Editor style for TinyMCE.
		add_editor_style();
		
		// Load options (calls get_option())
		$this->load_options();
		
		// Load up our theme options page and related code.
		require( dirname( __FILE__ ) . '/inc/themefm-dashboard.php' );
		
		// Register our primary navigation (top left) ans 404 page links
		if ( function_exists( 'register_nav_menu' ) ) {
			add_theme_support( 'nav_menus' );
			register_nav_menu( 'primary', __( 'Primary Navigation Menu', 'sankloud') );
		}
		
		/*
		 * Actions
		 *
		 * Registers sidebars for widgets, registers admin settings, fires
		 * a firstrun during admin init, registers a theme deactivation hook,
		 * adds the menu options, fires a welcome notice, footer text in template,
		 * color scheme preview scripts (sidebar), custom css.
		 *
		 */
		add_action( 'widgets_init', array( &$this, 'register_sidebars' ) );
		add_action( 'admin_init', array( &$this, 'register_admin_settings' ) );
		add_action( 'admin_init', array( &$this, 'firstrun' ) );
		add_action( 'switch_theme', array( &$this, 'deactivate' ) );
		add_action( 'admin_menu', array( &$this, 'add_admin_options' ) );
		add_action( 'admin_notices', array( &$this, 'welcome_notice' ) );
		add_action( 'wp_enqueue_scripts', array( &$this, 'color_scheme_scripts' ) );
		add_action( 'wp_print_styles', array( &$this, 'custom_css' ) );
		
		/*
		 * Filters
		 *
		 * Removes unnecessery CSS from WordPress galleries, defines exerpt length
		 *
		 */
		add_filter( 'gallery_style', array( &$this, 'remove_gallery_css' ) );
		add_filter( 'excerpt_length', array( &$this, 'excerpt_length' ) );
	}
	
	
	/*
	 * Excerpt Length
	 * 
	 * Increase the excerpt length for better archives visuals.
	 *
	 */
	function excerpt_length( $length ) {
		if ( ! is_search() )
			return 80;
			
		return $length;
	}
	
	/*	 
	 * Custom CSS Output
	 *
	 * Checks the custom CSS theme option and outputs the stylesheets inside
	 * a <style> tag in the header. Function is run during wp_print_styles.
	 *
	 */
	function custom_css() {
		if ( isset( $this->options['custom-css'] ) && strlen( $this->options['custom-css'] ) )
			echo "<style>\n" . $this->options['custom-css'] . "\n</style>\n";
	}
	
	/*
	 * Load Options
	 *
	 * Fired during theme setup, loads all the options into $options
	 * array accessible from all other functions.
	 *
	 */
	function load_options(){
		$this->options = (array) get_option( 'sankloud-options' );
		$this->options = array_merge( $this->defaults, $this->options );
	}
	
	/*
	 * Save Options
	 *
	 * Calls the update_option and saves the current $options
	 * array. Call this after modifying the values of $this->options.
	 *
	 */
	function update_options() {
		return update_option( 'sankloud-options', $this->options );
	}
	
	/*
	 * Theme Deactivation
	 *
	 * Remove all the options after theme deactivation. This includes
	 * footer nore, color scheme and all the rest, let's be nice
	 * and keep the database clean, even if the users didn't like our theme.
	 *
	 */
	function deactivate() {
		delete_option( 'sankloud-options' );
	}
	
	/*
	 * First Run
	 *
	 * This method is fired on every call, which is why it checks the 
	 * $options array to see if the theme was activated to make sure this
	 * runs only once. Populates the $options array with defaults and a few
	 * mandatory options.
	 *
	 */
	function firstrun() {
		if( ! isset( $this->options['activated'] ) || ! $this->options['activated'] ) {
			$this->options = $this->defaults;
			
			// Mandatory options during first run
			$this->options['options-visited'] = false;
			$this->options['activated'] = true;
			
			// Update the options.
			$this->update_options();
		}
	}
	
	/*
	 * Register Sidebars
	 *
	 * Registers a single right sidebar ready for widgets.
	 *
	 */
	function register_sidebars() {
		register_sidebar( array(
			'name'          => 'RightSidebar',
			'id'            => 'right-sidebar',
			'description'   => 'Main sidebar that will be displayed on every page',
			'before_widget' => '<div class="widget">',
			'after_widget' => '</div>',
			'before_title' => '<p class="heading">',
			'after_title' => '</p>',
		) );
	}
	
	/*
	 * Valid Color Schemes
	 *
	 * This function returns an array of available color schemes, where
	 * an array key is the value used in the database and the HTML layout,
	 * and value is used for captions. The function is used for theme settins
	 * page as well as options validation. Default is blue.
	 *
	 */
	function get_valid_color_schemes() {
		$color_schemes = array(
			'default' => array(
				'name' => __( 'Default', 'sankloud' ),
				'preview' => get_template_directory_uri() . '/colors/default/preview.png'
			),
			'orange' => array(
				'name' => __( 'Orange', 'sankloud' ),
				'preview' => get_template_directory_uri() . '/colors/orange/preview.png'
			),
			'green' => array(
				'name' => __( 'Green', 'sankloud' ),
				'preview' => get_template_directory_uri() . '/colors/green/preview.png'
			)
		);
		
		return apply_filters( 'sankloud_color_schemes', $color_schemes );
	}
	
	/*
	 * Color Schemes Head
	 *
	 * Enqueue any scripts or style necessary to display the chosen color
	 * scheme. This is passed through an action too for child themes.
	 *
	 */
	function color_scheme_scripts() {
		if ( isset( $this->options['color-scheme'] ) ) { 
			if ( $this->options['color-scheme'] == 'default' ) {
				wp_enqueue_style( 'sankloud-default', get_template_directory_uri() . '/colors/default/default.css', array(), null );
			} elseif ( $this->options['color-scheme'] == 'orange' ) {
				wp_enqueue_style( 'sankloud-orange', get_template_directory_uri() . '/colors/orange/orange.css', array(), null );
			} elseif ( $this->options['color-scheme'] == 'green' ) {
				wp_enqueue_style( 'sankloud-green', get_template_directory_uri() . '/colors/green/green.css', array(), null );
			}
	
			do_action( 'sankloud_enqueue_color_scheme', $this->options['color-scheme'] );
		} else {
			wp_enqueue_style( 'sankloud-default', get_template_directory_uri() . '/colors/default/default.css', array(), null );
		}
	}
	
	/*
	 * Gallery CSS Fix
	 *
	 * WordPress adds a style block when rendering the gallery. Since our
	 * gallery is styled in our stylesheet, and since W3C does not
	 * permit style that are not within the head tag, we get rig of
	 * them via a simple preg_replace.
	 *
	 */
	function remove_gallery_css($css) {
		return preg_replace( "#<style type='text/css'>(.*?)</style>#s", '', $css );
	}
	
	/*
	 * Register Settings
	 *
	 * Fired during admin_init, this function registers the settings used
	 * in the Theme options section, as well as attaches a validator to
	 * clean up the icoming data.
	 *
	 */
	function register_admin_settings() {
		register_setting( 'sankloud-options', 'sankloud-options', array( &$this, 'validate_options' ) );
		
		// Settings fields and sections
		add_settings_section( 'section_general', __( 'General Settings', 'sankloud' ), array( &$this, 'section_general' ), 'sankloud-options' );
		add_settings_field( 'color-scheme', __( 'Color Scheme', 'sankloud' ), array( &$this, 'setting_color_scheme' ), 'sankloud-options', 'section_general' );
		add_settings_field( 'custom-css', __( 'Custom CSS', 'sankloud' ), array( &$this, 'setting_custom_css' ), 'sankloud-options', 'section_general' );
	}
	
	/*
	 * Options Validation
	 *
	 * This function is used to validate the incoming options, mostly from
	 * the Theme Options admin page. We make sure that the 'activated' array
	 * is untouched and then verify the rest of the options.
	 *
	 */
	function validate_options($options) {
		// Mandatory.
		$options['activated'] = true;
	
		// Theme options.
		$options['color-scheme'] = array_key_exists( $options['color-scheme'], $this->get_valid_color_schemes() ) ? $options['color-scheme'] : 'default';
		$options['footer-note'] = trim( strip_tags( $options['footer-note'], '<a><b><strong><em><ol><li><div><span>' ) );
		$options['custom-css'] = trim( strip_tags( $options['custom-css'] ) );
		
		return $options;
	}
	
	/*
	 * Add Menu Options
	 *
	 * Registers a Theme Options page that appears under the Appearance
	 * menu in the WordPress dashboard. Uses the theme_options to render
	 * the page contents, requires edit_theme_options capabilities.
	 *
	 */
	function add_admin_options() {
		add_theme_page( __( 'Theme Options', 'sankloud' ), __('Theme Options', 'sankloud' ), 'edit_theme_options', 'sankloud-settings', array( &$this, 'theme_options' ) );
	}
	
	/*
	 * Comment walker
	 *
	 * This is used in the comments template, does the comments rendering.
	 * Taken from Twenty Ten and localized. Nothing much here.
	 *
	 */
	
	function comment_walker($comment, $args, $depth) {
		$GLOBALS['comment'] = $comment;
		switch ($comment->comment_type):
			case'':
		?>
		<li <?php comment_class(); ?>>
			<div class="comment-wrapper" id="comment-<?php comment_ID(); ?>">
				<div class="comment-body">
					<p class="comment-author-name">
						<?php echo get_comment_author_link(); ?>
					</p>
					
					<p class="comment-author-meta">
						<a href="<?php echo esc_url(get_comment_link($comment->comment_ID)); ?>">
						<?php
							/* translators: 1: date, 2:time*/
							printf(__('%1$s at %2$s', 'sankloud'), get_comment_date(), get_comment_time()); ?></a><?php edit_comment_link(__('(Edit)', 'sankloud'), ' ');
						?>
					</p>
					
					<?php if($comment->comment_approved == '0'): ?>
						<em><?php _e('Your comment is awaiting moderation.', 'sankloud'); ?></em>
					<?php endif; ?>
					<div class="comment-body-text"><?php comment_text(); ?></div>
					<div class="reply">
						<?php comment_reply_link(array_merge($args, array('depth' => $depth, 'max_depth' => $args['max_depth']))); ?>
					</div><!-- .reply -->
					<br class="clear" />
				</div>
				<div class="reply-wrapper">
					&nbsp;
				</div>
				<br class="clear" />
			</div><!-- #comment-## -->
		<!--</li>-->
		
		<?php
				break;
			case 'pingback':
			case 'trackback':
		?>
		<li class="post pingpack">
			<p><?php _e('Pingback:', 'sankloud'); ?> <?php comment_author_link(); ?> <?php edit_comment_link(__('(Edit)', 'sankloud'), ' '); ?></p>
		</li>
		<?php
				break;
		endswitch;
	}
	
	/*
	 * Theme Options
	 *
	 * This is the function that renders the Theme Options page under
	 * the Appearence menu in the admin section. Upon visiting this the
	 * first time we make sure that a state (options-visited) is saved
	 * to our options array.
	 *
	 * The rest is handled by Settings API and some HTML magic.
	 *
	 */
	function theme_options() {
	
		if ( ! isset( $this->options['options-visited'] ) || ! $this->options['options-visited'] ) {
			$this->options['options-visited'] = true;
			$this->update_options();
		}
?>
<div class="wrap">
	<div id="icon-themes" class="icon32"><br></div>
	<h2><?php _e( 'San Kloud Options', 'sankloud' ); ?></h2>
	
	<form method="post" action="options.php">
		<?php wp_nonce_field( 'update-options' ); ?>
		<?php settings_fields( 'sankloud-options' ); ?>
		<?php do_settings_sections( 'sankloud-options' ); ?>
		<p class="submit">
			<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes', 'sankloud'); ?>" />
		</p >
	</form>
</div>
<?php
	}
	
	/*
	 * Welcome Notice
	 *
	 * This notice is displayed to new users that have just activated the
	 * San Kloud theme. It displays a message on top saying that we've
	 * got options with a link to the Theme Options page. As soon as that page
	 * has been visited at least once, the message no longer bothers the visitor.
	 *
	 */
	function welcome_notice() {
		if( ! isset( $_REQUEST['page'] ) || $_REQUEST['page'] !== 'sankloud-settings' )
			if ( ! isset( $this->options['options-visited']) || ! $this->options['options-visited'] )
				echo "<div class='update-nag'>" . __("Welcome to <strong>San Fran</strong>. Thank you so much for using this theme. Now head over to the <a href='themes.php?page=sankloud-settings'>Theme Options</a> and have some fun!</div>");
	}
		
	/*
	 * Settings: General Section
	 *
	 * Used via the Settings API to output the description of the
	 * general settings under Theme Options in Appearance.
	 *
	 */
	function section_general() {
		_e( 'These settings affect the general look of your theme.', 'sankloud' );
	}
	
	/*
	 * Settings: Color Scheme
	 *
	 * Outputs a select box with available color schemes for the Theme
	 * Options page, as well as sets the selected color scheme as defined
	 * in $options.
	 *
	 */
	function setting_color_scheme() {
	?>
		<?php
			$color_schemes = $this->get_valid_color_schemes();
			foreach ( $color_schemes as $value => $scheme ):
		?>
		<div class="sc-color-scheme-item" style="float: left; margin-right: 14px; margin-bottom: 18px;">
			<input <?php checked( $value == $this->options['color-scheme'] ); ?> type="radio" name="sankloud-options[color-scheme]" id="sankloud-color-scheme-<?php echo $value; ?>" value="<?php echo $value; ?>" />
			<label for="sankloud-color-scheme-<?php echo $value; ?>" style="margin-top: 4px; float: left; clear: both;">
				<img src="<?php echo $scheme['preview']; ?>" /><br />
				<span class="description" style="margin-top: 8px; float: left;"><?php echo $scheme['name']; ?></span>
			</label>
		</div>
		<?php
			endforeach;
		?>
		<br class="clear" />
		<span class="description"><?php _e( 'Browse to your home page to see the new color scheme in action.', 'sankloud' ); ?></span>	
		<?php
	}
	
	/*
	 * Settings: Custom CSS
	 *
	 * Outputs a textarea for the custom CSS in Theme Options. The value
	 * is output during wp_head() if it exists.
	 *
	 */
	 function setting_custom_css() {
	 ?>
		<textarea rows="5" class="large-text code" name="sankloud-options[custom-css]"><?php echo esc_textarea( $this->options['custom-css'] ); ?></textarea><br />
		<span class="description"><?php _e( 'Custom stylesheets are included in the head section after all the theme stylesheets are loaded.', 'sankloud' ); ?></span>
	<?php
	}
};

function create_sankloud_object () {
	global $sankloud;
	$sankloud = new San_Kloud();
}
// Initialize the above class after theme setup
add_action( 'after_setup_theme', 'create_sankloud_object' );