<?php

/*
Plugin Name: Reuse Media Proof of Concept
Plugin URI: http://simonwheatley.co.uk/wordpress/rum-poc/
Description: Adds an upload screen to the edit categories screen to prove how cool this would all be.
Version: 0.1
Author: Simon Wheatley
Author URI: http://simonwheatley.co.uk/wordpress/ 
*/
 
/*  Copyright 2010 Simon Wheatley

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

/**
 * @package RumPoc
 **/
class RumPoc {
	
	/**
	 * Initiate!
	 *
	 * @return void
	 **/
	public function __construct() {
		if ( is_admin() ) {
			add_action( 'edit_category_form_fields', array( & $this, 'edit_category_form_fields' ) );
			add_action( 'load-edit-tags.php', array( & $this, 'load_edit_tags' ) );
			add_action( 'admin_head-edit-tags.php', array( & $this, 'print_scripts_edit_cat' ), 11 );
			add_action( 'admin_head-media-upload.php', array( & $this, 'print_scripts_media_up' ), 11 );
			add_action( 'admin_print_scripts-media-upload-popup', array( & $this, 'print_scripts_media_up' ), 11 );
			add_filter( 'media_upload_tabs', array( & $this, 'media_upload_tabs' ) );
			add_filter( 'gettext', array( & $this, 'translate' ), null, 3 );
			add_action( 'post-flash-upload-ui', array( & $this, 'post_upload_ui' ) );
			add_action( 'post-html-upload-ui', array( & $this, 'post_upload_ui' ) );
			add_filter( 'get_media_item_args', array( & $this, 'get_media_item_args' ) );
			add_filter( 'swfupload_post_params', array( & $this, 'swfupload_post_params' ) );
			add_filter( 'swfupload_success_handler', array( & $this, 'swfupload_success_handler' ) );
		}
	}
	
	/**
	 * Hooks the WP load-edit-tags.php action
	 *
	 * @return void
	 **/
	public function load_edit_tags() {
		$tax = @ $_GET[ 'taxonomy' ];
		if ( $tax != 'category' )
			return;
		wp_enqueue_script( 'jquery' );
		wp_enqueue_script( 'thickbox' );
		wp_enqueue_style( 'thickbox' );
		wp_enqueue_style( 'media' );
	}
	
	/**
	 * Hooks the WP admin_print_scripts-edit-tags.php action to print scripts on the cat edit screen
	 *
	 * @return void
	 **/
	public function print_scripts_edit_cat() {
		// Some JS to resize the Thickbox file upload overlay and commandeer the reply from
		// the overlay (which is currently expecting a post edit window JS function)
echo <<<END
<script type="text/javascript">
//<![CDATA[

// Hackety Hack: Hijack the function name which WP is expecting to choose the image
function send_to_editor(h) {
	// Obviously need to do more stuff here
	alert( "Received the object (we'd want to do things slightly differently here'): " );
	alert( h );
	tb_remove();
}

// thickbox settings
var tb_cat_position;
(function($) {
	tb_cat_position = function() {
		var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width;

		if ( tbWindow.size() ) {
			tbWindow.width( W - 50 ).height( H - 45 );
			$('#TB_iframeContent').width( W - 50 ).height( H - 75 );
			tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
			if ( typeof document.body.style.maxWidth != 'undefined' )
				tbWindow.css({'top':'20px','margin-top':'0'});
		};

		return $('a.thickbox').each( function() {
			var href = $(this).attr('href');
			if ( ! href ) return;
			href = href.replace(/&width=[0-9]+/g, '');
			href = href.replace(/&height=[0-9]+/g, '');
			$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 ) );
		});
	};

	$(window).resize(function(){ tb_cat_position(); });

})(jQuery);

jQuery( document ).ready( function($){ tb_cat_position(); } );

//]]>
</script>
END;
	}

	/**
	 * Hooks the WP admin_print_scripts-edit-tags.php action to print scripts on the cat edit screen
	 *
	 * @return void
	 **/
	public function print_scripts_media_up() {
		error_log( "Print scripts on media up" );
echo <<<END
<script type="text/javascript">
//<![CDATA[

function rmupoc_uploadSuccess(fileObj, serverData) {
	// if async-upload returned an error message, place it in the media item div and return
	if ( serverData.match('media-upload-error') ) {
		jQuery('#media-item-' + fileObj.id).html(serverData);
		return;
	}

	rmupoc_prepareMediaItem(fileObj, serverData);
	updateMediaForm();

	// Increment the counter.
	if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) )
		jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}

