(no commit message)
[lambda.git] / mathml.js
1 /*
2 March 19, 2004 MathHTML (c) Peter Jipsen http://www.chapman.edu/~jipsen
3 Released under the GNU General Public License version 2 or later.
4 See the GNU General Public License (at http://www.gnu.org/copyleft/gpl.html)
5 for more details.
6 */
7
8 function convertMath(node) {// for Gecko
9   if (node.nodeType==1) {
10     var newnode = 
11       document.createElementNS("http://www.w3.org/1998/Math/MathML",
12         node.nodeName.toLowerCase());
13     for(var i=0; i < node.attributes.length; i++)
14       newnode.setAttribute(node.attributes[i].nodeName,
15         node.attributes[i].nodeValue);
16     for (var i=0; i<node.childNodes.length; i++) {
17       var st = node.childNodes[i].nodeValue;
18       if (st==null || st.slice(0,1)!=" " && st.slice(0,1)!="\n") 
19         newnode.appendChild(convertMath(node.childNodes[i]));
20     }
21     return newnode;
22   }
23   else return node;
24 }
25
26 function convert() {
27   var mmlnode = document.getElementsByTagName("math");
28   var st,str,node,newnode;
29   for (var i=0; i<mmlnode.length; i++)
30     if (document.createElementNS!=null)
31       mmlnode[i].parentNode.replaceChild(convertMath(mmlnode[i]),mmlnode[i]);
32     else { // convert for IE
33       str = "";
34       node = mmlnode[i];
35       while (node.nodeName!="/MATH") {
36         st = node.nodeName.toLowerCase();
37         if (st=="#text") str += node.nodeValue;
38         else {
39           str += (st.slice(0,1)=="/" ? "</m:"+st.slice(1) : "<m:"+st);
40           if (st.slice(0,1)!="/") 
41              for(var j=0; j < node.attributes.length; j++)
42                if (node.attributes[j].nodeValue!="italic" &&
43                  node.attributes[j].nodeValue!="" &&
44                  node.attributes[j].nodeValue!="inherit" &&
45                  node.attributes[j].nodeValue!=undefined)
46                  str += " "+node.attributes[j].nodeName+"="+
47                      "\""+node.attributes[j].nodeValue+"\"";
48           str += ">";
49         }
50         node = node.nextSibling;
51         node.parentNode.removeChild(node.previousSibling);
52       }
53       str += "</m:math>";
54       newnode = document.createElement("span");
55       node.parentNode.replaceChild(newnode,node);
56       newnode.innerHTML = str;
57     }
58 }
59
60 if (document.createElementNS==null) {
61   document.write("<object id=\"mathplayer\"\
62   classid=\"clsid:32F66A20-7614-11D4-BD11-00104BD3F987\"></object>");
63   document.write("<?import namespace=\"m\" implementation=\"#mathplayer\"?>");
64 }
65 if(typeof window.addEventListener != 'undefined'){
66   window.addEventListener('load', convert, false);
67 }
68 if(typeof window.attachEvent != 'undefined') {
69   window.attachEvent('onload', convert);
70 }