<?php

/**********************
*
* hosek SETUP Functions 
*
***********************/

// Load Page Functions
	include( 'functions-pages.php' );

/* Frontend Scripts */
function hosek_scripts() {
	wp_enqueue_script('selectivizr-js',get_stylesheet_directory_uri().'/scripts/selectivizr.js',array( 'jquery' ));
	wp_enqueue_script('custom-js',get_stylesheet_directory_uri().'/scripts/custom.js',array( 'jquery' ));
	wp_enqueue_script('match-height-js',get_stylesheet_directory_uri().'/scripts/jquery.matchHeight.js',array( 'jquery' ));
	wp_enqueue_script('cycle2',get_stylesheet_directory_uri().'/scripts/jquery.cycle2.min.js',array( 'jquery' ));
	wp_enqueue_script('cycle2-swipe',get_stylesheet_directory_uri().'/scripts/jquery.cycle2.swipe.min.js',array( 'jquery', 'cycle2' ));
	wp_enqueue_script('hover-intent-js',get_stylesheet_directory_uri().'/scripts/hoverIntent.js',array( 'jquery' ));
	wp_enqueue_script('fancybox-js',get_stylesheet_directory_uri().'/scripts/fancyapps-fancyBox-18d1712/source/jquery.fancybox.js',array( 'jquery' ));
	
	if (is_singular() && get_option('thread_comments')) wp_enqueue_script( 'comment-reply' );
 
}
add_action('wp_enqueue_scripts', 'hosek_scripts');

/* Admin Scripts */
function hosek_extra_featured_image_enqueue() {
	wp_enqueue_media();
	
	// Add support for unlimited custom image fields in wp-admin
	wp_register_script( 'meta-box-image', get_stylesheet_directory_uri().'/scripts/meta-box-image.js', array( 'jquery' ) );
	wp_enqueue_script( 'meta-box-image' );
}
add_action( 'admin_enqueue_scripts', 'hosek_extra_featured_image_enqueue' );

/* Frontend CSS */
function hosek_enqueue_style() {
	wp_enqueue_style( 'hosek-base-style', get_template_directory_uri().'/css/base.css' );
    wp_enqueue_style( 'hosek-main-style', get_stylesheet_uri() ); 
	wp_enqueue_style( 'font-awesome-style', get_template_directory_uri().'/css/font-awesome/css/font-awesome.min.css' );
	wp_enqueue_style( 'fancybox-style', get_template_directory_uri().'/scripts/fancyapps-fancyBox-18d1712/source/jquery.fancybox.css' );
	
}
add_action( 'wp_enqueue_scripts', 'hosek_enqueue_style' );
 
/* Admin CSS */
function hosek_enqueue_admin_style() {
    wp_enqueue_style( 'hosek-admin-style', get_template_directory_uri() . '/css/admin.css' ); 
}
add_action( 'admin_enqueue_scripts', 'hosek_enqueue_admin_style' );
 
/* Load css into the login page */
function hosek_enqueue_login_style() {
    wp_enqueue_style( 'hosek-login-style', get_template_directory_uri() . '/css/login.css' ); 
}
add_action( 'login_enqueue_scripts', 'hosek_enqueue_login_style' );

/* Style login screen 
function hosek_login_bg() { 
	if ( 0 == (date('j') % 2) ) { ?>
		<style type="text/css">
            body.login { background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/login2.jpg) !important; }
        </style>
	<?php } else { ?>
		<style type="text/css">
            body.login { background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/login1.jpg) !important; }
        </style>	
	<?php }
}
add_action( 'login_enqueue_scripts', 'hosek_login_bg' );*/

/* Register Menus */
function hosek_register_menus() {
  register_nav_menus(
    array(
      'primary' 	=> __( 'Primary Navigation' ),
	  'footer' 	=> __( 'Footer Menu' ),
    )
  );
}
add_action( 'init', 'hosek_register_menus' );

