/*
* LaTeX Editor - JavaScript to launch the CodeCogs Equation Editor 
* Copyright (C) 2009 William Bateman, 2008 Waipot Ngamsaad 

* 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 3 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, see <http://www.gnu.org/licenses/>.
*/

// The following code was originally developed by Waipot Ngamsaad <waipot@ngamsaad.name> (Website: http://www.waipot.ngamsaad.name)
// It has been updated and adapted by Will Bateman for www.CodeCogs.com

function makeLink(latex_code) {
	var str = latex_code;
	//Clean code
	str.replace(/<br>/gi,"");
	str.replace(/<br \/>/gi,"");
	//Create img tag
	latex_img = " <img src=\"http://latex.codecogs.com/gif.latex?"+ str +"\" title=\""+ str +"\" alt=\""+ str +"\" align=\"absmiddle\" border=\"0\" /> ";

	return latex_img;
}

function renderTeX(tag) {
	var eqn = window.document.getElementsByTagName(tag);
	for (var i=0; i<eqn.length; i++) {
		if (eqn[i].getAttribute("lang") == "latex" || eqn[i].getAttribute("xml:lang") == "latex") { 
			if ( !eqn[i].innerHTML.match(/<img.*?>/i) )
				eqn[i].innerHTML = makeLink(eqn[i].innerHTML);
		} 
	}
}

function renderpre() { renderTeX("pre"); }
function rendercode() { renderTeX("code"); }

//Run
if (window.addEventListener)
{
  window.addEventListener("load", renderpre, false); 
  window.addEventListener("load", rendercode, false); 
}
else if (window.attachEvent)
{
	window.attachEvent("onload", renderpre); 
	window.attachEvent("onload", rendercode); 
}