;# MovableType Rich Editor - Enable WYSIWYG editing

package MT::Plugin::TinyMCEforMT;
use strict;

use vars qw( $MYNAME $VERSION );
$MYNAME = 'TinyMCEforMT';
$VERSION = 'Ver1.30 Ja';

use base qw( MT::Plugin );
my $plugin = new MT::Plugin ({
		name => $MYNAME,
		version => $VERSION,
		description =>
				'Enable you to edit the entry in WYSIWYG.<br />'.
				'This product includes <a href="http://tinymce.moxiecode.com/">TinyMCE</a>, '.
				'which is released under LGPL by <a href="http://www.moxiecode.com/">Moxiecode Systems AB</a>.',
		author_name => 'TinyMCE for Movable Type Development Project',
		author_link => 'http://sourceforge.jp/projects/tinymce-for-mt/' ,
		doc_link => 'http://www.dakiny.com/tinymce/'
});
MT->add_plugin ($plugin);
MT->add_text_filter('tinymce' => {
	label => 'WYSIWYG',
	on_format => sub { $_[0] }
});

;### Callback register for Transformer
MT->add_callback('MT::App::CMS::AppTemplateSource.header', 9, $plugin, \&add_wysiwyg_javascript);
MT->add_callback('MT::App::CMS::AppTemplateSource.edit_entry', 9, $plugin, \&add_wysiwyg);

sub instance { $plugin }



;### Customize the entry editing page of MovableType
sub add_wysiwyg {
	my ($cb, $app, $template) = @_;
;#
	;# When non-zero value is given, WYSIWYG edit mode *BECOMES SELECTABLE* by user.
	;# This does not mean that textarea is in WYSIWYG mode at first.
	add_wysiwyg_text ($cb, $app, $template) if 1;
	add_wysiwyg_text_more ($cb, $app, $template) if 1;
	add_wysiwyg_excerpt ($cb, $app, $template) if 1;
	add_wysiwyg_keywords ($cb, $app, $template) if 1;
}