/* Register Sidebar */
if ( function_exists('register_sidebar') ) {
	
    register_sidebar(array(
		'id'			=> 'sidebar-1',
		'name'			=>'Sidebar',
        'before_widget' => '<div class="widget">',
        'after_widget' 	=> '</div>',
        'before_title' 	=> '<h4>',
        'after_title' 	=> '</h4>',
    ));
}

/* Register custom image sizes */
function hosek_setup_thumbnails() {
   add_theme_support( 'post-thumbnails' );
}
add_action( 'after_setup_theme', 'hosek_setup_thumbnails');


/********************************
*
* hosek SETUP Functions EXTENDED
*
*********************************/

/* Add RSS Feed in head */
add_theme_support('automatic-feed-links');

function hosek_sitetitle() {
	global $page, $paged;
	
	wp_title('|', true, 'right');
	bloginfo('name');
	$site_description = get_bloginfo('description', 'display');
	if ($site_description && (is_home() || is_front_page())) echo " | $site_description";
	if ($paged >= 2 || $page >= 2) echo ' | '.sprintf(__('Page %s', 'npu'), max($paged, $page));
}

function hosek_getoption($option) {
	global $options;
	foreach ($options as $value) { 
		if(isset($value['id']) && $value['id'] == $option) {
			return (get_option( $value['id']) === FALSE) ? $value['std'] : get_option($value['id']);
		}
	}
}

// Template for comments and pingbacks.
function hosek_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case '' :
	?>
	<article <?php comment_class(); ?> id="comment-<?php comment_ID() ?>">
			<?php echo get_avatar( $comment, 40 ); ?>
			<?php printf( __( '%s says:', 'hosek' ), sprintf( '%s', get_comment_author_link() ) ); ?>
		<?php if ( $comment->comment_approved == '0' ) : ?>
			<?php _e( 'Your comment is awaiting moderation.', 'hosek' ); ?>
			<br />
		<?php endif; ?>

		<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
			<?php
				/* translators: 1: date, 2: time */
				printf( __( '%1$s at %2$s', 'hosek' ), get_comment_date(),  get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)', 'hosek' ), ' ' );
			?>

		<?php comment_text(); ?>

			<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>

	<?php
			break;
		case 'pingback'  :
		case 'trackback' :
	?>
	<article <?php comment_class(); ?> id="comment-<?php comment_ID() ?>">
		<p><?php _e( 'Pingback:', 'hosek' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __('(Edit)', 'hosek'), ' ' ); ?></p>
	<?php
			break;
	endswitch;
}

// Closes comments and pingbacks with </article> instead of </li>.
function hosek_comment_close() {
	echo '</article>';
}

// Adjusts the comment_form() input types for HTML5.
function hosek_fields($fields) {
	$commenter = wp_get_current_commenter();
	$req = get_option( 'require_name_email' );
	$aria_req = ( $req ? " aria-required='true'" : '' );
	$fields =  array(
		'author' => '<p><label for="author">' . __( 'First Name' ) . ( $req ? '*' : '' ) . '</label> ' .
		'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',
		'email'  => '<p><label for="email">' . __( 'Email' ) . ( $req ? '*' : '' ) . '</label> ' .
		'<input id="email" name="email" type="email" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></p>',
		'url'    => '<p><label for="url">' . __( 'Website' ) . '</label>' .
		'<input id="url" name="url" type="url" value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></p>',
	);
	return $fields;
}
add_filter('comment_form_default_fields','hosek_fields');

function hosek_remove_comment_form_allowed_tags( $defaults ) {
	$defaults['comment_notes_after'] = '';
	return $defaults;
}
add_filter( 'comment_form_defaults', 'hosek_remove_comment_form_allowed_tags' );