function rmupoc_prepareMediaItem(fileObj, serverData) {
	var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
	// Move the progress bar to 100%
	jQuery('.bar', item).remove();
	jQuery('.progress', item).hide();

	try {
		if ( typeof topWin.tb_remove != 'undefined' )
			topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
	} catch(e){}

	// New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
	item.load('async-upload.php', { attachment_id:serverData, fetch:f, app: 'rmupoc', cat_id: 1 }, function(){
		prepareMediaItemInit(fileObj);
		updateMediaForm();
	});
}

//]]>
</script>
END;
	}
	
	/**
	 * Hooks the (new) WP filter get_media_item_args
	 *
	 * @param array $args The args for get_media_item, after they've had the defaults applied 
	 * @return array The args, after we've amended them
	 * @author Simon Wheatley
	 **/
	public function get_media_item_args( $args ) {
		$args[ 'send' ] = true;
		return $args;
	}
	
	/**
	 * Hooks the (new) WP swfupload_post_params filter
	 *
	 * @param array $params An associative array of post params to pass to SWFUpload
	 * @return array An associative array of post params
	 * @author Simon Wheatley
	 **/
	public function swfupload_post_params( $params ) {
		if ( isset( $_REQUEST[ 'app' ] ) && $_REQUEST[ 'app' ] == 'rmupoc' ) {
			$params[ 'app' ] = 'rmupoc';
			$params[ 'cat_id' ] = (int) @ $_REQUEST[ 'cat_id' ];
		}
		return $params;
	}
	
	/**
	 * Hooks the (new) WP swfupload_success_handler filter
	 *
	 * @param string $handler The current handler name (JS function name) 
	 * @return string The (amended) handler name
	 * @author Simon Wheatley
	 **/
	public function swfupload_success_handler( $handler ) {
		$handler = 'rmupoc_uploadSuccess';
		return $handler;
	}
	
	/**
	 * Hook the WP edit_category_form_fields action
	 *
	 * @param object $cat The WP taxonomy object for the category being edited 
	 * @return void
	 **/
	public function edit_category_form_fields( $cat ) {
		// Hopefully some media upload JS will add sizes on
		$media_upload_iframe_src = "media-upload.php?cat_id={$cat->term_id}&amp;app=rmupoc&amp;TB_iframe=true&amp;cb=" . rand();
		$image_upload_iframe_src = apply_filters('image_upload_iframe_src', "$media_upload_iframe_src&amp;type=image");
		$image_link = __( 'Add a Category Image', 'category-images-ii' );
		echo "<tr><th>Category Image</th><td><a href='$image_upload_iframe_src' id='add_image' class='thickbox' title='$image_link'>$image_link</a></td></tr>";
	}
	
	/**
	 * Hooks the WP media_upload_tabs filter
	 *
	 * @param array $tabs An associative array of tab names 
	 * @return array An associative array of tab names
	 **/
	public function media_upload_tabs( $tabs ) {
		if ( isset( $_REQUEST[ 'app' ] ) && $_REQUEST[ 'app' ] == 'rmupoc' )
			unset( $tabs[ 'type_url' ] );
		return $tabs;
	}
	
	/**
	 * Hooks the WP post-flash-upload-ui & post-html-upload-ui actions
	 *
	 * @return void
	 **/
	public function post_upload_ui() {
		echo "<input type='hidden' name='app' value='rmupoc' />";
	}
	
	/**
	 * Hooks the WP gettext function to monkey with translations
	 *
	 * @param string $translation The current translation
	 * @param string $original The text before translation 
	 * @param string $domain The gettext domain
	 * @return void
	 **/
	public function translate( $translation, $original, $domain ) {
		// Dirty dirty hack
		if ( $original == 'Insert into Post' )
			error_log( "Change button: " . print_r( $_REQUEST, true ) );
		if ( isset( $_REQUEST[ 'app' ] ) && $_REQUEST[ 'app' ] == 'rmupoc' )
			if ( $original == 'Insert into Post' )
				return __( 'Set as Category Image', 'category-images-ii' );
		return $translation;
	}

} // END RumPoc class 

$rum_poc = new RumPoc();


?>