<?php

// Enqueue scripts for back-end use
function mts_enqueue_backend_scripts() {

	$screen = get_current_screen();
	$screen_id = $screen->id;

	if ( 'profile' == $screen_id ) {
		// Register our .js that triggers a custom media upload box to show up when we are uploading our author profile image
		wp_register_script( 'author-upload', get_template_directory_uri() . '/js/author-page-background.js', true );
		wp_enqueue_script( 'author-upload' );
	}
}
add_action('admin_enqueue_scripts', 'mts_enqueue_backend_scripts');


function mts_author_image_init() {

	global $pagenow;

	if ( 'media-upload.php' == $pagenow || 'async-upload.php' == $pagenow ) {

		add_filter( 'gettext', 'mts_replace_thickbox_button_text', 1, 3 ); // here we call our func to replace the button text for the avatar uploader
	}
}	
// Initialize the options
add_action('admin_init', 'mts_author_image_init');

// Here we grab the css for the elements in our admin page
function mts_plugin_styles() {

	wp_register_style( 'mts_author_image', get_template_directory_uri() . '/css/author-page-background.css', 'style' );
	wp_enqueue_style( 'mts_author_image' );
}
add_action('wp_enqueue_scripts', 'mts_plugin_styles');

// First, we'll add a special filter to change the text of the image uploader text when we're uploading an avatar	
function mts_replace_thickbox_button_text($translated_text, $text, $domain) {

	if ('Insert into Post' == $text) {

		$referer = strpos( wp_get_referer(), 'profile' );

		if ( $referer != '' ) {

			return __('Make this my author page background Image!', 'mythemeshop' );
		}
	}

	return $translated_text;
}


// Second, we'll have to manually push the new new profile field onto the profile page (as of 16-June-2013, user-edit.php (Core WP page) manually places the profile fields, and doesn't use do_settings_section(
function mts_add_custom_profile_fields( $user ) {

	// Display image uploader button
	$avatar = get_the_author_meta( 'author_profile_picture2', $user->ID );
	?>

		<h3><?php _e('Author Page Background Image','mythemeshop'); ?></h3>

		<input type="hidden" id="author_profile_picture2_url" name="author_profile_picture2_url" value="<?php echo esc_url( $avatar ); ?>" />

		<table class="form-table">

			<tr>

				<th><label for="author_profile_picture2_button"><span class="description"><?php _e('Upload a picture to use as the author page background image.', 'mythemeshop' ); ?></span></label></th>

				<?php $buttontext = ""; if('' != $avatar) { $buttontext = __("Change Background Image","mythemeshop");  } else { $buttontext = __("Upload new background Image","mythemeshop"); }?>

				<td>

					<input id="author_profile_picture2_button" type="button" class="button" value="<?php echo $buttontext; ?>" />

					<?php if('' != $avatar){?><input id="author_profile_picture2_remove" type="button" class="button" value="<?php _e("Delete Background Image","mythemeshop"); ?>" /><?php }?>

				</td>

			</tr>

			<tr>

				<th><label for="author_profile_picture2_preview"><span class="description"><?php _e('Preview:', 'mythemeshop' ); ?></span></label></th>

				<td>

					<?php if ( '' != $avatar ){ ?>

					<div id="author_profile_picture2_preview" style="min-height: 100px;">

						<img style="max-width:100%;border:2px solid #CCC" src="<?php echo esc_url( $avatar ); ?>" />

					</div>					

					<span class="description"><?php _e('You can update the picture from above.','mythemeshop'); ?></span>

				<?php } else { ?>

					<div id="author_profile_picture2_preview" style="height: 100px; width:100px; line-height:100px; border:2px solid #CCC; text-align:center; font-size:5em;">?</div>					

					<span class="description"><?php _e('This profile does not yet have an author page background image. Click the button above to upload one (or select one from your media gallery).','mythemeshop'); ?></span>

				<?php } ?>

					<span id="upload_success" style="color: #FF0000; font-weight: bold; display:block;"></span>

				</td>

			</tr>

		</table>

	<?php
}

// Third, we'll create this callback function to be called when the profile field is saved. 
function mts_save_custom_profile_fields( $user_id ) {

	if ( !current_user_can( 'edit_user', $user_id ) )
		return false;  

    update_user_meta( $user_id, 'author_profile_picture2', $_POST['author_profile_picture2_url'] );
}

// Add our functions to profile display and update hooks
add_action( 'show_user_profile', 'mts_add_custom_profile_fields' );
add_action( 'edit_user_profile', 'mts_add_custom_profile_fields' );
add_action( 'personal_options_update', 'mts_save_custom_profile_fields' );
add_action( 'edit_user_profile_update', 'mts_save_custom_profile_fields' );

// Now, let's create an easy function to grab our author image
function author_image_circle($user_id=999999, $_size="small") {

	if($user_id==999999){

		$avatar = get_the_author_meta('author_profile_picture2', get_the_ID());

	} else {

		$avatar = get_the_author_meta('author_profile_picture2', $user_id);
	}

	$size = ( ($_size == "small" || $_size == "medium" || $_size == "large") ? $_size : "medium");

	$output = '<div class="circular-'.$size.'" style="background: url('.$avatar.');"></div>';

	echo $output;
}

function get_author_image_url($user_id=999999) {

	if($user_id==999999){

		$avatar = get_the_author_meta('author_profile_picture2', get_the_ID());

	} else {

		$avatar = get_the_author_meta('author_profile_picture2', $user_id);

	}

	return $avatar;
}

function get_mts_author_image($avatar, $id_or_email, $size, $default='', $alt='') {

	$myavatar = "";

    if ( is_numeric($id_or_email) ) {

    	$id = (int) $id_or_email;
    	$user = get_userdata($id);

    	if ( $user ) {
    		$email = $user->user_email;
    	}

    } elseif ( is_object($id_or_email) ) {

        if ( !empty($id_or_email->user_id) ) {

            $id = (int) $id_or_email->user_id;
            $user = get_userdata($id);

            if ( $user) {
            	$email = $user->user_email;
            }

        } elseif ( !empty($id_or_email->comment_author_email) ) {

            $email = $id_or_email->comment_author_email;
        }

    } else {

    	$email = $id_or_email;
    }

    // First see if they're a registered user with email set
    if(!empty($email)) {

        // user exists + has email
        $avatar_user = get_user_by('email', $email);
        // check if author_profile_picture2 is set
        $url = get_the_author_meta('author_profile_picture2', $avatar_user->ID);

        if($avatar_user && $url){

        	// there is a url so user has an author profile picture
            $myavatar = '<img class="avatar avatar-'.$size.' photo" width="'.$size.'" height="'.$size.'" src="'.$url.'"/>';
        
        } else {

            // No author_profile_picture2 set OR user does not belong to blog, so default to Gravatar
            $gravatarUrl = "http://www.gravatar.com/avatar.php?gravatar_id=" . md5($email) . "&size=40";
            $myavatar = "<img src='$gravatarUrl' height='".$size."' width='".$size."' alt=".$email."' />";
        }

    } else {

        $myavatar = "<img alt='' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
    }              

    return $myavatar;
}
add_filter( 'get_author_banner', 'get_mts_author_image', 10, 5);
?>