// Get archive for post date
function hosek_postdate_link() {

	/* Get the year, month, and day of the current post. */
	$year = get_the_time( 'Y' );
	$month = get_the_time( 'm' );
	$day = get_the_time( 'd' );
	$out = '';

	/* Add a link to the monthly archive. */
	$out .= '<a href="' . get_month_link( $year, $month ) . '" title="Archive for ' . esc_attr( get_the_time( 'F Y' ) ) . '">' . get_the_time( 'F' ) . '</a>';

	/* Add a link to the daily archive. */
	$out .= ' <a href="' . get_day_link( $year, $month, $day ) . '" title="Archive for ' . esc_attr( get_the_time( 'F d, Y' ) ) . '">' . $day . '</a>';

	/* Add a link to the yearly archive. */
	$out .= ', <a href="' . get_year_link( $year ) . '" title="Archive for ' . esc_attr( $year ) . '">' . $year . '</a>';

	return $out;
}

// Theme Options Page (!!$shortname = theme dir!!)
$themename = "hosek";
$shortname = "hosek";
$options = array (

	array(  "type" => "open"),
	
	array(  "name" => "Appointment paragraph",
			"desc" => "This code will be added next to the scheudule appointment button",
			"id" => $shortname."_appointment_paragraph",
			"std" => "",
			"type" => "textarea"),
	
	array(  "name" => "Appointment button",
			"desc" => "This code will be added into to the scheudule appointment button",
			"id" => $shortname."_appointment_button",
			"std" => "",
			"type" => "text"),
			
	array(  "name" => "Appointment button url",
			"desc" => "This code will be added into to the scheudule appointment button url",
			"id" => $shortname."_appointment_button_url",
			"std" => "",
			"type" => "text"),
	
	array(	"name" => "Tracking Code",
			"desc" => "This code will be added to the footer before the &lt;/body&gt; closing tag (for Google Analytics and other JS scripts).",
			"id" => $shortname."_tracking_code",
			"std" => "",
			"type" => "textarea"),
					
	array( "type" => "close")
 
);

// Add / Update / Reset Options page
function hosek_add_admin() {
	global $themename, $shortname, $options;
	
	if (isset($_GET['page']) && $_GET['page'] == $shortname.'_options') {
	  if(isset($_REQUEST['action'])) {
		if ($_REQUEST['action'] == 'save') {
			foreach ($options as $value) {
		      if(!in_array($value['type'], array('open','close'))) {
				if($value['type'] == 'file') {	    
					$override = array('test_form' => false);     
					$file = wp_handle_upload( $_FILES[$value['id']], $override ); 
				    update_option( $value['id'], $file['url'] );
				} else {
					if( isset( $_REQUEST[ $value['id'] ] ) ) {
						update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
					} else {
						delete_option( $value['id'] );
					} 
				}
			  }
			}
			// Redirect 
			wp_safe_redirect("admin.php?page=".$shortname."_options&saved=true");exit;
		} else if( 'reset' == $_REQUEST['action'] ) {
			foreach ($options as $value) {
			delete_option( $value['id'] ); }
			// Redirect
			wp_safe_redirect("admin.php?page=".$shortname."_options&reset=true");exit;
		}
	  }
	}
	// Add Options page to the menu
	if(count($options) > 2)	add_menu_page($themename." Options", "".$themename." Options", 'manage_options', $shortname.'_options', 'hosek_admin', '/wp-content/themes/'.$shortname.'/images/favicon.png', '81');
}