;### Add JavaScript section
sub add_wysiwyg_javascript {
	my ($cb, $app, $template) = @_;
;#
	my $old = <<HTML;
</head>
HTML
	my $add = <<HTML;
<script type="text/javascript" src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
// Retrieve specified element by id
function E (id) { return document.getElementById (id) }

// Switch to Enable/Disable WYSIWYG Contoroler
function enableWYSIWYG (name, flag) {
	if (! E ('${MYNAME}_' + name + '_normal'))
		return false;	// not found '${MYNAME}_XXX'
	if (eval (flag)) { // Enable WYSIWYG
		E ('${MYNAME}_' + name + '_normal').style.display = 'none';
		tinyMCE.execCommand ('mceAddControl', false, name);
		E ('${MYNAME}_' + name + '_wysiwyg').style.display = 'block';
	} else { // Disable WYSIWYG
		E ('${MYNAME}_' + name + '_wysiwyg').style.display = 'none';
		tinyMCE.execCommand ('mceRemoveControl', false, name);
		E ('${MYNAME}_' + name + '_normal').style.display = 'block';
	}
	// Save the flag of WYSIWYG mode
	setCookie ('${MYNAME}_' + name + '_wysiwyg', flag);
	return false;
}

// Set value at specified name in cookie
function setCookie (name, value) {
	if (! navigator.cookieEnabled || ! name)
		return false;
	var expires = new Date ();
	// set expires span in milliseconds
	expires.setTime (expires.getTime () + 1000 * 60 * 60 * 24 * 365);
	document.cookie = name + '=' + escape (value) + ';expires=' + expires.toGMTString ();
	return true;
}

// Retrieve value of specified name in cookie
function getCookie (name) {
	var values = document.cookie + ';';
	var i = values.indexOf (name + '=');
	if (i == -1)
		return undefined;
	var j = values.indexOf (';', i);
	return unescape (values.substring (i + name.length + 1, j));
}

// Set the row size of textarea specified by name
function setRowsTextarea (name, value) {
	value = eval (value);// umm.
	var textarea = E (name);
	if (! value || ! textarea)
		return false;
	setCookie ('${MYNAME}_' + name + '_rows', (textarea.rows = value));
}

// Increase the row size of textarea specified by name
function addRowsTextarea (name, value) {
	var textarea = E(name);
	if (! textarea || textarea.rows + value <= 0)
		return false;
	setCookie ('${MYNAME}_' + name + '_rows', (textarea.rows += value));
}

// Whole page has been loaded, TinyMCE is going to intialize.
function ${MYNAME}_CallbackOnPageLoad () {
	// Set initial size of textareas with retrieving from cookie
	setRowsTextarea ('text', getCookie ('${MYNAME}_text_rows'));
	setRowsTextarea ('text_more', getCookie ('${MYNAME}_text_more_rows'));
	setRowsTextarea ('excerpt', getCookie ('${MYNAME}_excerpt_rows'));
	setRowsTextarea ('keywords', getCookie ('${MYNAME}_keywords_rows'));
}

// TinyMCE has been initialized
function ${MYNAME}_CallbackOnInit () {
	// Set initial mode with retrieving the flag from cookie
	enableWYSIWYG ('text', getCookie ('${MYNAME}_text_wysiwyg'));
	enableWYSIWYG ('text_more', getCookie ('${MYNAME}_text_more_wysiwyg'));
	enableWYSIWYG ('excerpt', getCookie ('${MYNAME}_excerpt_wysiwyg'));
	enableWYSIWYG ('keywords', getCookie ('${MYNAME}_keywords_wysiwyg'));
}

// TinyMCE Cleanup Callback
function ${MYNAME}_CallbackOnCleanup (type, html) {
	if (type == 'get_from_editor') {
		// trim continuous spacing
		html = html.replace(/\\s+</g,'<').replace(/>\\s+/g,'>');
		// break before tag
		html = html.replace (/(<(?:h1|h2|h3|h4|h5|h6)[^>]*\\/?>)/ig, '\\n\$1');
		// break after tag
		html = html.replace (/(<(?:br|\\/h1|\\/h2|\\/h3|\\/h4|\\/h5|\\/h6|\\/li)[^>]*>)/ig, '\$1\\n');
		// break before and behind of tag
		html = html.replace (/(<\\/?(?:address|blockquote|div|dl|form|hr|iframe|img|ol|p|pre|script|table|textarea|ul)[^>]*\\/?>)/ig, '\\n\$1\\n');
		// trim continuous line breaks
		html = html.replace(/\\n+/g, "\\n");
		// trim 'border="x"' in <img> tag
		html = html.replace(/(<\\s*img[^>]+)border="\\d+"\\s?/ig, '\$1');
		// trim 'border="x"' in <table> tag
		html = html.replace(/(<\\s*table[^>]+)border="\\d+"\\s?/ig, '\$1');
	}
	return html;
}

// FileBrowser Callback
    function fileBrowserCallBack(field_name, url, type, win) {
	    var connector = "<TMPL_VAR NAME=STATIC_URI>/$MYNAME/file_manager.php";
            my_field = field_name;
			my_win = win;
			switch (type) {
				case "image":
					connector += "?type=img";
					break;
				case "media":
					connector += "?type=media";
					break;
				case "flash": //for older versions of tinymce
					connector += "?type=media";
					break;
				case "file":
					connector += "?type=files";
					break;
			}
			window.open(connector, "file_manager", "modal,width=570,height=400,scrollbars=1");
}

// Initialize TinyMCE
tinyMCE.init({
		content_css : "<TMPL_VAR NAME=STATIC_URI>$MYNAME/mycontent.css",
		theme : "advanced",
		plugins : "table,advimage,advlink,emotions,insertdatetime,preview,youtube,contextmenu,paste,directionality,noneditable,style",
		theme_advanced_blockformats : "p,div,pre,h1,h2,h3,h4,h5,h6",
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,fontselect,fontsizeselect,zoom",
        theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,image,|,code,cleanup,removeformat,|,forecolor,backcolor,|,cut,copy,paste,pastetext,pasteword,|,help",
        theme_advanced_buttons3 : "styleprops,|,tablecontrols,|,hr,|,sub,sup,|,charmap,nonbreaking,emotions,|,youtube,|,preview",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_path_location : "bottom",
		theme_advanced_resize_horizontal : true,
		theme_advanced_resizing : true,
		theme_advanced_resizing_use_cookie : true,
   	    extended_valid_elements : "hr[class|width|size|noshade]",
		file_browser_callback : "fileBrowserCallBack",
		language : <TMPL_IF NAME=LANGUAGE_ID>'<TMPL_VAR NAME=LANGUAGE_ID>_<TMPL_VAR NAME=LANGUAGE_ENCODING>'<TMPL_ELSE>'en'</TMPL_IF>.toLowerCase (),
		convert_urls : false,
		convert_fonts_to_spans : true,
		convert_newlines_to_brs : false,
		force_p_newlines : true,
		force_br_newlines : false,
		relative_urls : false,
		apply_source_formatting : true,
        width : "569",
        height : "300",
		cleanup_callback : "${MYNAME}_CallbackOnCleanup",
		onpageload : "${MYNAME}_CallbackOnPageLoad",
		oninit : "${MYNAME}_CallbackOnInit"
});
</script>
HTML
	$old = quotemeta ($old);
	$$template =~ s/($old)/$add$1/;
}


