/***
!Metadata:
|''Name:''|HTMLAreaPlugin|
|''Description:''| |
|''Version:''|2.1.2|
|''Date:''|Oct 5, 2006|
|''Source:''|http://sourceforge.net/project/showfiles.php?group_id=150646|
|''Author:''|BramChen (bram.chen (at) gmail (dot) com)|
|''Original:''|Asciencepad, hijacked by PeterJipsen|
|''License:''|[[Creative Commons Attribution-ShareAlike 2.5 License]]|
|''~CoreVersion:''|2.1.2|
|''Browser:''|Firefox 1.5+; InternetExplorer 6.0|

!Required:
* TiddlyWiki 2.1.2
* HtmlArea eitor modified by PeterJipsen
!Reference: http://math.chapman.edu/~jipsen/asciencepad/asciencepad.html
!Installation: 
	# Add below statement to MarkupPostHead
<script type="text/javascript" src="HTMLArea/htmlareaPlugin.js"></script>

	# Add below statements to MarkupPreHead
{{{
<!--PJ-->
<script type="text/javascript" src="HTMLArea/plugins/AsciiMath/ASCIIMathML.js"></script>
<script type="text/javascript" src="HTMLArea/plugins/AsciiSvg/ASCIIsvg.js"></script>
<script type="text/javascript" src="HTMLArea/plugins/AsciiSvg/ASCIIsvgAddon.js"></script>
<!--script type="text/javascript" src="HTMLArea/plugins/AsciiMath/ASCIIMathCalculator.js"></script-->
<script type="text/javascript">
	_editor_url = "HTMLArea/";
	_editor_lang = "en";
</script>
<script type="text/javascript" src="HTMLArea/htmlarea.js"></script>
<!--PJ-->
}}}	
	# Save changes and reload page.

!Uninstall:
	* Open TW document in your edtior, and remove all lines added from installation step.

!Note:
	* Do not install this plugin as "systemConfig".
	* The content of tiddler is no more with wiki texts but a big <html>blahblah</html> block.
!Revision history:
	* Jun 27 2006 
		** for TiddlyWiki 2.1.0
		** cleaned up hijacking codes. 
	* Jnu 07 2006
		** Initial release, for TiddlyWiki 2.0.11
! Codes
***/
//{{{
version.extensions.HTMLAreaPlugin = {major: 2, minor: 1, revision: 2,
	date: new Date("Oct 5, 2006"),
	name: "HTMLAreaPlugin",
	type: "Plugin",
	author: "BramChen",
	source: "http://sourceforge.net/project/showfiles.php?group_id=150646"
};

// PJ

HTMLArea.loadPlugin("AsciiMath");
HTMLArea.loadPlugin("AsciiSvg");
var editors = {};
var editor = null;
var cureditor = null;

function initEditor(str) {
  editors[str] = new HTMLArea(str);
  editor = editors[str]; //hack to make setsscr in ascii-svg.js work in Firefox
  var line = editors[str].config.toolbar[1] ? 1 : 0;
  editors[str].config.toolbar[line].push("separator","insertnewmath",
                            "insertmath","swapmathmode");
  editors[str].config.toolbar[line].push("separator","insertsvg");
  editors[str].registerPlugin(AsciiMath);
  editors[str].registerPlugin(AsciiSvg);
  editors[str].config.hideSomeButtons(" subscript superscript popupeditor lefttoright righttoleft ");
  //surrounds AsciiMath in red box while editting.  Change to your liking
  editors[str].config.pageStyle = "span.AMedit {border:solid 1px #ff0000}";
  editors[str].generate();
  return false;
};
function wikifyTextNodes(w,e) { //recursively apply subWikify to e
  var tmp,ptmp,wtmp;
  if (!e.className || e.className.slice(0,2) != "AM") { //skip ASCIIMath nodes
    if (e.childNodes.length==0) {
      if (e.nodeValue) {
        wtmp = new Wikifier(e.nodeValue,w.formatter,null,w.tiddler);
        tmp=createTiddlyElement(w.output,"span");
        wtmp.subWikify(tmp);
        ptmp=e.parentNode;
        ptmp.replaceChild(tmp,e);
      }
    } else {
      for (var i=0; i<e.childNodes.length; i++)
        wikifyTextNodes(w,e.childNodes[i]);
    }
  }
}

// Hijack

for (var i=0; i<config.formatters.length; i++){
	if (config.formatters[i].name == "html"){
		config.formatters[i].handler = function(w){
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart)
			{
			var e = createTiddlyElement(w.output,"span");
			e.innerHTML = lookaheadMatch[1];
        	
wikifyTextNodes(w,e);//PJ

				w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
			}
		}
		break;	
	}
}

config.editPJ = config.macros.edit.handler;
config.macros.edit.handler = function(place,macroName,params,wikifier,paramString,tiddler){
	var field = params[0];
	if (field == "text"){

		if((tiddler instanceof Tiddler) && field){
			story.setDirty(tiddler.title,true);
			var wrapper1 = createTiddlyElement(place,"fieldset",null,"fieldsetFix");
			var wrapper2 = createTiddlyElement(wrapper1,"div");
			var e = createTiddlyElement(wrapper2,"textarea");
			if(tiddler.isReadOnly())
					e.setAttribute("readOnly","readOnly");
			var v = store.getValue(tiddler,field);
			e.value = (v)?v:"";
			var rows = 20;
			var lines = v.match(/\n/mg);
			var maxLines = Math.max(parseInt(config.options.txtMaxEditRows),5);
			if(lines != null && lines.length > rows)
				rows = lines.length + 5;
			rows = Math.min(rows,maxLines);
			e.setAttribute("rows",rows);
			e.setAttribute("edit","text");

if (tiddler.tags.length==0 || tiddler.tags[0].slice(0,6) != "system") { //PJ
  e.setAttribute("id","editorBody"+tiddler.title);
  initEditor("editorBody"+tiddler.title);
} //PJ
		}
	}
	else {
		config.editPJ(place,macroName,params,wikifier,paramString,tiddler);
	}
}

Story.prototype.refreshTiddlerPJ = Story.prototype.refreshTiddler;
Story.prototype.refreshTiddler = function(title,minorUpdate) {
	var theTiddler = story.refreshTiddlerPJ(title,minorUpdate);
	AMprocessNode(theTiddler,false); //PJ
	setTimeout('drawPictures()',100); //PJ
	return theTiddler;
}
Story.prototype.saveTiddlerPJ = Story.prototype.saveTiddler;
Story.prototype.saveTiddler = function(title,minorUpdate) {
	var tiddler = document.getElementById(this.idPrefix + title);
	if(tiddler != null)
		{
		var fields = {};
		if (tiddler.getAttribute("tags").slice(0,6) != "system") { //PJ
		  var str="editorBody"+title;
		  editors[str]._iframe.style.display = "none";
		  editors[str]._textArea.style.display = "block";
		  editors[str]._textArea.value = "<html>"+editors[str].getHTML().replace(/^\s+/g,'')+"</html>";
		} //PJ
	}
	return story.saveTiddlerPJ(title,minorUpdate);
}
//}}}