// Generate Options page fields
function hosek_admin() {
	global $themename, $shortname, $options;
	
	if(isset($_REQUEST['saved'])) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
	if(isset($_REQUEST['reset'])) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>';
	
	$options_page = '';
		
	foreach ($options as $value) {
		switch ( $value['type'] ) {
			
			case "open":
				  
				  $options_page .= '<div class="wrap">
						<div id="icon-options-general" class="icon32"><br /></div>
						<h2>'.$themename.' Options</h2>
						<form method="post" enctype="multipart/form-data">
						<table width="100%" border="0" style="padding:10px;">';
				  break;
			
			case "close":
			
				  $options_page .= '</table>
							<p class="submit">
								<input name="save" class="button-primary" type="submit" value="Save changes" />
								<input type="hidden" name="action" value="save" />
							</p>
						</form>
						<form method="post">
							<p class="submit">
								<input name="reset" class="button-secondary" type="submit" value="Reset" />
								<input type="hidden" name="action" value="reset" />
						</p>
						</form>';
				  break;

			case 'text':
				  
				  $val = (get_option($value['id']) != "") ? get_option($value['id']) : $value['std'];
				  $options_page .= '<tr>
				  			<td width="30%" rowspan="2" valign="middle">'.$value['name'].'</td>
							<td width="70%"><input style="width:500px; max-width: 100%;" name="'.$value['id'].'" id="'.$value['id'].'" type="'.$value['type'].'" value="'.$val.'" /></td>
						</tr>
						<tr><td><span style="color: #666;">'.$value['desc'].'</span></td>
						</tr>
						<tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dashed #aaa;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>';
				  break;
			
			case 'hidden':
				  
				  $options_page .= '<input name="'.$value['id'].'" id="'.$value['id'].'" type="'.$value['type'].'" value="'.$value['std'].'" />';
				  break;

			case 'textarea':
				  
				  $val = (get_option($value['id']) != "") ? htmlentities(get_option( $value['id'] )) :  htmlentities($value['std']);
				  $options_page .= '<tr>
							<td width="30%" rowspan="2" valign="middle">'.$value['name'].'</td>
							<td width="70%"><textarea name="'.$value['id'].'" style="width:500px; height:200px; max-width: 100%;" type="'.$value['type'].'" cols="" rows="">'.$val.'</textarea></td>
						</tr>
						<tr><td><span style="color: #666;">'.$value['desc'].'</span></td></tr>
						<tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dashed #aaa;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>';
				  break;

		case 'select':
		
				  $options_page .= '<tr>
							<td width="30%" rowspan="2" valign="middle"><strong>'.$value['name'].'</strong></td>
							<td width="70%"><select style="width: 500px; max-width: 100%;" name="'.$value['id'].'" id="'.$value['id'].'">';
							foreach ($value['options'] as $option) { 
							  $checked = (get_option($value['id']) == $option || $option == $value['std']) ? ' selected="selected"' : '';
							  $options_page .= '<option'.$checked.'>'.$option.'</option>';
							}
				  $options_page .= '</select></td>
						</tr>
						<tr><td><small>'.$value['desc'].'</small></td></tr>
						<tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #aaa;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>';
				  break;
		
		case "checkbox":
			 	  
				  $checked = (get_option($value['id'])) ? ' checked="checked"' : '';
				  $options_page .= '<tr>
							<td width="30%" rowspan="2" valign="middle">'.$value['name'].'</td>
							<td width="70%"><input type="checkbox" name="'.$value['id'].'" id="'.$value['id'].'" value="true" '.$checked.' />
								<span style="color: #666;">'.$value['desc'].'</span>
							</td>
						</tr>
						<tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dashed #aaa;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>';
				  break;
			  
		case "file":
		
				if(get_option( $value['id'] ) == "") {
				  $val = (get_option($value['id']) != "") ? get_option($value['id']) : $value['std'];
				  $options_page .= '<tr>
							<td width="30%" rowspan="2" valign="middle">'.$value['name'].'</td>
							<td width="70%"><input style="width: 500px; max-width: 100%;" name="'.$value['id'].'" id="'.$value['id'].'" type="'.$value['type'].'" value="'.$val.'" /></td>
						</tr>
						<tr><td><span style="color: #666;">'.$value['desc'].'</span></td></tr>';
				}
	
				if(get_option( $value['id'] ) != "") {
				  $options_page .= '<tr>
							<td width="30%" rowspan="2" valign="top">'.$value['name'].'</td>
							<td width="70%" >
								<div id="add_new_'.$value['id'].'"><a onclick="add_new_'.$value['id'].'(); return false;">Click for New File</a></div>
								<script type="text/javascript">
								  function add_new_'.$value['id'].'() { 
									jQuery(\'#add_new_'.$value['id'].' a\').hide();
									jQuery(\'<input style="width: 500px; max-width: 100%;" name="'.$value['id'].'" id="'.$value['id'].'" type="'.$value['type'].'" value="" />\').appendTo(jQuery(\'#add_new_'.$value['id'].'\'));
								  }
								</script>
							</td>
						</tr>
						<tr><td><span style="color: #666;">To remove file just click the "New File" button and save the page.</span></td></tr>';
				}
				  
				  $display = (get_option($value['id']) == "") ? ' style="display: none"' : '';
				  $options_page .= '<tr'.$display.'>
							<td width="30%" valign="top">Existing File</td>
							<td width="70%"><a target="_blank" href="'.get_option($value['id']).'"><img src="'.bloginfo('template_directory').'/images/uploadedfile.png" alt="Uploaded File" width="30" height="30" /></a></td>
						</tr>
						<tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dashed #aaa;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>';
				  break;
				  
		case 'editor':
			    
				$textarea_args = array("textarea_rows" => 5, "textarea_name" => $value['id']);
				
				ob_start();
				$val = (get_option($value['id']) != "") ? htmlentities(get_option($value['id'])) : htmlentities($value['std']);
				wp_editor($val, $value['id'], $textarea_args);
				$textarea_output = ob_get_clean();
				
			    $options_page .= '<tr>
							<td width="30%" rowspan="2" valign="middle">'.$value['name'].'</td>
							<td width="70%">'.$textarea_output.'</td>
						</tr>
						<tr><td><span style="color: #666;">'.$value['desc'].'</span></td></tr>
						<tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dashed #aaa;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>';
				break;
		}
	}
	
	echo $options_page;
}
add_action('admin_menu', 'hosek_add_admin');


/**********************
*
* hosek OUTPUT Functions 
*
***********************/


/* Echo 'checked' */
function hosek_echo_checked($data1 = '', $data2 = '') {
	if ( is_array($data2) ) {
		if ( in_array($data1, $data2) ) {
			echo 'checked="checked"';
		}
	} else {
		if ( $data1 == $data2 ) {
			echo 'checked="checked"';
		}
	}
}

/* Echo 'selected' */
function hosek_echo_selected($data1 = '', $data2 = '') {
	if ( is_array($data2) ) {
		if ( in_array($data1, $data2) ) {
			echo 'selected="selected"';
		}
	} else {
		if ( $data1 == $data2 ) {
			echo 'selected="selected"';
		}
	}
}

/* Use image ID or URL to get specified image size */
function hosek_get_attachment_image( $image_id = '', $image_url = '', $image_size = 'full', $class = '' ) { 
	if ( '' != $class ) {
		$attr = array( 'class' => $class );
	} else {
		$attr = array();
	}
	
	if ( '' != $image_id ) {
		echo wp_get_attachment_image( $image_id, $image_size, '', $attr );
	} elseif ( '' != $image_url ) { 
		$image_id = hosek_get_image_id( $image_url );
		echo wp_get_attachment_image( $image_id, $image_size, '', $attr );
	}
}

/* Retrieves the image ID from the file URL */
function hosek_get_image_id($image_url) {
	global $wpdb;
	$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
	if ( $attachment ) {
        return $attachment[0]; 
	} else {
	// Image is resized, need an extra effort to get it's ID
		global $wpdb;
		$attachment_id = false;
	 
		// If there is no url, return.
		if ( '' == $image_url )
			return;
	 
		// Get the upload directory paths
		$upload_dir_paths = wp_upload_dir();
	 
		// Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
		if ( false !== strpos( $image_url, $upload_dir_paths['baseurl'] ) ) {
	 
			// If this is the URL of an auto-generated thumbnail, get the URL of the original image
			$attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $image_url ); 
	 
			// Remove the upload path base directory from the attachment URL
			$attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );
	 
			// Finally, run a custom database query to get the attachment ID from the modified attachment URL
			$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url ) );
		}
		
	 	if ( $attachment_id ) {
			return $attachment_id;
		} else {
		// Image was modified in wp media editor
			$image_url = preg_replace ( '/-e([0-9]+)/', '', $image_url ); 
			$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
			return $attachment[0];	
		}
	}
}


?>