;### Add WYSIWYG control onto more - id='text'
sub add_wysiwyg_text {
	my ($cb, $app, $template) = @_;
;#
	my $old = <<HTML;
<label for="text"><MT_TRANS phrase="Entry Body"></label>
<a href="#" onclick="return openManual('entries', 'body')" class="help">?</a>
</div>
<div class="field-wrapper">
<div class="field-buttons">
<div class="field-buttons-formatting"
HTML
;#
	my $add = <<HTML;
 id="${MYNAME}_text_wysiwyg">
<a title="" href="#" onclick="return enableWYSIWYG('text', 0);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_off.gif" width="44" height="16" /></a>
</div>
<span id="${MYNAME}_text_normal"><div class="field-buttons-formatting">
<a title="" href="#" onclick="return enableWYSIWYG('text', 1);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_on.gif" width="44" height="16" /></a
HTML
	chop ($old); $old = quotemeta ($old);
	chop ($add);
	$$template =~ s/($old)/$1$add/;
;#
	$old = <<HTML;
width="26" height="19" /></a>');
}
</script>
</div>
</div>
HTML
;#'
	$add = <<HTML;
</span><!--${MYNAME}_wysiwyg-->
HTML
	chop ($old); $old = quotemeta ($old);
	chop ($add);
	$$template =~ s/($old)/$1$add/g;# has global option
}


;### Add WYSIWYG control onto more - id='text_more'
sub add_wysiwyg_text_more {
	my ($cb, $app, $template) = @_;
;#
	my $old = <<HTML;
<label for="text_more"><MT_TRANS phrase="Extended Entry"></label>
<a href="#" onclick="return openManual('entries', 'extended_entry')" class="help">?</a>
</div>
<div class="field-wrapper">
<div class="field-buttons">
<div class="field-buttons-formatting"
HTML
	my $add = <<HTML;
 id="${MYNAME}_text_more_wysiwyg">
<a title="" href="#" onclick="return enableWYSIWYG('text_more', 0);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_off.gif" width="44" height="16" /></a>
</div>
<span id="${MYNAME}_text_more_normal"><div class="field-buttons-formatting">
<a title="" href="#" onclick="return enableWYSIWYG('text_more', 1);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_on.gif" width="44" height="16" /></a
HTML
	chop ($old); $old = quotemeta ($old);
	chop ($add);
	$$template =~ s/($old)/$1$add/;
}


;### Add WYSIWYG control onto excerpt - id='excerpt'
sub add_wysiwyg_excerpt {
	my ($cb, $app, $template) = @_;
;#
	my $old = <<HTML;
<a href="#" onclick="return openManual('entries', 'excerpt')" class="help">?</a>
HTML
	my $add1 = <<HTML;
HTML
	my $add2 = <<HTML;
<span id="${MYNAME}_excerpt_wysiwyg">
<a title="" href="#" onclick="return enableWYSIWYG('excerpt', 0);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_off.gif" width="44" height="16" /></a>
</span>
<span id="${MYNAME}_excerpt_normal">
<a title="" href="#" onclick="return enableWYSIWYG('excerpt', 1);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_on.gif" width="44" height="16" /></a>
</span>
HTML
	chop ($old); $old = quotemeta ($old);
	chop ($add1);
	chop ($add2);
	$$template =~ s/($old)/$add1$1$add2/;
}


;### Add WYSIWYG control onto keywords - id='keywords'
sub add_wysiwyg_keywords {
	my ($cb, $app, $template) = @_;
;#
	my $old = <<HTML;
<a href="#" onclick="return openManual('entries', 'keywords')" class="help">?</a>
HTML
	my $add1 = <<HTML;
HTML
	my $add2 = <<HTML;
<span id="${MYNAME}_keywords_wysiwyg">
<a title="" href="#" onclick="return enableWYSIWYG('keywords', 0);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_off.gif" width="44" height="16" /></a>
</span>
<span id="${MYNAME}_keywords_normal">
<a title="" href="#" onclick="return enableWYSIWYG('keywords', 1);"><img src="<TMPL_VAR NAME=STATIC_URI>$MYNAME/images/wysiwyg_on.gif" width="44" height="16" /></a>
</span>
HTML
	chop ($old); $old = quotemeta ($old);
	chop ($add1);
	chop ($add2);
	$$template =~ s/($old)/$add1$1$add2/;
}

1;
__END__
